// Headless Chrome over the DevTools protocol: launch a private instance (fresh // profile, remote debugging on an OS-assigned port) or attach to a running one // via `--cdp http://127.0.0.1:`. Either way the kit works in its own page // target, and close() removes everything it created. import { spawn } from 'node:child_process'; import { mkdtemp, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { setTimeout as delay } from 'node:timers/promises'; const CALL_TIMEOUT_MS = 30000; const DEFAULT_CHROME ='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; async function launch(chromePath) { const profile = await mkdtemp(join(tmpdir(), 'pipelines-capture-chrome-')); const chrome = spawn(chromePath, [ '--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu', '--hide-scrollbars', '--mute-audio', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank', ], { stdio: ['ignore', 'ignore', 'pipe'] }); let stderr = ''; chrome.stderr.on('data', (d) => { stderr += d; }); const exited = new Promise((done) => chrome.once('exit', done)); const cleanup = async () => { if (chrome.exitCode === null && chrome.signalCode === null) { chrome.kill('SIGTERM'); const timedOut = await Promise.race([exited.then(() => false), delay(3000, true)]); if (timedOut) { chrome.kill('SIGKILL'); await exited; } } await rm(profile, { recursive: true, force: true }).catch(() => {}); }; for (let i = 0; i < 150; i++) { const ws = stderr.match(/DevTools listening on (ws:\/\/\S+)/)?.[1]; if (ws) return { ws, cleanup }; if (chrome.exitCode !== null) break; await delay(100); } await cleanup(); throw new Error(`Chrome did not start (${chromePath}): ${stderr.slice(-800)}`); } async function attach(cdp) { const version = await (await fetch(new URL('/json/version', cdp))).json(); return { ws: version.webSocketDebuggerUrl, cleanup: async () => {} }; } /** * Opens a page target. Returns `{ send, on, close }`: `send(method, params)` * talks to the page session; `on(method, fn)` subscribes to its events and * returns the unsubscribe function; `newPage()` opens a scratch page. */ export async function openBrowser({ cdp, chromePath = process.env.CHROME_PATH ?? DEFAULT_CHROME } = {}) { const { ws: endpoint, cleanup } = cdp ? await attach(cdp) : await launch(chromePath); const ws = new WebSocket(endpoint); try { await new Promise((ok, fail) => { ws.onopen = ok; ws.onerror = () => fail(new Error(`Cannot open ${endpoint}`)); }); } catch (error) { await cleanup(); throw error; } let nextId = 0; const pending = new Map(); const listeners = new Map(); let sessionId; ws.onmessage = (event) => { const m = JSON.parse(event.data); if (m.id && pending.has(m.id)) { const { ok, fail, method } = pending.get(m.id); pending.delete(m.id); return m.error ? fail(new Error(`${method}: ${m.error.message}`)) : ok(m.result ?? {}); } if (m.method && m.sessionId === sessionId) for (const fn of listeners.get(m.method) ?? []) fn(m.params); }; // Every call is bounded: an unresponsive page (for example a navigation to a // server that never answers) fails the step instead of hanging the kit. const raw = (method, params = {}, session) => new Promise((ok, fail) => { const id = ++nextId; const timer = setTimeout(() => { pending.delete(id); fail(new Error(`${method}: no reply within ${CALL_TIMEOUT_MS} ms`)); }, CALL_TIMEOUT_MS); const settle = (fn) => (value) => { clearTimeout(timer); fn(value); }; pending.set(id, { ok: settle(ok), fail: settle(fail), method }); ws.send(JSON.stringify({ id, method, params, ...(session ? { sessionId: session } : {}) })); }); let targetId; try { ({ targetId } = await raw('Target.createTarget', { url: 'about:blank' })); ({ sessionId } = await raw('Target.attachToTarget', { targetId, flatten: true })); } catch (error) { ws.close(); await cleanup(); throw error; } return { send: (method, params) => raw(method, params, sessionId), on: (method, fn) => { listeners.set(method, [...(listeners.get(method) ?? []), fn]); return () => listeners.set(method, listeners.get(method).filter((f) => f !== fn)); }, /** Every open page target (tabs a link opened included): `{ url, type }`. */ targets: async () => (await raw('Target.getTargets')).targetInfos .filter((t) => t.type === 'page').map((t) => ({ url: t.url, type: t.type })), newPage: async () => { const page = await raw('Target.createTarget', { url: 'about:blank' }); const { sessionId: sid } = await raw('Target.attachToTarget', { targetId: page.targetId, flatten: true }); return { send: (method, params) => raw(method, params, sid), close: () => raw('Target.closeTarget', { targetId: page.targetId }).catch(() => {}), }; }, close: async () => { await raw('Target.closeTarget', { targetId }).catch(() => {}); ws.close(); await cleanup(); }, }; }