cdp-toolkit 3.1.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Where the DevTools endpoint is, and which of its two transports this Chrome
3
+ * actually serves.
4
+ *
5
+ * THE FACT THIS MODULE EXISTS FOR. Chrome has always had two ways in, and
6
+ * until recently every build served both:
7
+ *
8
+ * A. the HTTP discovery endpoints — `/json/version`, `/json/list` — plus a
9
+ * per-target socket at `/devtools/page/<targetId>`;
10
+ * B. one browser-level socket at `/devtools/browser/<uuid>`, over which
11
+ * `Target.getTargets` lists and `Target.attachToTarget` reaches a page.
12
+ *
13
+ * A Chrome started with `--remote-debugging-port` serves both. A Chrome that
14
+ * had debugging turned on at RUNTIME, through the toggle on
15
+ * `chrome://inspect/#remote-debugging`, serves only (B) — measured on Chrome
16
+ * 153 (the same handshake on a `--remote-debugging-port` instance returns 101
17
+ * for all three):
18
+ *
19
+ * ws://127.0.0.1:<port>/devtools/browser/<uuid> -> HTTP 101
20
+ * ws://127.0.0.1:<port>/devtools/page/<targetId> -> HTTP 403
21
+ * http://127.0.0.1:<port>/json/version, /json/list -> HTTP 404
22
+ *
23
+ * That is not a degraded mode to work around, it is the transport a user gets
24
+ * when they attach to the browser they were already using rather than
25
+ * relaunching it. Everything the toolkit needs is reachable over (B).
26
+ *
27
+ * WHY DETECTED AND NOT CONFIGURED. Making the user declare the transport would
28
+ * make them diagnose a 404 first. The detection is cached per process.
29
+ *
30
+ * WHY THE FALLBACK IS DRIVEN BY A FAILED OPERATION, not by a probe that runs
31
+ * first. `listTargets` still issues its original `/json/list` request before
32
+ * anything here is consulted, and only a request that did NOT answer reaches
33
+ * the fallback. So on a Chrome that serves (A) the code path is the one that
34
+ * shipped, byte for byte, and the new transport cannot regress it — there is
35
+ * no added round-trip, no added failure mode, and no ordering question. The
36
+ * cost of (B) is one 404 on the first listing, then the decision is cached.
37
+ *
38
+ * WHY THE PORT FILE. The browser socket's URL contains a uuid that is minted
39
+ * fresh on every Chrome start, so it cannot be written into a config once. The
40
+ * uuid and the port are the two lines of `DevToolsActivePort` in the profile
41
+ * directory, which is where `/json/version` would otherwise have supplied it.
42
+ * Resolved at connect time for that reason, never memoized across a restart.
43
+ */
44
+ import { readFile } from "node:fs/promises";
45
+ import { homedir } from "node:os";
46
+ import { join } from "node:path";
47
+ import { currentEndpoint, isDefaultEndpoint } from "../endpoints.ts";
48
+ // A cycle (client.ts imports this module), safe because CdpConnection is only
49
+ // used at call time, never while either module is still evaluating.
50
+ import { CdpConnection } from "../client.ts";
51
+
52
+ /**
53
+ * Which transport this endpoint serves.
54
+ * "http" — `/json/*` answers; per-target sockets exist. The original path.
55
+ * "browser-ws" — only the browser socket answers; pages are reached by session.
56
+ */
57
+ export type CdpTransport = "http" | "browser-ws";
58
+
59
+ export interface EndpointInfo {
60
+ transport: CdpTransport;
61
+ /** The browser-level WebSocket URL. Always present: both transports have one. */
62
+ browserWsUrl: string;
63
+ }
64
+
65
+ /**
66
+ * The browser socket URL from a profile's `DevToolsActivePort`.
67
+ *
68
+ * The file is exactly two lines — port, then the path component including the
69
+ * uuid — and Chrome rewrites it on every start. A profile that is not running
70
+ * leaves a STALE file behind rather than deleting it, so a URL from here is a
71
+ * candidate to be handshaked, never a fact; `detectEndpoint` treats a failed
72
+ * connect as "not this profile" and moves on.
73
+ */
74
+ async function browserWsFromPortFile(dir: string, base: string): Promise<string | undefined> {
75
+ const raw = await readFile(join(dir, "DevToolsActivePort"), "utf8").catch(() => undefined);
76
+ if (!raw) return undefined;
77
+ const [port, path] = raw.split("\n");
78
+ if (!port?.trim() || !path?.trim()) return undefined;
79
+ const host = new URL(base).hostname;
80
+ return `ws://${host}:${port.trim()}${path.trim()}`;
81
+ }
82
+
83
+ /**
84
+ * The browser socket for an explicitly named profile, and ONLY an explicitly
85
+ * named one.
86
+ *
87
+ * NEVER SCANS THE DEFAULT PROFILE, and that restraint is the point rather than
88
+ * an omission. Connecting to a DevTools endpoint is not a neutral act: a Chrome
89
+ * with runtime debugging enabled raises a modal "Allow remote debugging?"
90
+ * consent prompt on the user's screen for each new client, and that prompt
91
+ * grants full access to a logged-in browsing session. A library that guesses
92
+ * its way to a browser nobody named would raise that prompt from a unit-test
93
+ * run — which is exactly how this restriction was found, by doing it.
94
+ *
95
+ * So the profile is opt-in: `CDP_USER_DATA_DIR` names it, or nothing is tried.
96
+ * Pointing this toolkit at a browser stays a decision the user makes.
97
+ */
98
+ async function discoverBrowserWs(base: string): Promise<string | undefined> {
99
+ const dir = process.env.CDP_USER_DATA_DIR;
100
+ return dir ? browserWsFromPortFile(dir, base) : undefined;
101
+ }
102
+
103
+ /**
104
+ * A bounded WebSocket handshake. The port file can name a Chrome that exited,
105
+ * and a dead port would otherwise stall the whole detection on a connect that
106
+ * never resolves. Goes through `CdpConnection` (CONTRIBUTING.md, code rule 2),
107
+ * whose connect is bounded by `timeoutMs`; the socket is closed either way.
108
+ */
109
+ async function handshake(url: string, timeoutMs: number): Promise<boolean> {
110
+ const conn = new CdpConnection(url, { timeoutMs });
111
+ try {
112
+ await conn.connect();
113
+ return true;
114
+ } catch {
115
+ return false;
116
+ } finally {
117
+ conn.close();
118
+ }
119
+ }
120
+
121
+ /** Keyed by endpoint base: named endpoints are separate browsers, each with its own transport. */
122
+ const cached = new Map<string, Promise<EndpointInfo>>();
123
+
124
+ /**
125
+ * Locate the browser socket for an endpoint that serves no `/json`.
126
+ *
127
+ * Called only after an HTTP request has already failed, so it never runs at all
128
+ * against a Chrome started with `--remote-debugging-port`. `CDP_BROWSER_WS`
129
+ * short-circuits the profile lookup, for an endpoint the port file cannot name
130
+ * (a container, a forwarded port, a profile outside the defaults).
131
+ *
132
+ * Per endpoint: the base comes from currentEndpoint() on each call. CDP_BROWSER_WS and
133
+ * CDP_USER_DATA_DIR each name ONE browser, so they apply to the default endpoint only;
134
+ * a named endpoint is detected from its own `/json/version`.
135
+ */
136
+ export function detectEndpoint(): Promise<EndpointInfo> {
137
+ // Only a resolved detection is worth keeping. A failure here is usually
138
+ // transient — Chrome still starting, a port file mid-rewrite — and caching
139
+ // the rejection would make the first unlucky call poison every later one.
140
+ const endpoint = currentEndpoint();
141
+ const base = endpoint.base;
142
+ const isDefault = isDefaultEndpoint(endpoint);
143
+ const hit = cached.get(base);
144
+ if (hit) return hit;
145
+ const detection = (async (): Promise<EndpointInfo> => {
146
+ const forced = isDefault ? process.env.CDP_BROWSER_WS : undefined;
147
+ if (forced) return { transport: "browser-ws", browserWsUrl: forced };
148
+
149
+ const discovered = isDefault ? await discoverBrowserWs(base) : undefined;
150
+ if (discovered && (await handshake(discovered, 5_000))) {
151
+ return { transport: "browser-ws", browserWsUrl: discovered };
152
+ }
153
+
154
+ // Bounded for the same reason the handshake above is: a host that accepts
155
+ // the connection and never answers would otherwise stall detection forever.
156
+ const version = await fetch(`${base}/json/version`, { signal: AbortSignal.timeout(5_000) })
157
+ .then((r) => (r.ok ? (r.json() as Promise<{ webSocketDebuggerUrl?: string }>) : undefined))
158
+ .catch(() => undefined);
159
+ if (version?.webSocketDebuggerUrl) {
160
+ return { transport: "http", browserWsUrl: version.webSocketDebuggerUrl };
161
+ }
162
+
163
+ const dir = isDefault ? process.env.CDP_USER_DATA_DIR : undefined;
164
+ throw new Error(
165
+ `no DevTools endpoint at ${base}: GET /json/version did not answer and ` +
166
+ (dir
167
+ ? `no live browser socket was named by ${dir}/DevToolsActivePort. `
168
+ : `no profile was searched — CDP_USER_DATA_DIR is unset, and no profile is ever scanned unless you name one. `) +
169
+ `Set CDP_BROWSER_WS to the ws://.../devtools/browser/<uuid> URL, or CDP_USER_DATA_DIR to the profile in use.`,
170
+ );
171
+ })().then(
172
+ (info) => {
173
+ // Keep only a browser-ws answer. An "http" one carries a `/json/version`
174
+ // uuid that a Chrome restart invalidates, and that endpoint can simply be
175
+ // asked again, as the HTTP path always has.
176
+ if (info.transport === "http") cached.delete(base);
177
+ return info;
178
+ },
179
+ (error: unknown) => {
180
+ cached.delete(base);
181
+ throw error;
182
+ },
183
+ );
184
+ cached.set(base, detection);
185
+ return detection;
186
+ }
187
+
188
+ /**
189
+ * Forget the current endpoint's detection, so the next `detectEndpoint` looks
190
+ * again. For a browser socket that stopped answering: its URL carries a uuid
191
+ * Chrome mints on every start, so after a restart the cached one is stale.
192
+ */
193
+ export function forgetEndpoint(): void {
194
+ cached.delete(currentEndpoint().base);
195
+ }
196
+
197
+ /** Test seam: drop the per-process detection cache. */
198
+ export function resetEndpointCache(): void {
199
+ cached.clear();
200
+ }
@@ -0,0 +1,246 @@
1
+ /**
2
+ * A page connection carried by a flat `Target.attachToTarget` session on the
3
+ * browser socket, for the endpoints that serve no per-target socket (see
4
+ * ./endpoint.ts for why those exist).
5
+ *
6
+ * WHAT THIS IS. `SessionConnection` presents the same surface as
7
+ * `CdpConnection` — `send`, `on`, `waitFor`, `close`, with the same
8
+ * per-command timeout — but instead of owning a socket it owns a sessionId and
9
+ * borrows the shared browser socket. Every tool module in the toolkit is typed
10
+ * against that surface, so none of them has to know which one it holds. The
11
+ * one-target-per-call guarantee is unchanged: a call attaches to the ONE
12
+ * target it named and detaches when it is done.
13
+ *
14
+ * WHY FLAT SESSIONS. With `flatten: true` every message for an attached target
15
+ * carries its `sessionId` on the same socket, so routing is a map lookup and
16
+ * two sessions never see each other's events. The nested alternative wraps
17
+ * each message in `Target.receivedMessageFromTarget`, which would mean
18
+ * re-implementing correlation a second time.
19
+ *
20
+ * WHY THE SOCKET IS SHARED AND REFERENCE-COUNTED. Chrome mints a NEW session
21
+ * per attach, and sessions on one socket are independent — measured: attaching
22
+ * twice to one target yields two distinct ids, and detaching one leaves the
23
+ * other working. So concurrent calls can and should share a single browser
24
+ * socket. What they must not do is close it while another call is still using
25
+ * it, hence the refcount: the socket opens on the first borrower and closes
26
+ * after the last one releases.
27
+ *
28
+ * THE WEDGED-TAB PROPERTY IS PRESERVED, and it is the reason the toolkit is
29
+ * worth pointing at a browser with a wedged tab in it. A command to a hung
30
+ * renderer times out in `CdpConnection.send` exactly as before — the timer is
31
+ * per command id, not per socket — and because this transport never attaches
32
+ * to a target it was not asked for, a wedged tab is only ever reached by a
33
+ * call that named it.
34
+ */
35
+ import { CdpConnection, CdpError, DEFAULT_TIMEOUT_MS } from "../client.ts";
36
+ import { detectEndpoint, forgetEndpoint } from "./endpoint.ts";
37
+
38
+ type EventHandler = (params: Record<string, unknown>, sessionId?: string) => void;
39
+
40
+ /* ----------------------------- shared browser socket ----------------------------- */
41
+
42
+ let shared: { conn: CdpConnection; refs: number; url: string } | undefined;
43
+ let opening: Promise<CdpConnection> | undefined;
44
+
45
+ /**
46
+ * Borrow the shared browser socket, opening it if nobody holds one.
47
+ *
48
+ * `opening` deduplicates a concurrent first borrow: two calls that arrive
49
+ * together must end up on ONE socket, not race to open two and leak the loser.
50
+ */
51
+ async function acquireBrowserConn(): Promise<CdpConnection> {
52
+ if (shared) {
53
+ shared.refs++;
54
+ return shared.conn;
55
+ }
56
+ if (!opening) {
57
+ opening = (async () => {
58
+ let { browserWsUrl } = await detectEndpoint();
59
+ let conn: CdpConnection;
60
+ try {
61
+ conn = await new CdpConnection(browserWsUrl).connect();
62
+ } catch (error) {
63
+ // The detection is cached, and a Chrome restart mints a new browser
64
+ // uuid, so a URL that stopped answering may just be stale: forget it and
65
+ // detect once more. Same URL again (CDP_BROWSER_WS, or Chrome really is
66
+ // down) means there is nothing newer to try.
67
+ forgetEndpoint();
68
+ const fresh = (await detectEndpoint().catch(() => undefined))?.browserWsUrl;
69
+ if (!fresh || fresh === browserWsUrl) throw error;
70
+ browserWsUrl = fresh;
71
+ conn = await new CdpConnection(browserWsUrl).connect();
72
+ }
73
+ shared = { conn, refs: 0, url: browserWsUrl };
74
+ return conn;
75
+ })().finally(() => {
76
+ opening = undefined;
77
+ });
78
+ }
79
+ const conn = await opening;
80
+ // `shared` is set by the block above before it resolves; a concurrent
81
+ // release cannot have run in between, because releasing requires a ref and
82
+ // this borrower has not taken one yet.
83
+ shared!.refs++;
84
+ return conn;
85
+ }
86
+
87
+ /** Return a borrow. The socket closes when the last holder lets go. */
88
+ function releaseBrowserConn(): void {
89
+ if (!shared) return;
90
+ shared.refs--;
91
+ if (shared.refs <= 0) {
92
+ const { conn } = shared;
93
+ shared = undefined;
94
+ conn.close();
95
+ }
96
+ }
97
+
98
+ /**
99
+ * Run `fn` on the shared browser socket. The browser-domain counterpart of
100
+ * client.ts's `withPage`, and the only way this module opens a socket.
101
+ */
102
+ export async function withBrowserSocket<T>(fn: (conn: CdpConnection) => Promise<T>): Promise<T> {
103
+ const conn = await acquireBrowserConn();
104
+ try {
105
+ return await fn(conn);
106
+ } finally {
107
+ releaseBrowserConn();
108
+ }
109
+ }
110
+
111
+ /* -------------------------------- page sessions -------------------------------- */
112
+
113
+ /**
114
+ * One attached target, shaped like a `CdpConnection`.
115
+ *
116
+ * Structural, not a subclass: `CdpConnection` owns a socket in its constructor
117
+ * and this owns a sessionId, so there is no state to inherit. Callers hold
118
+ * them through the shared `PageConnection` type below.
119
+ */
120
+ export class SessionConnection {
121
+ private detached = false;
122
+ private readonly offs: Array<() => void> = [];
123
+
124
+ constructor(
125
+ private readonly browser: CdpConnection,
126
+ readonly sessionId: string,
127
+ private readonly opts: { timeoutMs?: number } = {},
128
+ ) {}
129
+
130
+ /** Send over this session. Same timeout semantics as CdpConnection.send. */
131
+ send<T = Record<string, unknown>>(
132
+ method: string,
133
+ params: Record<string, unknown> = {},
134
+ opts: { timeoutMs?: number; sessionId?: string } = {},
135
+ ): Promise<T> {
136
+ if (this.detached) return Promise.reject(new CdpError("connection not open"));
137
+ // An explicit sessionId wins, so a caller that attached a NESTED session of
138
+ // its own (cdp/workers.ts does this for ServiceWorker) still addresses it.
139
+ return this.browser.send<T>(method, params, {
140
+ timeoutMs: opts.timeoutMs ?? this.opts.timeoutMs,
141
+ sessionId: opts.sessionId ?? this.sessionId,
142
+ });
143
+ }
144
+
145
+ /**
146
+ * Subscribe, filtered to THIS session.
147
+ *
148
+ * The filter is what makes one socket behave like many: the browser socket
149
+ * carries every attached target's events, and a handler registered here must
150
+ * see only its own. An event with no sessionId is browser-level (a
151
+ * `Target.*` notification) and is delivered too, matching what a per-target
152
+ * socket shows.
153
+ */
154
+ on(method: string, handler: EventHandler): () => void {
155
+ const off = this.browser.on(method, (params, sessionId) => {
156
+ if (sessionId && sessionId !== this.sessionId) return;
157
+ handler(params, sessionId);
158
+ });
159
+ this.offs.push(off);
160
+ return off;
161
+ }
162
+
163
+ waitFor<P = Record<string, unknown>>(
164
+ method: string,
165
+ predicate?: (params: P) => boolean,
166
+ timeoutMs = this.opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,
167
+ ): Promise<P> {
168
+ return new Promise<P>((resolve, reject) => {
169
+ const timer = setTimeout(() => {
170
+ off();
171
+ reject(new CdpError(`waitFor('${method}') timed out after ${timeoutMs}ms`));
172
+ }, timeoutMs);
173
+ const off = this.on(method, (params) => {
174
+ if (!predicate || predicate(params as P)) {
175
+ clearTimeout(timer);
176
+ off();
177
+ resolve(params as P);
178
+ }
179
+ });
180
+ });
181
+ }
182
+
183
+ /**
184
+ * Detach and return the socket borrow.
185
+ *
186
+ * Named `close` because that is the method every tool module already calls in
187
+ * its `finally`. The detach is fire-and-forget: the borrow must be returned
188
+ * even when the target died first, and a failed detach on a target that is
189
+ * already gone is not a caller's problem.
190
+ */
191
+ close(): void {
192
+ if (this.detached) return;
193
+ this.detached = true;
194
+ for (const off of this.offs) off();
195
+ this.offs.length = 0;
196
+ void this.browser.send("Target.detachFromTarget", { sessionId: this.sessionId }).catch(() => {
197
+ /* target already gone */
198
+ });
199
+ releaseBrowserConn();
200
+ }
201
+ }
202
+
203
+ /**
204
+ * What every tool module actually holds: a `CdpConnection` when the endpoint
205
+ * serves per-target sockets, a `SessionConnection` when it does not.
206
+ *
207
+ * AN INTERFACE, NOT A UNION, on purpose. A union of the two classes would make
208
+ * every tool module narrow before it could send, for a distinction none of them
209
+ * cares about. This is the surface they were already using — four methods —
210
+ * so both implementations satisfy it structurally and `withPage` hands over
211
+ * whichever one the transport produced.
212
+ */
213
+ export interface PageConnection {
214
+ send<T = Record<string, unknown>>(
215
+ method: string,
216
+ params?: Record<string, unknown>,
217
+ opts?: { timeoutMs?: number; sessionId?: string },
218
+ ): Promise<T>;
219
+ on(method: string, handler: EventHandler): () => void;
220
+ waitFor<P = Record<string, unknown>>(
221
+ method: string,
222
+ predicate?: (params: P) => boolean,
223
+ timeoutMs?: number,
224
+ ): Promise<P>;
225
+ close(): void;
226
+ }
227
+
228
+ /** Attach to one target and wrap the session. The caller closes it. */
229
+ export async function openSession(
230
+ targetId: string,
231
+ opts: { timeoutMs?: number } = {},
232
+ ): Promise<SessionConnection> {
233
+ const browser = await acquireBrowserConn();
234
+ try {
235
+ const { sessionId } = await browser.send<{ sessionId?: string }>(
236
+ "Target.attachToTarget",
237
+ { targetId, flatten: true },
238
+ { timeoutMs: opts.timeoutMs },
239
+ );
240
+ if (!sessionId) throw new CdpError(`Target.attachToTarget returned no sessionId for ${targetId}`);
241
+ return new SessionConnection(browser, sessionId, opts);
242
+ } catch (e) {
243
+ releaseBrowserConn();
244
+ throw e;
245
+ }
246
+ }
package/src/client.ts CHANGED
@@ -25,6 +25,9 @@ import {
25
25
  FRAME_EMPTY_NEEDLE_MESSAGE,
26
26
  } from "./frames.ts";
27
27
 
28
+ import { detectEndpoint, resetEndpointCache, type CdpTransport } from "./cdp/endpoint.ts";
29
+ import { openSession, withBrowserSocket, type PageConnection } from "./cdp/session.ts";
30
+ export { SessionConnection, withBrowserSocket, type PageConnection } from "./cdp/session.ts";
28
31
  /**
29
32
  * Base HTTP origin of the DEFAULT DevTools endpoint, fixed at import (CDP_BASE, else
30
33
  * http://127.0.0.1:9222, or the default named by CDP_ENDPOINTS / CDP_ENDPOINTS_FILE).
@@ -207,6 +210,18 @@ export class CdpConnection {
207
210
 
208
211
  /* ----------------------------- endpoint discovery ----------------------------- */
209
212
 
213
+ /**
214
+ * Which transport each endpoint turned out to serve, learned from its first
215
+ * listing that succeeded, keyed by endpoint base. Absent until then.
216
+ */
217
+ const knownTransports = new Map<string, CdpTransport>();
218
+
219
+ /** Test seam: forget the learned transport. */
220
+ export function resetTransportCache(): void {
221
+ knownTransports.clear();
222
+ resetEndpointCache();
223
+ }
224
+
210
225
  async function httpJson<T>(path: string): Promise<T> {
211
226
  // Resolved PER CALL, never cached: the endpoint comes from the dispatch scope, and an
212
227
  // endpoint that was down a moment ago is simply tried again.
@@ -215,15 +230,96 @@ async function httpJson<T>(path: string): Promise<T> {
215
230
  return (await res.json()) as T;
216
231
  }
217
232
 
218
- /** All targets (GET /json/list). */
219
- export function listTargets(): Promise<Target[]> {
220
- return httpJson<Target[]>("/json/list");
233
+ /**
234
+ * `Target.getTargets` reshaped into the `/json/list` record every caller
235
+ * already reads.
236
+ *
237
+ * TWO DIFFERENCES from the HTTP listing, both deliberate:
238
+ *
239
+ * `filter: [{}]` is passed because the DEFAULT filter is not "everything" — it
240
+ * omits types the empty filter includes. Measured on Chrome 153: default
241
+ * returned 4 targets (page, browser_ui), `[{}]` returned 6, and the missing
242
+ * ones were exactly the iframe/worker types that the `frame:` and `worker:`
243
+ * selector arms resolve against. Taking the default would silently delete two
244
+ * documented features.
245
+ *
246
+ * `webSocketDebuggerUrl` is EMPTY, and it has to be: on this transport there is
247
+ * no per-target socket to name, and inventing the `/devtools/page/<id>` URL
248
+ * would hand callers a string that 403s. Nothing reads the field on this path —
249
+ * `openPage` branches on transport before it would — and the emptiness is what
250
+ * makes a caller that ignored the branch fail loudly instead of hanging.
251
+ */
252
+ async function getTargetsOverBrowserWs(): Promise<Target[]> {
253
+ const { targetInfos } = await withBrowserSocket((conn) =>
254
+ conn.send<{ targetInfos: Array<{ targetId: string; type: string; title: string; url: string; openerId?: string }> }>(
255
+ "Target.getTargets",
256
+ { filter: [{}] },
257
+ ),
258
+ );
259
+ return targetInfos.map((t) => ({
260
+ id: t.targetId,
261
+ type: t.type,
262
+ title: t.title,
263
+ url: t.url,
264
+ webSocketDebuggerUrl: "",
265
+ ...(t.openerId ? { parentId: t.openerId } : {}),
266
+ }));
221
267
  }
222
268
 
223
- /** Browser-level WebSocket URL (GET /json/version), for Target.* / Browser.*. */
269
+ /**
270
+ * All targets: `GET /json/list`, falling back to `Target.getTargets` on the
271
+ * browser socket when this Chrome does not serve it.
272
+ *
273
+ * THE HTTP REQUEST GOES FIRST AND UNCONDITIONALLY, which is the whole
274
+ * no-regression story: against a Chrome that serves `/json/list` this function
275
+ * does exactly what it did before the fallback existed, and the fallback is
276
+ * unreachable. Only a request that failed opens a socket.
277
+ *
278
+ * Once a transport is known it is cached, so the 404 is paid once per process
279
+ * rather than on every listing.
280
+ */
281
+ export async function listTargets(): Promise<Target[]> {
282
+ const base = currentEndpoint().base;
283
+ if (knownTransports.get(base) === "browser-ws") return getTargetsOverBrowserWs();
284
+ try {
285
+ const listing = await httpJson<Target[]>("/json/list");
286
+ knownTransports.set(base, "http");
287
+ return listing;
288
+ } catch (httpError) {
289
+ // Switch only when detection says this endpoint really serves no `/json`.
290
+ // A Chrome that does serve it can still fail one `/json/list` (restarting,
291
+ // a timeout); its `/json/version` then answers, detection says "http", and
292
+ // pinning browser-ws here would move every later call off the per-target
293
+ // sockets for the rest of the process. Rethrow instead, so the next call
294
+ // tries HTTP again.
295
+ const detected = await detectEndpoint().catch(() => undefined);
296
+ if (detected?.transport !== "browser-ws") throw httpError;
297
+ const targets = await getTargetsOverBrowserWs().catch(() => {
298
+ // The HTTP failure is the one worth reporting: it names the endpoint the
299
+ // user configured, where the fallback's failure only says a profile
300
+ // lookup came up empty.
301
+ throw httpError;
302
+ });
303
+ knownTransports.set(base, "browser-ws");
304
+ return targets;
305
+ }
306
+ }
307
+
308
+ /**
309
+ * Browser-level WebSocket URL, for Target.* / Browser.*.
310
+ *
311
+ * `GET /json/version` first and on every call, as before the browser-ws
312
+ * transport existed: its uuid changes on every Chrome start, so a URL kept
313
+ * across calls goes stale after a restart. Only an endpoint already known to
314
+ * serve no `/json`, or one whose `/json/version` did not answer, goes through
315
+ * detection.
316
+ */
224
317
  export async function browserWsUrl(): Promise<string> {
225
- const v = await httpJson<{ webSocketDebuggerUrl: string }>("/json/version");
226
- return v.webSocketDebuggerUrl;
318
+ if (knownTransports.get(currentEndpoint().base) !== "browser-ws") {
319
+ const version = await httpJson<{ webSocketDebuggerUrl: string }>("/json/version").catch(() => undefined);
320
+ if (version?.webSocketDebuggerUrl) return version.webSocketDebuggerUrl;
321
+ }
322
+ return (await detectEndpoint()).browserWsUrl;
227
323
  }
228
324
 
229
325
  /** Resolve a TargetSelector to a concrete page target. See types.ts for grammar.
@@ -333,13 +429,25 @@ export async function openBrowser(opts: { timeoutMs?: number } = {}): Promise<Cd
333
429
  return new CdpConnection(await browserWsUrl(), opts).connect();
334
430
  }
335
431
 
336
- /** Open a connection to a page target. Returns the connection and the target. */
432
+ /**
433
+ * Open a connection to a page target. Returns the connection and the target.
434
+ *
435
+ * The one place the two transports diverge for a tool author: a per-target
436
+ * socket where Chrome serves one, an attached session on the shared browser
437
+ * socket where it does not. Both are closed by the caller the same way, and
438
+ * both carry the same per-command timeout, so no tool module branches on this.
439
+ */
337
440
  export async function openPage(
338
441
  selector: TargetSelector,
339
442
  opts: { timeoutMs?: number; lease?: string } = {},
340
- ): Promise<{ conn: CdpConnection; target: Target }> {
443
+ ): Promise<{ conn: PageConnection; target: Target }> {
444
+ // resolveTarget listed first, so the transport is already known here: an
445
+ // empty webSocketDebuggerUrl is the browser-ws listing's own marker that this
446
+ // target has no socket to dial (see getTargetsOverBrowserWs).
341
447
  const target = await resolveTarget(selector, { lease: opts.lease });
342
- const conn = await new CdpConnection(target.webSocketDebuggerUrl, opts).connect();
448
+ const conn = target.webSocketDebuggerUrl
449
+ ? await new CdpConnection(target.webSocketDebuggerUrl, opts).connect()
450
+ : await openSession(target.id, opts);
343
451
  return { conn, target };
344
452
  }
345
453
 
@@ -349,7 +457,7 @@ export async function openPage(
349
457
  */
350
458
  export async function withPage<T>(
351
459
  selector: TargetSelector,
352
- fn: (conn: CdpConnection, target: Target) => Promise<T>,
460
+ fn: (conn: PageConnection, target: Target) => Promise<T>,
353
461
  opts: { timeoutMs?: number; lease?: string } = {},
354
462
  ): Promise<T> {
355
463
  const { conn, target } = await openPage(selector, opts);
package/src/driver.ts CHANGED
@@ -148,11 +148,12 @@ export type Capability =
148
148
  | "input.insertTextAtomic" // atomic value commit, not synthesized keystrokes
149
149
  | "locate.text" // find a node by visible text substring
150
150
  | "locate.xpath" // find a node by xpath
151
- | "input.raw" // raw single mouse-event dispatch (dispatch_mouse's move/down/up primitive); Chrome only
151
+ | "input.raw" // raw single mouse-event dispatch (dispatch_mouse's move/down/up primitive); Chrome, and Firefox 160+ (BiDi)
152
+ | "input.modifierClick" // click with Alt/Control/Meta/Shift held; Chrome, and Firefox 160+ (BiDi key source ticked with the pointer)
152
153
  | "input.html5Drag" // real HTML5 drag events (drag's mode:"html5"); Chrome only, see PageDriver.drag
153
154
  | "emulate.focus" // fake page focus without moving the OS window (focus_emulation / click_focus_gated); Chrome only — BiDi's emulation module has no focus primitive
154
- | "browser.downloads" // capture a file download to a known path (wait_for_download); Chrome only
155
- | "browser.permissions" // grant/reset browser permissions for an origin (grant_permissions); Chrome only
155
+ | "browser.downloads" // capture a file download to a known path (wait_for_download); Chrome, Firefox 160+
156
+ | "browser.permissions" // grant/reset browser permissions for an origin (grant_permissions); Chrome, Firefox 160+
156
157
  | "worker.targets" // address a service/shared worker as a target ("worker:<substr>"), incl. waking an evicted MV3 worker; Chrome only
157
158
  | "frame.targets"; // address an out-of-process (cross-origin) iframe as a target ("frame:<substr>"); Chrome only — same-site iframes are not targets at all
158
159
 
@@ -262,12 +263,23 @@ export interface NavigateResult {
262
263
  waitedFor: "load" | "domcontentloaded" | "committed" | "timeout";
263
264
  }
264
265
 
266
+ /** One raw mouse event for PageDriver.dispatchMouse. `modifiers` are held for this one event only. */
267
+ export interface RawMouseEvent {
268
+ action: "move" | "down" | "up";
269
+ x: number;
270
+ y: number;
271
+ button?: "left" | "right" | "middle";
272
+ clickCount?: number;
273
+ modifiers?: readonly string[];
274
+ }
275
+
265
276
  export interface MouseButtonOptions {
266
277
  button?: "left" | "right" | "middle";
267
278
  clickCount?: number;
268
279
  /** "Alt" | "Control" | "Meta" | "Shift", held for the press/release. CDP bits: Alt=1,
269
- * Control=2, Meta=4, Shift=8 (cdp/driver.ts's inputModifierBits). A non-empty array is
270
- * "unsupported" on the Firefox/BiDi driver today: see click()'s implementation note. */
280
+ * Control=2, Meta=4, Shift=8 (cdp/driver.ts's inputModifierBits). On the Firefox/BiDi driver a
281
+ * non-empty array rides a key input source ticked with the pointer (capability
282
+ * "input.modifierClick", Firefox 160+; an older Firefox gets "unsupported"). */
271
283
  modifiers?: readonly string[];
272
284
  }
273
285
 
@@ -874,6 +886,11 @@ export interface PageDriver {
874
886
  * "wheel" input source via input.performActions. Universal: both drivers must implement it
875
887
  * (absent from driver.ts's REQUIRED_CAPABILITIES, unlike dispatch_mouse). */
876
888
  scroll(anchor: ElementLocator | { x: number; y: number } | undefined, opts: ScrollOptions): Promise<{ x: number; y: number }>;
889
+ /** One raw mouse event at viewport coordinates (dispatch_mouse), capability "input.raw". Only
890
+ * the Firefox/BiDi driver implements it on this interface: Chrome's dispatch_mouse is the
891
+ * standalone raw-CDP tool in tools/dispatch-mouse.ts, which has no PageDriver. Callers check the
892
+ * method exists; the Firefox tool handler (bidi-tools.ts) does. */
893
+ dispatchMouse?(event: RawMouseEvent): Promise<void>;
877
894
  /** Overwrite an element's value. One atomic commit under
878
895
  * "input.insertTextAtomic", else synthesized keystrokes, so per-key handlers
879
896
  * on the page WILL fire. Callers must not depend on either behavior. */