/** * CDP implementation of the browser-neutral Driver contract in ../driver.ts (ADR-001). A thin * wrapper: every command goes over client.ts's CdpConnection, so the per-command timeout that * prevents a wedged-tab hang applies exactly as in tools/. lifetime is "per-call": page() opens * one connection via openPage and holds it for the PageDriver's life; release() closes it. Uid * codec (scheme "cdp"): `cdp:`, or a bare legacy numeric uid, per THE UID CODEC block in ../driver.ts. */ import { CdpConnection, CdpError, listTargets, openBrowser, openPage, resolveTarget, type PageConnection } from "../client.ts"; import { openSession } from "./session.ts"; import { keepFrontApp } from "../frontApp.ts"; import type { Target, TargetSelector } from "../types.ts"; import { chromeLeaseBackend, isLongLivedProcess, LeaseConflictError } from "../leases.ts"; import { disposeHiddenTabs, existingHiddenTabOwner, hiddenTabOwner, hiddenTabsRequested, type HiddenTabOwner } from "./hiddenTabs.ts"; import { currentEndpoint } from "../endpoints.ts"; import { BEACON_READ_EXPRESSION, BEACON_SOURCE, BeaconSessions, RENDERER_PROBE_EXPRESSION, RENDERER_PROBE_TIMEOUT_MS, sendInput } from "../activity.ts"; import { resolveUid } from "../tools/snapshot.ts"; import { ContextTracker } from "./contexts.ts"; import { CONTEXT_AUTO_NEEDS_SELECTOR, autoCandidates, describeContext, parseContextSelector, pickExecutionContext, resolveSettle, type ContextEvalRow, type ExecutionContextInfo, type SettleOptions, } from "../contexts.ts"; import { resolveWorkerSelector } from "./workers.ts"; import { buildFulfillParams, effectiveAction, selectRule } from "../tools/network_mock.ts"; import { LEGACY_NUMERIC_UID, interpolatePoints, clearViewportRecord, readViewportRecord, renderRestoreFailureNote, writeViewportRecord, type BrowserCookie, type BrowserDriver, type Capability, type DeleteCookiesFilter, type HandledDialogInfo, type DriverError, type DriverErrorCode, type DriverEvent, type SetCookieParams, type DragDestination, type DragOptions, type DriverUid, type ElementLocator, type EmulationOptions, type InterceptRule, type KeyPress, type LifetimeModel, type MouseButtonOptions, type NavigateOptions, type NavigateResult, type PageDriver, type PageInfo, type ScreenshotOptions, type ScrollOptions, type SnapshotNode, type UidStability, type BandConsumer, type BandedCapture, type CaptureDelivery, type TiledScreenshotResult, type TextInputPath, } from "../driver.ts"; /* ------------------------------ error + uid codec ------------------------------ */ function driverError(code: DriverErrorCode, message: string, data?: unknown): DriverError { return Object.assign(new Error(message), { code, ...(data !== undefined ? { data } : {}) }) as DriverError; } function encodeUid(backendNodeId: number): DriverUid { return `cdp:${backendNodeId}`; } /** Accepts `cdp:` and, per the LEGACY rule, a bare numeric uid. */ function decodeUid(uid: DriverUid): number { if (LEGACY_NUMERIC_UID.test(uid)) return Number(uid); if (!uid.startsWith("cdp:")) throw driverError("foreign-uid", `uid is not owned by the cdp driver: ${uid}`); const n = Number(uid.slice(4)); if (!Number.isSafeInteger(n) || n <= 0) throw driverError("foreign-uid", `malformed cdp uid payload: ${uid}`); return n; } /* ---------------------------------- cookies ---------------------------------- */ /** The subset of CDP's `Network.Cookie` this driver reads. */ export interface CdpCookie { name: string; value: string; domain: string; path: string; expires: number; size: number; httpOnly: boolean; secure: boolean; session: boolean; sameSite?: string; } /** * CDP's cookie shape to the neutral one. Two mappings carry the difference: * `sameSite` is capitalized by CDP and absent when the cookie never set the * attribute, so it lowercases and falls back to "default" (BiDi's word for the * same state); `expires` is already CDP's Unix seconds with -1 for a session * cookie, so it passes through, with `session` kept as the browser's own flag * rather than re-derived from the timestamp. */ export function normalizeCdpCookie(c: CdpCookie): BrowserCookie { const same = (c.sameSite ?? "").toLowerCase(); const sameSite: BrowserCookie["sameSite"] = same === "strict" || same === "lax" || same === "none" ? same : "default"; return { name: c.name, value: c.value, domain: c.domain, path: c.path, expires: typeof c.expires === "number" ? c.expires : -1, size: typeof c.size === "number" ? c.size : Buffer.byteLength(`${c.name}${c.value}`, "utf8"), httpOnly: c.httpOnly === true, secure: c.secure === true, sameSite, session: c.session === true, }; } /** * The neutral lowercase `sameSite` back to CDP's own vocabulary. * * The inverse of normalizeCdpCookie's mapping, and it has to be the inverse: * CDP capitalizes the three real values and has NO word for "default", which * is BiDi's name for a cookie that never set the attribute. So "default" * returns undefined and the caller omits the field, which is exactly the state * it describes. */ export function cdpSameSite(sameSite?: "strict" | "lax" | "none" | "default"): "Strict" | "Lax" | "None" | undefined { if (sameSite === "strict") return "Strict"; if (sameSite === "lax") return "Lax"; if (sameSite === "none") return "None"; return undefined; } /* ---------------------- copied helpers, see attributions below ---------------------- */ // Copied verbatim from src/tools/input.ts `centerOf`: scroll into view, read viewport-space center. // // ONE ADDITION (issue #12): an element inside a NESTED same-process frame. getBoundingClientRect is // relative to that frame's own viewport, but Input.dispatchMouseEvent takes the target's root // viewport, so the old point missed by the frame's offset (measured: 79px/110px off for a frame // with margin and border). For such an element only (`nested`: its window has a frameElement, // which is null at the target's top, including an OOPIF's top, whose parent is cross-origin), the // point comes from DOM.getContentQuads, which is root-relative. Top-frame elements keep the exact // pre-#12 point, and a quads failure falls back to it. async function centerOf(conn: PageConnection, objectId: string): Promise<{ x: number; y: number }> { const fn = "function(){this.scrollIntoView({block:'center',inline:'center'});const r=this.getBoundingClientRect();if(r.width===0&&r.height===0)return null;var w=this.ownerDocument&&this.ownerDocument.defaultView;var nested=false;try{nested=!!(w&&w.frameElement);}catch(e){}return {x:r.left+r.width/2,y:r.top+r.height/2,nested:nested};}"; const { result, exceptionDetails } = await conn.send<{ result: { value?: { x: number; y: number; nested?: boolean } | null }; exceptionDetails?: { text?: string } }>( "Runtime.callFunctionOn", { objectId, functionDeclaration: fn, returnByValue: true }, ); if (exceptionDetails) throw driverError("page-error", `could not measure element: ${exceptionDetails.text ?? "error"}`); if (!result.value) throw driverError("page-error", "element has zero size / is not visible; cannot compute a click point"); const { x, y, nested } = result.value; if (nested) { const quads = await conn.send<{ quads?: number[][] }>("DOM.getContentQuads", { objectId }).catch(() => undefined); const q = quads?.quads?.[0]; if (q && q.length >= 8) { const xs = [q[0]!, q[2]!, q[4]!, q[6]!]; const ys = [q[1]!, q[3]!, q[5]!, q[7]!]; return { x: xs.reduce((a, b) => a + b, 0) / 4, y: ys.reduce((a, b) => a + b, 0) / 4 }; } } return { x, y }; } /** * Keyboard input on a BACKGROUND tab. Measured on Vivaldi (Chromium 156) with one page connection * held open: on a tab that never had a trusted click, Input.insertText and Input.dispatchKeyEvent * (keyDown with text, and type:"char") changed nothing in an input, a textarea or a * contenteditable, and no keydown event fired at all. Emulation.setFocusEmulationEnabled made * document.hasFocus() true and visibilityState "visible" but did not change that, and element * focus() did not either. A trusted click did (hasFocus() true, then insertText landed), and * document.execCommand('insertText') landed every time. * * So the trusted commit stays first, is VERIFIED, and an in-page commit runs only when it did not * land. "Landed" means the element's text changed from a snapshot taken just before the commit, * or a beforeinput/input event fired on it: never "equals the requested text", or an input mask * or maxlength would read as a miss and insert twice. */ const SNAPSHOT_TEXT_FN = "function(){var e=this;e.__cdpSawInput=false;var f=function(){e.__cdpSawInput=true;};" + "e.addEventListener('beforeinput',f,{capture:true,once:true});e.addEventListener('input',f,{capture:true,once:true});" + "return e.isContentEditable?e.textContent:('value' in e?String(e.value):null);}"; // Re-checked once after a short wait before calling it a miss: a false miss would double-insert. const LANDED_TEXT_FN = "function(before){var e=this;var now=function(){return e.isContentEditable?e.textContent:('value' in e?String(e.value):null);};" + "var hit=function(){return e.__cdpSawInput===true||now()!==before;};" + "if(hit())return true;return new Promise(function(r){setTimeout(function(){r(hit());},50);});}"; const FALLBACK_TEXT_FN = "function(t){var e=this;if(e.disabled||e.readOnly)return 'skipped';var ce=e.isContentEditable===true;" + "var ta=e instanceof HTMLTextAreaElement;var inp=e instanceof HTMLInputElement&&!/^(checkbox|radio|file|button|submit|reset|image|hidden|range|color)$/i.test(e.type);" + "if(!ce&&!ta&&!inp)return 'skipped';e.focus();" + "if(ce){var r=document.createRange();r.selectNodeContents(e);r.collapse(false);var s=window.getSelection();s.removeAllRanges();s.addRange(r);}" + "else{try{var n=e.value.length;e.setSelectionRange(n,n);}catch(x){}}" + "var read=function(){return ce?e.textContent:e.value;};var before=read();" + "if(document.execCommand('insertText',false,t)&&read()!==before){e.dispatchEvent(new Event('change',{bubbles:true}));return 'execCommand';}" + "if(ce)return 'failed';var proto=ta?HTMLTextAreaElement.prototype:HTMLInputElement.prototype;" + "Object.getOwnPropertyDescriptor(proto,'value').set.call(e,before+t);" + "e.dispatchEvent(new InputEvent('input',{bubbles:true,inputType:'insertText',data:t}));" + "e.dispatchEvent(new Event('change',{bubbles:true}));return 'setter';}"; /** Commit `text` at the element's caret: trusted Input.insertText, verified, else in-page. */ export async function insertTextVerified( conn: Pick, objectId: string, text: string, sendInput: (method: string, params: Record) => Promise, ): Promise { const call = async (fn: string, args: unknown[] = [], awaitPromise = false): Promise => { const { result, exceptionDetails } = await conn.send<{ result?: { value?: unknown }; exceptionDetails?: { text?: string } }>("Runtime.callFunctionOn", { objectId, functionDeclaration: fn, arguments: args.map((value) => ({ value })), returnByValue: true, awaitPromise, }); if (exceptionDetails) throw driverError("page-error", `text input check failed: ${exceptionDetails.text ?? "error"}`); return result?.value; }; const before = await call(SNAPSHOT_TEXT_FN); await sendInput("Input.insertText", { text }); if ((await call(LANDED_TEXT_FN, [before], true)) === true) return "trusted"; const via = await call(FALLBACK_TEXT_FN, [text]); if (via === "execCommand" || via === "setter" || via === "skipped") return via; throw driverError( "page-error", "text did not land: trusted Input.insertText was not delivered (a background tab gets no trusted keyboard input) and document.execCommand('insertText') changed nothing on this element", ); } /** * Run a trusted key press and report whether the page saw it. A background tab that never had a * trusted click gets no keydown at all (measured, see insertTextVerified), and an untrusted * synthetic key could not submit a form or move focus, so nothing is faked: the caller is told * { delivered:false } instead. A one-shot capture keydown listener on window is the witness. * Unknown is reported as nothing (void), never false: a probe that fails, or a key that * navigated the page away, says nothing about delivery. A key handled inside a cross-origin * iframe is invisible to the witness, so false is a strong hint, not proof. */ const ARM_KEY_WITNESS = "(function(){window.__cdpKeySeen=false;window.addEventListener('keydown',function(){window.__cdpKeySeen=true;},{capture:true,once:true});return true;})()"; const READ_KEY_WITNESS = "(function(){if(window.__cdpKeySeen===true)return true;return new Promise(function(r){setTimeout(function(){r(window.__cdpKeySeen===true);},50);});})()"; export async function pressKeyObserved(conn: Pick, dispatch: () => Promise): Promise<{ delivered: boolean } | void> { const eval_ = (expression: string, awaitPromise = false) => conn.send<{ result?: { value?: unknown } }>("Runtime.evaluate", { expression, returnByValue: true, awaitPromise }).then((r) => r.result?.value, () => undefined); const armed = (await eval_(ARM_KEY_WITNESS)) === true; await dispatch(); if (!armed) return; const seen = await eval_(READ_KEY_WITNESS, true); if (seen === false) return { delivered: false }; if (seen === true) return { delivered: true }; } async function focusElement(conn: PageConnection, objectId: string): Promise { await conn.send("Runtime.callFunctionOn", { objectId, functionDeclaration: "function(){this.focus&&this.focus();}", returnByValue: true }); } /** * Chrome smooth-scrolls wheel-triggered scrolling by default (a genuine UX feature, not something * a plain `--headless=new` launch turns off): Input.dispatchMouseEvent's mouseWheel command * resolves once the event is QUEUED, not once the resulting scroll animation has settled, so a * caller reading scrollTop immediately after dispatch can observe the PRE-scroll value. Verified * empirically against real headless Chrome 151 (not inferred): reading scrollTop in the same tick * after the command resolved showed 0; a fixed 300ms wait showed the expected value. * * Rather than a blind sleep (wrong for a large delta's longer animation, wasteful for a small * one), arm a CAPTURE-phase 'scroll' listener on window BEFORE dispatching the wheel event. * Capture-phase listeners on window see scroll events targeted at ANY descendant scrollable * element, even though 'scroll' itself does not bubble — the standard scroll-event-delegation * technique. The promise resolves once 60ms pass with no further scroll event (debounced, so a * multi-frame animation is waited out rather than caught mid-flight), capped at 500ms so a wheel * event that scrolls nothing (delta too small, target already at its scroll limit) cannot hang. */ const ARM_SCROLL_SETTLE_WATCH = "(function(){window.__cdpScrollSettle=new Promise((resolve)=>{let t;const done=()=>{window.removeEventListener('scroll',on,true);resolve(true);};" + "const on=()=>{clearTimeout(t);t=setTimeout(done,60);};window.addEventListener('scroll',on,true);t=setTimeout(done,60);setTimeout(done,500);});})()"; async function armScrollSettleWatch(conn: PageConnection): Promise { await conn.send("Runtime.evaluate", { expression: ARM_SCROLL_SETTLE_WATCH, returnByValue: true }); } async function awaitScrollSettle(conn: PageConnection): Promise { // Best-effort: a navigation racing the wheel event could tear down window.__cdpScrollSettle // before this reads it, and that is not a scroll failure worth surfacing as one. await conn.send("Runtime.evaluate", { expression: "window.__cdpScrollSettle", awaitPromise: true, returnByValue: true }).catch(() => undefined); } // Copied verbatim (behaviorally) from src/tools/input.ts `setValue`. CRITICAL: must stay // byte-identical to input.ts; see the side-by-side quote in the driver report. // // `sendInput` is the ONE addition, and it changes no command, no parameter and no ordering: // the Input.* leg is routed through the caller's input choke point instead of the raw // connection, so this function's dispatch is logged like every other (see ../activity.ts). // It is a parameter rather than a `conn.send` here because the choke point is per-PAGE // (it knows the target id) and this helper only has a connection. export async function setValueOnObject( conn: PageConnection, objectId: string, value: string, sendInput: (method: string, params: Record) => Promise, ): Promise { await focusElement(conn, objectId); // A disabled or read-only field is refused BEFORE the clear: clearing it would destroy a value // the user could not have changed either, and reporting filled:true for it would be a lie. const fn = "function(){if(this.disabled||this.readOnly)return this.disabled?'disabled':'readonly';if('value'in this){this.value='';this.dispatchEvent(new Event('input',{bubbles:true}));}else if(this.isContentEditable){this.textContent='';}return 'ok';}"; const { result } = await conn.send<{ result?: { value?: unknown } }>("Runtime.callFunctionOn", { objectId, functionDeclaration: fn, returnByValue: true }); if (result?.value === "disabled" || result?.value === "readonly") { throw driverError("page-error", `cannot fill a ${result.value} field: it was left unchanged`); } // The one behavioral departure from input.ts: the commit is verified, with an in-page fallback // for a background tab (see insertTextVerified). return value.length ? insertTextVerified(conn, objectId, value, sendInput) : "trusted"; } interface KeySpec { key: string; code: string; keyCode: number; text?: string } // Copied verbatim from src/tools/input.ts `NAMED_KEYS`. const NAMED_KEYS: Record = { enter: { key: "Enter", code: "Enter", keyCode: 13, text: "\r" }, return: { key: "Enter", code: "Enter", keyCode: 13, text: "\r" }, tab: { key: "Tab", code: "Tab", keyCode: 9 }, escape: { key: "Escape", code: "Escape", keyCode: 27 }, esc: { key: "Escape", code: "Escape", keyCode: 27 }, backspace: { key: "Backspace", code: "Backspace", keyCode: 8 }, delete: { key: "Delete", code: "Delete", keyCode: 46 }, space: { key: " ", code: "Space", keyCode: 32, text: " " }, arrowup: { key: "ArrowUp", code: "ArrowUp", keyCode: 38 }, arrowdown: { key: "ArrowDown", code: "ArrowDown", keyCode: 40 }, arrowleft: { key: "ArrowLeft", code: "ArrowLeft", keyCode: 37 }, arrowright: { key: "ArrowRight", code: "ArrowRight", keyCode: 39 }, up: { key: "ArrowUp", code: "ArrowUp", keyCode: 38 }, down: { key: "ArrowDown", code: "ArrowDown", keyCode: 40 }, left: { key: "ArrowLeft", code: "ArrowLeft", keyCode: 37 }, right: { key: "ArrowRight", code: "ArrowRight", keyCode: 39 }, home: { key: "Home", code: "Home", keyCode: 36 }, end: { key: "End", code: "End", keyCode: 35 }, pageup: { key: "PageUp", code: "PageUp", keyCode: 33 }, pagedown: { key: "PageDown", code: "PageDown", keyCode: 34 }, }; const MODIFIER_BITS: Record = { alt: 1, control: 2, ctrl: 2, meta: 4, cmd: 4, command: 4, shift: 8 }; // The closed click/dispatch_mouse modifiers enum (exact casing, no aliases): CDP bits Alt=1, // Control=2, Meta=4, Shift=8, per driver.ts's MouseButtonOptions doc. Exported for the unit tests // and for src/tools/dispatch-mouse.ts, which needs the identical bit math for its raw primitive. const CLICK_MODIFIER_BITS: Record = { Alt: 1, Control: 2, Meta: 4, Shift: 8 }; export function inputModifierBits(mods?: readonly string[]): number { let bits = 0; for (const m of mods ?? []) { const bit = CLICK_MODIFIER_BITS[m]; if (bit === undefined) throw driverError("page-error", `unknown modifier '${m}' (use Alt, Control, Meta, or Shift)`); bits |= bit; } return bits; } /** How long drag mode:"html5" waits for Chrome's Input.dragIntercepted before declaring the source * element undraggable. Deliberately well under the 15s default command timeout: a page that is * going to start a drag does so on the first move, so a longer wait only delays a clear error. */ const HTML5_DRAG_INTERCEPT_TIMEOUT_MS = 5_000; // Copied verbatim from src/tools/input.ts `resolveKey`. function resolveKey(key: string): KeySpec { const named = NAMED_KEYS[key.toLowerCase()]; if (named) return named; if (key.length === 1) { const upper = key.toUpperCase(); const isLetter = upper >= "A" && upper <= "Z"; const isDigit = key >= "0" && key <= "9"; const code = isLetter ? `Key${upper}` : isDigit ? `Digit${key}` : `Key${upper}`; return { key, code, keyCode: upper.charCodeAt(0), text: key }; } throw driverError("page-error", `unknown key '${key}' (use a named key like Enter/Tab/ArrowDown or a single character)`); } interface RemoteObject { type: string; value?: unknown; unserializableValue?: string; description?: string } interface ExceptionDetails { text?: string; exception?: RemoteObject } function unwrap(obj: RemoteObject): unknown { if (Object.prototype.hasOwnProperty.call(obj, "value")) return obj.value; if (obj.unserializableValue !== undefined) return obj.unserializableValue; return obj.type === "undefined" ? undefined : (obj.description ?? null); } function exceptionMessage(details: ExceptionDetails): string { const ex = details.exception; const fromObject = ex?.description ?? (typeof ex?.value === "string" ? ex.value : ex?.value !== undefined ? JSON.stringify(ex.value) : undefined); return fromObject ?? details.text ?? "evaluation threw"; } /* -------------------------- AX-tree walk (snapshot) -------------------------- */ interface AxValue { type?: string; value?: unknown } interface AxProperty { name: string; value?: AxValue } interface AxNode { nodeId: string; ignored?: boolean; role?: AxValue; name?: AxValue; value?: AxValue; properties?: AxProperty[]; childIds?: string[]; backendDOMNodeId?: number; parentId?: string; } const INTERACTIVE_ROLES = new Set([ "button", "link", "textbox", "searchbox", "checkbox", "radio", "combobox", "listbox", "option", "menuitem", "menuitemcheckbox", "menuitemradio", "tab", "switch", "slider", "spinbutton", "textfield", ]); function axString(v: AxValue | undefined): string | undefined { if (!v || v.value === undefined || v.value === null) return undefined; const s = String(v.value).trim(); return s.length ? s : undefined; } function propValue(node: AxNode, name: string): string | undefined { return axString(node.properties?.find((p) => p.name === name)?.value); } function isInteractive(role: string | undefined): boolean { return !!role && (INTERACTIVE_ROLES.has(role) || INTERACTIVE_ROLES.has(role.toLowerCase())); } /** * Copied verbatim (semantics, not just shape) from src/tools/snapshot.ts's `formatNode` extras * block, key order and all: value(quoted)/checked(unquoted, excluded only when literally * "false")/expanded(unquoted, included whenever the property is present AT ALL, INCLUDING the * literal string "false" - a legacy quirk, not a bug this migration is allowed to fix)/ * disabled(bare token)/url(unquoted)/focused(bare token). The render step (shared-tools.ts) * reproduces the exact quoting per key; this function only decides which keys are present and * with what value, in this order (a Record preserves string-key insertion order). */ function axExtras(node: AxNode): Record { const extras: Record = {}; const value = axString(node.value); if (value) extras.value = value; const checked = propValue(node, "checked"); if (checked && checked !== "false") extras.checked = checked; const expanded = propValue(node, "expanded"); if (expanded) extras.expanded = expanded; if (propValue(node, "disabled") === "true") extras.disabled = "true"; const url = propValue(node, "url"); if (url) extras.url = url; if (propValue(node, "focused") === "true") extras.focused = "true"; return extras; } /* ------------------------------- locator helpers ------------------------------- */ // css branch copied from src/tools/input.ts `resolveElement`; uid/text/xpath branches are new. // `contextId` (issue #12) scopes the css branch to one execution context; uid/text/xpath are // frame-agnostic already (DOM.resolveNode / DOM.performSearch work across same-process frames). async function resolveElementLocator(conn: PageConnection, loc: ElementLocator, contextId?: number): Promise<{ objectId: string }> { if ("uid" in loc) { return resolveUid(conn, decodeUid(loc.uid)).catch(() => { throw driverError("stale-uid", `uid does not resolve: ${loc.uid}`); }); } if ("css" in loc) { const { result, exceptionDetails } = await conn.send<{ result: { objectId?: string; subtype?: string }; exceptionDetails?: { text?: string } }>( "Runtime.evaluate", { expression: `document.querySelector(${JSON.stringify(loc.css)})`, returnByValue: false, ...(contextId !== undefined ? { contextId } : {}) }, ); if (exceptionDetails) throw driverError("page-error", `css '${loc.css}' evaluation failed: ${exceptionDetails.text ?? "error"}`); if (!result.objectId || result.subtype === "null") throw driverError("no-such-element", `css '${loc.css}' matched no element`); return { objectId: result.objectId }; } const backendNodeId = await searchLocate(conn, "xpath" in loc ? loc.xpath : loc.text); return resolveUid(conn, backendNodeId).catch(() => { throw driverError("stale-uid", "text/xpath match no longer resolves"); }); } /** * locate.text / locate.xpath: DOM.performSearch accepts plain text, a CSS selector, or an * XPath expression and disambiguates them itself. Not copied from any tools/ module (none * implement this); built only on the client primitives per CONTRACT.md rule 2. */ async function searchLocate(conn: PageConnection, query: string): Promise { await conn.send("DOM.getDocument", { depth: 0 }).catch(() => undefined); const { searchId, resultCount } = await conn.send<{ searchId: string; resultCount: number }>("DOM.performSearch", { query }); try { if (!resultCount) throw driverError("no-such-element", `locator matched nothing: ${query}`); const { nodeIds } = await conn.send<{ nodeIds: number[] }>("DOM.getSearchResults", { searchId, fromIndex: 0, toIndex: 1 }); const nodeId = nodeIds[0]; if (nodeId === undefined) throw driverError("no-such-element", `locator matched nothing: ${query}`); const { node } = await conn.send<{ node: { backendNodeId: number } }>("DOM.describeNode", { nodeId }); return node.backendNodeId; } finally { await conn.send("DOM.discardSearchResults", { searchId }).catch(() => undefined); } } async function backendNodeIdOf(conn: PageConnection, loc: ElementLocator, contextId?: number): Promise { if ("uid" in loc) return decodeUid(loc.uid); if ("css" in loc) { const { objectId } = await resolveElementLocator(conn, loc, contextId); const { node } = await conn.send<{ node: { backendNodeId: number } }>("DOM.describeNode", { objectId }); return node.backendNodeId; } return searchLocate(conn, "xpath" in loc ? loc.xpath : loc.text); } /** * The Page.getLayoutMetrics reply, read off a live browser rather than guessed. Measured shape, * Chrome/151.0.7922.76 on a deviceScaleFactor-2 display (2026-08-10): * layoutViewport {pageX:0,pageY:0,clientWidth:2780,clientHeight:2128} * visualViewport {offsetX,offsetY,pageX,pageY,clientWidth:2780,clientHeight:2128,scale:1,zoom:1} * contentSize {x,y,width:2780,height:2128} * cssLayoutViewport{pageX:0,pageY:0,clientWidth:1390,clientHeight:1064} * cssVisualViewport{offsetX,offsetY,pageX,pageY,clientWidth:1390,clientHeight:1064,scale:1,zoom:1} * cssContentSize {x,y,width:1390,height:1064} * The css-prefixed rects are CSS px and the legacy twins carry the SAME rect in device px, so their * clientWidth ratio is the live device-pixel multiplier (2 here). Every field is optional on this * type because the css-prefixed family is the newer half of the reply and an older Chrome answers * with only the legacy names. * * THE UNIT RULE HAS ONE MEASURED EXCEPTION, and it is a live footgun rather than trivia: on a * scrolled page `visualViewport.pageX`/`pageY` come back in CSS px, not device px, while * `clientWidth`/`clientHeight` on that very same rect stay device px. Scrolled to 700/4593 above: * cssVisualViewport 700/4593, cssLayoutViewport 700/4593, visualViewport 700/4593 (CSS!), * layoutViewport 1400/9186 (device). scrollOffsetCssPx below is the one reader of those offsets and * spells out which fields it trusts and why. */ interface LayoutMetrics { layoutViewport?: { pageX?: number; pageY?: number; clientWidth?: number; clientHeight?: number }; visualViewport?: { pageX?: number; pageY?: number; clientWidth?: number; clientHeight?: number }; contentSize?: { width: number; height: number }; cssLayoutViewport?: { pageX?: number; pageY?: number; clientWidth?: number; clientHeight?: number }; cssVisualViewport?: { pageX?: number; pageY?: number; clientWidth?: number; clientHeight?: number }; cssContentSize?: { width: number; height: number }; } async function layoutMetrics(conn: PageConnection): Promise { return conn.send("Page.getLayoutMetrics"); } /** * The rect a capture with no element clip covers — for `fullPage`, and ALSO for the plain * no-clip-no-fullPage call, because on this driver those two are the same picture. Measured, not * assumed: captureBeyondViewport is hardcoded true just below, so a no-clip capture of a 1390x3250 * css-px document at scroll y=1200 returned 2780x6500 device px from the document ORIGIN — the * same 72490 bytes, sha256 ab46801c…, as the same page captured with fullPage:true. * * That is why a scaled plain capture synthesizes THIS clip and not cssVisualViewport (which the * metrics reply also carries: pageX/pageY = the scroll offset, clientWidth/clientHeight = the * VISIBLE 1390x1064). Clipping to the visual viewport would make `scale` do two things at once — * multiply the resolution AND silently crop 3250 css px of document down to 1064 — so `--scale 3` * would return a different picture than `--scale 1`, not a bigger one. Here scale only ever * multiplies: 2780x6500 at scale 1 -> 5560x13000 at scale 2, same framing. */ function contentClip(m: LayoutMetrics): { x: number; y: number; width: number; height: number } { const size = m.cssContentSize ?? m.contentSize; if (!size) throw driverError("page-error", "Page.getLayoutMetrics returned no content size"); return { x: 0, y: 0, width: Math.ceil(size.width), height: Math.ceil(size.height) }; } /** * How many output pixels one CSS px of clip becomes BEFORE `scale` is applied — the display's (or * emulation override's) device-pixel multiplier, read as the ratio between the device-px and CSS-px * copies of the same viewport rect rather than from window.devicePixelRatio (no extra round trip, * same source of truth as the capture itself). Measured: clip {100x100, scale:1} on a ratio-2 * display returns a 200x200 PNG, so this factor really does multiply into the encoded size. * Falls back to 1 when a metrics reply carries only one of the two rects. */ function devicePixelsPerCssPx(m: LayoutMetrics): number { const css = m.cssVisualViewport?.clientWidth ?? m.cssLayoutViewport?.clientWidth; const dev = m.visualViewport?.clientWidth ?? m.layoutViewport?.clientWidth; if (!css || !dev) return 1; const ratio = dev / css; return Number.isFinite(ratio) && ratio > 0 ? ratio : 1; } /** * The page's scroll offset in CSS px — what has to be ADDED to a viewport-relative rect to make it * document-absolute, which is the frame `Page.captureScreenshot` reads its clip in whenever * captureBeyondViewport is true (hardcoded true below). * * WHICH FIELD, MEASURED rather than inferred from the "css" prefix, because that prefix is NOT a * clean CSS-px/device-px split for the offsets. Same reply, same instant, page scrolled to * window.scrollX/scrollY = 700/4593 on a deviceScaleFactor-2 display (Chrome/151.0.7922.76, * 2026-08-10): * cssVisualViewport pageX/pageY = 700 / 4593 <- CSS px (what this returns) * cssLayoutViewport pageX/pageY = 700 / 4593 <- CSS px, identical * visualViewport pageX/pageY = 700 / 4593 <- CSS px TOO, despite clientWidth/clientHeight * on that same rect reading 2780x2128 (device px) * layoutViewport pageX/pageY = 1400 / 9186 <- device px, exactly 2x * So `visualViewport` mixes units WITHIN one rect, and is the one field a "no css prefix means * device px" assumption would silently double. It is never read here. * * The legacy fallback rides `layoutViewport` over the measured ratio (9186/2 = 4593 exactly) and is * only reachable on a Chrome old enough to answer with no css-prefixed rects at all — where * devicePixelsPerCssPx above has already fallen back to 1 and contentClip is already handing Chrome * the DEVICE-px contentSize as a clip. The division is what keeps this offset in whatever frame the * rest of the reply put the file in, rather than correcting into a frame nothing else is using. */ function scrollOffsetCssPx(m: LayoutMetrics, devicePx: number): { x: number; y: number } { const css = m.cssVisualViewport ?? m.cssLayoutViewport; if (css) return { x: css.pageX ?? 0, y: css.pageY ?? 0 }; const legacy = m.layoutViewport; if (legacy) return { x: (legacy.pageX ?? 0) / devicePx, y: (legacy.pageY ?? 0) / devicePx }; return { x: 0, y: 0 }; } /** * Chrome's per-side encode limit. MEASURED against Chrome/151.0.7922.76, clip width x height in * CSS px at the given scale on a device-pixel-ratio-2 display, so the encoded size is * ceil(css * scale * ratio): * 1024x100 @8 -> 16384x1600 encoded: OK in ~1s * 1025x100 @8 -> 16400x1600 encoded: Page.captureScreenshot NEVER ANSWERS (killed at 45s, and * again at 180s on a fresh tab) — 16 px over the cap and the command just hangs * 100x1024 @8 -> 1600x16384 encoded: OK in ~1s (same cap on the other axis) * 100x1025 @8 -> 1600x16400 encoded: hangs the same way * 100x1064 @16 -> 3200x34048 encoded: fails fast with the opaque CDP error * "Page.captureScreenshot: Unable to capture screenshot" * So the failure is not a silent clamp — but it is either a wedged command or an error naming no * dimension, which is why this is refused BEFORE the capture, with the numbers spelled out. * * And the cost of just letting Chrome try is worse than a failed call: captureBeyondViewport * (hardcoded true below) RESIZES the page to the clip for the duration of the capture, and a * capture that never returns never puts it back. After the 1025x100 @8 hang above, that tab was * left reporting window.innerWidth/innerHeight of 8200x800 — the clip's own css size — and every * later screenshot on it timed out too. A refusal here is what keeps a caller's tab intact. */ const MAX_ENCODED_SIDE_PX = 16384; /** * `renderSize` is only for the message. It is named separately because it changes what the caller * should DO about the refusal: past the cap because of `scale`, the fix is a smaller scale, but past * it because a narrow render size made the document reflow taller, the fix is a different render * size (or dropping fullPage) and a "largest scale that fits" hint would be useless advice. */ function assertClipEncodable( clip: { width: number; height: number }, scale: number, devicePx: number, renderSize?: { width: number; height: number }, ): void { const outWidth = Math.ceil(clip.width * scale * devicePx); const outHeight = Math.ceil(clip.height * scale * devicePx); if (outWidth <= MAX_ENCODED_SIDE_PX && outHeight <= MAX_ENCODED_SIDE_PX) return; const at = renderSize ? ` at render size ${renderSize.width}x${renderSize.height}` : ""; const projection = `(clip ${clip.width}x${clip.height} css px${at} x scale ${scale} x device pixel ratio ${devicePx}), ` + `past Chrome's ${MAX_ENCODED_SIDE_PX} px per-side limit; `; if (scale !== 1) { // Floor to 2dp: a rounded-UP suggestion would be a scale that fails the same way. const fits = Math.floor((MAX_ENCODED_SIDE_PX / (Math.max(clip.width, clip.height) * devicePx)) * 100) / 100; throw driverError( "page-error", `screenshot scale ${scale} would encode ${outWidth}x${outHeight} px ${projection}` + (fits >= 0.01 ? `the largest scale that fits this clip is ${fits}.` : `this clip is already past the limit at scale 1 — capture a smaller region.`), ); } const maxCssSide = Math.floor(MAX_ENCODED_SIDE_PX / devicePx); throw driverError( "page-error", `this capture would encode ${outWidth}x${outHeight} px ${projection}` + `at device pixel ratio ${devicePx} the clip may be at most ${maxCssSide} css px per side` + (renderSize ? ` — a narrow renderWidth reflows the document TALLER, so widen it, shorten the page, or drop fullPage.` : ` — capture a smaller region or drop fullPage.`), ); } /** The encoded size a clip projects to, the one number every guard and every band decision is made * on. `scale` and the device pixel ratio BOTH multiply — measured, see devicePixelsPerCssPx. */ function projectedSide(cssLength: number, scale: number, devicePx: number): number { return Math.ceil(cssLength * scale * devicePx); } /** * How the capture is split, decided before a single Page.captureScreenshot is sent. Pure and * exported so the arithmetic is unit-testable without a browser: getting it wrong is invisible in * a small test and catastrophic on a 140,000 px page. * * BAND HEIGHT IS IN CSS PX AND SO IS clip.y, and that is MEASURED, not assumed. A ruler page with * a marker at CSS y=4000-4008, clipped {y:3980,height:40}, put the marker at the same CSS position * at scale 1 and at scale 2 — the output was simply twice the resolution. So a band advances by * bandHeightCss regardless of scale or device pixel ratio; multiplying the offset by either would * skip or repeat that factor's worth of page on every seam. * * WHY `tile:true` ON A FITTING REGION STILL SPLITS IN TWO. The flag exists so the banded path can * be exercised on an ordinary page. A band height derived only from the cap would return ONE band * for any page small enough to be convenient to test, i.e. `tile:true` would be a no-op on exactly * the pages someone would use it to check seams with. So an explicit `true` also halves a region * that already fits. It stays lossless either way (the stitcher is byte-exact; a seam is not a * resample), and the result reports the band count honestly. */ export interface TilePlan { tiled: boolean; /** How many Page.captureScreenshot calls. 1 when not tiled. */ bandCount: number; /** CSS-px height of every band but the last; the last is the remainder. */ bandHeightCss: number; } export function planTiledCapture( clip: { width: number; height: number }, scale: number, devicePx: number, tile: boolean | undefined, ): TilePlan { const untiled: TilePlan = { tiled: false, bandCount: 1, bandHeightCss: clip.height }; if (tile === false) return untiled; const fits = projectedSide(clip.width, scale, devicePx) <= MAX_ENCODED_SIDE_PX && projectedSide(clip.height, scale, devicePx) <= MAX_ENCODED_SIDE_PX; if (fits && tile !== true) return untiled; // WIDTH CANNOT BE TILED, and this refusal is the deliberate edge of the feature's scope. The // stitcher concatenates PNG scanlines, so it can only grow the image downward; a too-wide // capture would need a grid and a horizontal join it cannot do. Refusing names the two knobs // that actually shrink a width — the alternative, silently capturing 16384 px of a wider page, // would hand back a truncated picture indistinguishable from a complete one. const outWidth = projectedSide(clip.width, scale, devicePx); if (outWidth > MAX_ENCODED_SIDE_PX) { const maxCssWidth = Math.floor(MAX_ENCODED_SIDE_PX / (scale * devicePx)); throw driverError( "page-error", `this capture is ${outWidth} px WIDE (clip ${clip.width} css px x scale ${scale} x device pixel ratio ${devicePx}), ` + `past Chrome's ${MAX_ENCODED_SIDE_PX} px per-side limit, and width cannot be tiled: bands are stitched ` + `vertically only. Lower scale (at most ${Math.floor((MAX_ENCODED_SIDE_PX / (clip.width * devicePx)) * 100) / 100}), ` + `or set renderWidth at most ${maxCssWidth} css px, or clip to a narrower element.`, ); } // The largest band whose PROJECTION still fits: ceil(h x scale x devicePx) <= cap. The loop is a // floating-point backstop — floor() alone is right for every integer ratio, but a fractional // scale x ratio can land a hair above the cap after ceil(), and a band one pixel over is not an // off-by-one, it is the hang this whole feature exists to avoid. Measured by mutation: dropping // devicePx from the floor() alone changes NOTHING, because the loop walks the value back down to // the same answer (slowly, one px at a time). The loop is the correctness; the floor is the speed. let bandHeightCss = Math.floor(MAX_ENCODED_SIDE_PX / (scale * devicePx)); while (bandHeightCss > 1 && projectedSide(bandHeightCss, scale, devicePx) > MAX_ENCODED_SIDE_PX) bandHeightCss -= 1; // UNREACHABLE AS THINGS STAND, and said so rather than presented as a live branch: a band height // below 1 needs scale x devicePx past the cap, and every clip is at least 1 css px wide (both // clip builders ceil, and a zero-area element is refused before this), so the width check above // has already thrown. Kept because it is the invariant the loop depends on — a zero band height // would make bandCount infinite — not because a caller can get here today. if (bandHeightCss < 1) { throw driverError( "page-error", `scale ${scale} at device pixel ratio ${devicePx} projects a single css pixel to ${scale * devicePx} device px, ` + `past the ${MAX_ENCODED_SIDE_PX} px limit — no band height can fit. Lower scale.`, ); } // An explicit `true` on a region that already fits: split it for real (see the header). if (tile === true && clip.height <= bandHeightCss) bandHeightCss = Math.max(1, Math.ceil(clip.height / 2)); return { tiled: true, bandCount: Math.max(1, Math.ceil(clip.height / bandHeightCss)), bandHeightCss }; } /** * The element's content box, in CSS px and VIEWPORT-RELATIVE — which is the frame * `DOM.getBoxModel` answers in, measured rather than assumed: on a 10,000 css px document scrolled * to y=4593, the quad for an element whose real document position is y=5000 came back at y=407, * matching `getBoundingClientRect().top` to the pixel. NOT a capture clip; see documentClip below * for the frame conversion that has to happen before this can be one. * * THE SCROLL IS DELIBERATE, AND IT IS NOT WHAT MAKES THE CLIP CORRECT. With captureBeyondViewport * (hardcoded true in capture()) Chrome renders the whole document, so nothing here has to be on * screen to be captured, and the REJECTED ALTERNATIVE was to drop this call entirely and read the * box model where the page already sat. Measured consequence of dropping it, on a fixture whose * target only fills itself from an IntersectionObserver: with the scroll, the capture reads * "LAZY CONTENT LOADED"; without it, the same capture returns the element's "NOT LOADED * (placeholder)" state in the right region — because captureBeyondViewport renders what the DOM * currently IS (the tab still reported the placeholder text afterwards, scrollY 0), and never * triggers a viewport-driven load. So the scroll buys lazy content, costs one round trip, and the * document-frame correction below is what buys correctness. Keeping it also means the offset this * scroll CREATES must be read after it settles — see capture()'s ordering. */ async function elementBox(conn: PageConnection, loc: ElementLocator): Promise<{ x: number; y: number; width: number; height: number }> { const backendNodeId = await backendNodeIdOf(conn, loc); await conn.send("DOM.scrollIntoViewIfNeeded", { backendNodeId }).catch(() => undefined); const box = await conn.send<{ model: { content: number[] } }>("DOM.getBoxModel", { backendNodeId }); const q = box.model.content; const xs = [q[0], q[2], q[4], q[6]].filter((n): n is number => n != null); const ys = [q[1], q[3], q[5], q[7]].filter((n): n is number => n != null); if (!xs.length || !ys.length) throw driverError("page-error", "DOM.getBoxModel returned an empty content quad"); const minX = Math.min(...xs), minY = Math.min(...ys); const width = Math.ceil(Math.max(...xs) - minX), height = Math.ceil(Math.max(...ys) - minY); if (width <= 0 || height <= 0) throw driverError("page-error", "resolved element has zero area"); return { x: minX, y: minY, width, height }; } /** * A viewport-relative element box -> the document-absolute clip `Page.captureScreenshot` actually * wants. THE BUG THIS FIXES, measured on Chrome/151.0.7922.76: the box model's own x/y used to be * handed straight to the capture, so a `--selector` clip returned the wrong region of the page * whenever bringing the element into view required a scroll. On a 10,000 css px document with the * target at y=5000, `DOM.scrollIntoViewIfNeeded` left the page at scrollY 4593 and the element at * viewport y=407 — and the capture came back as document[407..657], a flat slab of page background, * with no part of the element in it. Starting the same call from scrollY 4950 instead, where the * element already sat at viewport y=50 and the scroll was a no-op, produced document[50..300]: the * document's own top banner for the first 100 css px, background below, boundary on the predicted * pixel. Both are the same arithmetic — a viewport-relative number read in the document frame — * and the pair is also why the old behaviour depended on where the CALLER had left the page. * * Adding the scroll offset is the whole correction, and it is added in CSS px because `clip` is in * CSS px (a clip of {1390 x 1064} on a ratio-2 display encodes 2780x2128, i.e. the multiplier is * applied by Chrome AFTER the clip, not expected in it). Mixing in the device-px twin of the offset * would be the same class of bug wearing different units. * * `scale`, `renderWidth`/`renderHeight` and `tile` all ride this same corrected rect and needed no * changes of their own: scale only ever rides clip.scale, a render size reflows the document before * anything here is measured, and the band walker starts from clip.y and walks in CSS px. */ function documentClip( box: { x: number; y: number; width: number; height: number }, m: LayoutMetrics, devicePx: number, ): { x: number; y: number; width: number; height: number } { const scroll = scrollOffsetCssPx(m, devicePx); return { x: box.x + scroll.x, y: box.y + scroll.y, width: box.width, height: box.height }; } /** * Chrome capabilities. network.responseBodyPostHoc is deliberately NOT declared: the Network * domain is enabled lazily (only by startBodyCapture/intercept), so a body is only readable for * a request that occurred after something armed capture first. That is arming by another name, * not "not armed in advance", so an honest capability set omits it rather than reading true by * construction. locate.text/locate.xpath both ride DOM.performSearch (see searchLocate above), * which is a real Chrome capability, not a line-budget artifact, so both ARE declared. * capture.screencast rides Page.startScreencast / Page.screencastFrame / Page.screencastFrameAck, * the streamed-repaint primitive behind start_screen_recording and stop_screen_recording. * input.raw rides Input.dispatchMouseEvent dispatched one event at a time with no scroll-into-view * or hover prefix (src/tools/dispatch-mouse.ts), the primitive behind dispatch_mouse; declared * chrome-only per ADR-001 rather than attempted over BiDi's per-call performActions device-state * model (see dispatch-mouse.ts's header for why that combination was not attempted this pass). * input.html5Drag rides Input.setInterceptDrags + Input.dragIntercepted + Input.dispatchDragEvent * (drag's mode:"html5", see CdpPageDriver.html5Drag). It is a PARAM-level capability, not a * whole-tool one: `drag` itself stays universal because mouse mode works on both backends, so * input.html5Drag is deliberately absent from driver.ts's REQUIRED_CAPABILITIES and is instead * checked by shared-tools.ts's drag() when mode:"html5" is asked for. ADR-001 governs whole tools; * a param gap surfaces as a clear validation error named in the manifest description, exactly like * click's modifiers-on-Firefox (Track P1). WebDriver BiDi has no drag-interception primitive at * all — no equivalent of setInterceptDrags, no drag event to subscribe to — so this is a genuine * protocol gap, not an unattempted port. * browser.downloads (wait_for_download) rides Browser.setDownloadBehavior + Browser.downloadWillBegin * + Browser.downloadProgress, and browser.permissions (grant_permissions) rides * Browser.grantPermissions + Browser.resetPermissions. Both are BROWSER-endpoint commands whose * effect is bound to the CDP client that issued them and is REVERTED when that client disconnects * (measured, both of them — see src/tools/browser-session.ts's header for the experiment), so both * tools run on the standing connection that module holds rather than on a per-call socket. Neither * is declared for BiDi: Firefox's browsingContext.downloadWillBegin/downloadEnd exist but there is * no BiDi command to redirect a download to a chosen directory, and BiDi has no permission-granting * command at all outside the optional `permissions` module this driver does not negotiate. * screenshot.scale rides Page.captureScreenshot's clip.scale, a per-CALL output multiplier that * leaves page emulation untouched (the deviceScaleFactor workaround does not: it re-lays-out the * page and persists until cleared). It is a PARAM-level capability like input.html5Drag, so * take_screenshot stays universal and only the `scale` argument is gated; WebDriver BiDi's * browsingContext.captureScreenshot has no scale parameter at all, so it is honestly Chrome-only. * screenshot.renderSize rides Emulation.setDeviceMetricsOverride applied for the length of one * capture and undone in a finally. Unlike screenshot.scale this is NOT a Chrome-only gap: BiDi's * browsingContext.setViewport is a real equivalent and the Firefox driver declares it too. Both * drivers already declare emulate.deviceMetrics on the very same primitive, so a backend that could * not honour this would be a backend that cannot emulate a viewport at all. * screenshot.tile rides the SAME clip.scale primitive as screenshot.scale, sent once per band with * clip.y walked down the document, plus ../png.ts's stitcher. It is declared here and NOT for BiDi, * for the honest reason rather than a protocol one: band tiling was measured against a real Chrome * (fixed and sticky elements do not repeat per band, seams are pixel-exact, clipped bands are * scroll-independent, and clip.y/clip.height stay CSS px while scale only changes resolution), and * no Firefox was driven to measure the same for browsingContext.captureScreenshot's clip:{type:"box"}. * Declaring an unmeasured tiling would be claiming a capability on the strength of a spec reading. */ const CDP_CAPABILITIES: ReadonlySet = new Set([ "trace.performance", "heap.snapshot", "audit.lighthouse", "emulate.cpuThrottling", "emulate.mediaFeatures", "emulate.deviceMetrics", "emulate.networkConditions", "screenshot.fullPage", "screenshot.element", "screenshot.scale", "screenshot.renderSize", "screenshot.tile", "network.intercept", "snapshot.accessibilityTree", "input.insertTextAtomic", "locate.text", "locate.xpath", "capture.screencast", "input.raw", "input.modifierClick", "input.html5Drag", "emulate.focus", "browser.downloads", "browser.permissions", "browser.tabGroups", "worker.targets", "frame.targets", "runtime.contexts", ]); /* ---------------------------------- PageDriver ---------------------------------- */ class CdpPageDriver implements PageDriver { readonly info: PageInfo; // Deliberately empty: page() does NOT eagerly enable Page/Runtime. Every domain is turned on // lazily, by the same method and with the same catch/no-catch nuance as the legacy tools/*.ts // module it replaces, so no tool call gets an extra CDP round-trip (or extra domain-enabled // side effect) it did not have before this migration. See the per-method comments below. private readonly enabledDomains = new Set(); private released = false; /** Issue #12: the context tracker, created on first need, and the context this call is pinned to. */ private tracker?: ContextTracker; private pinned?: ExecutionContextInfo; constructor(private readonly conn: PageConnection, target: Target, readonly browser: BrowserDriver) { this.info = { id: target.id, url: target.url, title: target.title, type: target.type }; } private async ensureDomain(name: string): Promise { if (this.enabledDomains.has(name)) return; this.enabledDomains.add(name); await this.conn.send(`${name}.enable`); } /** * THE INPUT DISPATCH CHOKE POINT for Chrome. Every synthesized-input command * this driver sends goes through here, and nothing else does. * * WHY IT IS A WRAPPER AND NOT A CALL AT THE TOP OF EACH METHOD. The * bookkeeping (../activity.ts's dispatch log) is what keeps the toolkit's own * clicks from reading as a human's, and a version of it that each new input * method had to REMEMBER to call would be silently wrong for the first tool * whose author did not know it existed — and the whole point of the log is * that it is complete. Wrapping the send makes the coupling structural: an * `Input.*` command cannot be sent from this class without being logged, * because `this.conn.send` is not what sends it. * * IF YOU ARE ADDING AN INPUT TOOL (scroll, dispatch_mouse, a drag mode, ...): * send through `this.dispatchInput(...)`, never `this.conn.send(...)`. That is * the entire integration. 1.8.0's scroll and html5 drag arrived on a branch * written before this method existed and did exactly that at merge time. * * The actual write lives in ../activity.ts's `sendInput`, which this delegates * to, because one chrome-only tool (tools/dispatch-mouse.ts) dispatches input * with a bare connection and no PageDriver to route through. Both callers share * that one writer, so `conn.send("Input.` appears nowhere in src/ and the * completeness of the log is a grep, not a convention. * * Deliberately NOT routed through here: DOM.setFileInputFiles (upload_file). * It attaches files to an input element and fires the page's change handler; * it synthesizes none of the beacon's events (pointerdown/mousedown/keydown/ * wheel/touchstart), so logging it could only suppress a genuine human input * that happened to land within the attribution window, never prevent a false * one. */ private async dispatchInput>(method: string, params: Record = {}): Promise { return sendInput(this.conn, chromeLeaseBackend(), this.info.id, method, params); } /** Same as ensureDomain but tolerates the enable call itself failing (matches a legacy * `.catch(() => undefined)` site); a failed enable is NOT re-attempted on the next call. */ private async ensureDomainSoft(name: string): Promise { if (this.enabledDomains.has(name)) return; this.enabledDomains.add(name); await this.conn.send(`${name}.enable`).catch(() => undefined); } /** * The history entry exactly one step `direction` from the current one. Throws when there is * none, naming the direction: NavigateOptions.history's contract forbids a silent no-op, and * Page.navigateToHistoryEntry with a bad id would fail with a protocol message that never * mentions "back" or "forward", which is not an answer a caller can act on. */ private async historyEntry(direction: "back" | "forward"): Promise<{ id: number; url: string }> { const h = await this.conn.send<{ currentIndex: number; entries: Array<{ id: number; url: string }> }>("Page.getNavigationHistory"); const entries = h.entries ?? []; const entry = entries[h.currentIndex + (direction === "back" ? -1 : 1)]; if (!entry) { throw driverError( "page-error", `navigate: no history entry to go ${direction} to (at entry ${h.currentIndex + 1} of ${entries.length})`, ); } return entry; } async navigate(opts: NavigateOptions): Promise { await this.ensureDomain("Page"); const reload = opts.reload === true; const history = opts.history; if (!reload && !history && !opts.url) throw driverError("page-error", "navigate: 'url' is required unless reload:true"); // Resolved BEFORE the milestone waiters are armed: a refused traversal must throw without // leaving two armed waitFor timers behind holding the event loop open for timeoutMs. const entry = history ? await this.historyEntry(history) : undefined; const waitUntil = opts.waitUntil ?? "load"; const milestoneMethod = waitUntil === "load" ? "Page.loadEventFired" : "Page.domContentEventFired"; const milestone = this.conn.waitFor(milestoneMethod, undefined, opts.timeoutMs).then(() => waitUntil as NavigateResult["waitedFor"]).catch(() => undefined); const stopped = this.conn.waitFor("Page.frameStoppedLoading", undefined, opts.timeoutMs).then(() => "committed" as NavigateResult["waitedFor"]).catch(() => undefined); let url: string, contextId: string, reloaded: boolean | undefined; if (reload) { await this.conn.send("Page.reload", { ignoreCache: opts.ignoreCache === true }, opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}); const tree = await this.conn.send<{ frameTree?: { frame?: { id?: string; url?: string } } }>("Page.getFrameTree").catch(() => undefined); contextId = tree?.frameTree?.frame?.id ?? ""; url = tree?.frameTree?.frame?.url ?? opts.url ?? ""; reloaded = true; } else if (entry) { await this.conn.send("Page.navigateToHistoryEntry", { entryId: entry.id }, opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}); // Provisional: the entry we asked for. The authoritative post-traversal url is read from the // frame tree AFTER the milestone race below — navigateToHistoryEntry resolves the moment the // traversal is dispatched, so reading the frame tree here would still report the OUTGOING // document (measured: the reload branch gets away with an immediate read only because a // reload's url cannot change). contextId = ""; url = entry.url; } else { const nav = await this.conn.send<{ frameId: string; errorText?: string }>("Page.navigate", { url: opts.url }, opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}); if (nav.errorText) throw driverError("page-error", `navigate: ${nav.errorText} (${opts.url})`); contextId = nav.frameId; url = opts.url as string; } const settled = await Promise.race([milestone, stopped]); if (entry) { const tree = await this.conn.send<{ frameTree?: { frame?: { id?: string; url?: string } } }>("Page.getFrameTree").catch(() => undefined); contextId = tree?.frameTree?.frame?.id ?? contextId; url = tree?.frameTree?.frame?.url ?? url; } // "timeout" here means the navigation already committed (Page.navigate/reload resolved) but // no load/domcontentloaded milestone arrived before opts.timeoutMs; it is NOT the navigate // call itself timing out. NavigateResult.waitedFor's vocabulary is BiDi-shaped (BiDi's // navigate takes an explicit readiness state) rather than CDP-native, so this is the // closest honest mapping onto CDP's milestone events. return { url, contextId, ...(reloaded ? { reloaded } : {}), ...(history ? { traversed: history } : {}), waitedFor: settled ?? "timeout", }; } async waitForText(text: string, timeoutMs = 15_000, pollMs = 250): Promise<{ found: true; elapsedMs: number }> { await this.ensureDomain("Runtime"); const start = Date.now(); const expr = `(() => { const b = document.body; return !!b && typeof b.innerText === 'string' && b.innerText.includes(${JSON.stringify(text)}); })()`; for (;;) { const { result } = await this.conn.send<{ result: { value?: unknown } }>("Runtime.evaluate", { expression: expr, returnByValue: true }); if (result?.value === true) return { found: true, elapsedMs: Date.now() - start }; if (Date.now() - start >= timeoutMs) throw driverError("timeout", `waitForText: '${text}' not found within ${timeoutMs}ms`); await new Promise((r) => setTimeout(r, Math.min(pollMs, Math.max(0, timeoutMs - (Date.now() - start))))); } } private async callFn(objectId: string, functionDeclaration: string, args: readonly unknown[], awaitPromise: boolean): Promise { const res = await this.conn.send<{ result: RemoteObject; exceptionDetails?: ExceptionDetails }>( "Runtime.callFunctionOn", { objectId, functionDeclaration, arguments: args.map((value) => ({ value })), returnByValue: true, awaitPromise }, ); if (res.exceptionDetails) throw driverError("page-error", exceptionMessage(res.exceptionDetails)); return unwrap(res.result); } async evaluate(expression: string, opts?: { args?: readonly unknown[]; awaitPromise?: boolean }): Promise { // Uncaught, matching tools/evaluate.ts's evaluateScript. resize_page's legacy Runtime.enable is // soft-caught instead; since Runtime.enable does not fail against a live connected page, the two // call sites converging on one hard enable here is not expected to be observable in practice. await this.ensureDomain("Runtime"); const awaitPromise = opts?.awaitPromise ?? true; return this.evaluateIn(this.pinned?.id, expression, opts?.args, awaitPromise); } /** evaluate()'s body, in one execution context (undefined = the target's default one). */ private async evaluateIn(contextId: number | undefined, expression: string, args: readonly unknown[] | undefined, awaitPromise: boolean): Promise { const ctx = contextId !== undefined ? { contextId } : {}; if (args && args.length > 0) { const globalObj = await this.conn.send<{ result: { objectId?: string } }>("Runtime.evaluate", { expression: "globalThis", returnByValue: false, ...ctx }); const objectId = globalObj.result.objectId; if (!objectId) throw driverError("page-error", "could not resolve global object for function call"); return this.callFn(objectId, expression, args, awaitPromise); } const res = await this.conn.send<{ result: RemoteObject; exceptionDetails?: ExceptionDetails }>("Runtime.evaluate", { expression, returnByValue: true, awaitPromise, ...ctx }); if (res.exceptionDetails) throw driverError("page-error", exceptionMessage(res.exceptionDetails)); return unwrap(res.result); } /* ----------------------------- execution contexts (issue #12) ----------------------------- */ private async contextTracker(): Promise { if (!this.tracker) { const tracker = new ContextTracker(this.conn); this.tracker = tracker; await tracker.start(this.enabledDomains.has("Runtime")); this.enabledDomains.add("Runtime"); } return this.tracker; } async listContexts(opts?: SettleOptions): Promise { const settle = resolveSettle(opts); const tracker = await this.contextTracker(); await tracker.settle(settle); return tracker.contexts(); } async useContext(context: unknown, opts?: { css?: string; settle?: SettleOptions }): Promise { const sel = parseContextSelector(context); const settle = resolveSettle(opts?.settle); const tracker = await this.contextTracker(); if (sel.kind === "auto") { const css = opts?.css; if (!css) throw driverError("page-error", CONTEXT_AUTO_NEEDS_SELECTOR); let found: ExecutionContextInfo | undefined; const probe = `document.querySelector(${JSON.stringify(css)}) !== null`; // Wait for the selector itself, not for quiet: a late frame's context can appear, and its // document fill in, well after the existing ones went quiet. Every round re-tests every // candidate, because a context is created before its document has parsed. await tracker.settle(settle, async () => { for (const c of autoCandidates(await tracker.contexts())) { const r = await this.conn .send<{ result?: { value?: unknown } }>("Runtime.evaluate", { expression: probe, returnByValue: true, contextId: c.id }) .catch(() => undefined); if (r?.result?.value === true) { found = c; return true; } } return false; }, true); if (!found) { const live = await tracker.contexts(); throw driverError( "no-such-element", `css '${css}' matched no element in any frame of this target within ${settle.capMs}ms ` + `(searched ${autoCandidates(live).length} frame context(s): ${autoCandidates(live).map(describeContext).join("; ") || "none"}). ` + "Raise settleCapMs if the frame loads late; a frame inside an out-of-process iframe is a separate target (frame:).", ); } this.pinned = found; return found; } // A named context: return as soon as it is there, else settle and decide. let pick = pickExecutionContext(await tracker.contexts(), sel); if (!pick.hit) { // Quiet is ignored here: the caller NAMED a context, so "nothing new for quietMs" is no // reason to give up on it. It waits for that context up to the cap, then reports the miss. await tracker.settle(settle, async () => !!pickExecutionContext(await tracker.contexts(), sel).hit, true); pick = pickExecutionContext(await tracker.contexts(), sel); } if (!pick.hit) throw driverError("page-error", pick.error ?? "no such execution context"); this.pinned = pick.hit; return pick.hit; } async evaluateAllContexts( expression: string, opts?: { args?: readonly unknown[]; awaitPromise?: boolean; settle?: SettleOptions }, ): Promise { const list = await this.listContexts(opts?.settle); const rows: ContextEvalRow[] = []; for (const c of list) { const row: ContextEvalRow = { contextId: c.id, ...(c.frameId ? { frameId: c.frameId } : {}), origin: c.origin, name: c.name, isDefault: c.isDefault, type: c.type, ...(c.frameUrl ? { frameUrl: c.frameUrl } : {}), ...(c.frameName ? { frameName: c.frameName } : {}), }; try { row.value = await this.evaluateIn(c.id, expression, opts?.args, opts?.awaitPromise ?? true); } catch (e) { // Per-context failures are data: one frame throwing (or vanishing mid-call) never sinks the rest. row.error = e instanceof Error ? e.message : String(e); } rows.push(row); } return rows; } async callOnElement(loc: ElementLocator, functionDeclaration: string, args: readonly unknown[] = []): Promise { const { objectId } = await resolveElementLocator(this.conn, loc, this.pinned?.id); return this.callFn(objectId, functionDeclaration, args, true); } /** * OOPIF MARKERS (issue #7 fix 1): which emitted snapshot nodes own an out-of-process iframe. * * Chrome's Accessibility.getFullAXTree includes the