cdp-toolkit 3.0.3 → 3.1.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 +13 -0
- package/CONTRACT.md +2 -2
- package/README.md +84 -1
- package/dist/bidi/mux-daemon.js +316 -10
- package/dist/cli.js +567 -85
- package/dist/index.js +404 -38
- package/dist/mcp.js +631 -130
- package/package.json +1 -1
- package/src/cdp/driver.ts +20 -9
- package/src/cli.ts +17 -4
- package/src/client.ts +22 -6
- 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 +72 -4
- package/src/toolDocs.ts +39 -36
- package/src/tools/browser-session.ts +26 -12
- package/src/tools/dispatch-mouse.ts +2 -1
- package/src/tools/focus-emulation.ts +5 -3
- package/src/tools/lighthouse.ts +4 -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
|
|
@@ -630,7 +929,7 @@ class CdpConnection {
|
|
|
630
929
|
}
|
|
631
930
|
}
|
|
632
931
|
async function httpJson(path) {
|
|
633
|
-
const res = await fetch(`${
|
|
932
|
+
const res = await fetch(`${currentEndpoint().base}${path}`);
|
|
634
933
|
if (!res.ok)
|
|
635
934
|
throw new CdpError(`${path} -> HTTP ${res.status}`);
|
|
636
935
|
return await res.json();
|
|
@@ -647,7 +946,7 @@ async function resolveTarget(selector, opts = {}) {
|
|
|
647
946
|
const hit = await pickTarget(targets, selector);
|
|
648
947
|
if (isWorkerTargetType(hit.type))
|
|
649
948
|
return hit;
|
|
650
|
-
await assertLeaseOk(
|
|
949
|
+
await assertLeaseOk(chromeLeaseBackend(), hit.id, { lease: opts.lease, url: hit.url, title: hit.title });
|
|
651
950
|
return hit;
|
|
652
951
|
}
|
|
653
952
|
async function pickTarget(targets, selector) {
|
|
@@ -679,7 +978,7 @@ async function pickTarget(targets, selector) {
|
|
|
679
978
|
}
|
|
680
979
|
if (selector.startsWith("label:")) {
|
|
681
980
|
const label = selector.slice(6);
|
|
682
|
-
const { matchIds, knownLabels } = await resolveLiveLabel(
|
|
981
|
+
const { matchIds, knownLabels } = await resolveLiveLabel(chromeLeaseBackend(), label, pages.map((t) => t.id));
|
|
683
982
|
if (matchIds.length > 1) {
|
|
684
983
|
throw new CdpError(`label 'label:${label}' matches more than one live target: ${matchIds.join(", ")}. Resolve by target id instead.`);
|
|
685
984
|
}
|
|
@@ -737,9 +1036,16 @@ var BASE, DEFAULT_TIMEOUT_MS, CdpError;
|
|
|
737
1036
|
var init_client = __esm(() => {
|
|
738
1037
|
init_leases();
|
|
739
1038
|
init_origins();
|
|
1039
|
+
init_endpoints();
|
|
740
1040
|
init_workers();
|
|
741
1041
|
init_frames();
|
|
742
|
-
BASE =
|
|
1042
|
+
BASE = (() => {
|
|
1043
|
+
try {
|
|
1044
|
+
return defaultEndpoint().base;
|
|
1045
|
+
} catch {
|
|
1046
|
+
return process.env.CDP_BASE ?? DEFAULT_CDP_BASE;
|
|
1047
|
+
}
|
|
1048
|
+
})();
|
|
743
1049
|
DEFAULT_TIMEOUT_MS = Number(process.env.CDP_TIMEOUT_MS ?? 15000);
|
|
744
1050
|
CdpError = class CdpError extends Error {
|
|
745
1051
|
code;
|
|
@@ -1142,6 +1448,7 @@ var init_driver = __esm(() => {
|
|
|
1142
1448
|
// src/cdp/driver.ts
|
|
1143
1449
|
init_client();
|
|
1144
1450
|
init_leases();
|
|
1451
|
+
init_endpoints();
|
|
1145
1452
|
init_activity();
|
|
1146
1453
|
|
|
1147
1454
|
// src/tools/snapshot.ts
|
|
@@ -1629,7 +1936,7 @@ class CdpPageDriver {
|
|
|
1629
1936
|
await this.conn.send(`${name}.enable`);
|
|
1630
1937
|
}
|
|
1631
1938
|
async dispatchInput(method, params = {}) {
|
|
1632
|
-
return sendInput(this.conn,
|
|
1939
|
+
return sendInput(this.conn, chromeLeaseBackend(), this.info.id, method, params);
|
|
1633
1940
|
}
|
|
1634
1941
|
async ensureDomainSoft(name) {
|
|
1635
1942
|
if (this.enabledDomains.has(name))
|
|
@@ -2223,6 +2530,10 @@ class CdpPageDriver {
|
|
|
2223
2530
|
}
|
|
2224
2531
|
}
|
|
2225
2532
|
var beaconSessions = new BeaconSessions((conn) => conn.close());
|
|
2533
|
+
function beaconKey(targetId) {
|
|
2534
|
+
const backend = chromeLeaseBackend(currentEndpoint());
|
|
2535
|
+
return backend === "chrome" ? targetId : `${backend}\x00${targetId}`;
|
|
2536
|
+
}
|
|
2226
2537
|
async function targetWsUrl(targetId) {
|
|
2227
2538
|
const hit = (await listTargets()).find((t) => t.id === targetId);
|
|
2228
2539
|
return hit?.webSocketDebuggerUrl;
|
|
@@ -2324,7 +2635,7 @@ class CdpBrowserDriver {
|
|
|
2324
2635
|
return withBrowserConn(async (conn) => {
|
|
2325
2636
|
const res = await conn.send("Target.closeTarget", { targetId: id });
|
|
2326
2637
|
if (res.success !== false)
|
|
2327
|
-
beaconSessions.drop(id);
|
|
2638
|
+
beaconSessions.drop(beaconKey(id));
|
|
2328
2639
|
return { success: res.success ?? true };
|
|
2329
2640
|
});
|
|
2330
2641
|
}
|
|
@@ -2342,12 +2653,13 @@ class CdpBrowserDriver {
|
|
|
2342
2653
|
return new CdpPageDriver(conn, target, this);
|
|
2343
2654
|
}
|
|
2344
2655
|
async installActivityBeacon(targetId) {
|
|
2345
|
-
const
|
|
2656
|
+
const key = beaconKey(targetId);
|
|
2657
|
+
const held = beaconSessions.get(key);
|
|
2346
2658
|
if (held) {
|
|
2347
2659
|
const rearmed = await held.send("Runtime.evaluate", { expression: BEACON_SOURCE, returnByValue: true }).then(() => true).catch(() => false);
|
|
2348
2660
|
if (rearmed)
|
|
2349
2661
|
return true;
|
|
2350
|
-
beaconSessions.drop(
|
|
2662
|
+
beaconSessions.drop(key);
|
|
2351
2663
|
}
|
|
2352
2664
|
const wsUrl = await targetWsUrl(targetId).catch(() => {
|
|
2353
2665
|
return;
|
|
@@ -2367,16 +2679,17 @@ class CdpBrowserDriver {
|
|
|
2367
2679
|
conn.close();
|
|
2368
2680
|
return false;
|
|
2369
2681
|
}
|
|
2370
|
-
beaconSessions.set(
|
|
2682
|
+
beaconSessions.set(key, conn);
|
|
2371
2683
|
return true;
|
|
2372
2684
|
}
|
|
2373
2685
|
async readActivityBeacon(targetId) {
|
|
2374
|
-
const
|
|
2686
|
+
const key = beaconKey(targetId);
|
|
2687
|
+
const held = beaconSessions.get(key);
|
|
2375
2688
|
if (held) {
|
|
2376
2689
|
const value = await readBeaconOver(held);
|
|
2377
2690
|
if (value !== undefined)
|
|
2378
2691
|
return value;
|
|
2379
|
-
beaconSessions.drop(
|
|
2692
|
+
beaconSessions.drop(key);
|
|
2380
2693
|
}
|
|
2381
2694
|
const wsUrl = await targetWsUrl(targetId).catch(() => {
|
|
2382
2695
|
return;
|
|
@@ -2395,7 +2708,7 @@ class CdpBrowserDriver {
|
|
|
2395
2708
|
}
|
|
2396
2709
|
}
|
|
2397
2710
|
async probeRenderer(targetId, timeoutMs = RENDERER_PROBE_TIMEOUT_MS) {
|
|
2398
|
-
const held = beaconSessions.get(targetId);
|
|
2711
|
+
const held = beaconSessions.get(beaconKey(targetId));
|
|
2399
2712
|
if (held)
|
|
2400
2713
|
return probeOver(held, timeoutMs);
|
|
2401
2714
|
const wsUrl = await targetWsUrl(targetId).catch(() => {
|
|
@@ -2428,6 +2741,7 @@ init_activity();
|
|
|
2428
2741
|
init_origins();
|
|
2429
2742
|
|
|
2430
2743
|
// src/reap.ts
|
|
2744
|
+
init_endpoints();
|
|
2431
2745
|
init_leases();
|
|
2432
2746
|
init_origins();
|
|
2433
2747
|
function staleAgentTabs(input) {
|
|
@@ -2456,6 +2770,11 @@ function reapGraceMs() {
|
|
|
2456
2770
|
const raw = Number(process.env.CDP_REAP_GRACE_MS);
|
|
2457
2771
|
return Number.isFinite(raw) && raw >= 0 ? raw : DEFAULT_REAP_GRACE_MS;
|
|
2458
2772
|
}
|
|
2773
|
+
function reapAllowed(driver) {
|
|
2774
|
+
if (driver.scheme === "bidi")
|
|
2775
|
+
return true;
|
|
2776
|
+
return !currentEndpoint().readOnly;
|
|
2777
|
+
}
|
|
2459
2778
|
async function reapStaleAgentTabs(driver, backend) {
|
|
2460
2779
|
const now = Date.now();
|
|
2461
2780
|
const livePageIds = (await driver.listPages()).map((p) => p.id);
|
|
@@ -2998,6 +3317,7 @@ init_activity();
|
|
|
2998
3317
|
init_origins();
|
|
2999
3318
|
init_workers();
|
|
3000
3319
|
init_frames();
|
|
3320
|
+
init_endpoints();
|
|
3001
3321
|
var ARTIFACT_DIR = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
|
|
3002
3322
|
var STATE_DIR = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
|
|
3003
3323
|
|
|
@@ -3007,7 +3327,7 @@ function target3(p) {
|
|
|
3007
3327
|
return { id: p.id, url: p.url, title: p.title };
|
|
3008
3328
|
}
|
|
3009
3329
|
function backendOf(driver) {
|
|
3010
|
-
return driver.scheme === "bidi" ? "firefox" :
|
|
3330
|
+
return driver.scheme === "bidi" ? "firefox" : chromeLeaseBackend();
|
|
3011
3331
|
}
|
|
3012
3332
|
async function withPage2(driver, target, fn) {
|
|
3013
3333
|
const page = await driver.page(target);
|
|
@@ -3095,8 +3415,44 @@ async function reapSet(driver, pages, all) {
|
|
|
3095
3415
|
}
|
|
3096
3416
|
}
|
|
3097
3417
|
async function listPages(driver, args = {}) {
|
|
3418
|
+
const one = { all: args.all, probe: args.probe };
|
|
3419
|
+
if (args.allEndpoints === true) {
|
|
3420
|
+
if (driver.scheme === "bidi")
|
|
3421
|
+
throw new SharedToolError("list_pages: allEndpoints needs the Chrome backend; named endpoints are CDP-only");
|
|
3422
|
+
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) }))));
|
|
3423
|
+
const pages = [];
|
|
3424
|
+
const reaped = [];
|
|
3425
|
+
const endpoints = [];
|
|
3426
|
+
for (const res of results) {
|
|
3427
|
+
const { ep } = res;
|
|
3428
|
+
if ("error" in res) {
|
|
3429
|
+
endpoints.push({ endpoint: ep.name, base: ep.base, readOnly: ep.readOnly, down: true, error: res.error });
|
|
3430
|
+
continue;
|
|
3431
|
+
}
|
|
3432
|
+
for (const p of res.r.pages)
|
|
3433
|
+
pages.push({ ...p, endpoint: ep.name });
|
|
3434
|
+
for (const t of res.r.reaped ?? [])
|
|
3435
|
+
reaped.push({ ...t, endpoint: ep.name });
|
|
3436
|
+
endpoints.push({ endpoint: ep.name, base: ep.base, readOnly: ep.readOnly, count: res.r.count });
|
|
3437
|
+
}
|
|
3438
|
+
return { pages, count: pages.length, ...reaped.length ? { reaped } : {}, endpoints };
|
|
3439
|
+
}
|
|
3440
|
+
const res = await listPagesOne(driver, one);
|
|
3441
|
+
if (driver.scheme !== "bidi") {
|
|
3442
|
+
const ep = currentEndpoint();
|
|
3443
|
+
if (!isDefaultEndpoint(ep)) {
|
|
3444
|
+
return {
|
|
3445
|
+
...res,
|
|
3446
|
+
pages: res.pages.map((p) => ({ ...p, endpoint: ep.name })),
|
|
3447
|
+
...res.reaped ? { reaped: res.reaped.map((t) => ({ ...t, endpoint: ep.name })) } : {}
|
|
3448
|
+
};
|
|
3449
|
+
}
|
|
3450
|
+
}
|
|
3451
|
+
return res;
|
|
3452
|
+
}
|
|
3453
|
+
async function listPagesOne(driver, args = {}) {
|
|
3098
3454
|
const backend = backendOf(driver);
|
|
3099
|
-
const reaped = requireLease() ? await reapStaleAgentTabs(driver, backend) : [];
|
|
3455
|
+
const reaped = requireLease() && reapAllowed(driver) ? await reapStaleAgentTabs(driver, backend) : [];
|
|
3100
3456
|
const reapedIds = new Set(reaped.map((r) => r.targetId));
|
|
3101
3457
|
const pages = (await driver.listPages({ all: args.all })).filter((p) => !reapedIds.has(p.id));
|
|
3102
3458
|
const ledger = await originIndex(backend, await reapSet(driver, pages, args.all));
|
|
@@ -3737,7 +4093,7 @@ init_leases();
|
|
|
3737
4093
|
class LeaseToolError extends Error {
|
|
3738
4094
|
}
|
|
3739
4095
|
function backendOf2(driver) {
|
|
3740
|
-
return driver.scheme === "bidi" ? "firefox" :
|
|
4096
|
+
return driver.scheme === "bidi" ? "firefox" : chromeLeaseBackend();
|
|
3741
4097
|
}
|
|
3742
4098
|
async function claimPage(driver, args = {}) {
|
|
3743
4099
|
const hasTarget = typeof args.target === "string" && args.target.length > 0;
|
|
@@ -3822,7 +4178,7 @@ async function releasePage(driver, args = {}) {
|
|
|
3822
4178
|
}
|
|
3823
4179
|
async function listLeasesTool(driver, _args = {}) {
|
|
3824
4180
|
const backend = backendOf2(driver);
|
|
3825
|
-
const reaped = requireLease() ? await reapStaleAgentTabs(driver, backend) : [];
|
|
4181
|
+
const reaped = requireLease() && reapAllowed(driver) ? await reapStaleAgentTabs(driver, backend) : [];
|
|
3826
4182
|
const reapedIds = new Set(reaped.map((r) => r.targetId));
|
|
3827
4183
|
const livePages = await driver.listPages();
|
|
3828
4184
|
const liveIds = livePages.map((p) => p.id);
|
|
@@ -4902,11 +5258,12 @@ async function takeHeapsnapshot(args = {}) {
|
|
|
4902
5258
|
|
|
4903
5259
|
// src/tools/lighthouse.ts
|
|
4904
5260
|
init_client();
|
|
5261
|
+
init_endpoints();
|
|
4905
5262
|
import { spawn as spawn2 } from "node:child_process";
|
|
4906
5263
|
import { mkdir as mkdir10, readFile as readFile7, stat as stat3 } from "node:fs/promises";
|
|
4907
5264
|
var ARTIFACT_DIR5 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
|
|
4908
5265
|
function cdpPort() {
|
|
4909
|
-
const base =
|
|
5266
|
+
const base = currentEndpoint().base;
|
|
4910
5267
|
const m = base.match(/:(\d+)/);
|
|
4911
5268
|
return m?.[1] ? Number(m[1]) : 9222;
|
|
4912
5269
|
}
|
|
@@ -5043,6 +5400,7 @@ init_network_mock();
|
|
|
5043
5400
|
// src/tools/dispatch-mouse.ts
|
|
5044
5401
|
init_activity();
|
|
5045
5402
|
init_client();
|
|
5403
|
+
init_leases();
|
|
5046
5404
|
var CLICK_MODIFIER_BITS2 = { Alt: 1, Control: 2, Meta: 4, Shift: 8 };
|
|
5047
5405
|
var BUTTONS = new Set(["left", "right", "middle"]);
|
|
5048
5406
|
var CDP_EVENT_TYPE = {
|
|
@@ -5079,7 +5437,7 @@ async function dispatchMouse(args) {
|
|
|
5079
5437
|
const params = { type: CDP_EVENT_TYPE[args.action], x: args.x, y: args.y, button, modifiers };
|
|
5080
5438
|
if (args.action !== "move")
|
|
5081
5439
|
params.clickCount = args.clickCount ?? 1;
|
|
5082
|
-
await sendInput(conn,
|
|
5440
|
+
await sendInput(conn, chromeLeaseBackend(), target.id, "Input.dispatchMouseEvent", params);
|
|
5083
5441
|
return { dispatched: args.action, x: args.x, y: args.y };
|
|
5084
5442
|
});
|
|
5085
5443
|
}
|
|
@@ -5087,6 +5445,7 @@ async function dispatchMouse(args) {
|
|
|
5087
5445
|
// src/tools/focus-emulation.ts
|
|
5088
5446
|
init_activity();
|
|
5089
5447
|
init_client();
|
|
5448
|
+
init_leases();
|
|
5090
5449
|
function validateFocusEmulationArgs(args) {
|
|
5091
5450
|
if (typeof args.enabled !== "boolean") {
|
|
5092
5451
|
throw new Error("focus_emulation requires { enabled } of true or false");
|
|
@@ -5153,9 +5512,10 @@ async function clickFocusGated(args) {
|
|
|
5153
5512
|
const btn = result?.value;
|
|
5154
5513
|
if (btn && !btn.disabled) {
|
|
5155
5514
|
const base = { x: btn.x, y: btn.y, button: "left", buttons: 1, clickCount: 1 };
|
|
5156
|
-
|
|
5157
|
-
await sendInput(conn,
|
|
5158
|
-
await sendInput(conn,
|
|
5515
|
+
const backend = chromeLeaseBackend();
|
|
5516
|
+
await sendInput(conn, backend, target.id, "Input.dispatchMouseEvent", { type: "mouseMoved", x: btn.x, y: btn.y });
|
|
5517
|
+
await sendInput(conn, backend, target.id, "Input.dispatchMouseEvent", { ...base, type: "mousePressed" });
|
|
5518
|
+
await sendInput(conn, backend, target.id, "Input.dispatchMouseEvent", { ...base, type: "mouseReleased" });
|
|
5159
5519
|
return {
|
|
5160
5520
|
clicked: true,
|
|
5161
5521
|
x: btn.x,
|
|
@@ -5184,12 +5544,16 @@ import { basename, extname, join as join9 } from "node:path";
|
|
|
5184
5544
|
|
|
5185
5545
|
// src/tools/browser-session.ts
|
|
5186
5546
|
init_client();
|
|
5547
|
+
init_endpoints();
|
|
5187
5548
|
import { mkdir as mkdir11 } from "node:fs/promises";
|
|
5188
5549
|
import { join as join8 } from "node:path";
|
|
5189
5550
|
var ARTIFACT_DIR6 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
|
|
5190
5551
|
var DOWNLOADS_DIR = join8(ARTIFACT_DIR6, "downloads");
|
|
5191
5552
|
var DOWNLOAD_BUFFER_LIMIT = 50;
|
|
5192
|
-
var
|
|
5553
|
+
var sessions2 = new Map;
|
|
5554
|
+
function sessionKey() {
|
|
5555
|
+
return currentEndpoint().name;
|
|
5556
|
+
}
|
|
5193
5557
|
function isDisconnect(e) {
|
|
5194
5558
|
const m = e instanceof Error ? e.message : String(e);
|
|
5195
5559
|
return /connection (not open|closed)|closed by caller|websocket|ECONNREFUSED|socket/i.test(m);
|
|
@@ -5234,13 +5598,15 @@ function subscribe(s) {
|
|
|
5234
5598
|
});
|
|
5235
5599
|
}
|
|
5236
5600
|
async function getBrowserSession() {
|
|
5601
|
+
const key = sessionKey();
|
|
5602
|
+
const session = sessions2.get(key);
|
|
5237
5603
|
if (session && !session.dead)
|
|
5238
5604
|
return session;
|
|
5239
5605
|
const previousPath = session?.armedPath;
|
|
5240
5606
|
const conn = await openBrowser();
|
|
5241
5607
|
const s = { conn, downloads: [], waiters: [], dead: false };
|
|
5242
5608
|
subscribe(s);
|
|
5243
|
-
|
|
5609
|
+
sessions2.set(key, s);
|
|
5244
5610
|
if (previousPath)
|
|
5245
5611
|
await armDownloadsAt(previousPath);
|
|
5246
5612
|
return s;
|
|
@@ -5271,7 +5637,7 @@ async function armDownloads() {
|
|
|
5271
5637
|
return { downloadPath: DOWNLOADS_DIR };
|
|
5272
5638
|
}
|
|
5273
5639
|
function pendingDownloads() {
|
|
5274
|
-
return (
|
|
5640
|
+
return (sessions2.get(sessionKey())?.downloads ?? []).filter((d) => d.state === "completed" && !d.consumed);
|
|
5275
5641
|
}
|
|
5276
5642
|
async function nextCompletedDownload(timeoutMs) {
|
|
5277
5643
|
const s = await getBrowserSession();
|
|
@@ -5295,14 +5661,14 @@ async function nextCompletedDownload(timeoutMs) {
|
|
|
5295
5661
|
});
|
|
5296
5662
|
}
|
|
5297
5663
|
async function disposeBrowserSession() {
|
|
5298
|
-
const
|
|
5299
|
-
|
|
5300
|
-
|
|
5301
|
-
|
|
5302
|
-
|
|
5303
|
-
|
|
5304
|
-
|
|
5305
|
-
}
|
|
5664
|
+
const all = [...sessions2.values()];
|
|
5665
|
+
sessions2.clear();
|
|
5666
|
+
for (const s of all) {
|
|
5667
|
+
s.dead = true;
|
|
5668
|
+
try {
|
|
5669
|
+
s.conn.close();
|
|
5670
|
+
} catch {}
|
|
5671
|
+
}
|
|
5306
5672
|
}
|
|
5307
5673
|
|
|
5308
5674
|
// src/tools/downloads.ts
|