cdp-toolkit 3.0.3 → 3.2.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.
- package/CHANGELOG.md +28 -0
- package/CONTRACT.md +2 -2
- package/README.md +122 -1
- package/dist/bidi/mux-daemon.js +675 -130
- package/dist/cli.js +1432 -635
- package/dist/index.js +1110 -116
- package/dist/mcp.js +1474 -658
- package/package.json +3 -1
- package/src/bidi/snapshot.ts +123 -113
- package/src/cdp/driver.ts +55 -41
- package/src/cdp/endpoint.ts +200 -0
- package/src/cdp/session.ts +246 -0
- package/src/cli.ts +17 -4
- package/src/client.ts +140 -16
- package/src/endpoints.ts +428 -0
- package/src/leases-tools.ts +6 -3
- package/src/leases.ts +28 -4
- package/src/manifest.ts +54 -42
- package/src/mcp.ts +52 -8
- package/src/origins.ts +5 -2
- package/src/policy.ts +163 -0
- package/src/reap.ts +14 -0
- package/src/shared-tools.ts +164 -25
- package/src/toolDocs.ts +41 -38
- package/src/tools/browser-session.ts +26 -12
- package/src/tools/dispatch-mouse.ts +2 -1
- package/src/tools/evaluate.ts +3 -3
- package/src/tools/focus-emulation.ts +5 -3
- package/src/tools/lighthouse.ts +4 -2
- package/src/tools/navigation.ts +3 -3
- package/src/tools/network_mock.ts +2 -2
- package/src/tools/performance.ts +5 -5
- package/src/tools/recorder.ts +3 -3
- package/src/tools/screencast.ts +46 -6
- package/src/tools/snapshot.ts +2 -2
- package/src/version.ts +1 -1
package/dist/index.js
CHANGED
|
@@ -10,11 +10,308 @@ var __esm = (fn, res, err) => () => {
|
|
|
10
10
|
return res;
|
|
11
11
|
};
|
|
12
12
|
|
|
13
|
-
// src/
|
|
13
|
+
// src/endpoints.ts
|
|
14
14
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
15
|
+
import { readFileSync } from "node:fs";
|
|
16
|
+
function checkName(name, where) {
|
|
17
|
+
if (!NAME_RE.test(name)) {
|
|
18
|
+
throw new EndpointConfigError(`${where}: endpoint name '${name}' is invalid; names are letters, digits and '_' only (no '-', '/', ':' or spaces)`);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function sameBase(a, b) {
|
|
22
|
+
return a.replace(/\/+$/, "") === b.replace(/\/+$/, "");
|
|
23
|
+
}
|
|
24
|
+
function parseBase(raw, where) {
|
|
25
|
+
let url;
|
|
26
|
+
try {
|
|
27
|
+
url = new URL(raw);
|
|
28
|
+
} catch {
|
|
29
|
+
throw new EndpointConfigError(`${where}: '${raw}' is not a valid URL (expected e.g. http://127.0.0.1:9222)`);
|
|
30
|
+
}
|
|
31
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
32
|
+
throw new EndpointConfigError(`${where}: '${raw}' must be an http:// or https:// DevTools origin, not ${url.protocol}`);
|
|
33
|
+
}
|
|
34
|
+
if (url.hash)
|
|
35
|
+
throw new EndpointConfigError(`${where}: '${raw}' must not carry a #fragment`);
|
|
36
|
+
let mode;
|
|
37
|
+
for (const [key, value] of url.searchParams) {
|
|
38
|
+
if (key !== "mode") {
|
|
39
|
+
throw new EndpointConfigError(`${where}: unknown query parameter '${key}' in '${raw}' (only ?mode=read or ?mode=write is understood)`);
|
|
40
|
+
}
|
|
41
|
+
if (value !== "read" && value !== "write") {
|
|
42
|
+
throw new EndpointConfigError(`${where}: unknown mode '${value}' in '${raw}' (use mode=read or mode=write)`);
|
|
43
|
+
}
|
|
44
|
+
mode = value;
|
|
45
|
+
}
|
|
46
|
+
const path = url.pathname.replace(/\/+$/, "");
|
|
47
|
+
return { base: `${url.protocol}//${url.host}${path}`, mode };
|
|
48
|
+
}
|
|
49
|
+
function parseEnvString(spec) {
|
|
50
|
+
const out = [];
|
|
51
|
+
const seen = new Set;
|
|
52
|
+
for (const part of spec.split(",")) {
|
|
53
|
+
const entry = part.trim();
|
|
54
|
+
if (!entry)
|
|
55
|
+
continue;
|
|
56
|
+
const eq = entry.indexOf("=");
|
|
57
|
+
if (eq <= 0) {
|
|
58
|
+
throw new EndpointConfigError(`CDP_ENDPOINTS: entry '${entry}' is not name=url (e.g. teams=http://127.0.0.1:9333)`);
|
|
59
|
+
}
|
|
60
|
+
const name = entry.slice(0, eq).trim();
|
|
61
|
+
checkName(name, "CDP_ENDPOINTS");
|
|
62
|
+
if (seen.has(name))
|
|
63
|
+
throw new EndpointConfigError(`CDP_ENDPOINTS: duplicate endpoint name '${name}'`);
|
|
64
|
+
seen.add(name);
|
|
65
|
+
const { base, mode } = parseBase(entry.slice(eq + 1).trim(), `CDP_ENDPOINTS endpoint '${name}'`);
|
|
66
|
+
out.push({ name, base, readOnly: mode === "read" });
|
|
67
|
+
}
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
function parseFile(path) {
|
|
71
|
+
let text;
|
|
72
|
+
try {
|
|
73
|
+
text = readFileSync(path, "utf8");
|
|
74
|
+
} catch (err) {
|
|
75
|
+
const code = err.code ?? String(err);
|
|
76
|
+
throw new EndpointConfigError(`CDP_ENDPOINTS_FILE: cannot read '${path}' (${code})`);
|
|
77
|
+
}
|
|
78
|
+
let json;
|
|
79
|
+
try {
|
|
80
|
+
json = JSON.parse(text);
|
|
81
|
+
} catch (err) {
|
|
82
|
+
throw new EndpointConfigError(`CDP_ENDPOINTS_FILE: '${path}' is not valid JSON (${err instanceof Error ? err.message : String(err)})`);
|
|
83
|
+
}
|
|
84
|
+
const where = `CDP_ENDPOINTS_FILE '${path}'`;
|
|
85
|
+
if (!json || typeof json !== "object" || Array.isArray(json)) {
|
|
86
|
+
throw new EndpointConfigError(`${where}: top level must be an object {"default"?, "endpoints": {...}}`);
|
|
87
|
+
}
|
|
88
|
+
const top = json;
|
|
89
|
+
for (const key of Object.keys(top)) {
|
|
90
|
+
if (key !== "default" && key !== "endpoints")
|
|
91
|
+
throw new EndpointConfigError(`${where}: unknown top-level key '${key}'`);
|
|
92
|
+
}
|
|
93
|
+
if (top.default !== undefined && typeof top.default !== "string") {
|
|
94
|
+
throw new EndpointConfigError(`${where}: "default" must be an endpoint name string`);
|
|
95
|
+
}
|
|
96
|
+
const raw = top.endpoints ?? {};
|
|
97
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
98
|
+
throw new EndpointConfigError(`${where}: "endpoints" must be an object keyed by endpoint name`);
|
|
99
|
+
}
|
|
100
|
+
const endpoints = [];
|
|
101
|
+
for (const [name, value] of Object.entries(raw)) {
|
|
102
|
+
checkName(name, where);
|
|
103
|
+
const at = `${where} endpoint '${name}'`;
|
|
104
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
105
|
+
throw new EndpointConfigError(`${at}: must be an object like {"base":"http://127.0.0.1:9333"}`);
|
|
106
|
+
}
|
|
107
|
+
const v = value;
|
|
108
|
+
for (const key of Object.keys(v)) {
|
|
109
|
+
if (key !== "base" && key !== "readOnly" && key !== "mode") {
|
|
110
|
+
throw new EndpointConfigError(`${at}: unknown key '${key}' (known: base, readOnly, mode)`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if (typeof v.base !== "string")
|
|
114
|
+
throw new EndpointConfigError(`${at}: "base" is required and must be a URL string`);
|
|
115
|
+
if (v.readOnly !== undefined && typeof v.readOnly !== "boolean")
|
|
116
|
+
throw new EndpointConfigError(`${at}: "readOnly" must be a boolean`);
|
|
117
|
+
if (v.mode !== undefined && v.mode !== "read" && v.mode !== "write") {
|
|
118
|
+
throw new EndpointConfigError(`${at}: unknown mode '${String(v.mode)}' (use "read" or "write")`);
|
|
119
|
+
}
|
|
120
|
+
const parsed = parseBase(v.base, at);
|
|
121
|
+
const votes = [parsed.mode, v.mode, v.readOnly === undefined ? undefined : v.readOnly ? "read" : "write"].filter((x) => x !== undefined);
|
|
122
|
+
if (new Set(votes).size > 1)
|
|
123
|
+
throw new EndpointConfigError(`${at}: readOnly / mode settings contradict each other`);
|
|
124
|
+
endpoints.push({ name, base: parsed.base, readOnly: votes[0] === "read" });
|
|
125
|
+
}
|
|
126
|
+
return { endpoints, defaultName: top.default };
|
|
127
|
+
}
|
|
128
|
+
function loadEndpoints(env = process.env) {
|
|
129
|
+
const fromEnv = env.CDP_ENDPOINTS !== undefined ? parseEnvString(env.CDP_ENDPOINTS) : [];
|
|
130
|
+
const file = env.CDP_ENDPOINTS_FILE ? parseFile(env.CDP_ENDPOINTS_FILE) : { endpoints: [], defaultName: undefined };
|
|
131
|
+
const merged = new Map;
|
|
132
|
+
for (const ep of fromEnv)
|
|
133
|
+
merged.set(ep.name, ep);
|
|
134
|
+
for (const ep of file.endpoints) {
|
|
135
|
+
const prior = merged.get(ep.name);
|
|
136
|
+
if (prior && (prior.base !== ep.base || prior.readOnly !== ep.readOnly)) {
|
|
137
|
+
throw new EndpointConfigError(`endpoint '${ep.name}' is defined differently in CDP_ENDPOINTS (${prior.base}${prior.readOnly ? " read-only" : ""}) and CDP_ENDPOINTS_FILE (${ep.base}${ep.readOnly ? " read-only" : ""})`);
|
|
138
|
+
}
|
|
139
|
+
if (!prior)
|
|
140
|
+
merged.set(ep.name, ep);
|
|
141
|
+
}
|
|
142
|
+
const cdpBase = env.CDP_BASE;
|
|
143
|
+
if (cdpBase !== undefined) {
|
|
144
|
+
const configured = merged.get("default");
|
|
145
|
+
if (configured && !sameBase(configured.base, cdpBase)) {
|
|
146
|
+
throw new EndpointConfigError(`CDP_BASE (${cdpBase}) and the configured endpoint 'default' (${configured.base}) disagree; drop one or make them match`);
|
|
147
|
+
}
|
|
148
|
+
merged.set("default", { name: "default", base: cdpBase, readOnly: configured?.readOnly ?? false });
|
|
149
|
+
}
|
|
150
|
+
const defaultName = file.defaultName ?? "default";
|
|
151
|
+
if (!merged.has(defaultName)) {
|
|
152
|
+
if (file.defaultName !== undefined) {
|
|
153
|
+
throw new EndpointConfigError(`CDP_ENDPOINTS_FILE names default endpoint '${file.defaultName}', which is not defined (known: ${[...merged.keys()].join(", ") || "none"})`);
|
|
154
|
+
}
|
|
155
|
+
merged.set("default", { name: "default", base: DEFAULT_CDP_BASE, readOnly: false });
|
|
156
|
+
}
|
|
157
|
+
const def = merged.get(defaultName);
|
|
158
|
+
const byName = new Map([[def.name, def]]);
|
|
159
|
+
for (const [name, ep] of merged)
|
|
160
|
+
if (name !== def.name)
|
|
161
|
+
byName.set(name, ep);
|
|
162
|
+
return { default: def, byName };
|
|
163
|
+
}
|
|
164
|
+
function signature(env) {
|
|
165
|
+
return JSON.stringify([env.CDP_BASE ?? null, env.CDP_ENDPOINTS ?? null, env.CDP_ENDPOINTS_FILE ?? null]);
|
|
166
|
+
}
|
|
167
|
+
function endpointConfig() {
|
|
168
|
+
const sig = signature(process.env);
|
|
169
|
+
if (cache?.sig === sig)
|
|
170
|
+
return cache.config;
|
|
171
|
+
const config = loadEndpoints(process.env);
|
|
172
|
+
cache = { sig, config };
|
|
173
|
+
return config;
|
|
174
|
+
}
|
|
175
|
+
function defaultEndpoint() {
|
|
176
|
+
return endpointConfig().default;
|
|
177
|
+
}
|
|
178
|
+
function allEndpoints() {
|
|
179
|
+
return [...endpointConfig().byName.values()];
|
|
180
|
+
}
|
|
181
|
+
function getEndpoint(name) {
|
|
182
|
+
const { byName } = endpointConfig();
|
|
183
|
+
const ep = byName.get(name);
|
|
184
|
+
if (!ep) {
|
|
185
|
+
throw new EndpointConfigError(`unknown endpoint '${name}' (known: ${[...byName.keys()].join(", ")}). Configure it with CDP_ENDPOINTS or CDP_ENDPOINTS_FILE.`);
|
|
186
|
+
}
|
|
187
|
+
return ep;
|
|
188
|
+
}
|
|
189
|
+
function leaseNamespace(ep) {
|
|
190
|
+
const { default: def, byName } = endpointConfig();
|
|
191
|
+
if (sameBase(ep.base, def.base))
|
|
192
|
+
return;
|
|
193
|
+
for (const other of byName.values())
|
|
194
|
+
if (sameBase(other.base, ep.base))
|
|
195
|
+
return other.name;
|
|
196
|
+
return ep.name;
|
|
197
|
+
}
|
|
198
|
+
function hasEndpointPrefix(target) {
|
|
199
|
+
return typeof target === "string" && target.startsWith(ENDPOINT_PREFIX);
|
|
200
|
+
}
|
|
201
|
+
function splitEndpointSelector(target) {
|
|
202
|
+
if (!hasEndpointPrefix(target))
|
|
203
|
+
return { endpoint: defaultEndpoint(), rest: target };
|
|
204
|
+
const body = target.slice(ENDPOINT_PREFIX.length);
|
|
205
|
+
const slash = body.indexOf("/");
|
|
206
|
+
const name = slash < 0 ? body : body.slice(0, slash);
|
|
207
|
+
if (!name)
|
|
208
|
+
throw new EndpointConfigError(`selector '${target}' has an empty endpoint name; use endpoint:<name>/<selector>`);
|
|
209
|
+
const rest = slash < 0 ? undefined : body.slice(slash + 1);
|
|
210
|
+
return { endpoint: getEndpoint(name), rest: rest === "" ? undefined : rest };
|
|
211
|
+
}
|
|
212
|
+
function usesEndpointArgs(args) {
|
|
213
|
+
if (!args || typeof args !== "object")
|
|
214
|
+
return false;
|
|
215
|
+
const a = args;
|
|
216
|
+
return SELECTOR_KEYS.some((k) => hasEndpointPrefix(a[k])) || a.endpoint !== undefined || a.allEndpoints === true;
|
|
217
|
+
}
|
|
218
|
+
function stripEndpointArgs(args) {
|
|
219
|
+
if (!args || typeof args !== "object" || Array.isArray(args))
|
|
220
|
+
return { endpoint: defaultEndpoint(), args };
|
|
221
|
+
const a = args;
|
|
222
|
+
const picks = [];
|
|
223
|
+
let out;
|
|
224
|
+
for (const key of SELECTOR_KEYS) {
|
|
225
|
+
const v = a[key];
|
|
226
|
+
if (!hasEndpointPrefix(v))
|
|
227
|
+
continue;
|
|
228
|
+
const { endpoint, rest } = splitEndpointSelector(v);
|
|
229
|
+
picks.push({ from: `${key} '${v}'`, endpoint });
|
|
230
|
+
out ??= { ...a };
|
|
231
|
+
if (rest === undefined)
|
|
232
|
+
delete out[key];
|
|
233
|
+
else
|
|
234
|
+
out[key] = rest;
|
|
235
|
+
}
|
|
236
|
+
if (a.endpoint !== undefined) {
|
|
237
|
+
if (typeof a.endpoint !== "string" || a.endpoint === "") {
|
|
238
|
+
throw new EndpointConfigError("`endpoint` must be a non-empty endpoint name string");
|
|
239
|
+
}
|
|
240
|
+
picks.push({ from: `endpoint '${a.endpoint}'`, endpoint: getEndpoint(a.endpoint) });
|
|
241
|
+
out ??= { ...a };
|
|
242
|
+
delete out.endpoint;
|
|
243
|
+
}
|
|
244
|
+
const token = leaseTokenNamespace(a.lease);
|
|
245
|
+
if (!picks.length) {
|
|
246
|
+
if (token?.ns === undefined)
|
|
247
|
+
return { endpoint: defaultEndpoint(), args };
|
|
248
|
+
return { endpoint: endpointForNamespace(token.ns), args };
|
|
249
|
+
}
|
|
250
|
+
const first = picks[0];
|
|
251
|
+
for (const p of picks.slice(1)) {
|
|
252
|
+
if (p.endpoint.name !== first.endpoint.name) {
|
|
253
|
+
throw new EndpointConfigError(`conflicting endpoints: ${first.from} vs ${p.from}; name one endpoint per call`);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (token && leaseNamespace(first.endpoint) !== token.ns) {
|
|
257
|
+
throw new EndpointConfigError(`conflicting endpoints: ${first.from} vs the lease token, which belongs to ${token.ns === undefined ? "the default endpoint" : `endpoint '${token.ns}'`}; name one endpoint per call`);
|
|
258
|
+
}
|
|
259
|
+
return { endpoint: first.endpoint, args: out ?? a };
|
|
260
|
+
}
|
|
261
|
+
function leaseTokenNamespace(lease) {
|
|
262
|
+
if (typeof lease !== "string")
|
|
263
|
+
return null;
|
|
264
|
+
const colon = lease.indexOf(":");
|
|
265
|
+
if (colon <= 0)
|
|
266
|
+
return null;
|
|
267
|
+
const head = lease.slice(0, colon);
|
|
268
|
+
if (head === "chrome")
|
|
269
|
+
return { ns: undefined };
|
|
270
|
+
if (!head.startsWith("chrome@"))
|
|
271
|
+
return null;
|
|
272
|
+
const ns = head.slice("chrome@".length);
|
|
273
|
+
return NAME_RE.test(ns) ? { ns } : null;
|
|
274
|
+
}
|
|
275
|
+
function endpointForNamespace(ns) {
|
|
276
|
+
for (const ep of endpointConfig().byName.values())
|
|
277
|
+
if (leaseNamespace(ep) === ns)
|
|
278
|
+
return ep;
|
|
279
|
+
throw new EndpointConfigError(`the lease token belongs to endpoint '${ns}', which is not configured (known: ${[...endpointConfig().byName.keys()].join(", ")})`);
|
|
280
|
+
}
|
|
281
|
+
function currentEndpoint() {
|
|
282
|
+
return endpointScope.getStore() ?? defaultEndpoint();
|
|
283
|
+
}
|
|
284
|
+
function isDefaultEndpoint(ep) {
|
|
285
|
+
return ep.name === defaultEndpoint().name;
|
|
286
|
+
}
|
|
287
|
+
function withEndpointScope(ep, fn) {
|
|
288
|
+
return endpointScope.run(ep, fn);
|
|
289
|
+
}
|
|
290
|
+
var EndpointConfigError, DEFAULT_CDP_BASE = "http://127.0.0.1:9222", ENDPOINT_PREFIX = "endpoint:", NAME_RE, cache, SELECTOR_KEYS, ENDPOINTS_FIREFOX_MESSAGE = "named CDP endpoints (an 'endpoint:<name>/' selector prefix, the endpoint arg, list_pages allEndpoints) need the Chrome backend; the Firefox BiDi backend has one session and no endpoints", endpointScope;
|
|
291
|
+
var init_endpoints = __esm(() => {
|
|
292
|
+
EndpointConfigError = class EndpointConfigError extends Error {
|
|
293
|
+
constructor(message) {
|
|
294
|
+
super(message);
|
|
295
|
+
this.name = "EndpointConfigError";
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
NAME_RE = /^[A-Za-z0-9_]+$/;
|
|
299
|
+
SELECTOR_KEYS = ["target", "targetId"];
|
|
300
|
+
endpointScope = new AsyncLocalStorage;
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
// src/leases.ts
|
|
304
|
+
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
|
|
15
305
|
import { randomBytes } from "node:crypto";
|
|
16
306
|
import { mkdir, readFile, readdir, unlink, writeFile } from "node:fs/promises";
|
|
17
307
|
import { join } from "node:path";
|
|
308
|
+
function chromeLeaseBackend(ep = currentEndpoint()) {
|
|
309
|
+
const ns = leaseNamespace(ep);
|
|
310
|
+
return ns === undefined ? "chrome" : `chrome@${ns}`;
|
|
311
|
+
}
|
|
312
|
+
function isLeaseBackend(value) {
|
|
313
|
+
return BACKEND_KEY_RE.test(value);
|
|
314
|
+
}
|
|
18
315
|
function leaseDir() {
|
|
19
316
|
return process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
|
|
20
317
|
}
|
|
@@ -51,7 +348,7 @@ function tokenParts(token) {
|
|
|
51
348
|
if (first <= 0 || last <= first)
|
|
52
349
|
return;
|
|
53
350
|
const backend = token.slice(0, first);
|
|
54
|
-
if (backend
|
|
351
|
+
if (!isLeaseBackend(backend))
|
|
55
352
|
return;
|
|
56
353
|
const targetId = token.slice(first + 1, last);
|
|
57
354
|
const nonce = token.slice(last + 1);
|
|
@@ -272,8 +569,10 @@ async function listLeases(opts = {}) {
|
|
|
272
569
|
}
|
|
273
570
|
return out;
|
|
274
571
|
}
|
|
275
|
-
var DEFAULT_LEASE_TTL_MS = 900000, longLived = false, LeaseConflictError, leaseScope, LEASE_FILE_RE;
|
|
572
|
+
var BACKEND_KEY_SOURCE = "chrome@[A-Za-z0-9_]+|chrome|firefox", BACKEND_KEY_RE, DEFAULT_LEASE_TTL_MS = 900000, longLived = false, LeaseConflictError, leaseScope, LEASE_FILE_RE;
|
|
276
573
|
var init_leases = __esm(() => {
|
|
574
|
+
init_endpoints();
|
|
575
|
+
BACKEND_KEY_RE = new RegExp(`^(?:${BACKEND_KEY_SOURCE})$`);
|
|
277
576
|
LeaseConflictError = class LeaseConflictError extends Error {
|
|
278
577
|
targetId;
|
|
279
578
|
holder;
|
|
@@ -284,8 +583,8 @@ var init_leases = __esm(() => {
|
|
|
284
583
|
this.name = "LeaseConflictError";
|
|
285
584
|
}
|
|
286
585
|
};
|
|
287
|
-
leaseScope = new
|
|
288
|
-
LEASE_FILE_RE =
|
|
586
|
+
leaseScope = new AsyncLocalStorage2;
|
|
587
|
+
LEASE_FILE_RE = new RegExp(`^lease-(${BACKEND_KEY_SOURCE})-(.+)\\.json$`);
|
|
289
588
|
});
|
|
290
589
|
|
|
291
590
|
// src/origins.ts
|
|
@@ -415,7 +714,7 @@ async function resolveLiveLabel(backend, label, liveIds) {
|
|
|
415
714
|
var ORIGIN_FILE_RE;
|
|
416
715
|
var init_origins = __esm(() => {
|
|
417
716
|
init_leases();
|
|
418
|
-
ORIGIN_FILE_RE =
|
|
717
|
+
ORIGIN_FILE_RE = new RegExp(`^origin-(${BACKEND_KEY_SOURCE})-(.+)\\.json$`);
|
|
419
718
|
});
|
|
420
719
|
|
|
421
720
|
// src/workers.ts
|
|
@@ -503,6 +802,204 @@ var init_frames = __esm(() => {
|
|
|
503
802
|
FRAME_SELECTOR_PAGE_ONLY_MESSAGE = "target 'frame:<substring>' selects an out-of-process iframe, and this tool is page-only " + "(closing, selecting, releasing or claiming an iframe is meaningless; these act on the embedder tab). " + `The page-only tools are ${FRAME_PAGE_ONLY_TOOLS.join(", ")}; every other tool that takes a 'target' ` + "accepts a frame: selector.";
|
|
504
803
|
});
|
|
505
804
|
|
|
805
|
+
// src/cdp/endpoint.ts
|
|
806
|
+
import { readFile as readFile3 } from "node:fs/promises";
|
|
807
|
+
import { join as join3 } from "node:path";
|
|
808
|
+
async function browserWsFromPortFile(dir, base) {
|
|
809
|
+
const raw = await readFile3(join3(dir, "DevToolsActivePort"), "utf8").catch(() => {
|
|
810
|
+
return;
|
|
811
|
+
});
|
|
812
|
+
if (!raw)
|
|
813
|
+
return;
|
|
814
|
+
const [port, path] = raw.split(`
|
|
815
|
+
`);
|
|
816
|
+
if (!port?.trim() || !path?.trim())
|
|
817
|
+
return;
|
|
818
|
+
const host = new URL(base).hostname;
|
|
819
|
+
return `ws://${host}:${port.trim()}${path.trim()}`;
|
|
820
|
+
}
|
|
821
|
+
async function discoverBrowserWs(base) {
|
|
822
|
+
const dir = process.env.CDP_USER_DATA_DIR;
|
|
823
|
+
return dir ? browserWsFromPortFile(dir, base) : undefined;
|
|
824
|
+
}
|
|
825
|
+
async function handshake(url, timeoutMs) {
|
|
826
|
+
const conn = new CdpConnection(url, { timeoutMs });
|
|
827
|
+
try {
|
|
828
|
+
await conn.connect();
|
|
829
|
+
return true;
|
|
830
|
+
} catch {
|
|
831
|
+
return false;
|
|
832
|
+
} finally {
|
|
833
|
+
conn.close();
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
function detectEndpoint() {
|
|
837
|
+
const endpoint = currentEndpoint();
|
|
838
|
+
const base = endpoint.base;
|
|
839
|
+
const isDefault = isDefaultEndpoint(endpoint);
|
|
840
|
+
const hit = cached.get(base);
|
|
841
|
+
if (hit)
|
|
842
|
+
return hit;
|
|
843
|
+
const detection = (async () => {
|
|
844
|
+
const forced = isDefault ? process.env.CDP_BROWSER_WS : undefined;
|
|
845
|
+
if (forced)
|
|
846
|
+
return { transport: "browser-ws", browserWsUrl: forced };
|
|
847
|
+
const discovered = isDefault ? await discoverBrowserWs(base) : undefined;
|
|
848
|
+
if (discovered && await handshake(discovered, 5000)) {
|
|
849
|
+
return { transport: "browser-ws", browserWsUrl: discovered };
|
|
850
|
+
}
|
|
851
|
+
const version = await fetch(`${base}/json/version`, { signal: AbortSignal.timeout(5000) }).then((r) => r.ok ? r.json() : undefined).catch(() => {
|
|
852
|
+
return;
|
|
853
|
+
});
|
|
854
|
+
if (version?.webSocketDebuggerUrl) {
|
|
855
|
+
return { transport: "http", browserWsUrl: version.webSocketDebuggerUrl };
|
|
856
|
+
}
|
|
857
|
+
const dir = isDefault ? process.env.CDP_USER_DATA_DIR : undefined;
|
|
858
|
+
throw new Error(`no DevTools endpoint at ${base}: GET /json/version did not answer and ` + (dir ? `no live browser socket was named by ${dir}/DevToolsActivePort. ` : `no profile was searched — CDP_USER_DATA_DIR is unset, and no profile is ever scanned unless you name one. `) + `Set CDP_BROWSER_WS to the ws://.../devtools/browser/<uuid> URL, or CDP_USER_DATA_DIR to the profile in use.`);
|
|
859
|
+
})().then((info) => {
|
|
860
|
+
if (info.transport === "http")
|
|
861
|
+
cached.delete(base);
|
|
862
|
+
return info;
|
|
863
|
+
}, (error) => {
|
|
864
|
+
cached.delete(base);
|
|
865
|
+
throw error;
|
|
866
|
+
});
|
|
867
|
+
cached.set(base, detection);
|
|
868
|
+
return detection;
|
|
869
|
+
}
|
|
870
|
+
function forgetEndpoint() {
|
|
871
|
+
cached.delete(currentEndpoint().base);
|
|
872
|
+
}
|
|
873
|
+
var cached;
|
|
874
|
+
var init_endpoint = __esm(() => {
|
|
875
|
+
init_endpoints();
|
|
876
|
+
init_client();
|
|
877
|
+
cached = new Map;
|
|
878
|
+
});
|
|
879
|
+
|
|
880
|
+
// src/cdp/session.ts
|
|
881
|
+
async function acquireBrowserConn() {
|
|
882
|
+
if (shared) {
|
|
883
|
+
shared.refs++;
|
|
884
|
+
return shared.conn;
|
|
885
|
+
}
|
|
886
|
+
if (!opening) {
|
|
887
|
+
opening = (async () => {
|
|
888
|
+
let { browserWsUrl } = await detectEndpoint();
|
|
889
|
+
let conn;
|
|
890
|
+
try {
|
|
891
|
+
conn = await new CdpConnection(browserWsUrl).connect();
|
|
892
|
+
} catch (error) {
|
|
893
|
+
forgetEndpoint();
|
|
894
|
+
const fresh = (await detectEndpoint().catch(() => {
|
|
895
|
+
return;
|
|
896
|
+
}))?.browserWsUrl;
|
|
897
|
+
if (!fresh || fresh === browserWsUrl)
|
|
898
|
+
throw error;
|
|
899
|
+
browserWsUrl = fresh;
|
|
900
|
+
conn = await new CdpConnection(browserWsUrl).connect();
|
|
901
|
+
}
|
|
902
|
+
shared = { conn, refs: 0, url: browserWsUrl };
|
|
903
|
+
return conn;
|
|
904
|
+
})().finally(() => {
|
|
905
|
+
opening = undefined;
|
|
906
|
+
});
|
|
907
|
+
}
|
|
908
|
+
const conn = await opening;
|
|
909
|
+
shared.refs++;
|
|
910
|
+
return conn;
|
|
911
|
+
}
|
|
912
|
+
function releaseBrowserConn() {
|
|
913
|
+
if (!shared)
|
|
914
|
+
return;
|
|
915
|
+
shared.refs--;
|
|
916
|
+
if (shared.refs <= 0) {
|
|
917
|
+
const { conn } = shared;
|
|
918
|
+
shared = undefined;
|
|
919
|
+
conn.close();
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
async function withBrowserSocket(fn) {
|
|
923
|
+
const conn = await acquireBrowserConn();
|
|
924
|
+
try {
|
|
925
|
+
return await fn(conn);
|
|
926
|
+
} finally {
|
|
927
|
+
releaseBrowserConn();
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
class SessionConnection {
|
|
932
|
+
browser;
|
|
933
|
+
sessionId;
|
|
934
|
+
opts;
|
|
935
|
+
detached = false;
|
|
936
|
+
offs = [];
|
|
937
|
+
constructor(browser, sessionId, opts = {}) {
|
|
938
|
+
this.browser = browser;
|
|
939
|
+
this.sessionId = sessionId;
|
|
940
|
+
this.opts = opts;
|
|
941
|
+
}
|
|
942
|
+
send(method, params = {}, opts = {}) {
|
|
943
|
+
if (this.detached)
|
|
944
|
+
return Promise.reject(new CdpError("connection not open"));
|
|
945
|
+
return this.browser.send(method, params, {
|
|
946
|
+
timeoutMs: opts.timeoutMs ?? this.opts.timeoutMs,
|
|
947
|
+
sessionId: opts.sessionId ?? this.sessionId
|
|
948
|
+
});
|
|
949
|
+
}
|
|
950
|
+
on(method, handler) {
|
|
951
|
+
const off = this.browser.on(method, (params, sessionId) => {
|
|
952
|
+
if (sessionId && sessionId !== this.sessionId)
|
|
953
|
+
return;
|
|
954
|
+
handler(params, sessionId);
|
|
955
|
+
});
|
|
956
|
+
this.offs.push(off);
|
|
957
|
+
return off;
|
|
958
|
+
}
|
|
959
|
+
waitFor(method, predicate, timeoutMs = this.opts.timeoutMs ?? DEFAULT_TIMEOUT_MS) {
|
|
960
|
+
return new Promise((resolve, reject) => {
|
|
961
|
+
const timer = setTimeout(() => {
|
|
962
|
+
off();
|
|
963
|
+
reject(new CdpError(`waitFor('${method}') timed out after ${timeoutMs}ms`));
|
|
964
|
+
}, timeoutMs);
|
|
965
|
+
const off = this.on(method, (params) => {
|
|
966
|
+
if (!predicate || predicate(params)) {
|
|
967
|
+
clearTimeout(timer);
|
|
968
|
+
off();
|
|
969
|
+
resolve(params);
|
|
970
|
+
}
|
|
971
|
+
});
|
|
972
|
+
});
|
|
973
|
+
}
|
|
974
|
+
close() {
|
|
975
|
+
if (this.detached)
|
|
976
|
+
return;
|
|
977
|
+
this.detached = true;
|
|
978
|
+
for (const off of this.offs)
|
|
979
|
+
off();
|
|
980
|
+
this.offs.length = 0;
|
|
981
|
+
this.browser.send("Target.detachFromTarget", { sessionId: this.sessionId }).catch(() => {});
|
|
982
|
+
releaseBrowserConn();
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
async function openSession(targetId, opts = {}) {
|
|
986
|
+
const browser = await acquireBrowserConn();
|
|
987
|
+
try {
|
|
988
|
+
const { sessionId } = await browser.send("Target.attachToTarget", { targetId, flatten: true }, { timeoutMs: opts.timeoutMs });
|
|
989
|
+
if (!sessionId)
|
|
990
|
+
throw new CdpError(`Target.attachToTarget returned no sessionId for ${targetId}`);
|
|
991
|
+
return new SessionConnection(browser, sessionId, opts);
|
|
992
|
+
} catch (e) {
|
|
993
|
+
releaseBrowserConn();
|
|
994
|
+
throw e;
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
var shared, opening;
|
|
998
|
+
var init_session = __esm(() => {
|
|
999
|
+
init_client();
|
|
1000
|
+
init_endpoint();
|
|
1001
|
+
});
|
|
1002
|
+
|
|
506
1003
|
// src/client.ts
|
|
507
1004
|
class CdpConnection {
|
|
508
1005
|
wsUrl;
|
|
@@ -630,24 +1127,59 @@ class CdpConnection {
|
|
|
630
1127
|
}
|
|
631
1128
|
}
|
|
632
1129
|
async function httpJson(path) {
|
|
633
|
-
const res = await fetch(`${
|
|
1130
|
+
const res = await fetch(`${currentEndpoint().base}${path}`);
|
|
634
1131
|
if (!res.ok)
|
|
635
1132
|
throw new CdpError(`${path} -> HTTP ${res.status}`);
|
|
636
1133
|
return await res.json();
|
|
637
1134
|
}
|
|
638
|
-
function
|
|
639
|
-
|
|
1135
|
+
async function getTargetsOverBrowserWs() {
|
|
1136
|
+
const { targetInfos } = await withBrowserSocket((conn) => conn.send("Target.getTargets", { filter: [{}] }));
|
|
1137
|
+
return targetInfos.map((t) => ({
|
|
1138
|
+
id: t.targetId,
|
|
1139
|
+
type: t.type,
|
|
1140
|
+
title: t.title,
|
|
1141
|
+
url: t.url,
|
|
1142
|
+
webSocketDebuggerUrl: "",
|
|
1143
|
+
...t.openerId ? { parentId: t.openerId } : {}
|
|
1144
|
+
}));
|
|
1145
|
+
}
|
|
1146
|
+
async function listTargets() {
|
|
1147
|
+
const base = currentEndpoint().base;
|
|
1148
|
+
if (knownTransports.get(base) === "browser-ws")
|
|
1149
|
+
return getTargetsOverBrowserWs();
|
|
1150
|
+
try {
|
|
1151
|
+
const listing = await httpJson("/json/list");
|
|
1152
|
+
knownTransports.set(base, "http");
|
|
1153
|
+
return listing;
|
|
1154
|
+
} catch (httpError) {
|
|
1155
|
+
const detected = await detectEndpoint().catch(() => {
|
|
1156
|
+
return;
|
|
1157
|
+
});
|
|
1158
|
+
if (detected?.transport !== "browser-ws")
|
|
1159
|
+
throw httpError;
|
|
1160
|
+
const targets = await getTargetsOverBrowserWs().catch(() => {
|
|
1161
|
+
throw httpError;
|
|
1162
|
+
});
|
|
1163
|
+
knownTransports.set(base, "browser-ws");
|
|
1164
|
+
return targets;
|
|
1165
|
+
}
|
|
640
1166
|
}
|
|
641
1167
|
async function browserWsUrl() {
|
|
642
|
-
|
|
643
|
-
|
|
1168
|
+
if (knownTransports.get(currentEndpoint().base) !== "browser-ws") {
|
|
1169
|
+
const version = await httpJson("/json/version").catch(() => {
|
|
1170
|
+
return;
|
|
1171
|
+
});
|
|
1172
|
+
if (version?.webSocketDebuggerUrl)
|
|
1173
|
+
return version.webSocketDebuggerUrl;
|
|
1174
|
+
}
|
|
1175
|
+
return (await detectEndpoint()).browserWsUrl;
|
|
644
1176
|
}
|
|
645
1177
|
async function resolveTarget(selector, opts = {}) {
|
|
646
1178
|
const targets = await listTargets();
|
|
647
1179
|
const hit = await pickTarget(targets, selector);
|
|
648
1180
|
if (isWorkerTargetType(hit.type))
|
|
649
1181
|
return hit;
|
|
650
|
-
await assertLeaseOk(
|
|
1182
|
+
await assertLeaseOk(chromeLeaseBackend(), hit.id, { lease: opts.lease, url: hit.url, title: hit.title });
|
|
651
1183
|
return hit;
|
|
652
1184
|
}
|
|
653
1185
|
async function pickTarget(targets, selector) {
|
|
@@ -679,7 +1211,7 @@ async function pickTarget(targets, selector) {
|
|
|
679
1211
|
}
|
|
680
1212
|
if (selector.startsWith("label:")) {
|
|
681
1213
|
const label = selector.slice(6);
|
|
682
|
-
const { matchIds, knownLabels } = await resolveLiveLabel(
|
|
1214
|
+
const { matchIds, knownLabels } = await resolveLiveLabel(chromeLeaseBackend(), label, pages.map((t) => t.id));
|
|
683
1215
|
if (matchIds.length > 1) {
|
|
684
1216
|
throw new CdpError(`label 'label:${label}' matches more than one live target: ${matchIds.join(", ")}. Resolve by target id instead.`);
|
|
685
1217
|
}
|
|
@@ -722,7 +1254,7 @@ async function openBrowser(opts = {}) {
|
|
|
722
1254
|
}
|
|
723
1255
|
async function openPage(selector, opts = {}) {
|
|
724
1256
|
const target = await resolveTarget(selector, { lease: opts.lease });
|
|
725
|
-
const conn = await new CdpConnection(target.webSocketDebuggerUrl, opts).connect();
|
|
1257
|
+
const conn = target.webSocketDebuggerUrl ? await new CdpConnection(target.webSocketDebuggerUrl, opts).connect() : await openSession(target.id, opts);
|
|
726
1258
|
return { conn, target };
|
|
727
1259
|
}
|
|
728
1260
|
async function withPage(selector, fn, opts = {}) {
|
|
@@ -733,13 +1265,23 @@ async function withPage(selector, fn, opts = {}) {
|
|
|
733
1265
|
conn.close();
|
|
734
1266
|
}
|
|
735
1267
|
}
|
|
736
|
-
var BASE, DEFAULT_TIMEOUT_MS, CdpError;
|
|
1268
|
+
var BASE, DEFAULT_TIMEOUT_MS, CdpError, knownTransports;
|
|
737
1269
|
var init_client = __esm(() => {
|
|
738
1270
|
init_leases();
|
|
739
1271
|
init_origins();
|
|
1272
|
+
init_endpoints();
|
|
740
1273
|
init_workers();
|
|
741
1274
|
init_frames();
|
|
742
|
-
|
|
1275
|
+
init_endpoint();
|
|
1276
|
+
init_session();
|
|
1277
|
+
init_session();
|
|
1278
|
+
BASE = (() => {
|
|
1279
|
+
try {
|
|
1280
|
+
return defaultEndpoint().base;
|
|
1281
|
+
} catch {
|
|
1282
|
+
return process.env.CDP_BASE ?? DEFAULT_CDP_BASE;
|
|
1283
|
+
}
|
|
1284
|
+
})();
|
|
743
1285
|
DEFAULT_TIMEOUT_MS = Number(process.env.CDP_TIMEOUT_MS ?? 15000);
|
|
744
1286
|
CdpError = class CdpError extends Error {
|
|
745
1287
|
code;
|
|
@@ -751,6 +1293,7 @@ var init_client = __esm(() => {
|
|
|
751
1293
|
this.name = "CdpError";
|
|
752
1294
|
}
|
|
753
1295
|
};
|
|
1296
|
+
knownTransports = new Map;
|
|
754
1297
|
});
|
|
755
1298
|
|
|
756
1299
|
// src/activity.ts
|
|
@@ -1067,8 +1610,8 @@ var init_network_mock = __esm(() => {
|
|
|
1067
1610
|
});
|
|
1068
1611
|
|
|
1069
1612
|
// src/driver.ts
|
|
1070
|
-
import { mkdir as mkdir3, readFile as
|
|
1071
|
-
import { join as
|
|
1613
|
+
import { mkdir as mkdir3, readFile as readFile4, unlink as unlink3, writeFile as writeFile3 } from "node:fs/promises";
|
|
1614
|
+
import { join as join4 } from "node:path";
|
|
1072
1615
|
function isDriverError(e) {
|
|
1073
1616
|
return e instanceof Error && typeof e.code === "string";
|
|
1074
1617
|
}
|
|
@@ -1084,11 +1627,11 @@ function isTiledCapture(delivery) {
|
|
|
1084
1627
|
return delivery.tiled === true;
|
|
1085
1628
|
}
|
|
1086
1629
|
function viewportRecordFile(scheme, targetId) {
|
|
1087
|
-
return
|
|
1630
|
+
return join4(leaseDir(), `viewport-${scheme}-${targetId.replace(/[^A-Za-z0-9._-]/g, "_")}.json`);
|
|
1088
1631
|
}
|
|
1089
1632
|
async function readViewportRecord(scheme, targetId) {
|
|
1090
1633
|
try {
|
|
1091
|
-
const raw = JSON.parse(await
|
|
1634
|
+
const raw = JSON.parse(await readFile4(viewportRecordFile(scheme, targetId), "utf8"));
|
|
1092
1635
|
if (typeof raw?.width !== "number" || typeof raw?.height !== "number")
|
|
1093
1636
|
return;
|
|
1094
1637
|
return {
|
|
@@ -1139,9 +1682,326 @@ var init_driver = __esm(() => {
|
|
|
1139
1682
|
};
|
|
1140
1683
|
});
|
|
1141
1684
|
|
|
1685
|
+
// src/bidi/snapshot.ts
|
|
1686
|
+
async function takeStampedSnapshot(evaluate) {
|
|
1687
|
+
const raw = await evaluate(buildSnapshotFunctionSource());
|
|
1688
|
+
return coerceSnapshotResult(raw);
|
|
1689
|
+
}
|
|
1690
|
+
function coerceSnapshotResult(raw) {
|
|
1691
|
+
if (typeof raw !== "object" || raw === null || typeof raw.snapshot !== "string" || typeof raw.nodeCount !== "number") {
|
|
1692
|
+
throw new Error("takeStampedSnapshot: evaluate() returned an unexpected shape");
|
|
1693
|
+
}
|
|
1694
|
+
return { snapshot: raw.snapshot, nodeCount: raw.nodeCount };
|
|
1695
|
+
}
|
|
1696
|
+
function buildSnapshotFunctionSource() {
|
|
1697
|
+
return `function() {
|
|
1698
|
+
var STAMP_ATTR = ${JSON.stringify(STAMP_ATTR)};
|
|
1699
|
+
var MAX_NAME_LENGTH = ${MAX_NAME_LENGTH};
|
|
1700
|
+
var lines = [];
|
|
1701
|
+
var nodeCount = 0;
|
|
1702
|
+
|
|
1703
|
+
// THE UID CODEC (driver.ts) documents a bidi payload as exactly 12 lowercase hex chars,
|
|
1704
|
+
// /^[0-9a-f]{12}$/. Build it from two padded random blocks so the length is exact regardless
|
|
1705
|
+
// of the random value drawn, never from string concatenation that could come up short.
|
|
1706
|
+
function nextStamp() {
|
|
1707
|
+
var hi = Math.floor(Math.random() * 0x100000000).toString(16).padStart(8, "0");
|
|
1708
|
+
var lo = Math.floor(Math.random() * 0x10000).toString(16).padStart(4, "0");
|
|
1709
|
+
return hi + lo;
|
|
1710
|
+
}
|
|
1711
|
+
|
|
1712
|
+
function stampOf(el) {
|
|
1713
|
+
var existing = el.getAttribute(STAMP_ATTR);
|
|
1714
|
+
if (existing) return existing;
|
|
1715
|
+
var stamp = nextStamp();
|
|
1716
|
+
el.setAttribute(STAMP_ATTR, stamp);
|
|
1717
|
+
return stamp;
|
|
1718
|
+
}
|
|
1719
|
+
|
|
1720
|
+
// skipSizeCheck exempts <option>/<optgroup> from the zero-size prune: a
|
|
1721
|
+
// closed select's popup is unpainted (0x0) though its options are still
|
|
1722
|
+
// present and pickable. Other visibility rules still apply to them.
|
|
1723
|
+
function isVisible(el, skipSizeCheck) {
|
|
1724
|
+
if (el.hidden) return false;
|
|
1725
|
+
if (el.getAttribute("aria-hidden") === "true") return false;
|
|
1726
|
+
var style;
|
|
1727
|
+
try {
|
|
1728
|
+
style = el.ownerDocument.defaultView.getComputedStyle(el);
|
|
1729
|
+
} catch (e) {
|
|
1730
|
+
style = null;
|
|
1731
|
+
}
|
|
1732
|
+
if (style) {
|
|
1733
|
+
if (style.display === "none" || style.visibility === "hidden") return false;
|
|
1734
|
+
}
|
|
1735
|
+
if (!skipSizeCheck) {
|
|
1736
|
+
var rect = el.getBoundingClientRect();
|
|
1737
|
+
if (rect.width === 0 && rect.height === 0) return false;
|
|
1738
|
+
}
|
|
1739
|
+
return true;
|
|
1740
|
+
}
|
|
1741
|
+
|
|
1742
|
+
${ACCNAME_HELPERS_SOURCE}
|
|
1743
|
+
|
|
1744
|
+
function headingLevel(el) {
|
|
1745
|
+
var m = /^H([1-6])$/.exec(el.tagName);
|
|
1746
|
+
return m ? m[1] : null;
|
|
1747
|
+
}
|
|
1748
|
+
|
|
1749
|
+
function currentValue(el) {
|
|
1750
|
+
var tag = el.tagName;
|
|
1751
|
+
if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") {
|
|
1752
|
+
return el.value;
|
|
1753
|
+
}
|
|
1754
|
+
if (el.isContentEditable) return textOf(el);
|
|
1755
|
+
return undefined;
|
|
1756
|
+
}
|
|
1757
|
+
|
|
1758
|
+
function isChecked(el) {
|
|
1759
|
+
var tag = el.tagName;
|
|
1760
|
+
if (tag === "INPUT") {
|
|
1761
|
+
var type = (el.getAttribute("type") || "").toLowerCase();
|
|
1762
|
+
if (type === "checkbox" || type === "radio") return !!el.checked;
|
|
1763
|
+
}
|
|
1764
|
+
var aria = el.getAttribute("aria-checked");
|
|
1765
|
+
if (aria === "true") return true;
|
|
1766
|
+
return false;
|
|
1767
|
+
}
|
|
1768
|
+
|
|
1769
|
+
function describeNode(el, role) {
|
|
1770
|
+
var contentNamed = !!CONTENT_NAMED_ROLES[role];
|
|
1771
|
+
var name = accessibleName(el, contentNamed);
|
|
1772
|
+
var extras = [];
|
|
1773
|
+
var value = currentValue(el);
|
|
1774
|
+
if (value !== undefined && value !== "") extras.push("value=" + JSON.stringify(String(value)));
|
|
1775
|
+
if (isChecked(el)) extras.push("checked=true");
|
|
1776
|
+
if (el.tagName === "OPTION" && el.selected) extras.push("selected");
|
|
1777
|
+
var href = el.getAttribute("href");
|
|
1778
|
+
if (href) extras.push("url=" + href);
|
|
1779
|
+
if (el.disabled || el.getAttribute("aria-disabled") === "true") extras.push("disabled");
|
|
1780
|
+
var level = headingLevel(el);
|
|
1781
|
+
if (level) extras.push("level=" + level);
|
|
1782
|
+
var label = name ? " " + JSON.stringify(name) : "";
|
|
1783
|
+
var extra = extras.length ? " [" + extras.join(" ") + "]" : "";
|
|
1784
|
+
return { role: role, label: label, extra: extra, name: name };
|
|
1785
|
+
}
|
|
1786
|
+
|
|
1787
|
+
// Traverses light DOM, open shadow roots, and same-origin iframe documents.
|
|
1788
|
+
// A cross-origin iframe throws on contentDocument access; caught and
|
|
1789
|
+
// skipped rather than aborting the whole walk, and noted in a comment
|
|
1790
|
+
// here rather than silently vanishing from the tree without a trace.
|
|
1791
|
+
function walk(root, depth) {
|
|
1792
|
+
var children = root.children ? Array.prototype.slice.call(root.children) : [];
|
|
1793
|
+
for (var i = 0; i < children.length; i++) {
|
|
1794
|
+
var el = children[i];
|
|
1795
|
+
var isSelectChild = el.tagName === "OPTION" || el.tagName === "OPTGROUP";
|
|
1796
|
+
if (!isVisible(el, isSelectChild)) continue;
|
|
1797
|
+
|
|
1798
|
+
var role = implicitRole(el);
|
|
1799
|
+
var isLandmarkOrControl = !!role;
|
|
1800
|
+
var described = null;
|
|
1801
|
+
if (isLandmarkOrControl) {
|
|
1802
|
+
described = describeNode(el, role);
|
|
1803
|
+
}
|
|
1804
|
+
|
|
1805
|
+
var hasContent = described && (described.name || described.extra);
|
|
1806
|
+
var isStructural = isLandmarkOrControl && (hasContent || isInteractiveRole(role) || isLandmarkRole(role));
|
|
1807
|
+
|
|
1808
|
+
// Role-less visible leaf text (measured vs Chrome's take_snapshot,
|
|
1809
|
+
// which keeps a StaticText under a generic wrapper for this case,
|
|
1810
|
+
// e.g. a plain status <div>). Only a leaf (no element children, so
|
|
1811
|
+
// its text is not already captured by a nested control/label).
|
|
1812
|
+
var hasElementChildren = !!(el.children && el.children.length > 0);
|
|
1813
|
+
var leafName = !isStructural && !hasElementChildren ? truncate(textOf(el)) : "";
|
|
1814
|
+
var isLeafText = !!leafName;
|
|
1815
|
+
|
|
1816
|
+
var nextDepth = depth;
|
|
1817
|
+
if (isStructural || isLeafText) {
|
|
1818
|
+
var stamp = stampOf(el);
|
|
1819
|
+
var indent = new Array(depth + 1).join(" ");
|
|
1820
|
+
var lineTail = isStructural
|
|
1821
|
+
? described.role + described.label + described.extra
|
|
1822
|
+
: "text " + JSON.stringify(leafName);
|
|
1823
|
+
lines.push(indent + "[" + stamp + "] " + lineTail);
|
|
1824
|
+
nodeCount += 1;
|
|
1825
|
+
nextDepth = depth + 1;
|
|
1826
|
+
}
|
|
1827
|
+
|
|
1828
|
+
if (el.shadowRoot) {
|
|
1829
|
+
walk(el.shadowRoot, nextDepth);
|
|
1830
|
+
} else if (el.tagName === "IFRAME") {
|
|
1831
|
+
try {
|
|
1832
|
+
var doc = el.contentDocument;
|
|
1833
|
+
if (doc && doc.body) walk(doc.body, nextDepth);
|
|
1834
|
+
} catch (e) {
|
|
1835
|
+
// cross-origin iframe: intentionally skipped, not silently merged
|
|
1836
|
+
// into the parent tree as though it were empty.
|
|
1837
|
+
}
|
|
1838
|
+
} else {
|
|
1839
|
+
walk(el, nextDepth);
|
|
1840
|
+
}
|
|
1841
|
+
}
|
|
1842
|
+
}
|
|
1843
|
+
|
|
1844
|
+
function isInteractiveRole(role) {
|
|
1845
|
+
return (
|
|
1846
|
+
role === "button" ||
|
|
1847
|
+
role === "link" ||
|
|
1848
|
+
role === "textbox" ||
|
|
1849
|
+
role === "searchbox" ||
|
|
1850
|
+
role === "checkbox" ||
|
|
1851
|
+
role === "radio" ||
|
|
1852
|
+
role === "combobox" ||
|
|
1853
|
+
role === "listbox" ||
|
|
1854
|
+
role === "option" ||
|
|
1855
|
+
role === "slider" ||
|
|
1856
|
+
role === "spinbutton" ||
|
|
1857
|
+
role === "progressbar" ||
|
|
1858
|
+
role === "meter"
|
|
1859
|
+
);
|
|
1860
|
+
}
|
|
1861
|
+
|
|
1862
|
+
function isLandmarkRole(role) {
|
|
1863
|
+
return (
|
|
1864
|
+
role === "navigation" ||
|
|
1865
|
+
role === "main" ||
|
|
1866
|
+
role === "form" ||
|
|
1867
|
+
role === "dialog" ||
|
|
1868
|
+
role === "region" ||
|
|
1869
|
+
role === "heading" ||
|
|
1870
|
+
role === "list" ||
|
|
1871
|
+
role === "listitem" ||
|
|
1872
|
+
role === "table" ||
|
|
1873
|
+
role === "row" ||
|
|
1874
|
+
role === "cell" ||
|
|
1875
|
+
role === "columnheader" ||
|
|
1876
|
+
role === "img"
|
|
1877
|
+
);
|
|
1878
|
+
}
|
|
1879
|
+
|
|
1880
|
+
walk(document.body, 0);
|
|
1881
|
+
return { snapshot: lines.join("\\n"), nodeCount: nodeCount };
|
|
1882
|
+
}`;
|
|
1883
|
+
}
|
|
1884
|
+
var STAMP_ATTR = "data-cdp-uid", ACCNAME_HELPERS_SOURCE = `
|
|
1885
|
+
function truncate(s) {
|
|
1886
|
+
s = s.trim().replace(/\\s+/g, " ");
|
|
1887
|
+
if (s.length > MAX_NAME_LENGTH) return s.slice(0, MAX_NAME_LENGTH - 1) + "\\u2026";
|
|
1888
|
+
return s;
|
|
1889
|
+
}
|
|
1890
|
+
|
|
1891
|
+
function textOf(el) {
|
|
1892
|
+
return el.textContent || "";
|
|
1893
|
+
}
|
|
1894
|
+
|
|
1895
|
+
function idRefsText(doc, ids) {
|
|
1896
|
+
var parts = [];
|
|
1897
|
+
var list = ids.trim().split(/\\s+/);
|
|
1898
|
+
for (var i = 0; i < list.length; i++) {
|
|
1899
|
+
var ref = doc.getElementById(list[i]);
|
|
1900
|
+
if (ref) parts.push(textOf(ref));
|
|
1901
|
+
}
|
|
1902
|
+
return parts.join(" ").trim();
|
|
1903
|
+
}
|
|
1904
|
+
|
|
1905
|
+
// Text of a <label>, minus any nested form control's own content: a
|
|
1906
|
+
// label that WRAPS its control ("<label>Color <select>...</select></label>")
|
|
1907
|
+
// would otherwise include every option's text in the control's own name.
|
|
1908
|
+
function labelOwnText(label) {
|
|
1909
|
+
var clone = label.cloneNode(true);
|
|
1910
|
+
var controls = clone.querySelectorAll("input, select, textarea, button");
|
|
1911
|
+
for (var i = 0; i < controls.length; i++) {
|
|
1912
|
+
controls[i].parentNode.removeChild(controls[i]);
|
|
1913
|
+
}
|
|
1914
|
+
return textOf(clone);
|
|
1915
|
+
}
|
|
1916
|
+
|
|
1917
|
+
// Guard: without this, an <option> inside a labelled <select> would
|
|
1918
|
+
// inherit the select's own label via closest("label"), not its text.
|
|
1919
|
+
var LABELABLE_TAGS = { INPUT: 1, TEXTAREA: 1, SELECT: 1, BUTTON: 1, METER: 1, OUTPUT: 1, PROGRESS: 1 };
|
|
1920
|
+
|
|
1921
|
+
function nativeLabelText(el) {
|
|
1922
|
+
if (!LABELABLE_TAGS[el.tagName]) return "";
|
|
1923
|
+
var doc = el.ownerDocument;
|
|
1924
|
+
if (el.id) {
|
|
1925
|
+
var forLabel = doc.querySelector('label[for="' + el.id + '"]');
|
|
1926
|
+
if (forLabel) return labelOwnText(forLabel);
|
|
1927
|
+
}
|
|
1928
|
+
var ancestor = el.closest ? el.closest("label") : null;
|
|
1929
|
+
if (ancestor) return labelOwnText(ancestor);
|
|
1930
|
+
return "";
|
|
1931
|
+
}
|
|
1932
|
+
|
|
1933
|
+
// Reduced accname: aria-labelledby, then aria-label, then native label,
|
|
1934
|
+
// then alt/title/placeholder, then trimmed own text for content-named
|
|
1935
|
+
// elements. Not the full W3C accname algorithm (no recursive traversal
|
|
1936
|
+
// rules for nested presentational content) but covers the common cases.
|
|
1937
|
+
function accessibleName(el, contentNamed) {
|
|
1938
|
+
var doc = el.ownerDocument;
|
|
1939
|
+
var labelledby = el.getAttribute("aria-labelledby");
|
|
1940
|
+
if (labelledby) {
|
|
1941
|
+
var viaIds = idRefsText(doc, labelledby);
|
|
1942
|
+
if (viaIds) return truncate(viaIds);
|
|
1943
|
+
}
|
|
1944
|
+
var ariaLabel = el.getAttribute("aria-label");
|
|
1945
|
+
if (ariaLabel && ariaLabel.trim()) return truncate(ariaLabel);
|
|
1946
|
+
var native = nativeLabelText(el);
|
|
1947
|
+
if (native && native.trim()) return truncate(native);
|
|
1948
|
+
var alt = el.getAttribute("alt");
|
|
1949
|
+
if (alt && alt.trim()) return truncate(alt);
|
|
1950
|
+
var title = el.getAttribute("title");
|
|
1951
|
+
if (title && title.trim()) return truncate(title);
|
|
1952
|
+
var placeholder = el.getAttribute("placeholder");
|
|
1953
|
+
if (placeholder && placeholder.trim()) return truncate(placeholder);
|
|
1954
|
+
if (contentNamed) {
|
|
1955
|
+
var text = textOf(el);
|
|
1956
|
+
if (text && text.trim()) return truncate(text);
|
|
1957
|
+
}
|
|
1958
|
+
return "";
|
|
1959
|
+
}
|
|
1960
|
+
|
|
1961
|
+
var IMPLICIT_ROLE_BY_TAG = {
|
|
1962
|
+
A: "link", BUTTON: "button", NAV: "navigation", MAIN: "main", FORM: "form", DIALOG: "dialog",
|
|
1963
|
+
UL: "list", OL: "list", LI: "listitem", TABLE: "table", TR: "row", TD: "cell", TH: "columnheader",
|
|
1964
|
+
SELECT: "combobox", OPTION: "option", TEXTAREA: "textbox", IMG: "img",
|
|
1965
|
+
H1: "heading", H2: "heading", H3: "heading", H4: "heading", H5: "heading", H6: "heading",
|
|
1966
|
+
PROGRESS: "progressbar", METER: "meter"
|
|
1967
|
+
};
|
|
1968
|
+
|
|
1969
|
+
var INPUT_TYPE_ROLE = {
|
|
1970
|
+
button: "button", submit: "button", reset: "button", checkbox: "checkbox", radio: "radio",
|
|
1971
|
+
range: "slider", number: "spinbutton", search: "searchbox", email: "textbox", tel: "textbox",
|
|
1972
|
+
url: "textbox", password: "textbox", text: "textbox", image: "button"
|
|
1973
|
+
};
|
|
1974
|
+
|
|
1975
|
+
var CONTENT_NAMED_ROLES = {
|
|
1976
|
+
button: true, link: true, heading: true, option: true, cell: true,
|
|
1977
|
+
columnheader: true, listitem: true, menuitem: true, tab: true
|
|
1978
|
+
};
|
|
1979
|
+
|
|
1980
|
+
function implicitRole(el) {
|
|
1981
|
+
var explicit = el.getAttribute("role");
|
|
1982
|
+
if (explicit) return explicit;
|
|
1983
|
+
var tag = el.tagName;
|
|
1984
|
+
if (tag === "INPUT") {
|
|
1985
|
+
var type = (el.getAttribute("type") || "text").toLowerCase();
|
|
1986
|
+
return INPUT_TYPE_ROLE[type] || "textbox";
|
|
1987
|
+
}
|
|
1988
|
+
if (tag === "A" && !el.getAttribute("href")) return "";
|
|
1989
|
+
if (Object.prototype.hasOwnProperty.call(IMPLICIT_ROLE_BY_TAG, tag)) {
|
|
1990
|
+
return IMPLICIT_ROLE_BY_TAG[tag];
|
|
1991
|
+
}
|
|
1992
|
+
// Deliberate divergence: Chrome's real AX tree says "generic" here,
|
|
1993
|
+
// but "textbox" is the useful signal an agent needs. Chrome is out of
|
|
1994
|
+
// step, do not "fix" this toward parity.
|
|
1995
|
+
if (el.isContentEditable) return "textbox";
|
|
1996
|
+
return "";
|
|
1997
|
+
}
|
|
1998
|
+
`, MAX_NAME_LENGTH = 120;
|
|
1999
|
+
|
|
1142
2000
|
// src/cdp/driver.ts
|
|
1143
2001
|
init_client();
|
|
2002
|
+
init_session();
|
|
1144
2003
|
init_leases();
|
|
2004
|
+
init_endpoints();
|
|
1145
2005
|
init_activity();
|
|
1146
2006
|
|
|
1147
2007
|
// src/tools/snapshot.ts
|
|
@@ -1629,7 +2489,7 @@ class CdpPageDriver {
|
|
|
1629
2489
|
await this.conn.send(`${name}.enable`);
|
|
1630
2490
|
}
|
|
1631
2491
|
async dispatchInput(method, params = {}) {
|
|
1632
|
-
return sendInput(this.conn,
|
|
2492
|
+
return sendInput(this.conn, chromeLeaseBackend(), this.info.id, method, params);
|
|
1633
2493
|
}
|
|
1634
2494
|
async ensureDomainSoft(name) {
|
|
1635
2495
|
if (this.enabledDomains.has(name))
|
|
@@ -2223,9 +3083,21 @@ class CdpPageDriver {
|
|
|
2223
3083
|
}
|
|
2224
3084
|
}
|
|
2225
3085
|
var beaconSessions = new BeaconSessions((conn) => conn.close());
|
|
2226
|
-
|
|
3086
|
+
function beaconKey(targetId) {
|
|
3087
|
+
const backend = chromeLeaseBackend(currentEndpoint());
|
|
3088
|
+
return backend === "chrome" ? targetId : `${backend}\x00${targetId}`;
|
|
3089
|
+
}
|
|
3090
|
+
async function openTargetConn(targetId, opts = {}) {
|
|
2227
3091
|
const hit = (await listTargets()).find((t) => t.id === targetId);
|
|
2228
|
-
|
|
3092
|
+
if (!hit)
|
|
3093
|
+
return;
|
|
3094
|
+
if (!hit.webSocketDebuggerUrl)
|
|
3095
|
+
return openSession(targetId, opts).catch(() => {
|
|
3096
|
+
return;
|
|
3097
|
+
});
|
|
3098
|
+
return new CdpConnection(hit.webSocketDebuggerUrl, opts).connect().catch(() => {
|
|
3099
|
+
return;
|
|
3100
|
+
});
|
|
2229
3101
|
}
|
|
2230
3102
|
async function readBeaconOver(conn) {
|
|
2231
3103
|
try {
|
|
@@ -2324,7 +3196,7 @@ class CdpBrowserDriver {
|
|
|
2324
3196
|
return withBrowserConn(async (conn) => {
|
|
2325
3197
|
const res = await conn.send("Target.closeTarget", { targetId: id });
|
|
2326
3198
|
if (res.success !== false)
|
|
2327
|
-
beaconSessions.drop(id);
|
|
3199
|
+
beaconSessions.drop(beaconKey(id));
|
|
2328
3200
|
return { success: res.success ?? true };
|
|
2329
3201
|
});
|
|
2330
3202
|
}
|
|
@@ -2342,19 +3214,15 @@ class CdpBrowserDriver {
|
|
|
2342
3214
|
return new CdpPageDriver(conn, target, this);
|
|
2343
3215
|
}
|
|
2344
3216
|
async installActivityBeacon(targetId) {
|
|
2345
|
-
const
|
|
3217
|
+
const key = beaconKey(targetId);
|
|
3218
|
+
const held = beaconSessions.get(key);
|
|
2346
3219
|
if (held) {
|
|
2347
3220
|
const rearmed = await held.send("Runtime.evaluate", { expression: BEACON_SOURCE, returnByValue: true }).then(() => true).catch(() => false);
|
|
2348
3221
|
if (rearmed)
|
|
2349
3222
|
return true;
|
|
2350
|
-
beaconSessions.drop(
|
|
3223
|
+
beaconSessions.drop(key);
|
|
2351
3224
|
}
|
|
2352
|
-
const
|
|
2353
|
-
return;
|
|
2354
|
-
});
|
|
2355
|
-
if (!wsUrl)
|
|
2356
|
-
return false;
|
|
2357
|
-
const conn = await new CdpConnection(wsUrl).connect().catch(() => {
|
|
3225
|
+
const conn = await openTargetConn(targetId).catch(() => {
|
|
2358
3226
|
return;
|
|
2359
3227
|
});
|
|
2360
3228
|
if (!conn)
|
|
@@ -2367,23 +3235,19 @@ class CdpBrowserDriver {
|
|
|
2367
3235
|
conn.close();
|
|
2368
3236
|
return false;
|
|
2369
3237
|
}
|
|
2370
|
-
beaconSessions.set(
|
|
3238
|
+
beaconSessions.set(key, conn);
|
|
2371
3239
|
return true;
|
|
2372
3240
|
}
|
|
2373
3241
|
async readActivityBeacon(targetId) {
|
|
2374
|
-
const
|
|
3242
|
+
const key = beaconKey(targetId);
|
|
3243
|
+
const held = beaconSessions.get(key);
|
|
2375
3244
|
if (held) {
|
|
2376
3245
|
const value = await readBeaconOver(held);
|
|
2377
3246
|
if (value !== undefined)
|
|
2378
3247
|
return value;
|
|
2379
|
-
beaconSessions.drop(
|
|
3248
|
+
beaconSessions.drop(key);
|
|
2380
3249
|
}
|
|
2381
|
-
const
|
|
2382
|
-
return;
|
|
2383
|
-
});
|
|
2384
|
-
if (!wsUrl)
|
|
2385
|
-
return null;
|
|
2386
|
-
const conn = await new CdpConnection(wsUrl).connect().catch(() => {
|
|
3250
|
+
const conn = await openTargetConn(targetId).catch(() => {
|
|
2387
3251
|
return;
|
|
2388
3252
|
});
|
|
2389
3253
|
if (!conn)
|
|
@@ -2395,20 +3259,14 @@ class CdpBrowserDriver {
|
|
|
2395
3259
|
}
|
|
2396
3260
|
}
|
|
2397
3261
|
async probeRenderer(targetId, timeoutMs = RENDERER_PROBE_TIMEOUT_MS) {
|
|
2398
|
-
const held = beaconSessions.get(targetId);
|
|
3262
|
+
const held = beaconSessions.get(beaconKey(targetId));
|
|
2399
3263
|
if (held)
|
|
2400
3264
|
return probeOver(held, timeoutMs);
|
|
2401
|
-
const
|
|
3265
|
+
const conn = await openTargetConn(targetId, { timeoutMs }).catch(() => {
|
|
2402
3266
|
return;
|
|
2403
3267
|
});
|
|
2404
|
-
if (!
|
|
2405
|
-
return { responsive: false, beaconTs: null };
|
|
2406
|
-
const conn = new CdpConnection(wsUrl, { timeoutMs });
|
|
2407
|
-
try {
|
|
2408
|
-
await conn.connect();
|
|
2409
|
-
} catch {
|
|
3268
|
+
if (!conn)
|
|
2410
3269
|
return { responsive: false, beaconTs: null };
|
|
2411
|
-
}
|
|
2412
3270
|
try {
|
|
2413
3271
|
return await probeOver(conn, timeoutMs);
|
|
2414
3272
|
} finally {
|
|
@@ -2428,6 +3286,7 @@ init_activity();
|
|
|
2428
3286
|
init_origins();
|
|
2429
3287
|
|
|
2430
3288
|
// src/reap.ts
|
|
3289
|
+
init_endpoints();
|
|
2431
3290
|
init_leases();
|
|
2432
3291
|
init_origins();
|
|
2433
3292
|
function staleAgentTabs(input) {
|
|
@@ -2456,6 +3315,11 @@ function reapGraceMs() {
|
|
|
2456
3315
|
const raw = Number(process.env.CDP_REAP_GRACE_MS);
|
|
2457
3316
|
return Number.isFinite(raw) && raw >= 0 ? raw : DEFAULT_REAP_GRACE_MS;
|
|
2458
3317
|
}
|
|
3318
|
+
function reapAllowed(driver) {
|
|
3319
|
+
if (driver.scheme === "bidi")
|
|
3320
|
+
return true;
|
|
3321
|
+
return !currentEndpoint().readOnly;
|
|
3322
|
+
}
|
|
2459
3323
|
async function reapStaleAgentTabs(driver, backend) {
|
|
2460
3324
|
const now = Date.now();
|
|
2461
3325
|
const livePageIds = (await driver.listPages()).map((p) => p.id);
|
|
@@ -2478,7 +3342,7 @@ async function reapStaleAgentTabs(driver, backend) {
|
|
|
2478
3342
|
// src/shared-tools.ts
|
|
2479
3343
|
init_driver();
|
|
2480
3344
|
import { mkdir as mkdir5, writeFile as writeFile4 } from "node:fs/promises";
|
|
2481
|
-
import { dirname as dirname2, join as
|
|
3345
|
+
import { dirname as dirname2, join as join5 } from "node:path";
|
|
2482
3346
|
|
|
2483
3347
|
// src/png.ts
|
|
2484
3348
|
import { once } from "node:events";
|
|
@@ -2998,6 +3862,7 @@ init_activity();
|
|
|
2998
3862
|
init_origins();
|
|
2999
3863
|
init_workers();
|
|
3000
3864
|
init_frames();
|
|
3865
|
+
init_endpoints();
|
|
3001
3866
|
var ARTIFACT_DIR = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
|
|
3002
3867
|
var STATE_DIR = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
|
|
3003
3868
|
|
|
@@ -3007,7 +3872,7 @@ function target3(p) {
|
|
|
3007
3872
|
return { id: p.id, url: p.url, title: p.title };
|
|
3008
3873
|
}
|
|
3009
3874
|
function backendOf(driver) {
|
|
3010
|
-
return driver.scheme === "bidi" ? "firefox" :
|
|
3875
|
+
return driver.scheme === "bidi" ? "firefox" : chromeLeaseBackend();
|
|
3011
3876
|
}
|
|
3012
3877
|
async function withPage2(driver, target, fn) {
|
|
3013
3878
|
const page = await driver.page(target);
|
|
@@ -3095,8 +3960,44 @@ async function reapSet(driver, pages, all) {
|
|
|
3095
3960
|
}
|
|
3096
3961
|
}
|
|
3097
3962
|
async function listPages(driver, args = {}) {
|
|
3963
|
+
const one = { all: args.all, probe: args.probe };
|
|
3964
|
+
if (args.allEndpoints === true) {
|
|
3965
|
+
if (driver.scheme === "bidi")
|
|
3966
|
+
throw new SharedToolError("list_pages: allEndpoints needs the Chrome backend; named endpoints are CDP-only");
|
|
3967
|
+
const results = await Promise.all(allEndpoints().map((ep) => withEndpointScope(ep, () => listPagesOne(driver, one)).then((r) => ({ ep, r }), (e) => ({ ep, error: e instanceof Error ? e.message : String(e) }))));
|
|
3968
|
+
const pages = [];
|
|
3969
|
+
const reaped = [];
|
|
3970
|
+
const endpoints = [];
|
|
3971
|
+
for (const res of results) {
|
|
3972
|
+
const { ep } = res;
|
|
3973
|
+
if ("error" in res) {
|
|
3974
|
+
endpoints.push({ endpoint: ep.name, base: ep.base, readOnly: ep.readOnly, down: true, error: res.error });
|
|
3975
|
+
continue;
|
|
3976
|
+
}
|
|
3977
|
+
for (const p of res.r.pages)
|
|
3978
|
+
pages.push({ ...p, endpoint: ep.name });
|
|
3979
|
+
for (const t of res.r.reaped ?? [])
|
|
3980
|
+
reaped.push({ ...t, endpoint: ep.name });
|
|
3981
|
+
endpoints.push({ endpoint: ep.name, base: ep.base, readOnly: ep.readOnly, count: res.r.count });
|
|
3982
|
+
}
|
|
3983
|
+
return { pages, count: pages.length, ...reaped.length ? { reaped } : {}, endpoints };
|
|
3984
|
+
}
|
|
3985
|
+
const res = await listPagesOne(driver, one);
|
|
3986
|
+
if (driver.scheme !== "bidi") {
|
|
3987
|
+
const ep = currentEndpoint();
|
|
3988
|
+
if (!isDefaultEndpoint(ep)) {
|
|
3989
|
+
return {
|
|
3990
|
+
...res,
|
|
3991
|
+
pages: res.pages.map((p) => ({ ...p, endpoint: ep.name })),
|
|
3992
|
+
...res.reaped ? { reaped: res.reaped.map((t) => ({ ...t, endpoint: ep.name })) } : {}
|
|
3993
|
+
};
|
|
3994
|
+
}
|
|
3995
|
+
}
|
|
3996
|
+
return res;
|
|
3997
|
+
}
|
|
3998
|
+
async function listPagesOne(driver, args = {}) {
|
|
3098
3999
|
const backend = backendOf(driver);
|
|
3099
|
-
const reaped = requireLease() ? await reapStaleAgentTabs(driver, backend) : [];
|
|
4000
|
+
const reaped = requireLease() && reapAllowed(driver) ? await reapStaleAgentTabs(driver, backend) : [];
|
|
3100
4001
|
const reapedIds = new Set(reaped.map((r) => r.targetId));
|
|
3101
4002
|
const pages = (await driver.listPages({ all: args.all })).filter((p) => !reapedIds.has(p.id));
|
|
3102
4003
|
const ledger = await originIndex(backend, await reapSet(driver, pages, args.all));
|
|
@@ -3146,7 +4047,7 @@ async function closePage(driver, args) {
|
|
|
3146
4047
|
}
|
|
3147
4048
|
async function writeSelectedFile(id) {
|
|
3148
4049
|
await mkdir5(STATE_DIR, { recursive: true });
|
|
3149
|
-
await writeFile4(
|
|
4050
|
+
await writeFile4(join5(STATE_DIR, "selected"), id, "utf8");
|
|
3150
4051
|
}
|
|
3151
4052
|
async function selectPage(driver, args) {
|
|
3152
4053
|
if (args.target === undefined || args.target === "")
|
|
@@ -3210,7 +4111,7 @@ function serializeForSink(value) {
|
|
|
3210
4111
|
return json ?? "null";
|
|
3211
4112
|
}
|
|
3212
4113
|
async function writeJsonSink(savePath, value) {
|
|
3213
|
-
const path = savePath.startsWith("/") ? savePath :
|
|
4114
|
+
const path = savePath.startsWith("/") ? savePath : join5(ARTIFACT_DIR, savePath);
|
|
3214
4115
|
await mkdir5(dirname2(path), { recursive: true });
|
|
3215
4116
|
const json = serializeForSink(value);
|
|
3216
4117
|
await writeFile4(path, json, "utf8");
|
|
@@ -3354,10 +4255,45 @@ async function takeSnapshot(driver, args = {}) {
|
|
|
3354
4255
|
`), target: target3(page.info), nodeCount: nodes.length };
|
|
3355
4256
|
});
|
|
3356
4257
|
}
|
|
4258
|
+
function describeElementSource() {
|
|
4259
|
+
return `function() {
|
|
4260
|
+
var MAX_NAME_LENGTH = ${MAX_NAME_LENGTH};
|
|
4261
|
+
${ACCNAME_HELPERS_SOURCE}
|
|
4262
|
+
var el = this;
|
|
4263
|
+
if (!el || el.nodeType !== 1) return null;
|
|
4264
|
+
var role = implicitRole(el);
|
|
4265
|
+
var name = accessibleName(el, !!CONTENT_NAMED_ROLES[role]);
|
|
4266
|
+
if (!name) name = truncate(el.innerText || el.textContent || "");
|
|
4267
|
+
return (role || el.tagName.toLowerCase()) + (name ? " " + JSON.stringify(name) : "");
|
|
4268
|
+
}`;
|
|
4269
|
+
}
|
|
4270
|
+
var DESCRIBE_TIMEOUT_MS = 2000;
|
|
4271
|
+
async function describeElement(page, loc) {
|
|
4272
|
+
let timer;
|
|
4273
|
+
try {
|
|
4274
|
+
const timeout = new Promise((r) => {
|
|
4275
|
+
timer = setTimeout(() => r(undefined), DESCRIBE_TIMEOUT_MS);
|
|
4276
|
+
});
|
|
4277
|
+
const desc = await Promise.race([page.callOnElement(loc, describeElementSource()), timeout]);
|
|
4278
|
+
return typeof desc === "string" && desc.length > 0 ? desc : undefined;
|
|
4279
|
+
} catch {
|
|
4280
|
+
return;
|
|
4281
|
+
} finally {
|
|
4282
|
+
clearTimeout(timer);
|
|
4283
|
+
}
|
|
4284
|
+
}
|
|
4285
|
+
function isElementLocator(d) {
|
|
4286
|
+
return !("x" in d) && !("dx" in d);
|
|
4287
|
+
}
|
|
4288
|
+
function elementField(element) {
|
|
4289
|
+
return element === undefined ? {} : { element };
|
|
4290
|
+
}
|
|
3357
4291
|
async function click(driver, args) {
|
|
4292
|
+
const loc = locatorOf(args);
|
|
3358
4293
|
return withPage2(driver, args.target, async (page) => {
|
|
3359
|
-
const
|
|
3360
|
-
|
|
4294
|
+
const element = await describeElement(page, loc);
|
|
4295
|
+
const { x, y } = await page.click(loc, { button: args.button ?? "left", clickCount: args.clickCount ?? 1, modifiers: args.modifiers });
|
|
4296
|
+
return { clicked: true, ...elementField(element), x, y };
|
|
3361
4297
|
});
|
|
3362
4298
|
}
|
|
3363
4299
|
function resolveScrollAnchor(args) {
|
|
@@ -3393,9 +4329,11 @@ async function scroll(driver, args) {
|
|
|
3393
4329
|
});
|
|
3394
4330
|
}
|
|
3395
4331
|
async function hover(driver, args) {
|
|
4332
|
+
const loc = locatorOf(args);
|
|
3396
4333
|
return withPage2(driver, args.target, async (page) => {
|
|
3397
|
-
const
|
|
3398
|
-
|
|
4334
|
+
const element = await describeElement(page, loc);
|
|
4335
|
+
const { x, y } = await page.hover(loc);
|
|
4336
|
+
return { hovered: true, ...elementField(element), x, y };
|
|
3399
4337
|
});
|
|
3400
4338
|
}
|
|
3401
4339
|
function resolveDragTo(to) {
|
|
@@ -3461,16 +4399,29 @@ async function drag(driver, args) {
|
|
|
3461
4399
|
const steps = resolveDragSteps(args.steps);
|
|
3462
4400
|
const mode = resolveDragMode(args.mode, driver.capabilities);
|
|
3463
4401
|
return withPage2(driver, args.target, async (page) => {
|
|
3464
|
-
const
|
|
3465
|
-
|
|
4402
|
+
const fromLoc = locatorOf(args.from);
|
|
4403
|
+
const element = await describeElement(page, fromLoc);
|
|
4404
|
+
const targetElement = isElementLocator(destination) ? await describeElement(page, destination) : undefined;
|
|
4405
|
+
const { from, to } = await page.drag(fromLoc, destination, { mode, steps });
|
|
4406
|
+
return {
|
|
4407
|
+
dragged: true,
|
|
4408
|
+
...elementField(element),
|
|
4409
|
+
...targetElement === undefined ? {} : { target_element: targetElement },
|
|
4410
|
+
mode,
|
|
4411
|
+
steps,
|
|
4412
|
+
from,
|
|
4413
|
+
to
|
|
4414
|
+
};
|
|
3466
4415
|
});
|
|
3467
4416
|
}
|
|
3468
4417
|
async function fill(driver, args) {
|
|
3469
4418
|
if (typeof args.value !== "string")
|
|
3470
4419
|
throw new SharedToolError("fill requires a string { value }");
|
|
4420
|
+
const loc = locatorOf(args);
|
|
3471
4421
|
return withPage2(driver, args.target, async (page) => {
|
|
3472
|
-
await page
|
|
3473
|
-
|
|
4422
|
+
const element = await describeElement(page, loc);
|
|
4423
|
+
await page.setValue(loc, args.value);
|
|
4424
|
+
return { filled: true, ...elementField(element), value: args.value };
|
|
3474
4425
|
});
|
|
3475
4426
|
}
|
|
3476
4427
|
async function fillForm(driver, args) {
|
|
@@ -3478,21 +4429,26 @@ async function fillForm(driver, args) {
|
|
|
3478
4429
|
throw new SharedToolError("fill_form requires a non-empty { fields } array");
|
|
3479
4430
|
return withPage2(driver, args.target, async (page) => {
|
|
3480
4431
|
let filled = 0;
|
|
4432
|
+
const elements = [];
|
|
3481
4433
|
for (const f of args.fields) {
|
|
3482
4434
|
if (typeof f.value !== "string")
|
|
3483
4435
|
throw new SharedToolError("each fill_form field requires a string value");
|
|
3484
|
-
|
|
4436
|
+
const loc = locatorOf(f);
|
|
4437
|
+
elements.push(await describeElement(page, loc) ?? null);
|
|
4438
|
+
await page.setValue(loc, f.value);
|
|
3485
4439
|
filled++;
|
|
3486
4440
|
}
|
|
3487
|
-
return { filled, fields: args.fields.length };
|
|
4441
|
+
return { filled, fields: args.fields.length, elements };
|
|
3488
4442
|
});
|
|
3489
4443
|
}
|
|
3490
4444
|
async function typeText(driver, args) {
|
|
3491
4445
|
if (typeof args.text !== "string")
|
|
3492
4446
|
throw new SharedToolError("type_text requires a string { text }");
|
|
4447
|
+
const loc = locatorOf(args);
|
|
3493
4448
|
return withPage2(driver, args.target, async (page) => {
|
|
3494
|
-
await page
|
|
3495
|
-
|
|
4449
|
+
const element = await describeElement(page, loc);
|
|
4450
|
+
await page.typeText(loc, args.text);
|
|
4451
|
+
return { typed: true, ...elementField(element), text: args.text };
|
|
3496
4452
|
});
|
|
3497
4453
|
}
|
|
3498
4454
|
async function pressKey(driver, args) {
|
|
@@ -3510,8 +4466,10 @@ async function uploadFile(driver, args) {
|
|
|
3510
4466
|
throw new SharedToolError("upload_file requires { files } as a non-empty path or array of paths");
|
|
3511
4467
|
}
|
|
3512
4468
|
return withPage2(driver, args.target, async (page) => {
|
|
3513
|
-
|
|
3514
|
-
|
|
4469
|
+
const loc = locatorOf(args);
|
|
4470
|
+
const element = await describeElement(page, loc);
|
|
4471
|
+
await page.setFiles(loc, files);
|
|
4472
|
+
return { uploaded: files, ...elementField(element) };
|
|
3515
4473
|
});
|
|
3516
4474
|
}
|
|
3517
4475
|
function stamp() {
|
|
@@ -3625,7 +4583,7 @@ async function takeScreenshot(driver, args = {}) {
|
|
|
3625
4583
|
return withPage2(driver, args.target, async (page) => {
|
|
3626
4584
|
const clip = args.uid !== undefined || args.selector ? locatorOf(args) : undefined;
|
|
3627
4585
|
const ext = format === "jpeg" ? "jpg" : "png";
|
|
3628
|
-
const path = args.savePath ??
|
|
4586
|
+
const path = args.savePath ?? join5(ARTIFACT_DIR, `screenshot-${page.info.id.slice(0, 8)}-${stamp()}.${ext}`);
|
|
3629
4587
|
const stitch = async (banded) => {
|
|
3630
4588
|
if (format !== "png")
|
|
3631
4589
|
throw tiledCaptureRefusal("format", banded);
|
|
@@ -3737,7 +4695,7 @@ init_leases();
|
|
|
3737
4695
|
class LeaseToolError extends Error {
|
|
3738
4696
|
}
|
|
3739
4697
|
function backendOf2(driver) {
|
|
3740
|
-
return driver.scheme === "bidi" ? "firefox" :
|
|
4698
|
+
return driver.scheme === "bidi" ? "firefox" : chromeLeaseBackend();
|
|
3741
4699
|
}
|
|
3742
4700
|
async function claimPage(driver, args = {}) {
|
|
3743
4701
|
const hasTarget = typeof args.target === "string" && args.target.length > 0;
|
|
@@ -3822,7 +4780,7 @@ async function releasePage(driver, args = {}) {
|
|
|
3822
4780
|
}
|
|
3823
4781
|
async function listLeasesTool(driver, _args = {}) {
|
|
3824
4782
|
const backend = backendOf2(driver);
|
|
3825
|
-
const reaped = requireLease() ? await reapStaleAgentTabs(driver, backend) : [];
|
|
4783
|
+
const reaped = requireLease() && reapAllowed(driver) ? await reapStaleAgentTabs(driver, backend) : [];
|
|
3826
4784
|
const reapedIds = new Set(reaped.map((r) => r.targetId));
|
|
3827
4785
|
const livePages = await driver.listPages();
|
|
3828
4786
|
const liveIds = livePages.map((p) => p.id);
|
|
@@ -3850,7 +4808,7 @@ var LEASE_TOOLS = {
|
|
|
3850
4808
|
|
|
3851
4809
|
// src/tools/console.ts
|
|
3852
4810
|
init_client();
|
|
3853
|
-
import { readFile as
|
|
4811
|
+
import { readFile as readFile5 } from "node:fs/promises";
|
|
3854
4812
|
|
|
3855
4813
|
// src/tools/recorder.ts
|
|
3856
4814
|
init_client();
|
|
@@ -4053,7 +5011,7 @@ function lineToEntry(line, index) {
|
|
|
4053
5011
|
async function readConsoleEntries(file) {
|
|
4054
5012
|
let raw;
|
|
4055
5013
|
try {
|
|
4056
|
-
raw = await
|
|
5014
|
+
raw = await readFile5(file, "utf8");
|
|
4057
5015
|
} catch {
|
|
4058
5016
|
return [];
|
|
4059
5017
|
}
|
|
@@ -4111,7 +5069,7 @@ async function getConsoleMessage(args = {}) {
|
|
|
4111
5069
|
|
|
4112
5070
|
// src/tools/network.ts
|
|
4113
5071
|
init_client();
|
|
4114
|
-
import { readFile as
|
|
5072
|
+
import { readFile as readFile6 } from "node:fs/promises";
|
|
4115
5073
|
var DEFAULT_CAPTURE_MS2 = 2500;
|
|
4116
5074
|
function asHeaders(v) {
|
|
4117
5075
|
if (!v || typeof v !== "object")
|
|
@@ -4178,7 +5136,7 @@ function correlate(lines) {
|
|
|
4178
5136
|
async function readNetworkRequests(file) {
|
|
4179
5137
|
let raw;
|
|
4180
5138
|
try {
|
|
4181
|
-
raw = await
|
|
5139
|
+
raw = await readFile6(file, "utf8");
|
|
4182
5140
|
} catch {
|
|
4183
5141
|
return [];
|
|
4184
5142
|
}
|
|
@@ -4263,8 +5221,8 @@ async function getNetworkRequest(args = {}) {
|
|
|
4263
5221
|
|
|
4264
5222
|
// src/tools/performance.ts
|
|
4265
5223
|
init_client();
|
|
4266
|
-
import { mkdir as mkdir7, readFile as
|
|
4267
|
-
import { join as
|
|
5224
|
+
import { mkdir as mkdir7, readFile as readFile7, writeFile as writeFile6, stat, unlink as unlink4 } from "node:fs/promises";
|
|
5225
|
+
import { join as join6 } from "node:path";
|
|
4268
5226
|
var ARTIFACT_DIR2 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
|
|
4269
5227
|
var STATE_DIR2 = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
|
|
4270
5228
|
var DEFAULT_CATEGORIES = [
|
|
@@ -4282,7 +5240,7 @@ function shortId(id) {
|
|
|
4282
5240
|
return id.slice(0, 8);
|
|
4283
5241
|
}
|
|
4284
5242
|
function stateFilePath() {
|
|
4285
|
-
return
|
|
5243
|
+
return join6(STATE_DIR2, "trace-state.json");
|
|
4286
5244
|
}
|
|
4287
5245
|
function bufferTraceData(conn, sink) {
|
|
4288
5246
|
return conn.on("Tracing.dataCollected", (params) => {
|
|
@@ -4305,7 +5263,7 @@ async function endTrace(conn, sink, timeoutMs = 30000) {
|
|
|
4305
5263
|
}
|
|
4306
5264
|
async function writeTrace(events, targetId) {
|
|
4307
5265
|
await mkdir7(ARTIFACT_DIR2, { recursive: true });
|
|
4308
|
-
const path =
|
|
5266
|
+
const path = join6(ARTIFACT_DIR2, `trace-${shortId(targetId)}-${stamp2()}.json`);
|
|
4309
5267
|
const body = JSON.stringify({ traceEvents: events, metadata: { source: "cdp-toolkit" } });
|
|
4310
5268
|
await writeFile6(path, body, "utf8");
|
|
4311
5269
|
const { size } = await stat(path);
|
|
@@ -4348,7 +5306,7 @@ async function performanceStopTrace(args = {}) {
|
|
|
4348
5306
|
if (!entry) {
|
|
4349
5307
|
let hint = "";
|
|
4350
5308
|
try {
|
|
4351
|
-
const raw = await
|
|
5309
|
+
const raw = await readFile7(stateFilePath(), "utf8");
|
|
4352
5310
|
const state = JSON.parse(raw);
|
|
4353
5311
|
hint = state.pid === process.pid ? ` (state file lists target ${shortId(state.targetId)} but its live connection is gone)` : ` (trace was started by a DIFFERENT process pid=${state.pid}; live recordings cannot cross process boundaries)`;
|
|
4354
5312
|
} catch {}
|
|
@@ -4478,7 +5436,7 @@ async function performanceAnalyzeInsight(args = {}) {
|
|
|
4478
5436
|
}
|
|
4479
5437
|
let raw;
|
|
4480
5438
|
try {
|
|
4481
|
-
raw = await
|
|
5439
|
+
raw = await readFile7(args.tracePath, "utf8");
|
|
4482
5440
|
} catch (err) {
|
|
4483
5441
|
throw new CdpError(`cannot read trace file '${args.tracePath}': ${err.message}`);
|
|
4484
5442
|
}
|
|
@@ -4498,7 +5456,7 @@ async function performanceAnalyzeInsight(args = {}) {
|
|
|
4498
5456
|
init_client();
|
|
4499
5457
|
import { spawn } from "node:child_process";
|
|
4500
5458
|
import { mkdir as mkdir8, rm as rm2, stat as stat2, writeFile as writeFile7 } from "node:fs/promises";
|
|
4501
|
-
import { join as
|
|
5459
|
+
import { join as join7 } from "node:path";
|
|
4502
5460
|
var ARTIFACT_DIR3 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
|
|
4503
5461
|
var FFMPEG_BIN = process.env.CDP_FFMPEG ?? "ffmpeg";
|
|
4504
5462
|
function frameDurationsMs(ledger, stopWallclockMs) {
|
|
@@ -4614,6 +5572,22 @@ function selectEncoder(encodersOutput) {
|
|
|
4614
5572
|
}
|
|
4615
5573
|
throw new CdpError(`ffmpeg reports none of the supported video encoders (${ENCODER_LADDER.map((c) => c.encoder).join(", ")}). ` + "Install a full ffmpeg build: 'brew install ffmpeg' (macOS) or 'apt install ffmpeg' (Debian/Ubuntu).");
|
|
4616
5574
|
}
|
|
5575
|
+
function supportsFpsMode(versionOutput) {
|
|
5576
|
+
const m = /ffmpeg version n?(\d+)\.(\d+)/.exec(versionOutput);
|
|
5577
|
+
if (!m)
|
|
5578
|
+
return /ffmpeg version N-/.test(versionOutput) ? true : undefined;
|
|
5579
|
+
const major = Number(m[1]);
|
|
5580
|
+
const minor = Number(m[2]);
|
|
5581
|
+
return major > 5 || major === 5 && minor >= 1;
|
|
5582
|
+
}
|
|
5583
|
+
function chooseFpsMode(versionOutput, helpOutput) {
|
|
5584
|
+
const byVersion = versionOutput === undefined ? undefined : supportsFpsMode(versionOutput);
|
|
5585
|
+
if (byVersion !== undefined)
|
|
5586
|
+
return byVersion;
|
|
5587
|
+
if (helpOutput !== undefined && /-vsync\b|-fps_mode\b/.test(helpOutput))
|
|
5588
|
+
return /-fps_mode\b/.test(helpOutput);
|
|
5589
|
+
return true;
|
|
5590
|
+
}
|
|
4617
5591
|
function buildFfmpegArgs(manifestPath, outPath, choice) {
|
|
4618
5592
|
return [
|
|
4619
5593
|
"-hide_banner",
|
|
@@ -4626,8 +5600,7 @@ function buildFfmpegArgs(manifestPath, outPath, choice) {
|
|
|
4626
5600
|
"0",
|
|
4627
5601
|
"-i",
|
|
4628
5602
|
manifestPath,
|
|
4629
|
-
"-vsync",
|
|
4630
|
-
"vfr",
|
|
5603
|
+
...choice.fpsMode ? ["-fps_mode", "vfr"] : ["-vsync", "vfr"],
|
|
4631
5604
|
"-vf",
|
|
4632
5605
|
"scale=trunc(iw/2)*2:trunc(ih/2)*2",
|
|
4633
5606
|
"-c:v",
|
|
@@ -4669,8 +5642,19 @@ async function probeEncoder() {
|
|
|
4669
5642
|
}
|
|
4670
5643
|
if (res.code !== 0)
|
|
4671
5644
|
throw new CdpError(`${FFMPEG_MISSING} ('-encoders' exited ${res.code}: ${res.stderr.trim().slice(0, 300)})`);
|
|
4672
|
-
|
|
5645
|
+
const choice = selectEncoder(`${res.stdout}
|
|
4673
5646
|
${res.stderr}`);
|
|
5647
|
+
const output = async (args) => {
|
|
5648
|
+
const r = await run(FFMPEG_BIN, args).catch(() => {
|
|
5649
|
+
return;
|
|
5650
|
+
});
|
|
5651
|
+
return r && r.code === 0 ? `${r.stdout}
|
|
5652
|
+
${r.stderr}` : undefined;
|
|
5653
|
+
};
|
|
5654
|
+
const version = await output(["-version"]);
|
|
5655
|
+
const byVersion = version === undefined ? undefined : supportsFpsMode(version);
|
|
5656
|
+
const help = byVersion === undefined ? await output(["-hide_banner", "-h", "full"]) : undefined;
|
|
5657
|
+
return { ...choice, fpsMode: chooseFpsMode(version, help) };
|
|
4674
5658
|
})();
|
|
4675
5659
|
encoderProbe.catch(() => {
|
|
4676
5660
|
encoderProbe = undefined;
|
|
@@ -4719,7 +5703,7 @@ async function startScreenRecording(args = {}) {
|
|
|
4719
5703
|
conn.close();
|
|
4720
5704
|
throw err;
|
|
4721
5705
|
}
|
|
4722
|
-
const spoolDir =
|
|
5706
|
+
const spoolDir = join7(ARTIFACT_DIR3, `screencast-${shortId2(target.id)}-${stamp3()}`);
|
|
4723
5707
|
try {
|
|
4724
5708
|
await mkdir8(spoolDir, { recursive: true });
|
|
4725
5709
|
} catch (err) {
|
|
@@ -4762,7 +5746,7 @@ async function startScreenRecording(args = {}) {
|
|
|
4762
5746
|
seq += 1;
|
|
4763
5747
|
const file = `frame-${String(seq).padStart(6, "0")}.${ext}`;
|
|
4764
5748
|
rec.ledger.push({ file, timestamp, width: size.width, height: size.height });
|
|
4765
|
-
rec.writes = rec.writes.then(() => writeFile7(
|
|
5749
|
+
rec.writes = rec.writes.then(() => writeFile7(join7(spoolDir, file), buf)).catch(() => {
|
|
4766
5750
|
rec.dropped += 1;
|
|
4767
5751
|
rec.unwritten.add(file);
|
|
4768
5752
|
});
|
|
@@ -4826,9 +5810,9 @@ async function stopScreenRecording(args = {}) {
|
|
|
4826
5810
|
throw new CdpError(`screen recording captured 0 frames for target ${shortId2(rec.target.id)}. Chrome emits a screencast frame only on repaint: a fully backgrounded or occluded tab may never paint. Retry with bringToFront:true, or drive the page while recording.`);
|
|
4827
5811
|
}
|
|
4828
5812
|
await mkdir8(ARTIFACT_DIR3, { recursive: true });
|
|
4829
|
-
const outPath = args.savePath ??
|
|
5813
|
+
const outPath = args.savePath ?? join7(ARTIFACT_DIR3, `screen-recording-${shortId2(rec.target.id)}-${stamp3()}.mp4`);
|
|
4830
5814
|
const frames = coalesceToConcatGrid(ledger, stoppedAt);
|
|
4831
|
-
const manifestPath =
|
|
5815
|
+
const manifestPath = join7(rec.spoolDir, "frames.ffconcat");
|
|
4832
5816
|
await writeFile7(manifestPath, buildConcatManifest(frames), "utf8");
|
|
4833
5817
|
const durationMs = frames.reduce((total, f) => total + f.durationMs, 0);
|
|
4834
5818
|
const { width, height } = evenDimensions(ledger[0].width, ledger[0].height);
|
|
@@ -4862,7 +5846,7 @@ ffmpeg said: ${res.stderr.trim().slice(0, 800)}`);
|
|
|
4862
5846
|
// src/tools/heap.ts
|
|
4863
5847
|
init_client();
|
|
4864
5848
|
import { mkdir as mkdir9, writeFile as writeFile8 } from "node:fs/promises";
|
|
4865
|
-
import { join as
|
|
5849
|
+
import { join as join8 } from "node:path";
|
|
4866
5850
|
var ARTIFACT_DIR4 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
|
|
4867
5851
|
function stamp4(targetId) {
|
|
4868
5852
|
const short = targetId.slice(0, 8);
|
|
@@ -4888,7 +5872,7 @@ async function takeHeapsnapshot(args = {}) {
|
|
|
4888
5872
|
throw new Error("HeapProfiler.takeHeapSnapshot produced no chunks");
|
|
4889
5873
|
}
|
|
4890
5874
|
await mkdir9(ARTIFACT_DIR4, { recursive: true });
|
|
4891
|
-
const path = args.savePath ? args.savePath.startsWith("/") ? args.savePath :
|
|
5875
|
+
const path = args.savePath ? args.savePath.startsWith("/") ? args.savePath : join8(ARTIFACT_DIR4, args.savePath) : join8(ARTIFACT_DIR4, `take_heapsnapshot-${stamp4(target.id)}.heapsnapshot`);
|
|
4892
5876
|
await writeFile8(path, snapshot, "utf8");
|
|
4893
5877
|
const bytes = Buffer.byteLength(snapshot, "utf8");
|
|
4894
5878
|
return {
|
|
@@ -4902,11 +5886,12 @@ async function takeHeapsnapshot(args = {}) {
|
|
|
4902
5886
|
|
|
4903
5887
|
// src/tools/lighthouse.ts
|
|
4904
5888
|
init_client();
|
|
5889
|
+
init_endpoints();
|
|
4905
5890
|
import { spawn as spawn2 } from "node:child_process";
|
|
4906
|
-
import { mkdir as mkdir10, readFile as
|
|
5891
|
+
import { mkdir as mkdir10, readFile as readFile8, stat as stat3 } from "node:fs/promises";
|
|
4907
5892
|
var ARTIFACT_DIR5 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
|
|
4908
5893
|
function cdpPort() {
|
|
4909
|
-
const base =
|
|
5894
|
+
const base = currentEndpoint().base;
|
|
4910
5895
|
const m = base.match(/:(\d+)/);
|
|
4911
5896
|
return m?.[1] ? Number(m[1]) : 9222;
|
|
4912
5897
|
}
|
|
@@ -4993,7 +5978,7 @@ async function lighthouseAudit(args) {
|
|
|
4993
5978
|
}
|
|
4994
5979
|
let raw;
|
|
4995
5980
|
try {
|
|
4996
|
-
raw = await
|
|
5981
|
+
raw = await readFile8(outPath, "utf8");
|
|
4997
5982
|
} catch {
|
|
4998
5983
|
raw = undefined;
|
|
4999
5984
|
}
|
|
@@ -5043,6 +6028,7 @@ init_network_mock();
|
|
|
5043
6028
|
// src/tools/dispatch-mouse.ts
|
|
5044
6029
|
init_activity();
|
|
5045
6030
|
init_client();
|
|
6031
|
+
init_leases();
|
|
5046
6032
|
var CLICK_MODIFIER_BITS2 = { Alt: 1, Control: 2, Meta: 4, Shift: 8 };
|
|
5047
6033
|
var BUTTONS = new Set(["left", "right", "middle"]);
|
|
5048
6034
|
var CDP_EVENT_TYPE = {
|
|
@@ -5079,7 +6065,7 @@ async function dispatchMouse(args) {
|
|
|
5079
6065
|
const params = { type: CDP_EVENT_TYPE[args.action], x: args.x, y: args.y, button, modifiers };
|
|
5080
6066
|
if (args.action !== "move")
|
|
5081
6067
|
params.clickCount = args.clickCount ?? 1;
|
|
5082
|
-
await sendInput(conn,
|
|
6068
|
+
await sendInput(conn, chromeLeaseBackend(), target.id, "Input.dispatchMouseEvent", params);
|
|
5083
6069
|
return { dispatched: args.action, x: args.x, y: args.y };
|
|
5084
6070
|
});
|
|
5085
6071
|
}
|
|
@@ -5087,6 +6073,7 @@ async function dispatchMouse(args) {
|
|
|
5087
6073
|
// src/tools/focus-emulation.ts
|
|
5088
6074
|
init_activity();
|
|
5089
6075
|
init_client();
|
|
6076
|
+
init_leases();
|
|
5090
6077
|
function validateFocusEmulationArgs(args) {
|
|
5091
6078
|
if (typeof args.enabled !== "boolean") {
|
|
5092
6079
|
throw new Error("focus_emulation requires { enabled } of true or false");
|
|
@@ -5153,9 +6140,10 @@ async function clickFocusGated(args) {
|
|
|
5153
6140
|
const btn = result?.value;
|
|
5154
6141
|
if (btn && !btn.disabled) {
|
|
5155
6142
|
const base = { x: btn.x, y: btn.y, button: "left", buttons: 1, clickCount: 1 };
|
|
5156
|
-
|
|
5157
|
-
await sendInput(conn,
|
|
5158
|
-
await sendInput(conn,
|
|
6143
|
+
const backend = chromeLeaseBackend();
|
|
6144
|
+
await sendInput(conn, backend, target.id, "Input.dispatchMouseEvent", { type: "mouseMoved", x: btn.x, y: btn.y });
|
|
6145
|
+
await sendInput(conn, backend, target.id, "Input.dispatchMouseEvent", { ...base, type: "mousePressed" });
|
|
6146
|
+
await sendInput(conn, backend, target.id, "Input.dispatchMouseEvent", { ...base, type: "mouseReleased" });
|
|
5159
6147
|
return {
|
|
5160
6148
|
clicked: true,
|
|
5161
6149
|
x: btn.x,
|
|
@@ -5180,16 +6168,20 @@ async function clickFocusGated(args) {
|
|
|
5180
6168
|
// src/tools/downloads.ts
|
|
5181
6169
|
init_client();
|
|
5182
6170
|
import { readdir as readdir3, rename as rename2, stat as stat4 } from "node:fs/promises";
|
|
5183
|
-
import { basename, extname, join as
|
|
6171
|
+
import { basename, extname, join as join10 } from "node:path";
|
|
5184
6172
|
|
|
5185
6173
|
// src/tools/browser-session.ts
|
|
5186
6174
|
init_client();
|
|
6175
|
+
init_endpoints();
|
|
5187
6176
|
import { mkdir as mkdir11 } from "node:fs/promises";
|
|
5188
|
-
import { join as
|
|
6177
|
+
import { join as join9 } from "node:path";
|
|
5189
6178
|
var ARTIFACT_DIR6 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
|
|
5190
|
-
var DOWNLOADS_DIR =
|
|
6179
|
+
var DOWNLOADS_DIR = join9(ARTIFACT_DIR6, "downloads");
|
|
5191
6180
|
var DOWNLOAD_BUFFER_LIMIT = 50;
|
|
5192
|
-
var
|
|
6181
|
+
var sessions2 = new Map;
|
|
6182
|
+
function sessionKey() {
|
|
6183
|
+
return currentEndpoint().name;
|
|
6184
|
+
}
|
|
5193
6185
|
function isDisconnect(e) {
|
|
5194
6186
|
const m = e instanceof Error ? e.message : String(e);
|
|
5195
6187
|
return /connection (not open|closed)|closed by caller|websocket|ECONNREFUSED|socket/i.test(m);
|
|
@@ -5234,13 +6226,15 @@ function subscribe(s) {
|
|
|
5234
6226
|
});
|
|
5235
6227
|
}
|
|
5236
6228
|
async function getBrowserSession() {
|
|
6229
|
+
const key = sessionKey();
|
|
6230
|
+
const session = sessions2.get(key);
|
|
5237
6231
|
if (session && !session.dead)
|
|
5238
6232
|
return session;
|
|
5239
6233
|
const previousPath = session?.armedPath;
|
|
5240
6234
|
const conn = await openBrowser();
|
|
5241
6235
|
const s = { conn, downloads: [], waiters: [], dead: false };
|
|
5242
6236
|
subscribe(s);
|
|
5243
|
-
|
|
6237
|
+
sessions2.set(key, s);
|
|
5244
6238
|
if (previousPath)
|
|
5245
6239
|
await armDownloadsAt(previousPath);
|
|
5246
6240
|
return s;
|
|
@@ -5271,7 +6265,7 @@ async function armDownloads() {
|
|
|
5271
6265
|
return { downloadPath: DOWNLOADS_DIR };
|
|
5272
6266
|
}
|
|
5273
6267
|
function pendingDownloads() {
|
|
5274
|
-
return (
|
|
6268
|
+
return (sessions2.get(sessionKey())?.downloads ?? []).filter((d) => d.state === "completed" && !d.consumed);
|
|
5275
6269
|
}
|
|
5276
6270
|
async function nextCompletedDownload(timeoutMs) {
|
|
5277
6271
|
const s = await getBrowserSession();
|
|
@@ -5295,14 +6289,14 @@ async function nextCompletedDownload(timeoutMs) {
|
|
|
5295
6289
|
});
|
|
5296
6290
|
}
|
|
5297
6291
|
async function disposeBrowserSession() {
|
|
5298
|
-
const
|
|
5299
|
-
|
|
5300
|
-
|
|
5301
|
-
|
|
5302
|
-
|
|
5303
|
-
|
|
5304
|
-
|
|
5305
|
-
}
|
|
6292
|
+
const all = [...sessions2.values()];
|
|
6293
|
+
sessions2.clear();
|
|
6294
|
+
for (const s of all) {
|
|
6295
|
+
s.dead = true;
|
|
6296
|
+
try {
|
|
6297
|
+
s.conn.close();
|
|
6298
|
+
} catch {}
|
|
6299
|
+
}
|
|
5306
6300
|
}
|
|
5307
6301
|
|
|
5308
6302
|
// src/tools/downloads.ts
|
|
@@ -5349,7 +6343,7 @@ async function waitForDownload(args = {}) {
|
|
|
5349
6343
|
const taken = new Set(await readdir3(DOWNLOADS_DIR).catch(() => []));
|
|
5350
6344
|
taken.delete(basename(rec.filePath));
|
|
5351
6345
|
const finalName = nextFreeName(suggestedFilename, taken);
|
|
5352
|
-
const path =
|
|
6346
|
+
const path = join10(DOWNLOADS_DIR, finalName);
|
|
5353
6347
|
await rename2(rec.filePath, path);
|
|
5354
6348
|
const bytes = (await stat4(path)).size;
|
|
5355
6349
|
return { path, suggestedFilename, bytes, ...rec.url ? { url: rec.url } : {}, target };
|
|
@@ -5408,7 +6402,7 @@ async function grantPermissions(args = {}) {
|
|
|
5408
6402
|
// src/tools/extract.ts
|
|
5409
6403
|
init_client();
|
|
5410
6404
|
import { mkdir as mkdir12, writeFile as writeFile9 } from "node:fs/promises";
|
|
5411
|
-
import { dirname as dirname3, join as
|
|
6405
|
+
import { dirname as dirname3, join as join11 } from "node:path";
|
|
5412
6406
|
var ARTIFACT_DIR7 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
|
|
5413
6407
|
var DEFAULT_BASE_URL = "http://127.0.0.1:8090/v1";
|
|
5414
6408
|
var DEFAULT_MODEL = "schematron";
|
|
@@ -5809,7 +6803,7 @@ async function extractPage(driver, args) {
|
|
|
5809
6803
|
};
|
|
5810
6804
|
if (args.savePath === undefined || args.savePath === "")
|
|
5811
6805
|
return result;
|
|
5812
|
-
const path = args.savePath.startsWith("/") ? args.savePath :
|
|
6806
|
+
const path = args.savePath.startsWith("/") ? args.savePath : join11(ARTIFACT_DIR7, args.savePath);
|
|
5813
6807
|
await mkdir12(dirname3(path), { recursive: true });
|
|
5814
6808
|
const json = JSON.stringify(result, null, 2);
|
|
5815
6809
|
await writeFile9(path, json, "utf8");
|