/** * A headless Chrome page driven over the DevTools protocol, for the landing's capture scripts, with * Chrome on `PATH` or in `CHROME`. Close it in a `finally`: it removes its profile. */ import { spawn } from 'node:child_process'; import { once } from 'node:events'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; export async function openChrome() { const chrome = process.env.CHROME ?? (process.platform === 'darwin' ? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' : 'google-chrome'); const profile = mkdtempSync(join(tmpdir(), 'landing-chrome-')); const browser = spawn(chrome, [ '--headless=new', '--remote-debugging-port=0', `--user-data-dir=${profile}`, '--hide-scrollbars', '--no-first-run', 'about:blank', ]); let socket: WebSocket | undefined; async function close() { socket?.close(); // the profile is removed once Chrome stops writing to it if (browser.exitCode === null && browser.signalCode === null) { browser.kill(); await once(browser, 'exit'); } rmSync(profile, { recursive: true, force: true }); } try { const endpoint = await new Promise((resolve, reject) => { browser.on('error', reject); browser.stderr.on('data', (chunk: Buffer) => { const found = /DevTools listening on (ws:\/\/\S+)/.exec(chunk.toString()); if (found) resolve(found[1]); }); }); const { origin } = new URL(endpoint.replace('ws:', 'http:')); const targets = (await (await fetch(`${origin}/json/list`)).json()) as { type: string; webSocketDebuggerUrl: string; }[]; socket = new WebSocket(targets.find((target) => target.type === 'page')!.webSocketDebuggerUrl); await new Promise((resolve) => socket!.addEventListener('open', resolve)); } catch (error) { await close(); throw error; } let id = 0; // a failed call rejects its own promise, so the run stops through `finally` and cleans up const waiting = new Map>>(); socket.addEventListener('message', (event) => { const message = JSON.parse(String(event.data)); const call = waiting.get(message.id); if (message.error) call?.reject(new Error(JSON.stringify(message.error))); else call?.resolve(message.result); }); const send = (method: string, params: object = {}) => { const call = Promise.withResolvers>(); waiting.set(++id, call); socket!.send(JSON.stringify({ id, method, params })); return call.promise; }; const run = async (expression: string) => { const { result, exceptionDetails } = (await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true, })) as { result: { value: unknown }; exceptionDetails?: { exception?: { description?: string } }; }; if (exceptionDetails) throw new Error(exceptionDetails.exception?.description); return result.value; }; return { send, run, close }; }