| 41 | export type ResponseSchema = unknown; |
| 42 | |
| 43 | export default class ChromiumFunctionPostRoute extends BrowserHTTPRoute { |
| 44 | name = BrowserlessRoutes.ChromiumFunctionPostRoute; |
| 45 | accepts = [contentTypes.json, contentTypes.javascript]; |
| 46 | auth = true; |
| 47 | browser = ChromiumCDP; |
| 48 | concurrency = true; |
| 49 | contentTypes = [contentTypes.any]; |
| 50 | description = dedent(` |
| 51 | A JSON or JavaScript content-type API for running puppeteer code in the browser's context. |
| 52 | Browserless sets up a blank page, injects your puppeteer code, and runs it. |
| 53 | You can optionally load external libraries via the "import" module that are meant for browser usage. |
| 54 | Values returned from the function are checked and an appropriate content-type and response is sent back |
| 55 | to your HTTP call.`); |
| 56 | method = Methods.post; |
| 57 | path = [HTTPRoutes.chromiumFunction, HTTPRoutes.function]; |
| 58 | tags = [APITags.browserAPI]; |
| 59 | async handler( |
| 60 | req: Request, |
| 61 | res: ServerResponse, |
| 62 | logger: Logger, |
| 63 | browser: BrowserInstance, |
| 64 | ): Promise<void> { |
| 65 | const config = this.config(); |
| 66 | const timeout = req.parsed.searchParams.get('timeout'); |
| 67 | const handler = functionHandler(config, logger, { |
| 68 | protocolTimeout: timeout ? +timeout : undefined, |
| 69 | }); |
| 70 | const { contentType, payload, page } = await handler(req, browser); |
| 71 | |
| 72 | logger.debug(`Got function response of "${contentType}"`); |
| 73 | page.removeAllListeners(); |
| 74 | page.close().catch(() => {}); |
| 75 | |
| 76 | if (contentType === 'uint8array') { |
| 77 | const response = new Uint8Array(payload as Buffer); |
| 78 | const type = ((await fileTypeFromBuffer(response)) || { mime: undefined }) |
| 79 | .mime; |
| 80 | |
| 81 | if (!type) { |
| 82 | throw new BadRequest(`Couldn't determine function's response type.`); |
| 83 | } else { |
| 84 | logger.debug(`Sending file-type response of "${type}"`); |
| 85 | const readStream = new Stream.PassThrough(); |
| 86 | readStream.end(response); |
| 87 | res.setHeader('Content-Type', type); |
| 88 | return new Promise((r) => readStream.pipe(res).once('close', r)); |
| 89 | } |
| 90 | } else { |
| 91 | writeResponse(res, 200, payload as string, contentType as contentTypes); |
| 92 | } |
| 93 | |
| 94 | return; |
| 95 | } |
| 96 | } |