/** * Core raw-CDP client. Zero runtime dependencies: uses Node's global * WebSocket (Node >= 22; verified on Node 25.9). Every tool module is built on * the primitives exported here. See CONTRACT.md. */ import type { CdpResponse, Target, TargetSelector } from "./types.ts"; import { assertLeaseOk, chromeLeaseBackend } from "./leases.ts"; import { resolveLiveLabel } from "./origins.ts"; import { currentEndpoint, defaultEndpoint, DEFAULT_CDP_BASE } from "./endpoints.ts"; import { isWorkerSelector, isWorkerTargetType, resolveWorkerTargets, workerAmbiguityMessage, workerMissMessage, workerNeedle, WORKER_EMPTY_NEEDLE_MESSAGE, } from "./workers.ts"; import { frameAmbiguityMessage, frameMissMessage, frameNeedle, isFrameSelector, resolveFrameTargets, FRAME_EMPTY_NEEDLE_MESSAGE, } from "./frames.ts"; import { detectEndpoint, resetEndpointCache, type CdpTransport } from "./cdp/endpoint.ts"; import { openSession, withBrowserSocket, type PageConnection } from "./cdp/session.ts"; import { markHiddenTargets } from "./cdp/hiddenTabs.ts"; export { SessionConnection, withBrowserSocket, type PageConnection } from "./cdp/session.ts"; /** * Base HTTP origin of the DEFAULT DevTools endpoint, fixed at import (CDP_BASE, else * http://127.0.0.1:9222, or the default named by CDP_ENDPOINTS / CDP_ENDPOINTS_FILE). * Kept for library callers; nothing in this package reads it to build a URL any more: * every request resolves its base per call through currentEndpoint() (src/endpoints.ts). * A malformed endpoint config must not crash the import, so this falls back to the old * expression and the config error surfaces on first use (or at MCP/CLI startup). */ export const BASE: string = (() => { try { return defaultEndpoint().base; } catch { return process.env.CDP_BASE ?? DEFAULT_CDP_BASE; } })(); /** Default per-command timeout (ms). Override with CDP_TIMEOUT_MS. */ export const DEFAULT_TIMEOUT_MS = Number(process.env.CDP_TIMEOUT_MS ?? 15_000); export class CdpError extends Error { constructor( message: string, readonly code?: number, readonly data?: unknown, ) { super(message); this.name = "CdpError"; } } type EventHandler = (params: Record, sessionId?: string) => void; /** * A single CDP WebSocket connection (to either the browser endpoint or a page * target endpoint). Correlates id->response, fans out events to subscribers, * and enforces a per-command timeout so a wedged renderer can never hang a * caller indefinitely (the exact failure mode that breaks the MCP layer). */ export class CdpConnection { private ws?: WebSocket; private nextId = 0; private readonly pending = new Map< number, { resolve: (r: CdpResponse) => void; reject: (e: Error) => void; timer: ReturnType } >(); private readonly listeners = new Map>(); private closed = false; constructor( readonly wsUrl: string, private readonly opts: { timeoutMs?: number } = {}, ) {} connect(): Promise { return new Promise((resolve, reject) => { const ws = new WebSocket(this.wsUrl); this.ws = ws; const openTimer = setTimeout(() => reject(new CdpError(`connect timeout: ${this.wsUrl}`)), this.opts.timeoutMs ?? DEFAULT_TIMEOUT_MS); ws.onopen = () => { clearTimeout(openTimer); resolve(this); }; ws.onerror = (e: Event) => { clearTimeout(openTimer); const msg = (e as ErrorEvent)?.message ?? "websocket error"; if (this.pending.size === 0) reject(new CdpError(msg)); this.rejectAll(new CdpError(msg)); }; ws.onclose = () => { this.closed = true; this.rejectAll(new CdpError("connection closed")); }; ws.onmessage = (ev: MessageEvent) => this.onMessage(String(ev.data)); }); } private onMessage(raw: string): void { let msg: CdpResponse & { method?: string; params?: Record; sessionId?: string }; try { msg = JSON.parse(raw); } catch { return; } if (typeof msg.id === "number" && this.pending.has(msg.id)) { const p = this.pending.get(msg.id)!; clearTimeout(p.timer); this.pending.delete(msg.id); p.resolve(msg); return; } if (msg.method) { const set = this.listeners.get(msg.method); if (set) for (const h of set) h(msg.params ?? {}, msg.sessionId); const star = this.listeners.get("*"); if (star) for (const h of star) h({ method: msg.method, ...(msg.params ?? {}) }, msg.sessionId); } } private rejectAll(err: Error): void { for (const [, p] of this.pending) { clearTimeout(p.timer); p.reject(err); } this.pending.clear(); } /** Send a CDP command and await its result. Rejects on CDP error or timeout. */ send>( method: string, params: Record = {}, opts: { timeoutMs?: number; sessionId?: string } = {}, ): Promise { if (this.closed || !this.ws) return Promise.reject(new CdpError("connection not open")); const id = ++this.nextId; const timeoutMs = opts.timeoutMs ?? this.opts.timeoutMs ?? DEFAULT_TIMEOUT_MS; const payload: Record = { id, method, params }; if (opts.sessionId) payload.sessionId = opts.sessionId; return new Promise((resolve, reject) => { const timer = setTimeout(() => { this.pending.delete(id); reject(new CdpError(`'${method}' timed out after ${timeoutMs}ms`)); }, timeoutMs); this.pending.set(id, { resolve: (r) => { if (r.error) reject(new CdpError(`${method}: ${r.error.message}`, r.error.code, r.error.data)); else resolve((r.result ?? {}) as T); }, reject, timer, }); this.ws!.send(JSON.stringify(payload)); }); } /** Subscribe to a CDP event method (or "*" for all). Returns an unsubscribe fn. */ on(method: string, handler: EventHandler): () => void { let set = this.listeners.get(method); if (!set) { set = new Set(); this.listeners.set(method, set); } set.add(handler); return () => set!.delete(handler); } /** * Resolve when an event matching `method` (and optional predicate) fires, or * reject on timeout. Useful for navigation/dialog/load synchronization. */ waitFor

>( method: string, predicate?: (params: P) => boolean, timeoutMs = this.opts.timeoutMs ?? DEFAULT_TIMEOUT_MS, ): Promise

{ return new Promise

((resolve, reject) => { const timer = setTimeout(() => { off(); reject(new CdpError(`waitFor('${method}') timed out after ${timeoutMs}ms`)); }, timeoutMs); const off = this.on(method, (params) => { if (!predicate || predicate(params as P)) { clearTimeout(timer); off(); resolve(params as P); } }); }); } /** False once the socket closed (either side) or before connect(). The hidden-tab owner reads * this to notice that the tabs it kept alive died with it. */ get isOpen(): boolean { return !this.closed && this.ws !== undefined; } close(): void { this.closed = true; this.rejectAll(new CdpError("closed by caller")); try { this.ws?.close(); } catch { /* ignore */ } } } /* ----------------------------- endpoint discovery ----------------------------- */ /** * Which transport each endpoint turned out to serve, learned from its first * listing that succeeded, keyed by endpoint base. Absent until then. */ const knownTransports = new Map(); /** Test seam: forget the learned transport. */ export function resetTransportCache(): void { knownTransports.clear(); resetEndpointCache(); } async function httpJson(path: string): Promise { // Resolved PER CALL, never cached: the endpoint comes from the dispatch scope, and an // endpoint that was down a moment ago is simply tried again. const res = await fetch(`${currentEndpoint().base}${path}`); if (!res.ok) throw new CdpError(`${path} -> HTTP ${res.status}`); return (await res.json()) as T; } /** * `Target.getTargets` reshaped into the `/json/list` record every caller * already reads. * * TWO DIFFERENCES from the HTTP listing, both deliberate: * * `filter: [{}]` is passed because the DEFAULT filter is not "everything" — it * omits types the empty filter includes. Measured on Chrome 153: default * returned 4 targets (page, browser_ui), `[{}]` returned 6, and the missing * ones were exactly the iframe/worker types that the `frame:` and `worker:` * selector arms resolve against. Taking the default would silently delete two * documented features. * * `webSocketDebuggerUrl` is EMPTY, and it has to be: on this transport there is * no per-target socket to name, and inventing the `/devtools/page/` URL * would hand callers a string that 403s. Nothing reads the field on this path — * `openPage` branches on transport before it would — and the emptiness is what * makes a caller that ignored the branch fail loudly instead of hanging. */ async function getTargetsOverBrowserWs(): Promise { const { targetInfos } = await withBrowserSocket((conn) => conn.send<{ targetInfos: Array<{ targetId: string; type: string; title: string; url: string; openerId?: string }> }>( "Target.getTargets", { filter: [{}] }, ), ); return targetInfos.map((t) => ({ id: t.targetId, type: t.type, title: t.title, url: t.url, webSocketDebuggerUrl: "", ...(t.openerId ? { parentId: t.openerId } : {}), })); } /** * All targets: `GET /json/list`, falling back to `Target.getTargets` on the * browser socket when this Chrome does not serve it. * * THE HTTP REQUEST GOES FIRST AND UNCONDITIONALLY, which is the whole * no-regression story: against a Chrome that serves `/json/list` this function * does exactly what it did before the fallback existed, and the fallback is * unreachable. Only a request that failed opens a socket. * * Once a transport is known it is cached, so the 404 is paid once per process * rather than on every listing. */ export async function listTargets(): Promise { const base = currentEndpoint().base; // markHiddenTargets returns the listing untouched unless this process holds hidden tabs on this // endpoint (CDP_HIDDEN_TABS, see cdp/hiddenTabs.ts). if (knownTransports.get(base) === "browser-ws") return markHiddenTargets(base, await getTargetsOverBrowserWs()); try { const listing = await httpJson("/json/list"); knownTransports.set(base, "http"); return markHiddenTargets(base, listing); } catch (httpError) { // Switch only when detection says this endpoint really serves no `/json`. // A Chrome that does serve it can still fail one `/json/list` (restarting, // a timeout); its `/json/version` then answers, detection says "http", and // pinning browser-ws here would move every later call off the per-target // sockets for the rest of the process. Rethrow instead, so the next call // tries HTTP again. const detected = await detectEndpoint().catch(() => undefined); if (detected?.transport !== "browser-ws") throw httpError; const targets = await getTargetsOverBrowserWs().catch(() => { // The HTTP failure is the one worth reporting: it names the endpoint the // user configured, where the fallback's failure only says a profile // lookup came up empty. throw httpError; }); knownTransports.set(base, "browser-ws"); return markHiddenTargets(base, targets); } } /** * Browser-level WebSocket URL, for Target.* / Browser.*. * * `GET /json/version` first and on every call, as before the browser-ws * transport existed: its uuid changes on every Chrome start, so a URL kept * across calls goes stale after a restart. Only an endpoint already known to * serve no `/json`, or one whose `/json/version` did not answer, goes through * detection. */ export async function browserWsUrl(): Promise { if (knownTransports.get(currentEndpoint().base) !== "browser-ws") { const version = await httpJson<{ webSocketDebuggerUrl: string }>("/json/version").catch(() => undefined); if (version?.webSocketDebuggerUrl) return version.webSocketDebuggerUrl; } return (await detectEndpoint()).browserWsUrl; } /** Resolve a TargetSelector to a concrete page target. See types.ts for grammar. * opts.lease is for library callers; the MCP/CLI path supplies the token through * the ambient lease scope instead (see leases.ts). */ export async function resolveTarget(selector: TargetSelector, opts: { lease?: string } = {}): Promise { const targets = await listTargets(); const hit = await pickTarget(targets, selector); // WORKER TARGETS BYPASS THE LEASE GATE ENTIRELY, and that is a decision, not // an omission. A lease answers "who is driving this TAB", and every // consequence of holding one is a tab consequence: reap CLOSES an abandoned // leased tab, and "close the stale tab" is meaningless for a service worker // that Chrome starts and stops on its own schedule (see ReapInput.livePageIds, // which is deliberately fed the page-only listing for exactly this reason). // Letting strict mode auto-acquire here would mint a lease file per worker // evaluate, keyed on an id that vanishes the moment the worker idles out — // garbage that the page-only reap set can never collect. It also cannot be // used to sneak past a lease: a worker is not a tab, so there is no tab // someone else holds that this could reach. if (isWorkerTargetType(hit.type)) return hit; // THE Chrome choke point. Every tool reaches a page through here, so a tool // added after this shipped is protected with no action from its author. // // Deliberately NOT passing liveIds. It would be inert here: pickTarget // returns an element of `targets`, so hit.id is always a member of that list // and the "target-gone" staleness condition could never fire for the very // target we just resolved. Passing it would only suggest a check is happening // that is not. target-gone earns its keep on claim, and on a list_leases // reap, where a record's id may genuinely be absent from the browser. await assertLeaseOk(chromeLeaseBackend(), hit.id, { lease: opts.lease, url: hit.url, title: hit.title }); return hit; } async function pickTarget(targets: Target[], selector: TargetSelector): Promise { const pages = targets.filter((t) => t.type === "page"); if (!selector || selector === "active") { if (!pages.length) throw new CdpError("no page targets open"); return pages[0]!; } if (selector.startsWith("index:")) { const i = Number(selector.slice(6)); if (!pages[i]) throw new CdpError(`no page target at index ${i} (have ${pages.length})`); return pages[i]!; } if (selector.startsWith("url:")) { const needle = selector.slice(4); const hit = pages.find((t) => t.url.includes(needle)); if (!hit) throw new CdpError(`no page url containing '${needle}'`); return hit; } if (selector.startsWith("title:")) { const needle = selector.slice(6); const hit = pages.find((t) => t.title.includes(needle)); if (!hit) throw new CdpError(`no page title containing '${needle}'`); return hit; } if (selector.startsWith("label:")) { const label = selector.slice(6); const { matchIds, knownLabels } = await resolveLiveLabel(chromeLeaseBackend(), label, pages.map((t) => t.id)); if (matchIds.length > 1) { throw new CdpError(`label 'label:${label}' matches more than one live target: ${matchIds.join(", ")}. Resolve by target id instead.`); } if (matchIds.length === 1) { const hit = pages.find((t) => t.id === matchIds[0]); if (hit) return hit; } throw new CdpError( knownLabels.length ? `no live target with label '${label}' (labels currently in use: ${knownLabels.join(", ")})` : `no live target with label '${label}' (no labels are currently assigned to any open target)`, ); } if (isWorkerSelector(selector)) { // Resolved against the UNFILTERED listing, never `pages`: a worker is not a // page target and would not be in it. Waking an evicted worker is NOT done // here — this stays a pure pick over what the browser already reports, and // the wake path lives in cdp/workers.ts, reached only from evaluate_script. const needle = workerNeedle(selector); if (needle === "") throw new CdpError(WORKER_EMPTY_NEEDLE_MESSAGE); const { matches, liveWorkers } = resolveWorkerTargets(targets, needle); if (matches.length > 1) throw new CdpError(workerAmbiguityMessage(needle, matches)); if (matches.length === 1) return matches[0]!; throw new CdpError(workerMissMessage(needle, { wakeAttempted: false, liveWorkers })); } if (isFrameSelector(selector)) { // Also resolved against the UNFILTERED listing: an out-of-process iframe is // its own target (site isolation), but not a PAGE target, so `pages` never // contains it. Unlike the worker arm, the returned hit deliberately still // flows through resolveTarget's lease gate below — a bare iframe id does // too today, and this arm is a way of NAMING that same target, not a new // permission to bypass who holds the embedder tab's lease. const needle = frameNeedle(selector); if (needle === "") throw new CdpError(FRAME_EMPTY_NEEDLE_MESSAGE); const { matches, liveFrames } = resolveFrameTargets(targets, needle); if (matches.length > 1) throw new CdpError(frameAmbiguityMessage(needle, matches)); if (matches.length === 1) return matches[0]!; throw new CdpError(frameMissMessage(needle, liveFrames)); } // bare id const byId = targets.find((t) => t.id === selector); if (!byId) throw new CdpError(`no target with id '${selector}'`); return byId; } /** Open a connection to the browser endpoint (Target.* / Browser.* domains). */ export async function openBrowser(opts: { timeoutMs?: number } = {}): Promise { return new CdpConnection(await browserWsUrl(), opts).connect(); } /** * Open a connection to a page target. Returns the connection and the target. * * The one place the two transports diverge for a tool author: a per-target * socket where Chrome serves one, an attached session on the shared browser * socket where it does not. Both are closed by the caller the same way, and * both carry the same per-command timeout, so no tool module branches on this. */ export async function openPage( selector: TargetSelector, opts: { timeoutMs?: number; lease?: string } = {}, ): Promise<{ conn: PageConnection; target: Target }> { // resolveTarget listed first, so the transport is already known here: an // empty webSocketDebuggerUrl is the browser-ws listing's own marker that this // target has no socket to dial (see getTargetsOverBrowserWs). const target = await resolveTarget(selector, { lease: opts.lease }); const conn = target.webSocketDebuggerUrl ? await new CdpConnection(target.webSocketDebuggerUrl, opts).connect() : await openSession(target.id, opts); return { conn, target }; } /** * Convenience: open a page, run `fn`, and always close the connection. * The standard wrapper for stateless one-shot tools. */ export async function withPage( selector: TargetSelector, fn: (conn: PageConnection, target: Target) => Promise, opts: { timeoutMs?: number; lease?: string } = {}, ): Promise { const { conn, target } = await openPage(selector, opts); try { return await fn(conn, target); } finally { conn.close(); } }