@howaboua/pi-durable-browser 0.0.0-stage → 0.10.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/LICENSE +21 -0
- package/NOTICE +52 -0
- package/README.md +86 -2
- package/dist/activation.d.ts +9 -0
- package/dist/activation.js +3759 -0
- package/dist/browser/artifact-store.d.ts +16 -0
- package/dist/browser/artifacts.d.ts +20 -0
- package/dist/browser/bounds.d.ts +4 -0
- package/dist/browser/config-store.d.ts +11 -0
- package/dist/browser/config.d.ts +7 -0
- package/dist/browser/help.d.ts +1 -0
- package/dist/browser/launcher.d.ts +1 -0
- package/dist/browser/operation-executor.d.ts +12 -0
- package/dist/browser/operation-input.d.ts +10 -0
- package/dist/browser/operation.d.ts +115 -0
- package/dist/browser/parse-operation.d.ts +6 -0
- package/dist/browser/parse-tab-operation.d.ts +3 -0
- package/dist/browser/remote-helper.d.ts +3 -0
- package/dist/browser/remote-process.d.ts +6 -0
- package/dist/browser/remote.d.ts +4 -0
- package/dist/browser/request.d.ts +8 -0
- package/dist/browser/routes.d.ts +15 -0
- package/dist/browser/runtime.d.ts +35 -0
- package/dist/browser/voice-start.d.ts +17 -0
- package/dist/browser/worker-client.d.ts +1 -0
- package/dist/browser/worker-server.d.ts +1 -0
- package/dist/browser/worker-socket.d.ts +11 -0
- package/dist/cdp/accessibility-snapshot.d.ts +11 -0
- package/dist/cdp/actions/click.d.ts +6 -0
- package/dist/cdp/actions/element.d.ts +22 -0
- package/dist/cdp/actions/fill.d.ts +8 -0
- package/dist/cdp/actions/key.d.ts +20 -0
- package/dist/cdp/actions/page.d.ts +7 -0
- package/dist/cdp/actions/screenshot.d.ts +14 -0
- package/dist/cdp/actions/selector.d.ts +2 -0
- package/dist/cdp/actions/type.d.ts +3 -0
- package/dist/cdp/actions/wait.d.ts +9 -0
- package/dist/cdp/client.d.ts +20 -0
- package/dist/cdp/discovery.d.ts +7 -0
- package/dist/cdp/evaluate.d.ts +3 -0
- package/dist/cdp/pages.d.ts +4 -0
- package/dist/cdp/serial.d.ts +1 -0
- package/dist/cdp/session.d.ts +27 -0
- package/dist/cdp/snapshot-contract.d.ts +38 -0
- package/dist/cdp/snapshot.d.ts +3 -0
- package/dist/cdp/tab-bridge.d.ts +26 -0
- package/dist/cdp/tabs.d.ts +32 -0
- package/dist/cdp/types.d.ts +22 -0
- package/dist/cdp/url.d.ts +1 -0
- package/dist/index.d.ts +119 -0
- package/dist/index.js +3951 -0
- package/dist/presentation.d.ts +43 -0
- package/dist/presentation.js +82 -0
- package/dist/remote-worker.d.ts +2 -0
- package/dist/remote-worker.js +3850 -0
- package/package.json +67 -5
|
@@ -0,0 +1,3850 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// @howaboua/pi-durable-browser managed worker
|
|
3
|
+
|
|
4
|
+
// packages/browser/src/remote-worker.ts
|
|
5
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
6
|
+
import { readFileSync as readFileSync2, realpathSync } from "node:fs";
|
|
7
|
+
import { resolve as resolve2 } from "node:path";
|
|
8
|
+
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
9
|
+
|
|
10
|
+
// packages/browser/src/browser/worker-client.ts
|
|
11
|
+
import { spawn } from "node:child_process";
|
|
12
|
+
import { rm } from "node:fs/promises";
|
|
13
|
+
import { createConnection } from "node:net";
|
|
14
|
+
|
|
15
|
+
// packages/browser/src/browser/operation-input.ts
|
|
16
|
+
function isRecordValue(value) {
|
|
17
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
18
|
+
}
|
|
19
|
+
function requiredString(value, field) {
|
|
20
|
+
if (typeof value !== "string" || !value.trim()) {
|
|
21
|
+
throw new Error(`${field} must be a non-empty string`);
|
|
22
|
+
}
|
|
23
|
+
return value.trim();
|
|
24
|
+
}
|
|
25
|
+
function optionalString(value, field) {
|
|
26
|
+
if (value === undefined)
|
|
27
|
+
return;
|
|
28
|
+
return requiredString(value, field);
|
|
29
|
+
}
|
|
30
|
+
function requiredRef(value, action) {
|
|
31
|
+
if (typeof value !== "string" || !value.trim()) {
|
|
32
|
+
throw new Error(`${action} requires a ref_id returned by tabs; call tabs first`);
|
|
33
|
+
}
|
|
34
|
+
return value.trim();
|
|
35
|
+
}
|
|
36
|
+
function offset(value, field = "offset", fallback = 0) {
|
|
37
|
+
if (value === undefined)
|
|
38
|
+
return fallback;
|
|
39
|
+
if (!Number.isInteger(value) || Number(value) < 0) {
|
|
40
|
+
throw new Error(`${field} must be a non-negative integer`);
|
|
41
|
+
}
|
|
42
|
+
return Number(value);
|
|
43
|
+
}
|
|
44
|
+
function line(value) {
|
|
45
|
+
const parsed = offset(value, "lineno", 1);
|
|
46
|
+
if (parsed < 1)
|
|
47
|
+
throw new Error("lineno must be at least 1");
|
|
48
|
+
return parsed;
|
|
49
|
+
}
|
|
50
|
+
function elementId(value) {
|
|
51
|
+
if (value === undefined)
|
|
52
|
+
return;
|
|
53
|
+
if (!Number.isInteger(value) || Number(value) < 1) {
|
|
54
|
+
throw new Error("id must be a positive integer from open/find");
|
|
55
|
+
}
|
|
56
|
+
return Number(value);
|
|
57
|
+
}
|
|
58
|
+
function responseLength(value) {
|
|
59
|
+
if (value === undefined)
|
|
60
|
+
return "medium";
|
|
61
|
+
if (value !== "short" && value !== "medium" && value !== "long") {
|
|
62
|
+
throw new Error("response_length must be one of: short, medium, long");
|
|
63
|
+
}
|
|
64
|
+
return value;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// packages/browser/src/browser/worker-socket.ts
|
|
68
|
+
import { chmod, lstat, mkdir } from "node:fs/promises";
|
|
69
|
+
import { tmpdir } from "node:os";
|
|
70
|
+
import { dirname, join } from "node:path";
|
|
71
|
+
import { StringDecoder } from "node:string_decoder";
|
|
72
|
+
var INPUT_LIMIT_BYTES = 8 * 1024 * 1024;
|
|
73
|
+
var IS_WINDOWS = process.platform === "win32";
|
|
74
|
+
function workerSocketPath(workerId) {
|
|
75
|
+
if (IS_WINDOWS)
|
|
76
|
+
return `\\\\.\\pipe\\pi-durable-browser-worker-${workerId}`;
|
|
77
|
+
const directory = process.env["XDG_RUNTIME_DIR"] ? join(process.env["XDG_RUNTIME_DIR"], "pi-durable-browser") : join(tmpdir(), `pi-durable-browser-${process.getuid?.() ?? "user"}`);
|
|
78
|
+
return join(directory, `worker-${workerId}.sock`);
|
|
79
|
+
}
|
|
80
|
+
async function ensureWorkerSocketDirectory(workerId) {
|
|
81
|
+
if (IS_WINDOWS)
|
|
82
|
+
return;
|
|
83
|
+
const directory = dirname(workerSocketPath(workerId));
|
|
84
|
+
await mkdir(directory, { recursive: true, mode: 448 });
|
|
85
|
+
const info = await lstat(directory);
|
|
86
|
+
const uid = process.getuid?.();
|
|
87
|
+
if (info.isSymbolicLink() || !info.isDirectory()) {
|
|
88
|
+
throw new Error(`Browser worker socket directory is not a directory: ${directory}`);
|
|
89
|
+
}
|
|
90
|
+
if (uid === undefined || info.uid !== uid) {
|
|
91
|
+
throw new Error(`Browser worker socket directory is not owned by this user: ${directory}`);
|
|
92
|
+
}
|
|
93
|
+
if ((info.mode & 63) !== 0)
|
|
94
|
+
await chmod(directory, 448);
|
|
95
|
+
}
|
|
96
|
+
function readLine(socket) {
|
|
97
|
+
return new Promise((resolveValue, reject) => {
|
|
98
|
+
let input = "";
|
|
99
|
+
let bytes = 0;
|
|
100
|
+
const decoder = new StringDecoder("utf8");
|
|
101
|
+
const cleanup = () => {
|
|
102
|
+
socket.off("data", onData);
|
|
103
|
+
socket.off("end", onEnd);
|
|
104
|
+
socket.off("error", onError);
|
|
105
|
+
};
|
|
106
|
+
const onError = (error) => {
|
|
107
|
+
cleanup();
|
|
108
|
+
reject(error);
|
|
109
|
+
};
|
|
110
|
+
const onEnd = () => onError(new Error("Browser worker closed early"));
|
|
111
|
+
const onData = (chunk) => {
|
|
112
|
+
bytes += chunk.length;
|
|
113
|
+
if (bytes > INPUT_LIMIT_BYTES) {
|
|
114
|
+
cleanup();
|
|
115
|
+
reject(new Error("Browser worker input exceeded 8 MiB"));
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
input += decoder.write(chunk);
|
|
119
|
+
const newline = input.indexOf(`
|
|
120
|
+
`);
|
|
121
|
+
if (newline < 0)
|
|
122
|
+
return;
|
|
123
|
+
cleanup();
|
|
124
|
+
resolveValue(input.slice(0, newline));
|
|
125
|
+
};
|
|
126
|
+
socket.on("data", onData);
|
|
127
|
+
socket.once("end", onEnd);
|
|
128
|
+
socket.once("error", onError);
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// packages/browser/src/browser/worker-client.ts
|
|
133
|
+
var START_TIMEOUT_MS = 5000;
|
|
134
|
+
var IS_WINDOWS2 = process.platform === "win32";
|
|
135
|
+
async function requestOnce(input, workerId, signal) {
|
|
136
|
+
if (signal?.aborted) {
|
|
137
|
+
return Promise.reject(signal.reason ?? new Error("Browser worker request aborted"));
|
|
138
|
+
}
|
|
139
|
+
await ensureWorkerSocketDirectory(workerId);
|
|
140
|
+
if (signal?.aborted) {
|
|
141
|
+
throw signal.reason ?? new Error("Browser worker request aborted");
|
|
142
|
+
}
|
|
143
|
+
return new Promise((resolveValue, reject) => {
|
|
144
|
+
const socket = createConnection(workerSocketPath(workerId));
|
|
145
|
+
const abort = () => {
|
|
146
|
+
socket.destroy();
|
|
147
|
+
reject(signal?.reason ?? new Error("Browser worker request aborted"));
|
|
148
|
+
};
|
|
149
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
150
|
+
socket.once("connect", () => socket.write(`${input}
|
|
151
|
+
`));
|
|
152
|
+
readLine(socket).then((line) => {
|
|
153
|
+
signal?.removeEventListener("abort", abort);
|
|
154
|
+
socket.destroy();
|
|
155
|
+
try {
|
|
156
|
+
const response = JSON.parse(line);
|
|
157
|
+
if (!isRecordValue(response) || typeof response["ok"] !== "boolean") {
|
|
158
|
+
throw new Error("Browser worker returned an invalid response");
|
|
159
|
+
}
|
|
160
|
+
if (response["ok"] === true && isRecordValue(response["result"])) {
|
|
161
|
+
resolveValue({ ok: true, result: response["result"] });
|
|
162
|
+
} else if (response["ok"] === false && typeof response["error"] === "string") {
|
|
163
|
+
resolveValue({ ok: false, error: response["error"] });
|
|
164
|
+
} else {
|
|
165
|
+
throw new Error("Browser worker returned an invalid response");
|
|
166
|
+
}
|
|
167
|
+
} catch (error) {
|
|
168
|
+
reject(error);
|
|
169
|
+
}
|
|
170
|
+
}, (error) => {
|
|
171
|
+
signal?.removeEventListener("abort", abort);
|
|
172
|
+
socket.destroy();
|
|
173
|
+
reject(error);
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
function canStartWorker(error) {
|
|
178
|
+
return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ECONNREFUSED");
|
|
179
|
+
}
|
|
180
|
+
async function requestBrowserWorker(input, entryPath, workerId, signal) {
|
|
181
|
+
try {
|
|
182
|
+
const response = await requestOnce(input, workerId, signal);
|
|
183
|
+
if (!response.ok)
|
|
184
|
+
throw new Error(response.error ?? "Browser worker failed");
|
|
185
|
+
if (!response.result)
|
|
186
|
+
throw new Error("Browser worker returned no result");
|
|
187
|
+
return response.result;
|
|
188
|
+
} catch (error) {
|
|
189
|
+
if (!canStartWorker(error))
|
|
190
|
+
throw error;
|
|
191
|
+
}
|
|
192
|
+
if (!IS_WINDOWS2)
|
|
193
|
+
await rm(workerSocketPath(workerId), { force: true });
|
|
194
|
+
signal?.throwIfAborted();
|
|
195
|
+
const child = spawn(process.execPath, ["--preserve-symlinks-main", entryPath, "--daemon"], { detached: true, stdio: "ignore" });
|
|
196
|
+
child.unref();
|
|
197
|
+
const deadline = Date.now() + START_TIMEOUT_MS;
|
|
198
|
+
let lastError;
|
|
199
|
+
while (Date.now() < deadline) {
|
|
200
|
+
try {
|
|
201
|
+
const response = await requestOnce(input, workerId, signal);
|
|
202
|
+
if (!response.ok)
|
|
203
|
+
throw new Error(response.error ?? "Browser worker failed");
|
|
204
|
+
if (!response.result)
|
|
205
|
+
throw new Error("Browser worker returned no result");
|
|
206
|
+
return response.result;
|
|
207
|
+
} catch (error) {
|
|
208
|
+
if (!canStartWorker(error))
|
|
209
|
+
throw error;
|
|
210
|
+
lastError = error;
|
|
211
|
+
await new Promise((resolveValue) => setTimeout(resolveValue, 50));
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
throw new Error(`Browser worker did not start within ${START_TIMEOUT_MS}ms${lastError instanceof Error ? `: ${lastError.message}` : ""}`);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// packages/browser/src/browser/worker-server.ts
|
|
218
|
+
import { rm as rm5 } from "node:fs/promises";
|
|
219
|
+
import { createServer } from "node:net";
|
|
220
|
+
import { dirname as dirname2 } from "node:path";
|
|
221
|
+
|
|
222
|
+
// packages/browser/src/browser/artifact-store.ts
|
|
223
|
+
import {
|
|
224
|
+
mkdir as mkdir2,
|
|
225
|
+
readdir,
|
|
226
|
+
readFile,
|
|
227
|
+
rm as rm2,
|
|
228
|
+
stat,
|
|
229
|
+
writeFile
|
|
230
|
+
} from "node:fs/promises";
|
|
231
|
+
import { isAbsolute, join as join2 } from "node:path";
|
|
232
|
+
function nodeArtifactStore(directory) {
|
|
233
|
+
if (!isAbsolute(directory))
|
|
234
|
+
throw new Error("Native artifact directory must be absolute");
|
|
235
|
+
const path = (name) => join2(directory, name);
|
|
236
|
+
return {
|
|
237
|
+
path,
|
|
238
|
+
async write(name, data) {
|
|
239
|
+
await mkdir2(directory, { recursive: true, mode: 448 });
|
|
240
|
+
await writeFile(path(name), data, { mode: 384 });
|
|
241
|
+
},
|
|
242
|
+
async read(name) {
|
|
243
|
+
return readFile(path(name), "utf8");
|
|
244
|
+
},
|
|
245
|
+
async remove(name) {
|
|
246
|
+
await rm2(path(name), { force: true });
|
|
247
|
+
},
|
|
248
|
+
async entries() {
|
|
249
|
+
try {
|
|
250
|
+
return await Promise.all((await readdir(directory)).map(async (name) => ({
|
|
251
|
+
name,
|
|
252
|
+
mtimeMs: (await stat(path(name))).mtimeMs
|
|
253
|
+
})));
|
|
254
|
+
} catch (error) {
|
|
255
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT")
|
|
256
|
+
return [];
|
|
257
|
+
throw error;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// packages/browser/src/cdp/actions/key.ts
|
|
264
|
+
var MODIFIERS = { Alt: 1, Control: 2, Meta: 4, Shift: 8 };
|
|
265
|
+
var ALIASES = {
|
|
266
|
+
Ctrl: "Control",
|
|
267
|
+
Cmd: "Meta",
|
|
268
|
+
Option: "Alt"
|
|
269
|
+
};
|
|
270
|
+
var NAMED_KEYS = {
|
|
271
|
+
Backspace: 8,
|
|
272
|
+
Tab: 9,
|
|
273
|
+
Enter: 13,
|
|
274
|
+
Escape: 27,
|
|
275
|
+
Space: 32,
|
|
276
|
+
PageUp: 33,
|
|
277
|
+
PageDown: 34,
|
|
278
|
+
End: 35,
|
|
279
|
+
Home: 36,
|
|
280
|
+
ArrowLeft: 37,
|
|
281
|
+
ArrowUp: 38,
|
|
282
|
+
ArrowRight: 39,
|
|
283
|
+
ArrowDown: 40,
|
|
284
|
+
Insert: 45,
|
|
285
|
+
Delete: 46
|
|
286
|
+
};
|
|
287
|
+
var PUNCTUATION = {
|
|
288
|
+
"`~": { code: "Backquote", keyCode: 192 },
|
|
289
|
+
"-_": { code: "Minus", keyCode: 189 },
|
|
290
|
+
"=+": { code: "Equal", keyCode: 187 },
|
|
291
|
+
"[{": { code: "BracketLeft", keyCode: 219 },
|
|
292
|
+
"]}": { code: "BracketRight", keyCode: 221 },
|
|
293
|
+
"\\|": { code: "Backslash", keyCode: 220 },
|
|
294
|
+
";:": { code: "Semicolon", keyCode: 186 },
|
|
295
|
+
"'\"": { code: "Quote", keyCode: 222 },
|
|
296
|
+
",<": { code: "Comma", keyCode: 188 },
|
|
297
|
+
".>": { code: "Period", keyCode: 190 },
|
|
298
|
+
"/?": { code: "Slash", keyCode: 191 }
|
|
299
|
+
};
|
|
300
|
+
function keyDefinition(name, shift) {
|
|
301
|
+
const namedCode = Object.hasOwn(NAMED_KEYS, name) ? NAMED_KEYS[name] : undefined;
|
|
302
|
+
if (namedCode !== undefined) {
|
|
303
|
+
return {
|
|
304
|
+
key: name === "Space" ? " " : name,
|
|
305
|
+
code: name,
|
|
306
|
+
windowsVirtualKeyCode: namedCode,
|
|
307
|
+
...name === "Enter" ? { text: "\r" } : name === "Space" ? { text: " " } : {}
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
if (/^F(?:[1-9]|1[0-2])$/.test(name)) {
|
|
311
|
+
return {
|
|
312
|
+
key: name,
|
|
313
|
+
code: name,
|
|
314
|
+
windowsVirtualKeyCode: 111 + Number(name.slice(1))
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
const key = name === "Plus" ? "+" : name;
|
|
318
|
+
if ([...key].length !== 1) {
|
|
319
|
+
throw new Error(`Unknown key ${name}; use a character, Enter, Tab, Escape, arrows, or a chord such as Control+a`);
|
|
320
|
+
}
|
|
321
|
+
if (/^[a-z]$/i.test(key)) {
|
|
322
|
+
const text = shift ? key.toUpperCase() : key;
|
|
323
|
+
return {
|
|
324
|
+
key: text,
|
|
325
|
+
code: `Key${key.toUpperCase()}`,
|
|
326
|
+
windowsVirtualKeyCode: key.toUpperCase().charCodeAt(0),
|
|
327
|
+
text
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
const digit = "0123456789".indexOf(key);
|
|
331
|
+
const shiftedDigit = ")!@#$%^&*(".indexOf(key);
|
|
332
|
+
if (digit >= 0 || shiftedDigit >= 0) {
|
|
333
|
+
const number = digit >= 0 ? digit : shiftedDigit;
|
|
334
|
+
const text = shift && digit >= 0 ? ")!@#$%^&*(".charAt(number) : key;
|
|
335
|
+
return {
|
|
336
|
+
key: text,
|
|
337
|
+
code: `Digit${number}`,
|
|
338
|
+
windowsVirtualKeyCode: 48 + number,
|
|
339
|
+
text
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
for (const [characters, definition] of Object.entries(PUNCTUATION)) {
|
|
343
|
+
if (!characters.includes(key))
|
|
344
|
+
continue;
|
|
345
|
+
const text = shift ? characters.charAt(1) : key;
|
|
346
|
+
return {
|
|
347
|
+
key: text,
|
|
348
|
+
code: definition.code,
|
|
349
|
+
windowsVirtualKeyCode: definition.keyCode,
|
|
350
|
+
text
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
return { key, code: "", windowsVirtualKeyCode: 0, text: key };
|
|
354
|
+
}
|
|
355
|
+
function parseKeyChord(chord) {
|
|
356
|
+
const parts = chord === "+" ? ["Plus"] : chord.split("+").map((part) => part.trim());
|
|
357
|
+
const name = parts.pop();
|
|
358
|
+
if (!name)
|
|
359
|
+
throw new Error("Missing key; use Plus for + in a chord");
|
|
360
|
+
const modifiers = [];
|
|
361
|
+
for (const part of parts) {
|
|
362
|
+
const modifier = ALIASES[part] ?? part;
|
|
363
|
+
if (!Object.hasOwn(MODIFIERS, modifier))
|
|
364
|
+
throw new Error(`Unknown modifier ${part}; use Control, Alt, Shift, or Meta`);
|
|
365
|
+
const valid = modifier;
|
|
366
|
+
if (modifiers.includes(valid))
|
|
367
|
+
throw new Error(`Repeated modifier ${part}`);
|
|
368
|
+
modifiers.push(valid);
|
|
369
|
+
}
|
|
370
|
+
return { modifiers, key: keyDefinition(name, modifiers.includes("Shift")) };
|
|
371
|
+
}
|
|
372
|
+
async function pressKey(cdp, sessionId, chord, signal) {
|
|
373
|
+
const { modifiers, key } = parseKeyChord(chord);
|
|
374
|
+
const held = [];
|
|
375
|
+
let mask = 0;
|
|
376
|
+
let failure;
|
|
377
|
+
try {
|
|
378
|
+
for (const modifier of modifiers) {
|
|
379
|
+
signal?.throwIfAborted();
|
|
380
|
+
const bit = MODIFIERS[modifier];
|
|
381
|
+
const keyCode = { Alt: 18, Control: 17, Meta: 91, Shift: 16 }[modifier];
|
|
382
|
+
const modifierKey = {
|
|
383
|
+
key: modifier,
|
|
384
|
+
code: `${modifier}Left`,
|
|
385
|
+
windowsVirtualKeyCode: keyCode
|
|
386
|
+
};
|
|
387
|
+
mask |= bit;
|
|
388
|
+
held.push({ key: modifierKey, bit });
|
|
389
|
+
await cdp.send("Input.dispatchKeyEvent", { ...modifierKey, type: "rawKeyDown", modifiers: mask }, sessionId, signal);
|
|
390
|
+
}
|
|
391
|
+
signal?.throwIfAborted();
|
|
392
|
+
held.push({ key, bit: 0 });
|
|
393
|
+
const { text, ...identity } = key;
|
|
394
|
+
const insertsText = text !== undefined && (mask & ~MODIFIERS.Shift) === 0;
|
|
395
|
+
await cdp.send("Input.dispatchKeyEvent", {
|
|
396
|
+
...identity,
|
|
397
|
+
type: insertsText ? "keyDown" : "rawKeyDown",
|
|
398
|
+
modifiers: mask,
|
|
399
|
+
...insertsText ? { text } : {}
|
|
400
|
+
}, sessionId, signal);
|
|
401
|
+
} catch (error) {
|
|
402
|
+
failure = error;
|
|
403
|
+
} finally {
|
|
404
|
+
for (const heldKey of held.reverse()) {
|
|
405
|
+
mask &= ~heldKey.bit;
|
|
406
|
+
const { text: _text, ...identity } = heldKey.key;
|
|
407
|
+
try {
|
|
408
|
+
await cdp.send("Input.dispatchKeyEvent", { ...identity, type: "keyUp", modifiers: mask }, sessionId);
|
|
409
|
+
} catch (error) {
|
|
410
|
+
failure = failure ? new AggregateError([failure, error], "Key press failed; key release also failed") : error;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
if (failure)
|
|
415
|
+
throw failure;
|
|
416
|
+
signal?.throwIfAborted();
|
|
417
|
+
return `Pressed ${chord}`;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
// packages/browser/src/browser/parse-tab-operation.ts
|
|
421
|
+
function parseTabOperation(action, refId, value) {
|
|
422
|
+
if (action === "network" || action === "show" || action === "close")
|
|
423
|
+
return { action, ref_id: refId };
|
|
424
|
+
if (action === "navigate") {
|
|
425
|
+
return {
|
|
426
|
+
action,
|
|
427
|
+
ref_id: refId,
|
|
428
|
+
url: requiredString(value["url"], "url")
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
if (action === "evaluate") {
|
|
432
|
+
return {
|
|
433
|
+
action,
|
|
434
|
+
ref_id: refId,
|
|
435
|
+
expression: requiredString(value["expression"], "expression")
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
if (action === "click") {
|
|
439
|
+
const id = elementId(value["id"]);
|
|
440
|
+
const selector = optionalString(value["selector"], "selector");
|
|
441
|
+
const hasX = value["x"] !== undefined;
|
|
442
|
+
const hasY = value["y"] !== undefined;
|
|
443
|
+
let coordinates;
|
|
444
|
+
if (hasX !== hasY) {
|
|
445
|
+
throw new Error("click coordinates require both x and y");
|
|
446
|
+
}
|
|
447
|
+
if (hasX && (typeof value["x"] !== "number" || !Number.isFinite(value["x"]) || typeof value["y"] !== "number" || !Number.isFinite(value["y"]))) {
|
|
448
|
+
throw new Error("x and y must be finite CSS-pixel numbers");
|
|
449
|
+
}
|
|
450
|
+
if (typeof value["x"] === "number" && typeof value["y"] === "number") {
|
|
451
|
+
coordinates = { x: value["x"], y: value["y"] };
|
|
452
|
+
}
|
|
453
|
+
if (Number(id !== undefined) + Number(Boolean(selector)) + Number(hasX) !== 1) {
|
|
454
|
+
throw new Error("click requires exactly one of id, selector, or x+y");
|
|
455
|
+
}
|
|
456
|
+
if (id !== undefined)
|
|
457
|
+
return { action, ref_id: refId, id };
|
|
458
|
+
if (selector)
|
|
459
|
+
return { action, ref_id: refId, selector };
|
|
460
|
+
if (coordinates) {
|
|
461
|
+
return { action, ref_id: refId, ...coordinates };
|
|
462
|
+
}
|
|
463
|
+
throw new Error("click requires id, selector, or x+y");
|
|
464
|
+
}
|
|
465
|
+
if (action === "type") {
|
|
466
|
+
if (typeof value["text"] !== "string" || value["text"].length === 0) {
|
|
467
|
+
throw new Error("text must be a non-empty string");
|
|
468
|
+
}
|
|
469
|
+
const id = elementId(value["id"]);
|
|
470
|
+
return {
|
|
471
|
+
action,
|
|
472
|
+
ref_id: refId,
|
|
473
|
+
...id === undefined ? {} : { id },
|
|
474
|
+
text: value["text"]
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
if (action === "screenshot" || action === "html") {
|
|
478
|
+
const id = elementId(value["id"]);
|
|
479
|
+
const selector = optionalString(value["selector"], "selector");
|
|
480
|
+
if (id !== undefined && selector) {
|
|
481
|
+
throw new Error(`${action} accepts id or selector, not both`);
|
|
482
|
+
}
|
|
483
|
+
return {
|
|
484
|
+
action,
|
|
485
|
+
ref_id: refId,
|
|
486
|
+
...id === undefined ? {} : { id },
|
|
487
|
+
...selector ? { selector } : {}
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
if (action === "fill") {
|
|
491
|
+
const id = elementId(value["id"]);
|
|
492
|
+
const selector = optionalString(value["selector"], "selector");
|
|
493
|
+
if (Number(id !== undefined) + Number(selector !== undefined) !== 1) {
|
|
494
|
+
throw new Error("fill requires exactly one of id or selector");
|
|
495
|
+
}
|
|
496
|
+
const fillValue = value["value"];
|
|
497
|
+
if (typeof fillValue !== "string" && typeof fillValue !== "boolean") {
|
|
498
|
+
throw new Error("value must be text or a boolean for checkbox/radio");
|
|
499
|
+
}
|
|
500
|
+
if (id !== undefined)
|
|
501
|
+
return { action, ref_id: refId, id, value: fillValue };
|
|
502
|
+
if (selector)
|
|
503
|
+
return { action, ref_id: refId, selector, value: fillValue };
|
|
504
|
+
throw new Error("fill requires id or selector");
|
|
505
|
+
}
|
|
506
|
+
if (action === "press") {
|
|
507
|
+
const key = requiredString(value["key"], "key");
|
|
508
|
+
parseKeyChord(key);
|
|
509
|
+
return { action, ref_id: refId, key };
|
|
510
|
+
}
|
|
511
|
+
if (action === "wait") {
|
|
512
|
+
const conditions = ["selector", "text", "url_includes"];
|
|
513
|
+
const provided = conditions.filter((field) => value[field] !== undefined);
|
|
514
|
+
const field = provided[0];
|
|
515
|
+
if (provided.length !== 1 || !field) {
|
|
516
|
+
throw new Error("wait requires exactly one of selector, text, or url_includes");
|
|
517
|
+
}
|
|
518
|
+
const match = value[field];
|
|
519
|
+
if (typeof match !== "string" || !match.trim()) {
|
|
520
|
+
throw new Error(`${field} must be a non-empty string`);
|
|
521
|
+
}
|
|
522
|
+
const timeout = value["timeout_ms"] ?? 1e4;
|
|
523
|
+
if (!Number.isInteger(timeout) || Number(timeout) < 1 || Number(timeout) > 60000) {
|
|
524
|
+
throw new Error("timeout_ms must be an integer from 1 to 60000");
|
|
525
|
+
}
|
|
526
|
+
const base = {
|
|
527
|
+
action,
|
|
528
|
+
ref_id: refId,
|
|
529
|
+
timeout_ms: Number(timeout)
|
|
530
|
+
};
|
|
531
|
+
if (field === "selector")
|
|
532
|
+
return { ...base, selector: match };
|
|
533
|
+
if (field === "text")
|
|
534
|
+
return { ...base, text: match };
|
|
535
|
+
return { ...base, url_includes: match };
|
|
536
|
+
}
|
|
537
|
+
if (action === "load_all") {
|
|
538
|
+
const interval = value["interval_ms"] ?? 1500;
|
|
539
|
+
if (!Number.isInteger(interval) || Number(interval) < 0 || Number(interval) > 60000) {
|
|
540
|
+
throw new Error("interval_ms must be an integer from 0 to 60000");
|
|
541
|
+
}
|
|
542
|
+
return {
|
|
543
|
+
action,
|
|
544
|
+
ref_id: refId,
|
|
545
|
+
selector: requiredString(value["selector"], "selector"),
|
|
546
|
+
interval_ms: Number(interval)
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
if (action === "raw") {
|
|
550
|
+
const params = value["params"] ?? {};
|
|
551
|
+
if (!isRecordValue(params)) {
|
|
552
|
+
throw new Error("params must be an object when provided");
|
|
553
|
+
}
|
|
554
|
+
return {
|
|
555
|
+
action,
|
|
556
|
+
ref_id: refId,
|
|
557
|
+
method: requiredString(value["method"], "method"),
|
|
558
|
+
params
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
throw new Error(`unsupported action: ${action}`);
|
|
562
|
+
}
|
|
563
|
+
// packages/browser/src/browser/operation.ts
|
|
564
|
+
var BROWSER_ACTIONS = [
|
|
565
|
+
"help",
|
|
566
|
+
"start",
|
|
567
|
+
"tabs",
|
|
568
|
+
"open",
|
|
569
|
+
"show",
|
|
570
|
+
"close",
|
|
571
|
+
"find",
|
|
572
|
+
"click",
|
|
573
|
+
"type",
|
|
574
|
+
"fill",
|
|
575
|
+
"press",
|
|
576
|
+
"wait",
|
|
577
|
+
"screenshot",
|
|
578
|
+
"html",
|
|
579
|
+
"navigate",
|
|
580
|
+
"evaluate",
|
|
581
|
+
"network",
|
|
582
|
+
"load_all",
|
|
583
|
+
"raw",
|
|
584
|
+
"read_result",
|
|
585
|
+
"discard_result",
|
|
586
|
+
"stop"
|
|
587
|
+
];
|
|
588
|
+
var OPERATION_ORDER = BROWSER_ACTIONS.filter((action) => action !== "help");
|
|
589
|
+
|
|
590
|
+
// packages/browser/src/browser/parse-operation.ts
|
|
591
|
+
var fields = (...names) => new Set(["action", ...names]);
|
|
592
|
+
var ACTION_FIELDS = {
|
|
593
|
+
help: fields(),
|
|
594
|
+
start: fields(),
|
|
595
|
+
tabs: fields("query", "offset", "owned_only"),
|
|
596
|
+
open: fields("ref_id", "url", "lineno", "response_length"),
|
|
597
|
+
show: fields("ref_id"),
|
|
598
|
+
close: fields("ref_id"),
|
|
599
|
+
find: fields("ref_id", "pattern", "lineno", "response_length"),
|
|
600
|
+
click: fields("ref_id", "id", "selector", "x", "y"),
|
|
601
|
+
type: fields("ref_id", "id", "text"),
|
|
602
|
+
fill: fields("ref_id", "id", "selector", "value"),
|
|
603
|
+
press: fields("ref_id", "key"),
|
|
604
|
+
wait: fields("ref_id", "selector", "text", "url_includes", "timeout_ms"),
|
|
605
|
+
screenshot: fields("ref_id", "id", "selector"),
|
|
606
|
+
html: fields("ref_id", "id", "selector"),
|
|
607
|
+
navigate: fields("ref_id", "url"),
|
|
608
|
+
evaluate: fields("ref_id", "expression"),
|
|
609
|
+
network: fields("ref_id"),
|
|
610
|
+
load_all: fields("ref_id", "selector", "interval_ms"),
|
|
611
|
+
raw: fields("ref_id", "method", "params"),
|
|
612
|
+
read_result: fields("handle", "offset"),
|
|
613
|
+
discard_result: fields("handle"),
|
|
614
|
+
stop: fields("ref_id")
|
|
615
|
+
};
|
|
616
|
+
function resultHandle(value) {
|
|
617
|
+
const handle = requiredString(value, "handle");
|
|
618
|
+
if (!/^[a-f0-9-]{36}$/.test(handle)) {
|
|
619
|
+
throw new Error("handle is invalid");
|
|
620
|
+
}
|
|
621
|
+
return handle;
|
|
622
|
+
}
|
|
623
|
+
function browserAction(value) {
|
|
624
|
+
if (typeof value !== "string" || !BROWSER_ACTIONS.includes(value)) {
|
|
625
|
+
throw new Error(`action must be one of: ${BROWSER_ACTIONS.join(", ")}`);
|
|
626
|
+
}
|
|
627
|
+
return value;
|
|
628
|
+
}
|
|
629
|
+
function parseActionRequest(value) {
|
|
630
|
+
if (!isRecordValue(value))
|
|
631
|
+
throw new Error("input must be a JSON object");
|
|
632
|
+
const action = browserAction(value["action"]);
|
|
633
|
+
const unknown = Object.keys(value).filter((key) => key !== "response_length" && !ACTION_FIELDS[action].has(key));
|
|
634
|
+
if (unknown.length > 0) {
|
|
635
|
+
throw new Error(`unknown ${action} field(s): ${unknown.join(", ")}`);
|
|
636
|
+
}
|
|
637
|
+
if (action === "help" || action === "start")
|
|
638
|
+
return { action };
|
|
639
|
+
if (action === "tabs") {
|
|
640
|
+
const query = optionalString(value["query"], "query");
|
|
641
|
+
const ownedOnly = value["owned_only"];
|
|
642
|
+
if (ownedOnly !== undefined && typeof ownedOnly !== "boolean")
|
|
643
|
+
throw new Error("owned_only must be a boolean");
|
|
644
|
+
return {
|
|
645
|
+
action,
|
|
646
|
+
...query ? { query } : {},
|
|
647
|
+
offset: offset(value["offset"]),
|
|
648
|
+
...ownedOnly === undefined ? {} : { owned_only: ownedOnly }
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
if (action === "open") {
|
|
652
|
+
const refId = optionalString(value["ref_id"], "ref_id");
|
|
653
|
+
const url = optionalString(value["url"], "url");
|
|
654
|
+
if (Boolean(refId) === Boolean(url)) {
|
|
655
|
+
throw new Error("open requires exactly one of ref_id or url");
|
|
656
|
+
}
|
|
657
|
+
if (url)
|
|
658
|
+
return { action, url };
|
|
659
|
+
if (!refId)
|
|
660
|
+
throw new Error("open requires ref_id or url");
|
|
661
|
+
return {
|
|
662
|
+
action,
|
|
663
|
+
ref_id: refId,
|
|
664
|
+
lineno: line(value["lineno"]),
|
|
665
|
+
response_length: responseLength(value["response_length"])
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
if (action === "find") {
|
|
669
|
+
return {
|
|
670
|
+
action,
|
|
671
|
+
ref_id: requiredRef(value["ref_id"], action),
|
|
672
|
+
pattern: requiredString(value["pattern"], "pattern"),
|
|
673
|
+
lineno: line(value["lineno"]),
|
|
674
|
+
response_length: responseLength(value["response_length"])
|
|
675
|
+
};
|
|
676
|
+
}
|
|
677
|
+
if (action === "read_result") {
|
|
678
|
+
return {
|
|
679
|
+
action,
|
|
680
|
+
handle: resultHandle(value["handle"]),
|
|
681
|
+
offset: offset(value["offset"])
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
if (action === "discard_result") {
|
|
685
|
+
return { action, handle: resultHandle(value["handle"]) };
|
|
686
|
+
}
|
|
687
|
+
if (action === "stop") {
|
|
688
|
+
const refId = optionalString(value["ref_id"], "ref_id");
|
|
689
|
+
return { action, ...refId ? { ref_id: refId } : {} };
|
|
690
|
+
}
|
|
691
|
+
return parseTabOperation(action, requiredRef(value["ref_id"], action), value);
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
// packages/browser/src/browser/routes.ts
|
|
695
|
+
class BrowserRoutes {
|
|
696
|
+
names;
|
|
697
|
+
routes;
|
|
698
|
+
constructor(routes = new Map) {
|
|
699
|
+
this.routes = routes;
|
|
700
|
+
this.names = [...routes.keys()];
|
|
701
|
+
}
|
|
702
|
+
resolve(name) {
|
|
703
|
+
const route = this.routes.get(name);
|
|
704
|
+
if (route)
|
|
705
|
+
return route;
|
|
706
|
+
if (this.names.length === 0) {
|
|
707
|
+
throw new Error("Browser host routing is disabled");
|
|
708
|
+
}
|
|
709
|
+
throw new Error(`browser host must be one of: ${this.names.join(", ")}`);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
// packages/browser/src/browser/runtime.ts
|
|
714
|
+
import { randomUUID } from "node:crypto";
|
|
715
|
+
import { isAbsolute as isAbsolute2, join as join5 } from "node:path";
|
|
716
|
+
|
|
717
|
+
// packages/browser/src/cdp/serial.ts
|
|
718
|
+
function waitForTurn(promise, signal) {
|
|
719
|
+
if (!signal)
|
|
720
|
+
return promise;
|
|
721
|
+
if (signal.aborted) {
|
|
722
|
+
return Promise.reject(signal.reason ?? new Error("Operation aborted"));
|
|
723
|
+
}
|
|
724
|
+
return new Promise((resolveValue, reject) => {
|
|
725
|
+
const abort = () => reject(signal.reason ?? new Error("Operation aborted"));
|
|
726
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
727
|
+
promise.then((value) => {
|
|
728
|
+
signal.removeEventListener("abort", abort);
|
|
729
|
+
resolveValue(value);
|
|
730
|
+
}, (error) => {
|
|
731
|
+
signal.removeEventListener("abort", abort);
|
|
732
|
+
reject(error);
|
|
733
|
+
});
|
|
734
|
+
});
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
// packages/browser/src/cdp/discovery.ts
|
|
738
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
739
|
+
import http from "node:http";
|
|
740
|
+
import { homedir } from "node:os";
|
|
741
|
+
import { resolve } from "node:path";
|
|
742
|
+
|
|
743
|
+
// packages/browser/src/cdp/types.ts
|
|
744
|
+
function asRecord(value, label = "CDP response") {
|
|
745
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
746
|
+
throw new Error(`${label} is not an object`);
|
|
747
|
+
}
|
|
748
|
+
return value;
|
|
749
|
+
}
|
|
750
|
+
function asString(value, label) {
|
|
751
|
+
if (typeof value !== "string")
|
|
752
|
+
throw new Error(`${label} is not a string`);
|
|
753
|
+
return value;
|
|
754
|
+
}
|
|
755
|
+
function errorMessage(error) {
|
|
756
|
+
return error instanceof Error ? error.message : String(error);
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
// packages/browser/src/cdp/discovery.ts
|
|
760
|
+
var CDP_TIMEOUT_MS = 15000;
|
|
761
|
+
var NAVIGATION_TIMEOUT_MS = 30000;
|
|
762
|
+
var MIN_TARGET_PREFIX_LENGTH = 8;
|
|
763
|
+
var IS_WINDOWS3 = process.platform === "win32";
|
|
764
|
+
function getJson(url, timeout = 2000, signal) {
|
|
765
|
+
return new Promise((resolveValue, reject) => {
|
|
766
|
+
const request = http.get(url, { timeout, signal }, (response) => {
|
|
767
|
+
let body = "";
|
|
768
|
+
response.setEncoding("utf8");
|
|
769
|
+
response.on("data", (chunk) => {
|
|
770
|
+
body += chunk;
|
|
771
|
+
if (Buffer.byteLength(body) > 1024 * 1024)
|
|
772
|
+
request.destroy(new Error("CDP discovery response exceeded 1 MiB"));
|
|
773
|
+
});
|
|
774
|
+
response.on("end", () => {
|
|
775
|
+
const status = response.statusCode ?? 0;
|
|
776
|
+
if (status < 200 || status >= 300) {
|
|
777
|
+
reject(new Error(`HTTP ${status} from ${url}`));
|
|
778
|
+
return;
|
|
779
|
+
}
|
|
780
|
+
try {
|
|
781
|
+
resolveValue(JSON.parse(body));
|
|
782
|
+
} catch (error) {
|
|
783
|
+
reject(error);
|
|
784
|
+
}
|
|
785
|
+
});
|
|
786
|
+
});
|
|
787
|
+
request.on("timeout", () => request.destroy(new Error(`Timeout fetching ${url}`)));
|
|
788
|
+
request.on("error", reject);
|
|
789
|
+
});
|
|
790
|
+
}
|
|
791
|
+
async function probeDebugPort(port, host = process.env["CDP_HOST"] ?? "127.0.0.1", signal) {
|
|
792
|
+
const version = asRecord(await getJson(`http://${host}:${port}/json/version`, 2000, signal), "CDP version response");
|
|
793
|
+
return asString(version["webSocketDebuggerUrl"], "CDP webSocketDebuggerUrl");
|
|
794
|
+
}
|
|
795
|
+
async function getWebSocketUrl(signal, recovery = "Enable remote debugging or set CDP_PORT/CDP_PORT_FILE.") {
|
|
796
|
+
const home = homedir();
|
|
797
|
+
const macBrowsers = [
|
|
798
|
+
"Google/Chrome",
|
|
799
|
+
"Google/Chrome Beta",
|
|
800
|
+
"Google/Chrome for Testing",
|
|
801
|
+
"Chromium",
|
|
802
|
+
"BraveSoftware/Brave-Browser",
|
|
803
|
+
"Microsoft Edge"
|
|
804
|
+
];
|
|
805
|
+
const linuxBrowsers = [
|
|
806
|
+
"google-chrome",
|
|
807
|
+
"google-chrome-beta",
|
|
808
|
+
"chromium",
|
|
809
|
+
"vivaldi",
|
|
810
|
+
"vivaldi-snapshot",
|
|
811
|
+
"BraveSoftware/Brave-Browser",
|
|
812
|
+
"microsoft-edge"
|
|
813
|
+
];
|
|
814
|
+
const flatpakBrowsers = [
|
|
815
|
+
["org.chromium.Chromium", "chromium"],
|
|
816
|
+
["com.google.Chrome", "google-chrome"],
|
|
817
|
+
["com.brave.Browser", "BraveSoftware/Brave-Browser"],
|
|
818
|
+
["com.microsoft.Edge", "microsoft-edge"],
|
|
819
|
+
["com.vivaldi.Vivaldi", "vivaldi"]
|
|
820
|
+
];
|
|
821
|
+
const candidates = [
|
|
822
|
+
process.env["CDP_PORT_FILE"],
|
|
823
|
+
...macBrowsers.flatMap((browser) => [
|
|
824
|
+
resolve(home, "Library/Application Support", browser, "DevToolsActivePort"),
|
|
825
|
+
resolve(home, "Library/Application Support", browser, "Default/DevToolsActivePort")
|
|
826
|
+
]),
|
|
827
|
+
...linuxBrowsers.flatMap((browser) => [
|
|
828
|
+
resolve(home, ".config", browser, "DevToolsActivePort"),
|
|
829
|
+
resolve(home, ".config", browser, "Default/DevToolsActivePort")
|
|
830
|
+
]),
|
|
831
|
+
...flatpakBrowsers.flatMap(([appId, browser]) => [
|
|
832
|
+
resolve(home, ".var/app", appId, "config", browser, "DevToolsActivePort"),
|
|
833
|
+
resolve(home, ".var/app", appId, "config", browser, "Default/DevToolsActivePort")
|
|
834
|
+
]),
|
|
835
|
+
...IS_WINDOWS3 ? [
|
|
836
|
+
"Google/Chrome",
|
|
837
|
+
"BraveSoftware/Brave-Browser",
|
|
838
|
+
"Microsoft/Edge"
|
|
839
|
+
].flatMap((browser) => {
|
|
840
|
+
const base = process.env["LOCALAPPDATA"] ?? resolve(home, "AppData/Local");
|
|
841
|
+
return [
|
|
842
|
+
resolve(base, browser, "User Data", "DevToolsActivePort"),
|
|
843
|
+
resolve(base, browser, "User Data", "Default/DevToolsActivePort")
|
|
844
|
+
];
|
|
845
|
+
}) : []
|
|
846
|
+
].filter((candidate) => Boolean(candidate));
|
|
847
|
+
const host = process.env["CDP_HOST"] ?? "127.0.0.1";
|
|
848
|
+
const port = process.env["CDP_PORT"] ?? "9222";
|
|
849
|
+
try {
|
|
850
|
+
return await probeDebugPort(port, host, signal);
|
|
851
|
+
} catch (error) {
|
|
852
|
+
signal?.throwIfAborted();
|
|
853
|
+
const portFile = candidates.find((candidate) => existsSync(candidate));
|
|
854
|
+
if (portFile) {
|
|
855
|
+
const lines = readFileSync(portFile, "utf8").trim().split(`
|
|
856
|
+
`);
|
|
857
|
+
if (!lines[0] || !lines[1]) {
|
|
858
|
+
throw new Error(`Invalid DevToolsActivePort file: ${portFile}`);
|
|
859
|
+
}
|
|
860
|
+
return `ws://${host}:${lines[0]}${lines[1]}`;
|
|
861
|
+
}
|
|
862
|
+
throw new Error(`CDP HTTP discovery failed and no DevToolsActivePort found. ${recovery} Tried: ${host}:${port} ${errorMessage(error)}`);
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
function sleep(ms, signal) {
|
|
866
|
+
if (signal?.aborted) {
|
|
867
|
+
return Promise.reject(signal.reason ?? new Error("Operation aborted"));
|
|
868
|
+
}
|
|
869
|
+
return new Promise((resolveValue, reject) => {
|
|
870
|
+
const cleanup = () => signal?.removeEventListener("abort", abort);
|
|
871
|
+
const timer = setTimeout(() => {
|
|
872
|
+
cleanup();
|
|
873
|
+
resolveValue();
|
|
874
|
+
}, ms);
|
|
875
|
+
const abort = () => {
|
|
876
|
+
clearTimeout(timer);
|
|
877
|
+
cleanup();
|
|
878
|
+
reject(signal?.reason ?? new Error("Operation aborted"));
|
|
879
|
+
};
|
|
880
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
881
|
+
});
|
|
882
|
+
}
|
|
883
|
+
function resolvePrefix(prefix, candidates, noun = "target", missingHint = "") {
|
|
884
|
+
const upper = prefix.toUpperCase();
|
|
885
|
+
const matches = candidates.filter((candidate) => candidate.toUpperCase().startsWith(upper));
|
|
886
|
+
if (matches.length === 0) {
|
|
887
|
+
throw new Error(`No ${noun} matching prefix "${prefix}".${missingHint ? ` ${missingHint}` : ""}`);
|
|
888
|
+
}
|
|
889
|
+
if (matches.length > 1) {
|
|
890
|
+
throw new Error(`Ambiguous prefix "${prefix}" matches ${matches.length} ${noun}s. Use more characters.`);
|
|
891
|
+
}
|
|
892
|
+
const match = matches[0];
|
|
893
|
+
if (!match)
|
|
894
|
+
throw new Error(`No ${noun} matching prefix "${prefix}".`);
|
|
895
|
+
return match;
|
|
896
|
+
}
|
|
897
|
+
function getDisplayPrefixLength(targetIds) {
|
|
898
|
+
if (targetIds.length === 0)
|
|
899
|
+
return MIN_TARGET_PREFIX_LENGTH;
|
|
900
|
+
const maxLength = Math.max(...targetIds.map((id) => id.length));
|
|
901
|
+
for (let length = MIN_TARGET_PREFIX_LENGTH;length <= maxLength; length++) {
|
|
902
|
+
const prefixes = new Set(targetIds.map((id) => id.slice(0, length).toUpperCase()));
|
|
903
|
+
if (prefixes.size === targetIds.length)
|
|
904
|
+
return length;
|
|
905
|
+
}
|
|
906
|
+
return maxLength;
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
// packages/browser/src/cdp/client.ts
|
|
910
|
+
var RETRYABLE_TIMEOUT_METHODS = new Set([
|
|
911
|
+
"Accessibility.getFullAXTree",
|
|
912
|
+
"Page.captureScreenshot",
|
|
913
|
+
"Runtime.enable"
|
|
914
|
+
]);
|
|
915
|
+
|
|
916
|
+
class CdpTimeoutError extends Error {
|
|
917
|
+
}
|
|
918
|
+
function cdpTimeoutAttempts(method) {
|
|
919
|
+
return RETRYABLE_TIMEOUT_METHODS.has(method) ? 2 : 1;
|
|
920
|
+
}
|
|
921
|
+
function timeoutError(method, attempts) {
|
|
922
|
+
const seconds = CDP_TIMEOUT_MS / 1000;
|
|
923
|
+
if (attempts > 1) {
|
|
924
|
+
return new Error(`Chrome did not answer ${method} after two ${seconds}s attempts. The tab may be unresponsive or suspended.`);
|
|
925
|
+
}
|
|
926
|
+
if (method === "Runtime.evaluate") {
|
|
927
|
+
return new Error(`Chrome did not answer Runtime.evaluate within ${seconds}s. The expression or awaited promise may still be running; check its effect before retrying.`);
|
|
928
|
+
}
|
|
929
|
+
return new Error(`Chrome did not answer ${method} within ${seconds}s.`);
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
class CdpClient {
|
|
933
|
+
socket;
|
|
934
|
+
nextId = 0;
|
|
935
|
+
pending = new Map;
|
|
936
|
+
eventHandlers = new Map;
|
|
937
|
+
closeHandlers = new Set;
|
|
938
|
+
async connect(url, signal) {
|
|
939
|
+
if (signal?.aborted) {
|
|
940
|
+
throw signal.reason ?? new Error("CDP connection aborted");
|
|
941
|
+
}
|
|
942
|
+
await new Promise((resolveValue, reject) => {
|
|
943
|
+
const socket = new WebSocket(url);
|
|
944
|
+
this.socket = socket;
|
|
945
|
+
let settled = false;
|
|
946
|
+
const cleanup = () => signal?.removeEventListener("abort", abort);
|
|
947
|
+
const fail = (error) => {
|
|
948
|
+
if (settled)
|
|
949
|
+
return;
|
|
950
|
+
settled = true;
|
|
951
|
+
cleanup();
|
|
952
|
+
reject(error);
|
|
953
|
+
};
|
|
954
|
+
const abort = () => {
|
|
955
|
+
socket.close();
|
|
956
|
+
fail(signal?.reason ?? new Error("CDP connection aborted"));
|
|
957
|
+
};
|
|
958
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
959
|
+
socket.onopen = () => {
|
|
960
|
+
if (settled)
|
|
961
|
+
return;
|
|
962
|
+
settled = true;
|
|
963
|
+
cleanup();
|
|
964
|
+
resolveValue();
|
|
965
|
+
};
|
|
966
|
+
socket.onerror = (event) => fail(new Error(`WebSocket error: ${"message" in event ? String(event.message) : event.type}`));
|
|
967
|
+
socket.onmessage = (event) => this.handleMessage(event.data);
|
|
968
|
+
socket.onclose = () => this.handleClose();
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
async send(method, params = {}, sessionId, signal) {
|
|
972
|
+
const attempts = cdpTimeoutAttempts(method);
|
|
973
|
+
for (let attempt = 1;attempt <= attempts; attempt++) {
|
|
974
|
+
try {
|
|
975
|
+
return await this.sendOnce(method, params, sessionId, signal);
|
|
976
|
+
} catch (error) {
|
|
977
|
+
if (!(error instanceof CdpTimeoutError))
|
|
978
|
+
throw error;
|
|
979
|
+
if (attempt === attempts)
|
|
980
|
+
throw timeoutError(method, attempts);
|
|
981
|
+
await sleep(100, signal);
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
throw new Error(`Could not send ${method}`);
|
|
985
|
+
}
|
|
986
|
+
onEvent(method, handler) {
|
|
987
|
+
const handlers = this.eventHandlers.get(method) ?? new Set;
|
|
988
|
+
handlers.add(handler);
|
|
989
|
+
this.eventHandlers.set(method, handlers);
|
|
990
|
+
return () => {
|
|
991
|
+
handlers.delete(handler);
|
|
992
|
+
if (handlers.size === 0)
|
|
993
|
+
this.eventHandlers.delete(method);
|
|
994
|
+
};
|
|
995
|
+
}
|
|
996
|
+
waitForEvent(method, timeout = CDP_TIMEOUT_MS, signal) {
|
|
997
|
+
if (signal?.aborted) {
|
|
998
|
+
return {
|
|
999
|
+
promise: Promise.reject(signal.reason ?? new Error("Operation aborted")),
|
|
1000
|
+
cancel() {}
|
|
1001
|
+
};
|
|
1002
|
+
}
|
|
1003
|
+
let settled = false;
|
|
1004
|
+
let timer;
|
|
1005
|
+
let off;
|
|
1006
|
+
let abort;
|
|
1007
|
+
const cleanup = () => {
|
|
1008
|
+
if (timer)
|
|
1009
|
+
clearTimeout(timer);
|
|
1010
|
+
off?.();
|
|
1011
|
+
if (abort)
|
|
1012
|
+
signal?.removeEventListener("abort", abort);
|
|
1013
|
+
};
|
|
1014
|
+
const promise = new Promise((resolveValue, reject) => {
|
|
1015
|
+
off = this.onEvent(method, (params) => {
|
|
1016
|
+
if (settled)
|
|
1017
|
+
return;
|
|
1018
|
+
settled = true;
|
|
1019
|
+
cleanup();
|
|
1020
|
+
resolveValue(params);
|
|
1021
|
+
});
|
|
1022
|
+
timer = setTimeout(() => {
|
|
1023
|
+
if (settled)
|
|
1024
|
+
return;
|
|
1025
|
+
settled = true;
|
|
1026
|
+
cleanup();
|
|
1027
|
+
reject(new Error(`Timeout waiting for event: ${method}`));
|
|
1028
|
+
}, timeout);
|
|
1029
|
+
abort = () => {
|
|
1030
|
+
if (settled)
|
|
1031
|
+
return;
|
|
1032
|
+
settled = true;
|
|
1033
|
+
cleanup();
|
|
1034
|
+
reject(signal?.reason ?? new Error("Operation aborted"));
|
|
1035
|
+
};
|
|
1036
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
1037
|
+
});
|
|
1038
|
+
return {
|
|
1039
|
+
promise,
|
|
1040
|
+
cancel() {
|
|
1041
|
+
if (settled)
|
|
1042
|
+
return;
|
|
1043
|
+
settled = true;
|
|
1044
|
+
cleanup();
|
|
1045
|
+
}
|
|
1046
|
+
};
|
|
1047
|
+
}
|
|
1048
|
+
onClose(handler) {
|
|
1049
|
+
this.closeHandlers.add(handler);
|
|
1050
|
+
return () => this.closeHandlers.delete(handler);
|
|
1051
|
+
}
|
|
1052
|
+
close() {
|
|
1053
|
+
this.socket?.close();
|
|
1054
|
+
this.socket = undefined;
|
|
1055
|
+
}
|
|
1056
|
+
sendOnce(method, params, sessionId, signal) {
|
|
1057
|
+
if (signal?.aborted) {
|
|
1058
|
+
return Promise.reject(signal.reason ?? new Error(`${method} aborted`));
|
|
1059
|
+
}
|
|
1060
|
+
const socket = this.socket;
|
|
1061
|
+
if (!socket || socket.readyState !== WebSocket.OPEN) {
|
|
1062
|
+
return Promise.reject(new Error("CDP is not connected"));
|
|
1063
|
+
}
|
|
1064
|
+
const id = ++this.nextId;
|
|
1065
|
+
return new Promise((resolveValue, reject) => {
|
|
1066
|
+
const timer = setTimeout(() => {
|
|
1067
|
+
this.finishPending(id)?.reject(new CdpTimeoutError(method));
|
|
1068
|
+
}, CDP_TIMEOUT_MS);
|
|
1069
|
+
const abort = () => {
|
|
1070
|
+
const pending = this.pending.get(id);
|
|
1071
|
+
if (!pending)
|
|
1072
|
+
return;
|
|
1073
|
+
this.pending.delete(id);
|
|
1074
|
+
clearTimeout(pending.timer);
|
|
1075
|
+
reject(signal?.reason ?? new Error(`${method} aborted`));
|
|
1076
|
+
};
|
|
1077
|
+
this.pending.set(id, {
|
|
1078
|
+
resolve: resolveValue,
|
|
1079
|
+
reject,
|
|
1080
|
+
timer,
|
|
1081
|
+
...signal ? { signal, abort } : {}
|
|
1082
|
+
});
|
|
1083
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
1084
|
+
try {
|
|
1085
|
+
socket.send(JSON.stringify({
|
|
1086
|
+
id,
|
|
1087
|
+
method,
|
|
1088
|
+
params,
|
|
1089
|
+
...sessionId ? { sessionId } : {}
|
|
1090
|
+
}));
|
|
1091
|
+
} catch (error) {
|
|
1092
|
+
this.finishPending(id);
|
|
1093
|
+
reject(error);
|
|
1094
|
+
}
|
|
1095
|
+
});
|
|
1096
|
+
}
|
|
1097
|
+
handleMessage(data) {
|
|
1098
|
+
let message;
|
|
1099
|
+
try {
|
|
1100
|
+
message = asRecord(JSON.parse(String(data)), "CDP message");
|
|
1101
|
+
} catch {
|
|
1102
|
+
return;
|
|
1103
|
+
}
|
|
1104
|
+
const id = message["id"];
|
|
1105
|
+
if (typeof id === "number" && this.pending.has(id)) {
|
|
1106
|
+
const pending = this.finishPending(id);
|
|
1107
|
+
if (!pending)
|
|
1108
|
+
return;
|
|
1109
|
+
const error = message["error"];
|
|
1110
|
+
if (error) {
|
|
1111
|
+
const record = asRecord(error, "CDP error");
|
|
1112
|
+
pending.reject(new Error(typeof record["message"] === "string" ? record["message"] : "Unknown CDP error"));
|
|
1113
|
+
} else {
|
|
1114
|
+
pending.resolve(message["result"]);
|
|
1115
|
+
}
|
|
1116
|
+
return;
|
|
1117
|
+
}
|
|
1118
|
+
const method = message["method"];
|
|
1119
|
+
if (typeof method !== "string")
|
|
1120
|
+
return;
|
|
1121
|
+
for (const handler of this.eventHandlers.get(method) ?? []) {
|
|
1122
|
+
handler(message["params"] ?? {});
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
finishPending(id) {
|
|
1126
|
+
const pending = this.pending.get(id);
|
|
1127
|
+
if (!pending)
|
|
1128
|
+
return;
|
|
1129
|
+
this.pending.delete(id);
|
|
1130
|
+
clearTimeout(pending.timer);
|
|
1131
|
+
if (pending.abort) {
|
|
1132
|
+
pending.signal?.removeEventListener("abort", pending.abort);
|
|
1133
|
+
}
|
|
1134
|
+
return pending;
|
|
1135
|
+
}
|
|
1136
|
+
handleClose() {
|
|
1137
|
+
this.socket = undefined;
|
|
1138
|
+
for (const [id, pending] of this.pending) {
|
|
1139
|
+
this.finishPending(id);
|
|
1140
|
+
pending.reject(new Error("Chrome disconnected"));
|
|
1141
|
+
}
|
|
1142
|
+
for (const handler of this.closeHandlers) {
|
|
1143
|
+
try {
|
|
1144
|
+
handler();
|
|
1145
|
+
} catch (error) {
|
|
1146
|
+
process.stderr.write(`Browser close handler failed: ${errorMessage(error)}
|
|
1147
|
+
`);
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
// packages/browser/src/cdp/tab-bridge.ts
|
|
1154
|
+
var TAB_IDLE_MS = 20 * 60 * 1000;
|
|
1155
|
+
|
|
1156
|
+
class TabBridge {
|
|
1157
|
+
elementRefs = new Map;
|
|
1158
|
+
targetId;
|
|
1159
|
+
cdp;
|
|
1160
|
+
sessionId;
|
|
1161
|
+
tail = Promise.resolve();
|
|
1162
|
+
idleTimer;
|
|
1163
|
+
closed = false;
|
|
1164
|
+
closing;
|
|
1165
|
+
backgroundRendering = false;
|
|
1166
|
+
onClose;
|
|
1167
|
+
constructor(targetId, cdp, sessionId, onClose) {
|
|
1168
|
+
this.targetId = targetId;
|
|
1169
|
+
this.cdp = cdp;
|
|
1170
|
+
this.sessionId = sessionId;
|
|
1171
|
+
this.onClose = onClose;
|
|
1172
|
+
this.resetIdle();
|
|
1173
|
+
cdp.onEvent("Target.targetDestroyed", (value) => {
|
|
1174
|
+
const event = asRecord(value, "target destroyed event");
|
|
1175
|
+
if (event["targetId"] === targetId)
|
|
1176
|
+
this.close(false);
|
|
1177
|
+
});
|
|
1178
|
+
cdp.onEvent("Target.detachedFromTarget", (value) => {
|
|
1179
|
+
const event = asRecord(value, "target detached event");
|
|
1180
|
+
if (event["sessionId"] === sessionId)
|
|
1181
|
+
this.close(false);
|
|
1182
|
+
});
|
|
1183
|
+
cdp.onClose(() => this.close(false));
|
|
1184
|
+
}
|
|
1185
|
+
static async connect(targetId, onClose, signal, discover) {
|
|
1186
|
+
const cdp = new CdpClient;
|
|
1187
|
+
try {
|
|
1188
|
+
await cdp.connect(await discover(signal), signal);
|
|
1189
|
+
const response = asRecord(await cdp.send("Target.attachToTarget", { targetId, flatten: true }, undefined, signal), "Target.attachToTarget response");
|
|
1190
|
+
if (typeof response["sessionId"] !== "string") {
|
|
1191
|
+
throw new Error("Chrome did not return a tab session");
|
|
1192
|
+
}
|
|
1193
|
+
return new TabBridge(targetId, cdp, response["sessionId"], onClose);
|
|
1194
|
+
} catch (error) {
|
|
1195
|
+
cdp.close();
|
|
1196
|
+
throw error;
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
async run(refId, signal, action) {
|
|
1200
|
+
if (this.closed)
|
|
1201
|
+
throw new Error("Tab bridge is closed");
|
|
1202
|
+
let release;
|
|
1203
|
+
const turn = new Promise((resolveValue) => {
|
|
1204
|
+
release = resolveValue;
|
|
1205
|
+
});
|
|
1206
|
+
const previous = this.tail;
|
|
1207
|
+
this.tail = previous.then(() => turn, () => turn);
|
|
1208
|
+
try {
|
|
1209
|
+
await waitForTurn(previous, signal);
|
|
1210
|
+
if (this.closed)
|
|
1211
|
+
throw new Error("Tab bridge is closed");
|
|
1212
|
+
this.resetIdle();
|
|
1213
|
+
return await action({
|
|
1214
|
+
cdp: this.cdp,
|
|
1215
|
+
sessionId: this.sessionId,
|
|
1216
|
+
elementRefs: this.elementRefs,
|
|
1217
|
+
refId
|
|
1218
|
+
});
|
|
1219
|
+
} finally {
|
|
1220
|
+
release();
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
async setBackgroundRendering(enabled, signal) {
|
|
1224
|
+
if (this.backgroundRendering === enabled)
|
|
1225
|
+
return;
|
|
1226
|
+
this.backgroundRendering = undefined;
|
|
1227
|
+
await this.cdp.send("Emulation.setFocusEmulationEnabled", { enabled }, this.sessionId, signal);
|
|
1228
|
+
this.backgroundRendering = enabled;
|
|
1229
|
+
}
|
|
1230
|
+
close(detach = true) {
|
|
1231
|
+
if (this.closing)
|
|
1232
|
+
return this.closing;
|
|
1233
|
+
if (this.closed)
|
|
1234
|
+
return Promise.resolve();
|
|
1235
|
+
this.closed = true;
|
|
1236
|
+
if (this.idleTimer)
|
|
1237
|
+
clearTimeout(this.idleTimer);
|
|
1238
|
+
this.elementRefs.clear();
|
|
1239
|
+
if (detach) {
|
|
1240
|
+
this.closing = this.cdp.send("Target.detachFromTarget", { sessionId: this.sessionId }, undefined, undefined).then(() => {
|
|
1241
|
+
return;
|
|
1242
|
+
}).catch(() => {
|
|
1243
|
+
return;
|
|
1244
|
+
}).finally(() => this.cdp.close());
|
|
1245
|
+
} else {
|
|
1246
|
+
this.cdp.close();
|
|
1247
|
+
this.closing = Promise.resolve();
|
|
1248
|
+
}
|
|
1249
|
+
this.onClose();
|
|
1250
|
+
return this.closing;
|
|
1251
|
+
}
|
|
1252
|
+
resetIdle() {
|
|
1253
|
+
if (this.idleTimer)
|
|
1254
|
+
clearTimeout(this.idleTimer);
|
|
1255
|
+
this.idleTimer = setTimeout(() => this.close(), TAB_IDLE_MS);
|
|
1256
|
+
this.idleTimer.unref?.();
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
// packages/browser/src/cdp/tabs.ts
|
|
1261
|
+
import { createHash } from "node:crypto";
|
|
1262
|
+
import { lstat as lstat2, mkdir as mkdir3, readdir as readdir2, rm as rm3, utimes, writeFile as writeFile2 } from "node:fs/promises";
|
|
1263
|
+
import { join as join3 } from "node:path";
|
|
1264
|
+
|
|
1265
|
+
// packages/browser/src/cdp/pages.ts
|
|
1266
|
+
function pageInfo(value) {
|
|
1267
|
+
const record = asRecord(value, "CDP target");
|
|
1268
|
+
return {
|
|
1269
|
+
targetId: asString(record["targetId"], "targetId"),
|
|
1270
|
+
title: typeof record["title"] === "string" ? record["title"] : "",
|
|
1271
|
+
url: asString(record["url"], "target URL"),
|
|
1272
|
+
...typeof record["type"] === "string" ? { type: record["type"] } : {},
|
|
1273
|
+
...typeof record["openerId"] === "string" ? { openerId: record["openerId"] } : {}
|
|
1274
|
+
};
|
|
1275
|
+
}
|
|
1276
|
+
async function getPageTargets(cdp, signal) {
|
|
1277
|
+
const response = asRecord(await cdp.send("Target.getTargets", {}, undefined, signal), "Target.getTargets response");
|
|
1278
|
+
const targetInfos = response["targetInfos"];
|
|
1279
|
+
if (!Array.isArray(targetInfos)) {
|
|
1280
|
+
throw new Error("Target.getTargets response has no targetInfos");
|
|
1281
|
+
}
|
|
1282
|
+
return targetInfos.map(pageInfo).filter((target) => target.type === "page");
|
|
1283
|
+
}
|
|
1284
|
+
function getDisplayedPages(targets) {
|
|
1285
|
+
return targets.filter((target) => !target.url.startsWith("chrome://"));
|
|
1286
|
+
}
|
|
1287
|
+
async function waitForOpenedTarget(cdp, targetId, requestedUrl, timeout = 5000, signal) {
|
|
1288
|
+
if (requestedUrl === "about:blank") {
|
|
1289
|
+
return {
|
|
1290
|
+
targetId,
|
|
1291
|
+
title: requestedUrl,
|
|
1292
|
+
url: requestedUrl,
|
|
1293
|
+
type: "page"
|
|
1294
|
+
};
|
|
1295
|
+
}
|
|
1296
|
+
const deadline = Date.now() + timeout;
|
|
1297
|
+
while (Date.now() < deadline) {
|
|
1298
|
+
const response = asRecord(await cdp.send("Target.getTargetInfo", { targetId }, undefined, signal), "Target.getTargetInfo response");
|
|
1299
|
+
const target = pageInfo(response["targetInfo"]);
|
|
1300
|
+
if (target.url && target.url !== "about:blank")
|
|
1301
|
+
return target;
|
|
1302
|
+
await sleep(100, signal);
|
|
1303
|
+
}
|
|
1304
|
+
throw new Error(`New tab did not begin navigating to ${requestedUrl}`);
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
// packages/browser/src/cdp/url.ts
|
|
1308
|
+
function assertHttpUrl(value) {
|
|
1309
|
+
let parsed;
|
|
1310
|
+
try {
|
|
1311
|
+
parsed = new URL(value);
|
|
1312
|
+
} catch {
|
|
1313
|
+
throw new Error(`Invalid URL: ${value}`);
|
|
1314
|
+
}
|
|
1315
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
1316
|
+
throw new Error(`Only http/https URLs allowed, got: ${value}`);
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
// packages/browser/src/cdp/tabs.ts
|
|
1321
|
+
var TARGET_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
1322
|
+
var SCOPE_ID = /^[a-f0-9]{64}$/;
|
|
1323
|
+
var SCOPE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
1324
|
+
var SCOPE_PRUNE_LIMIT = 32;
|
|
1325
|
+
function missing(error) {
|
|
1326
|
+
return error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
1327
|
+
}
|
|
1328
|
+
async function pruneOwnershipScopes(directory, currentScope, now = Date.now()) {
|
|
1329
|
+
let entries;
|
|
1330
|
+
try {
|
|
1331
|
+
entries = await readdir2(directory, { withFileTypes: true });
|
|
1332
|
+
} catch (error) {
|
|
1333
|
+
if (missing(error))
|
|
1334
|
+
return;
|
|
1335
|
+
throw error;
|
|
1336
|
+
}
|
|
1337
|
+
const stale = [];
|
|
1338
|
+
for (const entry of entries) {
|
|
1339
|
+
if (entry.name === currentScope || !SCOPE_ID.test(entry.name) || !entry.isDirectory())
|
|
1340
|
+
continue;
|
|
1341
|
+
const path = join3(directory, entry.name);
|
|
1342
|
+
try {
|
|
1343
|
+
const info = await lstat2(path);
|
|
1344
|
+
if (info.isDirectory() && !info.isSymbolicLink() && now - info.mtimeMs > SCOPE_TTL_MS) {
|
|
1345
|
+
stale.push({ path, mtimeMs: info.mtimeMs });
|
|
1346
|
+
}
|
|
1347
|
+
} catch (error) {
|
|
1348
|
+
if (!missing(error))
|
|
1349
|
+
throw error;
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
stale.sort((left, right) => left.mtimeMs - right.mtimeMs);
|
|
1353
|
+
await Promise.all(stale.slice(0, SCOPE_PRUNE_LIMIT).map((scope) => rm3(scope.path, { force: true, recursive: true })));
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
class BrowserTabs {
|
|
1357
|
+
cdp;
|
|
1358
|
+
directory;
|
|
1359
|
+
ownershipDirectory;
|
|
1360
|
+
scope;
|
|
1361
|
+
tail = Promise.resolve();
|
|
1362
|
+
closed = false;
|
|
1363
|
+
prepared = false;
|
|
1364
|
+
constructor(cdp, ownerId, directory, browserUrl) {
|
|
1365
|
+
this.cdp = cdp;
|
|
1366
|
+
this.ownershipDirectory = directory;
|
|
1367
|
+
this.scope = createHash("sha256").update(`${browserUrl}\x00${ownerId}`).digest("hex");
|
|
1368
|
+
this.directory = join3(directory, this.scope);
|
|
1369
|
+
}
|
|
1370
|
+
list(signal) {
|
|
1371
|
+
return this.enqueue(() => this.listNow(signal), signal);
|
|
1372
|
+
}
|
|
1373
|
+
async shutdown() {
|
|
1374
|
+
this.closed = true;
|
|
1375
|
+
await this.tail;
|
|
1376
|
+
}
|
|
1377
|
+
enqueue(action, signal) {
|
|
1378
|
+
const pending = this.tail.then(async () => {
|
|
1379
|
+
signal?.throwIfAborted();
|
|
1380
|
+
if (this.closed)
|
|
1381
|
+
throw new Error("Browser session closed");
|
|
1382
|
+
if (!this.prepared) {
|
|
1383
|
+
await this.touchDirectory();
|
|
1384
|
+
await pruneOwnershipScopes(this.ownershipDirectory, this.scope);
|
|
1385
|
+
this.prepared = true;
|
|
1386
|
+
}
|
|
1387
|
+
return action();
|
|
1388
|
+
});
|
|
1389
|
+
this.tail = pending.then(() => {
|
|
1390
|
+
return;
|
|
1391
|
+
}, () => {
|
|
1392
|
+
return;
|
|
1393
|
+
});
|
|
1394
|
+
return waitForTurn(pending, signal);
|
|
1395
|
+
}
|
|
1396
|
+
async listNow(signal) {
|
|
1397
|
+
const owned = await this.readOwned();
|
|
1398
|
+
const targets = await getPageTargets(this.cdp, signal);
|
|
1399
|
+
const pages = getDisplayedPages(targets);
|
|
1400
|
+
const known = new Set(owned);
|
|
1401
|
+
let changed = true;
|
|
1402
|
+
while (changed) {
|
|
1403
|
+
changed = false;
|
|
1404
|
+
for (const page of pages) {
|
|
1405
|
+
if (!page.openerId || !known.has(page.openerId) || known.has(page.targetId))
|
|
1406
|
+
continue;
|
|
1407
|
+
await this.remember(page.targetId);
|
|
1408
|
+
known.add(page.targetId);
|
|
1409
|
+
changed = true;
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
const live = new Set(targets.map((page) => page.targetId));
|
|
1413
|
+
await Promise.all(owned.filter((id) => !live.has(id)).map((id) => this.forget(id)));
|
|
1414
|
+
return pages.map((page) => ({ ...page, owned: known.has(page.targetId) }));
|
|
1415
|
+
}
|
|
1416
|
+
async resolve(refId, signal) {
|
|
1417
|
+
const pages = await this.list(signal);
|
|
1418
|
+
const ids = pages.map((page) => page.targetId);
|
|
1419
|
+
const targetId = resolvePrefix(refId, ids, "target", "Run tabs.");
|
|
1420
|
+
const page = pages.find((candidate) => candidate.targetId === targetId);
|
|
1421
|
+
if (!page)
|
|
1422
|
+
throw new Error("Tab disappeared; run tabs again");
|
|
1423
|
+
return { page, refId: targetId.slice(0, getDisplayPrefixLength(ids)) };
|
|
1424
|
+
}
|
|
1425
|
+
async open(url, signal) {
|
|
1426
|
+
assertHttpUrl(url);
|
|
1427
|
+
const targetId = await this.enqueue(async () => {
|
|
1428
|
+
let response;
|
|
1429
|
+
try {
|
|
1430
|
+
response = asRecord(await this.cdp.send("Target.createTarget", { url, background: true }), "Target.createTarget response");
|
|
1431
|
+
} catch (error) {
|
|
1432
|
+
throw new Error(`Chrome did not confirm tab creation; a shared tab may exist. Run tabs before retrying: ${errorMessage(error)}`);
|
|
1433
|
+
}
|
|
1434
|
+
if (typeof response["targetId"] !== "string")
|
|
1435
|
+
throw new Error("Chrome did not return a new tab target; run tabs before retrying");
|
|
1436
|
+
const created = response["targetId"];
|
|
1437
|
+
try {
|
|
1438
|
+
await this.remember(created);
|
|
1439
|
+
} catch (error) {
|
|
1440
|
+
throw new Error(`Opened tab ${created} but could not save ownership; it remains shared: ${errorMessage(error)}`);
|
|
1441
|
+
}
|
|
1442
|
+
return created;
|
|
1443
|
+
}, signal);
|
|
1444
|
+
await waitForOpenedTarget(this.cdp, targetId, url, 5000, signal);
|
|
1445
|
+
const { refId } = await this.resolve(targetId, signal);
|
|
1446
|
+
return { refId };
|
|
1447
|
+
}
|
|
1448
|
+
async show(refId, signal) {
|
|
1449
|
+
const resolved = await this.resolve(refId, signal);
|
|
1450
|
+
await this.cdp.send("Target.activateTarget", { targetId: resolved.page.targetId }, undefined, signal);
|
|
1451
|
+
return resolved.refId;
|
|
1452
|
+
}
|
|
1453
|
+
async close(refId, signal) {
|
|
1454
|
+
const resolved = await this.resolve(refId, signal);
|
|
1455
|
+
const targetId = resolved.page.targetId;
|
|
1456
|
+
const response = asRecord(await this.cdp.send("Target.closeTarget", { targetId }, undefined, signal), "Target.closeTarget response");
|
|
1457
|
+
if (response["success"] !== true)
|
|
1458
|
+
throw new Error("Chrome did not close the tab; run tabs to inspect it");
|
|
1459
|
+
await this.forget(targetId);
|
|
1460
|
+
return { targetId, refId: resolved.refId };
|
|
1461
|
+
}
|
|
1462
|
+
targetPath(targetId) {
|
|
1463
|
+
if (!TARGET_ID.test(targetId))
|
|
1464
|
+
throw new Error("Chrome returned an invalid target id");
|
|
1465
|
+
return join3(this.directory, targetId);
|
|
1466
|
+
}
|
|
1467
|
+
async readOwned() {
|
|
1468
|
+
if (!await this.touchDirectory())
|
|
1469
|
+
return [];
|
|
1470
|
+
try {
|
|
1471
|
+
const files = await readdir2(this.directory, { withFileTypes: true });
|
|
1472
|
+
for (const file of files) {
|
|
1473
|
+
if (!file.isFile() || !TARGET_ID.test(file.name))
|
|
1474
|
+
throw new Error("Invalid browser ownership record; refusing to infer tab ownership");
|
|
1475
|
+
}
|
|
1476
|
+
return files.map((file) => file.name);
|
|
1477
|
+
} catch (error) {
|
|
1478
|
+
if (missing(error))
|
|
1479
|
+
return [];
|
|
1480
|
+
throw error;
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
async touchDirectory() {
|
|
1484
|
+
try {
|
|
1485
|
+
const info = await lstat2(this.directory);
|
|
1486
|
+
if (!info.isDirectory() || info.isSymbolicLink())
|
|
1487
|
+
throw new Error("Invalid browser ownership directory");
|
|
1488
|
+
const now = new Date;
|
|
1489
|
+
await utimes(this.directory, now, now);
|
|
1490
|
+
return true;
|
|
1491
|
+
} catch (error) {
|
|
1492
|
+
if (missing(error))
|
|
1493
|
+
return false;
|
|
1494
|
+
throw error;
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
async remember(targetId) {
|
|
1498
|
+
const path = this.targetPath(targetId);
|
|
1499
|
+
await mkdir3(this.directory, { recursive: true, mode: 448 });
|
|
1500
|
+
const info = await lstat2(this.directory);
|
|
1501
|
+
if (!info.isDirectory() || info.isSymbolicLink())
|
|
1502
|
+
throw new Error("Invalid browser ownership directory");
|
|
1503
|
+
try {
|
|
1504
|
+
await writeFile2(path, "", { flag: "wx", mode: 384 });
|
|
1505
|
+
} catch (error) {
|
|
1506
|
+
if (!(error instanceof Error && ("code" in error) && error.code === "EEXIST"))
|
|
1507
|
+
throw error;
|
|
1508
|
+
if (!(await lstat2(path)).isFile())
|
|
1509
|
+
throw new Error("Invalid browser ownership record");
|
|
1510
|
+
}
|
|
1511
|
+
}
|
|
1512
|
+
async forget(targetId) {
|
|
1513
|
+
await rm3(this.targetPath(targetId), { force: true });
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
// packages/browser/src/cdp/session.ts
|
|
1518
|
+
class BrowserCdpSession {
|
|
1519
|
+
closing;
|
|
1520
|
+
root;
|
|
1521
|
+
rootPending;
|
|
1522
|
+
ownerId;
|
|
1523
|
+
ownershipDirectory;
|
|
1524
|
+
tabs = new Map;
|
|
1525
|
+
tabPromises = new Map;
|
|
1526
|
+
discover;
|
|
1527
|
+
constructor(ownerId, ownershipDirectory, discover = getWebSocketUrl) {
|
|
1528
|
+
this.discover = discover;
|
|
1529
|
+
this.ownerId = ownerId;
|
|
1530
|
+
this.ownershipDirectory = ownershipDirectory;
|
|
1531
|
+
}
|
|
1532
|
+
async pages(signal) {
|
|
1533
|
+
return (await this.rootConnection(signal)).tabs.list(signal);
|
|
1534
|
+
}
|
|
1535
|
+
async open(url, signal) {
|
|
1536
|
+
return (await this.rootConnection(signal)).tabs.open(url, signal);
|
|
1537
|
+
}
|
|
1538
|
+
async show(refId, signal) {
|
|
1539
|
+
return (await this.rootConnection(signal)).tabs.show(refId, signal);
|
|
1540
|
+
}
|
|
1541
|
+
async closeTab(refId, signal) {
|
|
1542
|
+
const root = await this.rootConnection(signal);
|
|
1543
|
+
const resolved = await root.tabs.resolve(refId, signal);
|
|
1544
|
+
const targetId = resolved.page.targetId;
|
|
1545
|
+
this.stopPendingTab(targetId, "Tab is closing");
|
|
1546
|
+
const bridge = this.tabs.get(targetId);
|
|
1547
|
+
const close = () => root.tabs.close(targetId, signal);
|
|
1548
|
+
const closed = bridge ? await bridge.run(resolved.refId, signal, close) : await close();
|
|
1549
|
+
bridge?.close(false);
|
|
1550
|
+
return closed.refId;
|
|
1551
|
+
}
|
|
1552
|
+
async withTab(refId, signal, action, rendering = "background") {
|
|
1553
|
+
const pages = await this.pages(signal);
|
|
1554
|
+
const targetId = resolvePrefix(refId, pages.map((page) => page.targetId), "target", "Run tabs.");
|
|
1555
|
+
let bridge = this.tabs.get(targetId);
|
|
1556
|
+
if (!bridge) {
|
|
1557
|
+
let pending = this.tabPromises.get(targetId);
|
|
1558
|
+
if (!pending) {
|
|
1559
|
+
const controller = new AbortController;
|
|
1560
|
+
const promise = this.connectTab(targetId, controller.signal);
|
|
1561
|
+
pending = { controller, promise };
|
|
1562
|
+
this.tabPromises.set(targetId, pending);
|
|
1563
|
+
promise.then((value) => {
|
|
1564
|
+
pending.value = value;
|
|
1565
|
+
}, () => {
|
|
1566
|
+
if (this.tabPromises.get(targetId) === pending) {
|
|
1567
|
+
this.tabPromises.delete(targetId);
|
|
1568
|
+
}
|
|
1569
|
+
});
|
|
1570
|
+
}
|
|
1571
|
+
const connected = await waitForTurn(pending.promise, signal);
|
|
1572
|
+
bridge = this.tabs.get(targetId);
|
|
1573
|
+
if (!bridge) {
|
|
1574
|
+
if (this.tabPromises.get(targetId) !== pending) {
|
|
1575
|
+
connected.close();
|
|
1576
|
+
throw new Error("Tab bridge was stopped while connecting");
|
|
1577
|
+
}
|
|
1578
|
+
this.tabPromises.delete(targetId);
|
|
1579
|
+
this.tabs.set(targetId, connected);
|
|
1580
|
+
bridge = connected;
|
|
1581
|
+
} else if (bridge !== connected) {
|
|
1582
|
+
connected.close();
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
const prefixLength = getDisplayPrefixLength(pages.map((page) => page.targetId));
|
|
1586
|
+
const owned = pages.some((page) => page.targetId === targetId && page.owned === true);
|
|
1587
|
+
const current = bridge;
|
|
1588
|
+
return current.run(targetId.slice(0, prefixLength), signal, async (tab) => {
|
|
1589
|
+
await current.setBackgroundRendering(owned && rendering === "background", signal);
|
|
1590
|
+
if (rendering === "foreground") {
|
|
1591
|
+
await tab.cdp.send("Target.activateTarget", { targetId }, undefined, signal);
|
|
1592
|
+
}
|
|
1593
|
+
return action(tab);
|
|
1594
|
+
});
|
|
1595
|
+
}
|
|
1596
|
+
async stop(refId) {
|
|
1597
|
+
if (!refId) {
|
|
1598
|
+
for (const targetId of this.tabPromises.keys()) {
|
|
1599
|
+
this.stopPendingTab(targetId, "All tab bridges were stopped");
|
|
1600
|
+
}
|
|
1601
|
+
await Promise.all([...this.tabs.values()].map((bridge) => bridge.close()));
|
|
1602
|
+
this.tabs.clear();
|
|
1603
|
+
return;
|
|
1604
|
+
}
|
|
1605
|
+
const pages = await this.pages();
|
|
1606
|
+
const targetId = resolvePrefix(refId, pages.map((page) => page.targetId), "target");
|
|
1607
|
+
this.stopPendingTab(targetId, "Tab bridge " + refId + " was stopped");
|
|
1608
|
+
await this.tabs.get(targetId)?.close();
|
|
1609
|
+
this.tabs.delete(targetId);
|
|
1610
|
+
}
|
|
1611
|
+
close() {
|
|
1612
|
+
if (this.closing)
|
|
1613
|
+
return this.closing;
|
|
1614
|
+
const pendingTabs = [...this.tabPromises.values()].map((pending) => pending.promise.then((bridge) => bridge.close(), () => {
|
|
1615
|
+
return;
|
|
1616
|
+
}));
|
|
1617
|
+
for (const targetId of this.tabPromises.keys()) {
|
|
1618
|
+
this.stopPendingTab(targetId, "Browser session closed");
|
|
1619
|
+
}
|
|
1620
|
+
const closingTabs = [...this.tabs.values()].map((bridge) => bridge.close());
|
|
1621
|
+
this.tabs.clear();
|
|
1622
|
+
const rootPending = this.rootPending;
|
|
1623
|
+
this.rootPending = undefined;
|
|
1624
|
+
rootPending?.controller.abort(new Error("Browser session closed"));
|
|
1625
|
+
const root = this.root;
|
|
1626
|
+
this.root = undefined;
|
|
1627
|
+
this.closing = (async () => {
|
|
1628
|
+
await Promise.all([...pendingTabs, ...closingTabs]);
|
|
1629
|
+
const connected = await rootPending?.promise.catch(() => {
|
|
1630
|
+
return;
|
|
1631
|
+
});
|
|
1632
|
+
for (const connection of new Set([root, connected])) {
|
|
1633
|
+
if (!connection)
|
|
1634
|
+
continue;
|
|
1635
|
+
try {
|
|
1636
|
+
await connection.tabs.shutdown();
|
|
1637
|
+
} finally {
|
|
1638
|
+
connection.cdp.close();
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
})();
|
|
1642
|
+
return this.closing;
|
|
1643
|
+
}
|
|
1644
|
+
async rootConnection(signal) {
|
|
1645
|
+
if (this.closing)
|
|
1646
|
+
throw new Error("Browser session closed");
|
|
1647
|
+
if (this.root)
|
|
1648
|
+
return this.root;
|
|
1649
|
+
let pending = this.rootPending;
|
|
1650
|
+
if (!pending) {
|
|
1651
|
+
const controller = new AbortController;
|
|
1652
|
+
const promise = this.connectRoot(controller.signal);
|
|
1653
|
+
pending = { controller, promise };
|
|
1654
|
+
this.rootPending = pending;
|
|
1655
|
+
promise.then((value) => {
|
|
1656
|
+
pending.value = value;
|
|
1657
|
+
if (this.rootPending === pending)
|
|
1658
|
+
this.rootPending = undefined;
|
|
1659
|
+
}, () => {
|
|
1660
|
+
if (this.rootPending === pending)
|
|
1661
|
+
this.rootPending = undefined;
|
|
1662
|
+
});
|
|
1663
|
+
}
|
|
1664
|
+
return waitForTurn(pending.promise, signal);
|
|
1665
|
+
}
|
|
1666
|
+
async connectTab(targetId, signal) {
|
|
1667
|
+
let bridge;
|
|
1668
|
+
bridge = await TabBridge.connect(targetId, () => {
|
|
1669
|
+
if (bridge && this.tabs.get(targetId) === bridge) {
|
|
1670
|
+
this.tabs.delete(targetId);
|
|
1671
|
+
}
|
|
1672
|
+
const pending = this.tabPromises.get(targetId);
|
|
1673
|
+
if (bridge && pending?.value === bridge) {
|
|
1674
|
+
this.tabPromises.delete(targetId);
|
|
1675
|
+
}
|
|
1676
|
+
}, signal, this.discover);
|
|
1677
|
+
return bridge;
|
|
1678
|
+
}
|
|
1679
|
+
stopPendingTab(targetId, message) {
|
|
1680
|
+
const pending = this.tabPromises.get(targetId);
|
|
1681
|
+
if (!pending)
|
|
1682
|
+
return;
|
|
1683
|
+
this.tabPromises.delete(targetId);
|
|
1684
|
+
pending.controller.abort(new Error(message));
|
|
1685
|
+
pending.promise.then((bridge) => bridge.close(), () => {
|
|
1686
|
+
return;
|
|
1687
|
+
});
|
|
1688
|
+
}
|
|
1689
|
+
async connectRoot(signal) {
|
|
1690
|
+
const client = new CdpClient;
|
|
1691
|
+
const url = await this.discover(signal);
|
|
1692
|
+
try {
|
|
1693
|
+
await client.connect(url, signal);
|
|
1694
|
+
signal.throwIfAborted();
|
|
1695
|
+
if (this.closing)
|
|
1696
|
+
throw new Error("Browser session closed");
|
|
1697
|
+
} catch (error) {
|
|
1698
|
+
client.close();
|
|
1699
|
+
throw error;
|
|
1700
|
+
}
|
|
1701
|
+
const connection = {
|
|
1702
|
+
cdp: client,
|
|
1703
|
+
tabs: new BrowserTabs(client, this.ownerId, this.ownershipDirectory, url)
|
|
1704
|
+
};
|
|
1705
|
+
this.root = connection;
|
|
1706
|
+
client.onClose(() => {
|
|
1707
|
+
if (this.root !== connection)
|
|
1708
|
+
return;
|
|
1709
|
+
this.root = undefined;
|
|
1710
|
+
});
|
|
1711
|
+
return connection;
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
|
|
1715
|
+
// packages/browser/src/browser/artifacts.ts
|
|
1716
|
+
var RESULT_TTL_MS = 60 * 60 * 1000;
|
|
1717
|
+
var SCREENSHOT_TTL_MS = 24 * 60 * 60 * 1000;
|
|
1718
|
+
var TEXT_BUDGET_BYTES = 32000;
|
|
1719
|
+
function chunkForJson(value, offset = 0, budget = TEXT_BUDGET_BYTES) {
|
|
1720
|
+
let bytes = 2;
|
|
1721
|
+
let end = offset;
|
|
1722
|
+
for (const character of value.slice(offset)) {
|
|
1723
|
+
const next = Buffer.byteLength(JSON.stringify(character)) - 2;
|
|
1724
|
+
if (bytes + next > budget)
|
|
1725
|
+
break;
|
|
1726
|
+
bytes += next;
|
|
1727
|
+
end += character.length;
|
|
1728
|
+
}
|
|
1729
|
+
return { text: value.slice(offset, end), end };
|
|
1730
|
+
}
|
|
1731
|
+
|
|
1732
|
+
class BrowserArtifacts {
|
|
1733
|
+
store;
|
|
1734
|
+
constructor(store) {
|
|
1735
|
+
this.store = store;
|
|
1736
|
+
}
|
|
1737
|
+
screenshotTarget(request) {
|
|
1738
|
+
const suffix = request.id !== undefined ? `-element-${request.id}` : request.selector ? "-element" : "";
|
|
1739
|
+
const safeRef = request.ref_id.slice(0, 12).replace(/[^A-Za-z0-9_-]/g, "_");
|
|
1740
|
+
const name = `browser-${safeRef}${suffix}-${crypto.randomUUID()}.png`;
|
|
1741
|
+
return {
|
|
1742
|
+
file: this.store.path(name),
|
|
1743
|
+
write: (data) => this.store.write(name, data)
|
|
1744
|
+
};
|
|
1745
|
+
}
|
|
1746
|
+
async prune(now = Date.now()) {
|
|
1747
|
+
let removed = 0;
|
|
1748
|
+
for (const entry of await this.store.entries()) {
|
|
1749
|
+
if (!/^(?:result-[a-f0-9-]{36}\.txt|browser-.*\.png)$/.test(entry.name))
|
|
1750
|
+
continue;
|
|
1751
|
+
const age = entry.name.startsWith("result-") ? RESULT_TTL_MS : SCREENSHOT_TTL_MS;
|
|
1752
|
+
if (now - entry.mtimeMs > age) {
|
|
1753
|
+
await this.store.remove(entry.name);
|
|
1754
|
+
removed++;
|
|
1755
|
+
}
|
|
1756
|
+
}
|
|
1757
|
+
return removed;
|
|
1758
|
+
}
|
|
1759
|
+
async limitedText(base, field, value) {
|
|
1760
|
+
const chunk = chunkForJson(value);
|
|
1761
|
+
if (chunk.end >= value.length)
|
|
1762
|
+
return { ...base, [field]: value };
|
|
1763
|
+
const handle = crypto.randomUUID();
|
|
1764
|
+
await this.store.write(`result-${handle}.txt`, value);
|
|
1765
|
+
return {
|
|
1766
|
+
...base,
|
|
1767
|
+
[field]: chunk.text,
|
|
1768
|
+
truncated: true,
|
|
1769
|
+
omitted_chars: value.length - chunk.end,
|
|
1770
|
+
result_handle: handle,
|
|
1771
|
+
next_offset: chunk.end
|
|
1772
|
+
};
|
|
1773
|
+
}
|
|
1774
|
+
async readCachedResult(request) {
|
|
1775
|
+
let value;
|
|
1776
|
+
try {
|
|
1777
|
+
value = await this.store.read(`result-${request.handle}.txt`);
|
|
1778
|
+
} catch (error) {
|
|
1779
|
+
if (error && typeof error === "object" && "code" in error && (error.code === "ENOENT" || error.code === "not_found")) {
|
|
1780
|
+
throw new Error(`result handle not found: ${request.handle}; check the host or rerun the original action`);
|
|
1781
|
+
}
|
|
1782
|
+
throw error;
|
|
1783
|
+
}
|
|
1784
|
+
if (request.offset > value.length) {
|
|
1785
|
+
throw new Error(`offset ${request.offset} exceeds result length ${value.length}`);
|
|
1786
|
+
}
|
|
1787
|
+
const chunk = chunkForJson(value, request.offset);
|
|
1788
|
+
const complete = chunk.end >= value.length;
|
|
1789
|
+
if (complete) {
|
|
1790
|
+
await this.store.remove(`result-${request.handle}.txt`);
|
|
1791
|
+
}
|
|
1792
|
+
return {
|
|
1793
|
+
handle: request.handle,
|
|
1794
|
+
offset: request.offset,
|
|
1795
|
+
text: chunk.text,
|
|
1796
|
+
complete,
|
|
1797
|
+
...complete ? {} : { next_offset: chunk.end }
|
|
1798
|
+
};
|
|
1799
|
+
}
|
|
1800
|
+
async discardCachedResult(handle) {
|
|
1801
|
+
await this.store.remove(`result-${handle}.txt`);
|
|
1802
|
+
return { discarded: handle };
|
|
1803
|
+
}
|
|
1804
|
+
}
|
|
1805
|
+
|
|
1806
|
+
// packages/browser/src/browser/help.ts
|
|
1807
|
+
function browserHelp(hosts = []) {
|
|
1808
|
+
const routed = hosts.length > 0;
|
|
1809
|
+
return {
|
|
1810
|
+
input: "{action,...fields}",
|
|
1811
|
+
...routed ? {
|
|
1812
|
+
host: `${hosts.join("|")} optional; keep a user-named host on every call and its refs/handles`
|
|
1813
|
+
} : {},
|
|
1814
|
+
refs: "tabs -> open; keep ref_id/id/cursors with their result",
|
|
1815
|
+
safety: "Ask before unfamiliar low-trust navigation or consequential action unless authorized; never close shared browser",
|
|
1816
|
+
batch: "{action_name:[{...fields}],...}; nonempty arrays; items omit action; host/response_length at request root; independent only",
|
|
1817
|
+
actions: {
|
|
1818
|
+
tabs: "query? offset? owned_only? -> ref_id title url owned",
|
|
1819
|
+
open: "ref_id lineno? | url; new tabs open in background",
|
|
1820
|
+
show: "ref_id; bring tab to foreground",
|
|
1821
|
+
close: "ref_id",
|
|
1822
|
+
find: "ref_id pattern lineno?",
|
|
1823
|
+
click: "ref_id id|selector|x+y",
|
|
1824
|
+
type: "ref_id text id?; id focuses",
|
|
1825
|
+
fill: "ref_id id|selector value; replace/clear text, select option value/label, boolean checks/unchecks",
|
|
1826
|
+
press: "ref_id key; focused element, e.g. Enter or Control+a",
|
|
1827
|
+
wait: "ref_id selector|text|url_includes timeout_ms?; DOM presence or substring, default 10000ms",
|
|
1828
|
+
screenshot: "ref_id id?|selector? -> file; brings tab to foreground",
|
|
1829
|
+
navigate: "ref_id url",
|
|
1830
|
+
html: "ref_id id?|selector?",
|
|
1831
|
+
evaluate: "ref_id expression",
|
|
1832
|
+
network: "ref_id",
|
|
1833
|
+
load_all: "ref_id selector interval_ms?",
|
|
1834
|
+
raw: "ref_id method params?",
|
|
1835
|
+
start: "",
|
|
1836
|
+
stop: "ref_id?; detach without closing tabs",
|
|
1837
|
+
read_result: "handle offset",
|
|
1838
|
+
discard_result: "handle"
|
|
1839
|
+
},
|
|
1840
|
+
continue: "next_lineno/next_offset; response_length=short|medium|long"
|
|
1841
|
+
};
|
|
1842
|
+
}
|
|
1843
|
+
|
|
1844
|
+
// packages/browser/src/cdp/snapshot-contract.ts
|
|
1845
|
+
var SNAPSHOT_LIMITS = {
|
|
1846
|
+
short: 60,
|
|
1847
|
+
medium: 140,
|
|
1848
|
+
long: 300
|
|
1849
|
+
};
|
|
1850
|
+
function positiveInteger(value, label) {
|
|
1851
|
+
const source = String(value);
|
|
1852
|
+
if (!/^[1-9]\d*$/.test(source)) {
|
|
1853
|
+
throw new Error(`${label} must be a positive integer`);
|
|
1854
|
+
}
|
|
1855
|
+
const parsed = Number(source);
|
|
1856
|
+
if (!Number.isSafeInteger(parsed)) {
|
|
1857
|
+
throw new Error(`${label} must be a safe positive integer`);
|
|
1858
|
+
}
|
|
1859
|
+
return parsed;
|
|
1860
|
+
}
|
|
1861
|
+
function snapshotResponseLength(value) {
|
|
1862
|
+
const resolved = value ?? "medium";
|
|
1863
|
+
if (resolved !== "short" && resolved !== "medium" && resolved !== "long") {
|
|
1864
|
+
throw new Error(`response length must be one of: ${Object.keys(SNAPSHOT_LIMITS).join(", ")}`);
|
|
1865
|
+
}
|
|
1866
|
+
return resolved;
|
|
1867
|
+
}
|
|
1868
|
+
|
|
1869
|
+
// packages/browser/src/cdp/actions/element.ts
|
|
1870
|
+
function requireElementRef(elementRefs, id) {
|
|
1871
|
+
const parsed = positiveInteger(id, "element id");
|
|
1872
|
+
const backendNodeId = elementRefs.get(parsed);
|
|
1873
|
+
if (!backendNodeId) {
|
|
1874
|
+
throw new Error(`Unknown element id ${id}; run open again and use a current element id`);
|
|
1875
|
+
}
|
|
1876
|
+
return { id: parsed, backendNodeId };
|
|
1877
|
+
}
|
|
1878
|
+
async function resolveBackendObject(cdp, sessionId, backendNodeId, signal) {
|
|
1879
|
+
const response = asRecord(await cdp.send("DOM.resolveNode", { backendNodeId }, sessionId, signal), "DOM.resolveNode response");
|
|
1880
|
+
const object = asRecord(response["object"], "resolved DOM object");
|
|
1881
|
+
if (typeof object["objectId"] !== "string") {
|
|
1882
|
+
throw new Error("Element is no longer available; run open again");
|
|
1883
|
+
}
|
|
1884
|
+
return object["objectId"];
|
|
1885
|
+
}
|
|
1886
|
+
async function withBackendObject(cdp, sessionId, backendNodeId, action, signal) {
|
|
1887
|
+
const objectId = await resolveBackendObject(cdp, sessionId, backendNodeId, signal);
|
|
1888
|
+
try {
|
|
1889
|
+
return await action(objectId);
|
|
1890
|
+
} finally {
|
|
1891
|
+
await cdp.send("Runtime.releaseObject", { objectId }, sessionId, undefined).catch(() => {
|
|
1892
|
+
return;
|
|
1893
|
+
});
|
|
1894
|
+
}
|
|
1895
|
+
}
|
|
1896
|
+
async function scrollBackendIntoView(cdp, sessionId, backendNodeId, signal) {
|
|
1897
|
+
await withBackendObject(cdp, sessionId, backendNodeId, (objectId) => cdp.send("Runtime.callFunctionOn", {
|
|
1898
|
+
objectId,
|
|
1899
|
+
functionDeclaration: 'function() { this.scrollIntoView({block: "center", inline: "center"}); }'
|
|
1900
|
+
}, sessionId, signal), signal);
|
|
1901
|
+
await sleep(50, signal);
|
|
1902
|
+
}
|
|
1903
|
+
async function backendCenter(cdp, sessionId, backendNodeId, scroll = true, signal) {
|
|
1904
|
+
if (scroll) {
|
|
1905
|
+
await scrollBackendIntoView(cdp, sessionId, backendNodeId, signal);
|
|
1906
|
+
}
|
|
1907
|
+
const response = await withBackendObject(cdp, sessionId, backendNodeId, (objectId) => cdp.send("Runtime.callFunctionOn", {
|
|
1908
|
+
objectId,
|
|
1909
|
+
functionDeclaration: `function() {
|
|
1910
|
+
const view = this.ownerDocument.defaultView;
|
|
1911
|
+
if (view && (view.innerWidth <= 0 || view.innerHeight <= 0)) {
|
|
1912
|
+
return { ok: false, error: 'Browser viewport is ' + view.innerWidth + 'x' + view.innerHeight + '; restore or resize its window, then retry' };
|
|
1913
|
+
}
|
|
1914
|
+
const rect = this.getBoundingClientRect();
|
|
1915
|
+
const style = getComputedStyle(this);
|
|
1916
|
+
const disabled = this.matches(':disabled') ||
|
|
1917
|
+
this.getAttribute('aria-disabled') === 'true';
|
|
1918
|
+
const hidden = rect.width <= 0 || rect.height <= 0 ||
|
|
1919
|
+
style.display === 'none' || style.visibility === 'hidden' ||
|
|
1920
|
+
style.visibility === 'collapse' || style.pointerEvents === 'none' ||
|
|
1921
|
+
Number(style.opacity) === 0 || this.closest('[inert]') !== null;
|
|
1922
|
+
if (hidden) return { ok: false, error: 'Element is not visible or interactable' };
|
|
1923
|
+
if (disabled) return { ok: false, error: 'Element is disabled' };
|
|
1924
|
+
const x = rect.left + rect.width / 2;
|
|
1925
|
+
const y = rect.top + rect.height / 2;
|
|
1926
|
+
const root = this.getRootNode();
|
|
1927
|
+
const hit = root && typeof root.elementFromPoint === 'function'
|
|
1928
|
+
? root.elementFromPoint(x, y)
|
|
1929
|
+
: this.ownerDocument.elementFromPoint(x, y);
|
|
1930
|
+
if (!hit || (hit !== this && !this.contains(hit))) {
|
|
1931
|
+
const blocker = hit ? '<' + hit.tagName.toLowerCase() + '>' : 'no element';
|
|
1932
|
+
return { ok: false, error: 'Element center is covered by ' + blocker };
|
|
1933
|
+
}
|
|
1934
|
+
return {
|
|
1935
|
+
ok: true,
|
|
1936
|
+
x,
|
|
1937
|
+
y,
|
|
1938
|
+
tag: this.tagName,
|
|
1939
|
+
text: (this.textContent || '').trim().substring(0, 80)
|
|
1940
|
+
};
|
|
1941
|
+
}`,
|
|
1942
|
+
returnByValue: true
|
|
1943
|
+
}, sessionId, signal), signal);
|
|
1944
|
+
const result = asRecord(response, "element center response");
|
|
1945
|
+
const point = asRecord(asRecord(result["result"], "element center result")["value"], "element center");
|
|
1946
|
+
if (point["ok"] !== true) {
|
|
1947
|
+
throw new Error(typeof point["error"] === "string" ? point["error"] : "Element has no clickable box");
|
|
1948
|
+
}
|
|
1949
|
+
if (typeof point["x"] !== "number" || typeof point["y"] !== "number") {
|
|
1950
|
+
throw new Error("Element center has invalid coordinates");
|
|
1951
|
+
}
|
|
1952
|
+
return {
|
|
1953
|
+
x: point["x"],
|
|
1954
|
+
y: point["y"],
|
|
1955
|
+
tag: typeof point["tag"] === "string" ? point["tag"] : "ELEMENT",
|
|
1956
|
+
text: typeof point["text"] === "string" ? point["text"] : ""
|
|
1957
|
+
};
|
|
1958
|
+
}
|
|
1959
|
+
async function visibleElementClip(cdp, sessionId, quad, padding = 10, signal) {
|
|
1960
|
+
const response = asRecord(await cdp.send("Page.getLayoutMetrics", {}, sessionId, signal), "layout metrics");
|
|
1961
|
+
const viewportValue = response["cssVisualViewport"] ?? response["visualViewport"] ?? response["cssLayoutViewport"] ?? response["layoutViewport"];
|
|
1962
|
+
const viewport = asRecord(viewportValue, "layout viewport");
|
|
1963
|
+
if (typeof viewport["clientWidth"] !== "number" || typeof viewport["clientHeight"] !== "number" || viewport["clientWidth"] <= 0 || viewport["clientHeight"] <= 0) {
|
|
1964
|
+
throw new Error("Could not determine a bounded screenshot viewport");
|
|
1965
|
+
}
|
|
1966
|
+
const pageX = typeof viewport["pageX"] === "number" ? viewport["pageX"] : 0;
|
|
1967
|
+
const pageY = typeof viewport["pageY"] === "number" ? viewport["pageY"] : 0;
|
|
1968
|
+
const xs = [quad[0], quad[2], quad[4], quad[6]].filter((value) => typeof value === "number");
|
|
1969
|
+
const ys = [quad[1], quad[3], quad[5], quad[7]].filter((value) => typeof value === "number");
|
|
1970
|
+
if (xs.length !== 4 || ys.length !== 4) {
|
|
1971
|
+
throw new Error("Element has an invalid screenshot box");
|
|
1972
|
+
}
|
|
1973
|
+
const x = Math.max(pageX, Math.min(...xs) - padding);
|
|
1974
|
+
const y = Math.max(pageY, Math.min(...ys) - padding);
|
|
1975
|
+
const right = Math.min(pageX + viewport["clientWidth"], Math.max(...xs) + padding);
|
|
1976
|
+
const bottom = Math.min(pageY + viewport["clientHeight"], Math.max(...ys) + padding);
|
|
1977
|
+
if (right <= x || bottom <= y) {
|
|
1978
|
+
throw new Error("Element has no visible screenshot box");
|
|
1979
|
+
}
|
|
1980
|
+
return {
|
|
1981
|
+
x,
|
|
1982
|
+
y,
|
|
1983
|
+
width: right - x,
|
|
1984
|
+
height: bottom - y,
|
|
1985
|
+
scale: 1
|
|
1986
|
+
};
|
|
1987
|
+
}
|
|
1988
|
+
|
|
1989
|
+
// packages/browser/src/cdp/actions/selector.ts
|
|
1990
|
+
async function selectorBackendNode(cdp, sessionId, selector, signal) {
|
|
1991
|
+
await cdp.send("Runtime.enable", {}, sessionId, signal);
|
|
1992
|
+
const selected = asRecord(await cdp.send("Runtime.evaluate", {
|
|
1993
|
+
expression: `(() => {
|
|
1994
|
+
const selector = ${JSON.stringify(selector)};
|
|
1995
|
+
const matches = document.querySelectorAll(selector);
|
|
1996
|
+
if (matches.length === 0) throw new Error('Element not found: ' + selector);
|
|
1997
|
+
if (matches.length > 1) throw new Error(
|
|
1998
|
+
'Selector matched ' + matches.length + ' elements: ' + selector
|
|
1999
|
+
);
|
|
2000
|
+
return matches[0];
|
|
2001
|
+
})()`,
|
|
2002
|
+
returnByValue: false,
|
|
2003
|
+
awaitPromise: true
|
|
2004
|
+
}, sessionId, signal), "selector response");
|
|
2005
|
+
if (selected["exceptionDetails"]) {
|
|
2006
|
+
const details = asRecord(selected["exceptionDetails"], "selector exception");
|
|
2007
|
+
throw new Error(typeof details["text"] === "string" ? details["text"] : `Could not select ${selector}`);
|
|
2008
|
+
}
|
|
2009
|
+
const result = asRecord(selected["result"], "selector result");
|
|
2010
|
+
if (typeof result["objectId"] !== "string") {
|
|
2011
|
+
throw new Error(`Element is no longer available: ${selector}`);
|
|
2012
|
+
}
|
|
2013
|
+
const objectId = result["objectId"];
|
|
2014
|
+
try {
|
|
2015
|
+
const described = asRecord(await cdp.send("DOM.describeNode", { objectId }, sessionId, signal), "DOM.describeNode response");
|
|
2016
|
+
const node = asRecord(described["node"], "described node");
|
|
2017
|
+
if (typeof node["backendNodeId"] !== "number") {
|
|
2018
|
+
throw new Error(`Element is no longer available: ${selector}`);
|
|
2019
|
+
}
|
|
2020
|
+
return node["backendNodeId"];
|
|
2021
|
+
} finally {
|
|
2022
|
+
await cdp.send("Runtime.releaseObject", { objectId }, sessionId, undefined).catch(() => {
|
|
2023
|
+
return;
|
|
2024
|
+
});
|
|
2025
|
+
}
|
|
2026
|
+
}
|
|
2027
|
+
|
|
2028
|
+
// packages/browser/src/cdp/actions/click.ts
|
|
2029
|
+
function dispatchMouse(cdp, sessionId, type, point, signal) {
|
|
2030
|
+
return cdp.send("Input.dispatchMouseEvent", {
|
|
2031
|
+
x: point.x,
|
|
2032
|
+
y: point.y,
|
|
2033
|
+
button: "left",
|
|
2034
|
+
clickCount: 1,
|
|
2035
|
+
modifiers: 0,
|
|
2036
|
+
type
|
|
2037
|
+
}, sessionId, signal);
|
|
2038
|
+
}
|
|
2039
|
+
async function pressAndRelease(cdp, sessionId, point, signal) {
|
|
2040
|
+
let pressed = false;
|
|
2041
|
+
try {
|
|
2042
|
+
await dispatchMouse(cdp, sessionId, "mousePressed", point, signal);
|
|
2043
|
+
pressed = true;
|
|
2044
|
+
await sleep(50, signal);
|
|
2045
|
+
await dispatchMouse(cdp, sessionId, "mouseReleased", point, signal);
|
|
2046
|
+
pressed = false;
|
|
2047
|
+
} finally {
|
|
2048
|
+
if (pressed) {
|
|
2049
|
+
await dispatchMouse(cdp, sessionId, "mouseReleased", point, undefined).catch(() => {
|
|
2050
|
+
return;
|
|
2051
|
+
});
|
|
2052
|
+
}
|
|
2053
|
+
}
|
|
2054
|
+
}
|
|
2055
|
+
async function clickBackendNode(cdp, sessionId, backendNodeId, signal) {
|
|
2056
|
+
const initial = await backendCenter(cdp, sessionId, backendNodeId, true, signal);
|
|
2057
|
+
await dispatchMouse(cdp, sessionId, "mouseMoved", initial, signal);
|
|
2058
|
+
const point = await backendCenter(cdp, sessionId, backendNodeId, false, signal);
|
|
2059
|
+
await pressAndRelease(cdp, sessionId, point, signal);
|
|
2060
|
+
return point;
|
|
2061
|
+
}
|
|
2062
|
+
async function clickSelector(cdp, sessionId, selector, signal) {
|
|
2063
|
+
if (!selector)
|
|
2064
|
+
throw new Error("CSS selector required");
|
|
2065
|
+
const backendNodeId = await selectorBackendNode(cdp, sessionId, selector, signal);
|
|
2066
|
+
const point = await clickBackendNode(cdp, sessionId, backendNodeId, signal);
|
|
2067
|
+
return `Clicked <${point.tag}> "${point.text}"`;
|
|
2068
|
+
}
|
|
2069
|
+
async function clickRef(cdp, sessionId, elementRefs, id, signal) {
|
|
2070
|
+
const ref = requireElementRef(elementRefs, id);
|
|
2071
|
+
await clickBackendNode(cdp, sessionId, ref.backendNodeId, signal);
|
|
2072
|
+
return `Clicked element ${ref.id}`;
|
|
2073
|
+
}
|
|
2074
|
+
async function clickCoordinates(cdp, sessionId, x, y, signal) {
|
|
2075
|
+
if (!Number.isFinite(x) || !Number.isFinite(y)) {
|
|
2076
|
+
throw new Error("x and y must be finite CSS-pixel numbers");
|
|
2077
|
+
}
|
|
2078
|
+
const point = { x, y };
|
|
2079
|
+
await dispatchMouse(cdp, sessionId, "mouseMoved", point, signal);
|
|
2080
|
+
await pressAndRelease(cdp, sessionId, point, signal);
|
|
2081
|
+
return `Clicked at CSS (${x}, ${y})`;
|
|
2082
|
+
}
|
|
2083
|
+
|
|
2084
|
+
// packages/browser/src/cdp/actions/fill.ts
|
|
2085
|
+
function prepareFill(value) {
|
|
2086
|
+
if (!this.isConnected)
|
|
2087
|
+
throw new Error("Element detached; run open again");
|
|
2088
|
+
if (this.matches(":disabled") || this.getAttribute("aria-disabled") === "true" || this.closest("[inert]")) {
|
|
2089
|
+
throw new Error("Element is disabled or inert");
|
|
2090
|
+
}
|
|
2091
|
+
const input = this instanceof HTMLInputElement;
|
|
2092
|
+
const textarea = this instanceof HTMLTextAreaElement;
|
|
2093
|
+
const select = this instanceof HTMLSelectElement;
|
|
2094
|
+
if ((input || textarea) && this.readOnly)
|
|
2095
|
+
throw new Error("Element is read-only");
|
|
2096
|
+
const toggle = input && (this.type === "checkbox" || this.type === "radio");
|
|
2097
|
+
if (toggle) {
|
|
2098
|
+
if (typeof value !== "boolean")
|
|
2099
|
+
throw new Error("Checkbox/radio requires a boolean value");
|
|
2100
|
+
if (this.type === "radio" && !value && this.checked) {
|
|
2101
|
+
throw new Error("Select another radio option with value true instead of unchecking this one");
|
|
2102
|
+
}
|
|
2103
|
+
const indeterminate = this.type === "checkbox" && this.indeterminate;
|
|
2104
|
+
if (indeterminate && this.checked === value) {
|
|
2105
|
+
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "checked")?.set;
|
|
2106
|
+
if (!setter)
|
|
2107
|
+
throw new Error("Checkbox has no native checked setter");
|
|
2108
|
+
setter.call(this, !value);
|
|
2109
|
+
}
|
|
2110
|
+
return {
|
|
2111
|
+
kind: "checked",
|
|
2112
|
+
expected: value,
|
|
2113
|
+
needsClick: this.checked !== value || indeterminate
|
|
2114
|
+
};
|
|
2115
|
+
}
|
|
2116
|
+
if (typeof value !== "string")
|
|
2117
|
+
throw new Error("Text fields and selects require a string value");
|
|
2118
|
+
if (input && ![
|
|
2119
|
+
"text",
|
|
2120
|
+
"search",
|
|
2121
|
+
"email",
|
|
2122
|
+
"url",
|
|
2123
|
+
"tel",
|
|
2124
|
+
"password",
|
|
2125
|
+
"number",
|
|
2126
|
+
"date",
|
|
2127
|
+
"time",
|
|
2128
|
+
"datetime-local",
|
|
2129
|
+
"month",
|
|
2130
|
+
"week"
|
|
2131
|
+
].includes(this.type)) {
|
|
2132
|
+
throw new Error(`Input type ${this.type} does not support fill`);
|
|
2133
|
+
}
|
|
2134
|
+
if (!input && !textarea && !select && !this.isContentEditable) {
|
|
2135
|
+
throw new Error("Element is not an editable form control");
|
|
2136
|
+
}
|
|
2137
|
+
let replacement = value;
|
|
2138
|
+
if (select) {
|
|
2139
|
+
if (this.multiple)
|
|
2140
|
+
throw new Error("fill requires a single-select control");
|
|
2141
|
+
const options = Array.from(this.options);
|
|
2142
|
+
const byValue = options.filter((option) => option.value === value);
|
|
2143
|
+
const matches = byValue.length ? byValue : options.filter((option) => option.label.trim() === value);
|
|
2144
|
+
const option = matches[0];
|
|
2145
|
+
if (matches.length !== 1 || !option)
|
|
2146
|
+
throw new Error("Option value/label must match exactly one option");
|
|
2147
|
+
if (option.matches(":disabled"))
|
|
2148
|
+
throw new Error("Option is disabled");
|
|
2149
|
+
replacement = option.value;
|
|
2150
|
+
}
|
|
2151
|
+
this.focus({ preventScroll: true });
|
|
2152
|
+
const root = this.getRootNode();
|
|
2153
|
+
if (!this.isConnected || root.activeElement !== this) {
|
|
2154
|
+
throw new Error("Could not focus element; fill was not sent");
|
|
2155
|
+
}
|
|
2156
|
+
if (!input && !textarea && !select) {
|
|
2157
|
+
const selection = this.ownerDocument.getSelection();
|
|
2158
|
+
if (!selection)
|
|
2159
|
+
throw new Error("Could not select editable text");
|
|
2160
|
+
const range = this.ownerDocument.createRange();
|
|
2161
|
+
range.selectNodeContents(this);
|
|
2162
|
+
selection.removeAllRanges();
|
|
2163
|
+
selection.addRange(range);
|
|
2164
|
+
return { kind: "contenteditable", expected: value };
|
|
2165
|
+
}
|
|
2166
|
+
const prototype = input ? HTMLInputElement.prototype : textarea ? HTMLTextAreaElement.prototype : HTMLSelectElement.prototype;
|
|
2167
|
+
const setter = Object.getOwnPropertyDescriptor(prototype, "value")?.set;
|
|
2168
|
+
if (!setter)
|
|
2169
|
+
throw new Error("Form control has no native value setter");
|
|
2170
|
+
if (input || textarea) {
|
|
2171
|
+
const probe = this.cloneNode(false);
|
|
2172
|
+
setter.call(probe, replacement);
|
|
2173
|
+
if (probe.value !== replacement)
|
|
2174
|
+
throw new Error("Value is not accepted by this control; fill was not sent");
|
|
2175
|
+
}
|
|
2176
|
+
setter.call(this, replacement);
|
|
2177
|
+
this.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
|
|
2178
|
+
this.dispatchEvent(new Event("change", { bubbles: true }));
|
|
2179
|
+
return { kind: "value", expected: replacement };
|
|
2180
|
+
}
|
|
2181
|
+
async function callElement(cdp, sessionId, objectId, declaration, value, signal) {
|
|
2182
|
+
const response = asRecord(await cdp.send("Runtime.callFunctionOn", {
|
|
2183
|
+
objectId,
|
|
2184
|
+
functionDeclaration: declaration,
|
|
2185
|
+
arguments: [{ value }],
|
|
2186
|
+
returnByValue: true
|
|
2187
|
+
}, sessionId, signal));
|
|
2188
|
+
if (response["exceptionDetails"]) {
|
|
2189
|
+
const details = asRecord(response["exceptionDetails"]);
|
|
2190
|
+
const exception = details["exception"] ? asRecord(details["exception"]) : {};
|
|
2191
|
+
throw new Error(typeof exception["description"] === "string" ? exception["description"] : "Fill failed; run open to inspect the control before retrying");
|
|
2192
|
+
}
|
|
2193
|
+
return asRecord(asRecord(response["result"])["value"], "fill result");
|
|
2194
|
+
}
|
|
2195
|
+
async function fillElement(cdp, sessionId, elementRefs, target, value, signal) {
|
|
2196
|
+
const backendNodeId = target.id !== undefined ? requireElementRef(elementRefs, target.id).backendNodeId : await selectorBackendNode(cdp, sessionId, target.selector, signal);
|
|
2197
|
+
await backendCenter(cdp, sessionId, backendNodeId, true, signal);
|
|
2198
|
+
return withBackendObject(cdp, sessionId, backendNodeId, async (objectId) => {
|
|
2199
|
+
const prepared = await callElement(cdp, sessionId, objectId, prepareFill.toString(), value, signal);
|
|
2200
|
+
if (prepared["kind"] === "checked" && prepared["needsClick"] === true) {
|
|
2201
|
+
await clickBackendNode(cdp, sessionId, backendNodeId, signal);
|
|
2202
|
+
} else if (prepared["kind"] === "contenteditable") {
|
|
2203
|
+
const focused = await callElement(cdp, sessionId, objectId, `function() {
|
|
2204
|
+
const selection = this.ownerDocument.getSelection();
|
|
2205
|
+
return { ok: this.isConnected && this.getRootNode().activeElement === this &&
|
|
2206
|
+
selection && this.contains(selection.anchorNode) && this.contains(selection.focusNode) };
|
|
2207
|
+
}`, null, signal);
|
|
2208
|
+
if (focused["ok"] !== true)
|
|
2209
|
+
throw new Error("Focus or selection changed; fill was not sent");
|
|
2210
|
+
if (value === "")
|
|
2211
|
+
await pressKey(cdp, sessionId, "Backspace", signal);
|
|
2212
|
+
else
|
|
2213
|
+
await cdp.send("Input.insertText", { text: value }, sessionId, signal);
|
|
2214
|
+
}
|
|
2215
|
+
const verified = await callElement(cdp, sessionId, objectId, `function(expected) {
|
|
2216
|
+
if (!this.isConnected) return { ok: false };
|
|
2217
|
+
const toggle = this instanceof HTMLInputElement && (this.type === 'checkbox' || this.type === 'radio');
|
|
2218
|
+
// Editable DOM has no value property. Native editing introduces NBSPs
|
|
2219
|
+
// and block/BR nodes, so compare equivalent rendered text, not markup.
|
|
2220
|
+
if (this.isContentEditable) {
|
|
2221
|
+
const normalize = text => text.replace(/\\s+/g, ' ').trim();
|
|
2222
|
+
return { ok: normalize(this.innerText) === normalize(expected) };
|
|
2223
|
+
}
|
|
2224
|
+
const actual = toggle ? this.checked : this.value;
|
|
2225
|
+
return { ok: actual === expected && (!toggle || !this.indeterminate) };
|
|
2226
|
+
}`, prepared["expected"], signal);
|
|
2227
|
+
if (verified["ok"] !== true) {
|
|
2228
|
+
throw new Error("Fill did not retain the requested value; run open to inspect the control before retrying");
|
|
2229
|
+
}
|
|
2230
|
+
return target.id === undefined ? "Filled selected element" : `Filled element ${target.id}`;
|
|
2231
|
+
}, signal);
|
|
2232
|
+
}
|
|
2233
|
+
|
|
2234
|
+
// packages/browser/src/cdp/evaluate.ts
|
|
2235
|
+
async function evaluate(cdp, sessionId, expression, signal) {
|
|
2236
|
+
await cdp.send("Runtime.enable", {}, sessionId, signal);
|
|
2237
|
+
const response = asRecord(await cdp.send("Runtime.evaluate", {
|
|
2238
|
+
expression,
|
|
2239
|
+
returnByValue: true,
|
|
2240
|
+
awaitPromise: true
|
|
2241
|
+
}, sessionId, signal), "Runtime.evaluate response");
|
|
2242
|
+
const exception = response["exceptionDetails"];
|
|
2243
|
+
if (exception) {
|
|
2244
|
+
const details = asRecord(exception, "Runtime exception");
|
|
2245
|
+
const nested = details["exception"] && typeof details["exception"] === "object" && !Array.isArray(details["exception"]) ? details["exception"] : undefined;
|
|
2246
|
+
throw new Error(typeof nested?.["description"] === "string" ? nested["description"] : typeof details["text"] === "string" ? details["text"] : "Runtime evaluation failed");
|
|
2247
|
+
}
|
|
2248
|
+
const result = asRecord(response["result"], "Runtime result");
|
|
2249
|
+
return result["value"];
|
|
2250
|
+
}
|
|
2251
|
+
async function evaluateText(cdp, sessionId, expression, signal) {
|
|
2252
|
+
const value = await evaluate(cdp, sessionId, expression, signal);
|
|
2253
|
+
return typeof value === "object" && value !== null ? JSON.stringify(value, null, 2) : String(value ?? "");
|
|
2254
|
+
}
|
|
2255
|
+
|
|
2256
|
+
// packages/browser/src/cdp/actions/page.ts
|
|
2257
|
+
async function html(cdp, sessionId, selector, signal) {
|
|
2258
|
+
if (!selector) {
|
|
2259
|
+
return evaluateText(cdp, sessionId, "document.documentElement.outerHTML", signal);
|
|
2260
|
+
}
|
|
2261
|
+
const value = asRecord(await evaluate(cdp, sessionId, `(() => {
|
|
2262
|
+
const element = document.querySelector(${JSON.stringify(selector)});
|
|
2263
|
+
return element
|
|
2264
|
+
? { ok: true, html: element.outerHTML }
|
|
2265
|
+
: { ok: false };
|
|
2266
|
+
})()`, signal), "HTML result");
|
|
2267
|
+
if (value["ok"] !== true || typeof value["html"] !== "string") {
|
|
2268
|
+
throw new Error(`Element not found: ${selector}`);
|
|
2269
|
+
}
|
|
2270
|
+
return value["html"];
|
|
2271
|
+
}
|
|
2272
|
+
async function htmlRef(cdp, sessionId, elementRefs, id, signal) {
|
|
2273
|
+
const ref = requireElementRef(elementRefs, id);
|
|
2274
|
+
const response = await withBackendObject(cdp, sessionId, ref.backendNodeId, (objectId) => cdp.send("Runtime.callFunctionOn", {
|
|
2275
|
+
objectId,
|
|
2276
|
+
functionDeclaration: "function() { return this.outerHTML; }",
|
|
2277
|
+
returnByValue: true
|
|
2278
|
+
}, sessionId, signal), signal);
|
|
2279
|
+
const record = asRecord(response, "HTML element response");
|
|
2280
|
+
const result = asRecord(record["result"], "HTML element result");
|
|
2281
|
+
return typeof result["value"] === "string" ? result["value"] : "";
|
|
2282
|
+
}
|
|
2283
|
+
async function waitForDocumentReady(cdp, sessionId, timeout = NAVIGATION_TIMEOUT_MS, signal) {
|
|
2284
|
+
const deadline = Date.now() + timeout;
|
|
2285
|
+
let lastState = "";
|
|
2286
|
+
let lastError;
|
|
2287
|
+
while (Date.now() < deadline) {
|
|
2288
|
+
try {
|
|
2289
|
+
lastState = await evaluateText(cdp, sessionId, "document.readyState", signal);
|
|
2290
|
+
if (lastState === "complete")
|
|
2291
|
+
return;
|
|
2292
|
+
} catch (error) {
|
|
2293
|
+
lastError = error;
|
|
2294
|
+
}
|
|
2295
|
+
await sleep(200, signal);
|
|
2296
|
+
}
|
|
2297
|
+
if (lastState) {
|
|
2298
|
+
throw new Error(`Timed out waiting for navigation to finish (last readyState: ${lastState})`);
|
|
2299
|
+
}
|
|
2300
|
+
if (lastError instanceof Error) {
|
|
2301
|
+
throw new Error(`Timed out waiting for navigation to finish (${lastError.message})`);
|
|
2302
|
+
}
|
|
2303
|
+
throw new Error("Timed out waiting for navigation to finish");
|
|
2304
|
+
}
|
|
2305
|
+
async function navigate(cdp, sessionId, url, signal) {
|
|
2306
|
+
assertHttpUrl(url);
|
|
2307
|
+
await cdp.send("Page.enable", {}, sessionId, signal);
|
|
2308
|
+
const loadEvent = cdp.waitForEvent("Page.loadEventFired", NAVIGATION_TIMEOUT_MS, signal);
|
|
2309
|
+
let responseValue;
|
|
2310
|
+
try {
|
|
2311
|
+
responseValue = await cdp.send("Page.navigate", { url }, sessionId, signal);
|
|
2312
|
+
} catch (error) {
|
|
2313
|
+
cancelEventWait(loadEvent);
|
|
2314
|
+
throw error;
|
|
2315
|
+
}
|
|
2316
|
+
const response = asRecord(responseValue, "Page.navigate response");
|
|
2317
|
+
if (typeof response["errorText"] === "string") {
|
|
2318
|
+
cancelEventWait(loadEvent);
|
|
2319
|
+
throw new Error(response["errorText"]);
|
|
2320
|
+
}
|
|
2321
|
+
if (response["loaderId"])
|
|
2322
|
+
await loadEvent.promise;
|
|
2323
|
+
else
|
|
2324
|
+
cancelEventWait(loadEvent);
|
|
2325
|
+
await waitForDocumentReady(cdp, sessionId, 5000, signal);
|
|
2326
|
+
return `Navigated to ${url}`;
|
|
2327
|
+
}
|
|
2328
|
+
function cancelEventWait(wait) {
|
|
2329
|
+
wait.cancel();
|
|
2330
|
+
wait.promise.catch(() => {
|
|
2331
|
+
return;
|
|
2332
|
+
});
|
|
2333
|
+
}
|
|
2334
|
+
async function networkEntries(cdp, sessionId, signal) {
|
|
2335
|
+
const value = await evaluate(cdp, sessionId, `performance.getEntriesByType('resource').map(e => ({
|
|
2336
|
+
name: e.name.substring(0, 120),
|
|
2337
|
+
type: e.initiatorType,
|
|
2338
|
+
duration: Math.round(e.duration),
|
|
2339
|
+
size: e.transferSize
|
|
2340
|
+
}))`, signal);
|
|
2341
|
+
if (!Array.isArray(value)) {
|
|
2342
|
+
throw new Error("Browser resource timing is not an array");
|
|
2343
|
+
}
|
|
2344
|
+
return value.map((entry) => {
|
|
2345
|
+
const record = asRecord(entry, "resource timing entry");
|
|
2346
|
+
const duration = typeof record["duration"] === "number" ? record["duration"] : 0;
|
|
2347
|
+
const size = typeof record["size"] === "number" ? String(record["size"]) : "?";
|
|
2348
|
+
const type = typeof record["type"] === "string" ? record["type"] : "";
|
|
2349
|
+
const name = typeof record["name"] === "string" ? record["name"] : "";
|
|
2350
|
+
return `${String(duration).padStart(5)}ms ${size.padStart(8)}B ${type.padEnd(8)} ${name}`;
|
|
2351
|
+
}).join(`
|
|
2352
|
+
`);
|
|
2353
|
+
}
|
|
2354
|
+
async function loadAll(cdp, sessionId, selector, intervalMs = 1500, signal) {
|
|
2355
|
+
if (!selector)
|
|
2356
|
+
throw new Error("CSS selector required");
|
|
2357
|
+
let clicks = 0;
|
|
2358
|
+
const deadline = Date.now() + 5 * 60 * 1000;
|
|
2359
|
+
while (Date.now() < deadline) {
|
|
2360
|
+
const exists = await evaluate(cdp, sessionId, `!!document.querySelector(${JSON.stringify(selector)})`, signal);
|
|
2361
|
+
if (exists !== true) {
|
|
2362
|
+
return `Clicked "${selector}" ${clicks} time(s) until it disappeared`;
|
|
2363
|
+
}
|
|
2364
|
+
await clickSelector(cdp, sessionId, selector, signal);
|
|
2365
|
+
clicks++;
|
|
2366
|
+
await sleep(intervalMs, signal);
|
|
2367
|
+
}
|
|
2368
|
+
return `Clicked "${selector}" ${clicks} time(s); stopped at the five-minute deadline while it was still present`;
|
|
2369
|
+
}
|
|
2370
|
+
async function rawCommand(cdp, sessionId, method, params, signal) {
|
|
2371
|
+
if (!method) {
|
|
2372
|
+
throw new Error('CDP method required, for example "DOM.getDocument"');
|
|
2373
|
+
}
|
|
2374
|
+
const result = await cdp.send(method, params, sessionId, signal);
|
|
2375
|
+
return JSON.stringify(result, null, 2);
|
|
2376
|
+
}
|
|
2377
|
+
|
|
2378
|
+
// packages/browser/src/cdp/actions/screenshot.ts
|
|
2379
|
+
async function devicePixelRatio(cdp, sessionId, signal) {
|
|
2380
|
+
try {
|
|
2381
|
+
const value = await evaluate(cdp, sessionId, "window.devicePixelRatio", signal);
|
|
2382
|
+
if (typeof value === "number" && value > 0)
|
|
2383
|
+
return value;
|
|
2384
|
+
} catch {}
|
|
2385
|
+
return 1;
|
|
2386
|
+
}
|
|
2387
|
+
async function capture(cdp, sessionId, target, clip, signal) {
|
|
2388
|
+
const response = asRecord(await cdp.send("Page.captureScreenshot", {
|
|
2389
|
+
format: "png",
|
|
2390
|
+
...clip ? { clip, captureBeyondViewport: false } : {}
|
|
2391
|
+
}, sessionId, signal), "screenshot response");
|
|
2392
|
+
const data = asString(response["data"], "screenshot data");
|
|
2393
|
+
await target.write(Buffer.from(data, "base64"));
|
|
2394
|
+
return {
|
|
2395
|
+
file: target.file,
|
|
2396
|
+
dpr: await devicePixelRatio(cdp, sessionId, signal),
|
|
2397
|
+
...clip ? { width: clip.width, height: clip.height } : {}
|
|
2398
|
+
};
|
|
2399
|
+
}
|
|
2400
|
+
function captureViewport(cdp, sessionId, target, signal) {
|
|
2401
|
+
return capture(cdp, sessionId, target, undefined, signal);
|
|
2402
|
+
}
|
|
2403
|
+
async function captureSelector(cdp, sessionId, selector, target, signal) {
|
|
2404
|
+
if (!selector)
|
|
2405
|
+
throw new Error("CSS selector required");
|
|
2406
|
+
const value = asRecord(await evaluate(cdp, sessionId, `(() => {
|
|
2407
|
+
const el = document.querySelector(${JSON.stringify(selector)});
|
|
2408
|
+
if (!el) return {
|
|
2409
|
+
ok: false,
|
|
2410
|
+
error: 'Element not found: ' + ${JSON.stringify(selector)}
|
|
2411
|
+
};
|
|
2412
|
+
el.scrollIntoView({ block: 'center', inline: 'center' });
|
|
2413
|
+
const r = el.getBoundingClientRect();
|
|
2414
|
+
const padding = 10;
|
|
2415
|
+
const x = Math.max(0, r.left - padding);
|
|
2416
|
+
const y = Math.max(0, r.top - padding);
|
|
2417
|
+
const right = Math.min(window.innerWidth, r.right + padding);
|
|
2418
|
+
const bottom = Math.min(window.innerHeight, r.bottom + padding);
|
|
2419
|
+
return {
|
|
2420
|
+
ok: true,
|
|
2421
|
+
clip: {
|
|
2422
|
+
x,
|
|
2423
|
+
y,
|
|
2424
|
+
width: Math.max(1, right - x),
|
|
2425
|
+
height: Math.max(1, bottom - y),
|
|
2426
|
+
scale: 1
|
|
2427
|
+
}
|
|
2428
|
+
};
|
|
2429
|
+
})()`, signal), "element screenshot geometry");
|
|
2430
|
+
if (value["ok"] !== true) {
|
|
2431
|
+
throw new Error(typeof value["error"] === "string" ? value["error"] : `Could not capture ${selector}`);
|
|
2432
|
+
}
|
|
2433
|
+
const clipRecord = asRecord(value["clip"], "element screenshot clip");
|
|
2434
|
+
const [x, y, width, height] = ["x", "y", "width", "height"].map((field) => Number(clipRecord[field]));
|
|
2435
|
+
if (x === undefined || y === undefined || width === undefined || height === undefined || ![x, y, width, height].every(Number.isFinite) || width <= 0 || height <= 0) {
|
|
2436
|
+
throw new Error("Element has an invalid screenshot box");
|
|
2437
|
+
}
|
|
2438
|
+
const clip = {
|
|
2439
|
+
x,
|
|
2440
|
+
y,
|
|
2441
|
+
width,
|
|
2442
|
+
height,
|
|
2443
|
+
scale: 1
|
|
2444
|
+
};
|
|
2445
|
+
return capture(cdp, sessionId, target, clip, signal);
|
|
2446
|
+
}
|
|
2447
|
+
async function captureRef(cdp, sessionId, elementRefs, id, target, signal) {
|
|
2448
|
+
const ref = requireElementRef(elementRefs, id);
|
|
2449
|
+
await scrollBackendIntoView(cdp, sessionId, ref.backendNodeId, signal);
|
|
2450
|
+
const response = asRecord(await cdp.send("DOM.getBoxModel", { backendNodeId: ref.backendNodeId }, sessionId, signal), "DOM box model");
|
|
2451
|
+
const model = asRecord(response["model"], "DOM box model");
|
|
2452
|
+
const border = model["border"];
|
|
2453
|
+
if (!Array.isArray(border) || !border.every((value) => typeof value === "number")) {
|
|
2454
|
+
throw new Error("Element has no screenshot box");
|
|
2455
|
+
}
|
|
2456
|
+
const clip = await visibleElementClip(cdp, sessionId, border, 10, signal);
|
|
2457
|
+
return capture(cdp, sessionId, target, clip, signal);
|
|
2458
|
+
}
|
|
2459
|
+
|
|
2460
|
+
// packages/browser/src/cdp/actions/type.ts
|
|
2461
|
+
async function typeAtFocus(cdp, sessionId, text, signal) {
|
|
2462
|
+
if (!text)
|
|
2463
|
+
throw new Error("text required");
|
|
2464
|
+
const focusState = asRecord(await evaluate(cdp, sessionId, `(() => {
|
|
2465
|
+
const el = document.activeElement;
|
|
2466
|
+
if (!el || el === document.body || el === document.documentElement)
|
|
2467
|
+
return { ok: false, error: 'No editable element is focused' };
|
|
2468
|
+
const tag = el.tagName;
|
|
2469
|
+
const inputTypes = new Set([
|
|
2470
|
+
'text', 'search', 'email', 'url', 'tel', 'password', 'number'
|
|
2471
|
+
]);
|
|
2472
|
+
const input = tag === 'INPUT' &&
|
|
2473
|
+
inputTypes.has((el.type || 'text').toLowerCase());
|
|
2474
|
+
const textarea = tag === 'TEXTAREA';
|
|
2475
|
+
const contentEditable = el.isContentEditable;
|
|
2476
|
+
const iframe = tag === 'IFRAME';
|
|
2477
|
+
if (!input && !textarea && !contentEditable && !iframe)
|
|
2478
|
+
return { ok: false, error: 'Focused <' + tag + '> is not editable' };
|
|
2479
|
+
if ((input || textarea) && (el.disabled || el.readOnly))
|
|
2480
|
+
return { ok: false, error: 'Focused <' + tag + '> is disabled or read-only' };
|
|
2481
|
+
return {
|
|
2482
|
+
ok: true,
|
|
2483
|
+
tag,
|
|
2484
|
+
iframe,
|
|
2485
|
+
inspectable: !iframe,
|
|
2486
|
+
before: input || textarea
|
|
2487
|
+
? el.value
|
|
2488
|
+
: contentEditable ? el.textContent : null
|
|
2489
|
+
};
|
|
2490
|
+
})()`, signal), "focused element state");
|
|
2491
|
+
if (focusState["ok"] !== true) {
|
|
2492
|
+
throw new Error(typeof focusState["error"] === "string" ? focusState["error"] : "Focused element is not editable");
|
|
2493
|
+
}
|
|
2494
|
+
await cdp.send("Input.insertText", { text }, sessionId, signal);
|
|
2495
|
+
const tag = typeof focusState["tag"] === "string" ? focusState["tag"] : "ELEMENT";
|
|
2496
|
+
if (focusState["inspectable"] !== true) {
|
|
2497
|
+
return `Sent ${text.length} characters to focused <${tag}>; cross-origin result is not inspectable`;
|
|
2498
|
+
}
|
|
2499
|
+
const after = asRecord(await evaluate(cdp, sessionId, `(() => {
|
|
2500
|
+
const el = document.activeElement;
|
|
2501
|
+
if (!el) return { focused: false, value: null };
|
|
2502
|
+
const tag = el.tagName;
|
|
2503
|
+
const value = tag === 'INPUT' || tag === 'TEXTAREA'
|
|
2504
|
+
? el.value
|
|
2505
|
+
: el.isContentEditable ? el.textContent : null;
|
|
2506
|
+
return { focused: true, tag, value };
|
|
2507
|
+
})()`, signal), "focused element result");
|
|
2508
|
+
if (after["focused"] !== true || after["tag"] !== tag) {
|
|
2509
|
+
throw new Error("Focus changed while typing; input result could not be verified");
|
|
2510
|
+
}
|
|
2511
|
+
if (after["value"] === focusState["before"]) {
|
|
2512
|
+
throw new Error(`Input.insertText completed but focused <${tag}> did not change`);
|
|
2513
|
+
}
|
|
2514
|
+
return `Typed ${text.length} characters into focused <${tag}>`;
|
|
2515
|
+
}
|
|
2516
|
+
async function typeRef(cdp, sessionId, elementRefs, id, text, signal) {
|
|
2517
|
+
if (!text)
|
|
2518
|
+
throw new Error("text required");
|
|
2519
|
+
const ref = requireElementRef(elementRefs, id);
|
|
2520
|
+
await backendCenter(cdp, sessionId, ref.backendNodeId, true, signal);
|
|
2521
|
+
return withBackendObject(cdp, sessionId, ref.backendNodeId, async (objectId) => {
|
|
2522
|
+
const focused = asRecord(await cdp.send("Runtime.callFunctionOn", {
|
|
2523
|
+
objectId,
|
|
2524
|
+
functionDeclaration: `function() {
|
|
2525
|
+
const tag = this.tagName;
|
|
2526
|
+
const inputTypes = new Set([
|
|
2527
|
+
'text', 'search', 'email', 'url', 'tel',
|
|
2528
|
+
'password', 'number'
|
|
2529
|
+
]);
|
|
2530
|
+
const input = tag === 'INPUT' &&
|
|
2531
|
+
inputTypes.has((this.type || 'text').toLowerCase());
|
|
2532
|
+
const textarea = tag === 'TEXTAREA';
|
|
2533
|
+
const contentEditable = this.isContentEditable;
|
|
2534
|
+
if (!input && !textarea && !contentEditable)
|
|
2535
|
+
return { ok: false, error: '<' + tag + '> is not editable' };
|
|
2536
|
+
if ((input || textarea) && (this.disabled || this.readOnly))
|
|
2537
|
+
return { ok: false, error: '<' + tag + '> is disabled or read-only' };
|
|
2538
|
+
this.focus({ preventScroll: true });
|
|
2539
|
+
const root = this.getRootNode();
|
|
2540
|
+
if (root.activeElement !== this &&
|
|
2541
|
+
this.ownerDocument.activeElement !== this)
|
|
2542
|
+
return { ok: false, error: 'Could not focus editable <' + tag + '>' };
|
|
2543
|
+
const before = input || textarea ? this.value : this.textContent;
|
|
2544
|
+
return { ok: true, tag, before };
|
|
2545
|
+
}`,
|
|
2546
|
+
returnByValue: true
|
|
2547
|
+
}, sessionId, signal), "focus response");
|
|
2548
|
+
const focusState = asRecord(asRecord(focused["result"], "focus result")["value"], "focus state");
|
|
2549
|
+
if (focusState["ok"] !== true) {
|
|
2550
|
+
throw new Error(typeof focusState["error"] === "string" ? focusState["error"] : "Element is not editable");
|
|
2551
|
+
}
|
|
2552
|
+
const activeResponse = asRecord(await cdp.send("Runtime.callFunctionOn", {
|
|
2553
|
+
objectId,
|
|
2554
|
+
functionDeclaration: `function() {
|
|
2555
|
+
const root = this.getRootNode();
|
|
2556
|
+
return root.activeElement === this ||
|
|
2557
|
+
this.ownerDocument.activeElement === this;
|
|
2558
|
+
}`,
|
|
2559
|
+
returnByValue: true
|
|
2560
|
+
}, sessionId, signal), "active element response");
|
|
2561
|
+
const activeResult = asRecord(activeResponse["result"], "active element result");
|
|
2562
|
+
if (activeResult["value"] !== true) {
|
|
2563
|
+
throw new Error("Focus changed before typing; input was not sent");
|
|
2564
|
+
}
|
|
2565
|
+
await cdp.send("Input.insertText", { text }, sessionId, signal);
|
|
2566
|
+
const afterResponse = asRecord(await cdp.send("Runtime.callFunctionOn", {
|
|
2567
|
+
objectId,
|
|
2568
|
+
functionDeclaration: `function(before) {
|
|
2569
|
+
const root = this.getRootNode();
|
|
2570
|
+
const active = root.activeElement === this ||
|
|
2571
|
+
this.ownerDocument.activeElement === this;
|
|
2572
|
+
const value = this.tagName === 'INPUT' ||
|
|
2573
|
+
this.tagName === 'TEXTAREA'
|
|
2574
|
+
? this.value
|
|
2575
|
+
: this.textContent;
|
|
2576
|
+
return { active, changed: value !== before };
|
|
2577
|
+
}`,
|
|
2578
|
+
arguments: [{ value: focusState["before"] }],
|
|
2579
|
+
returnByValue: true
|
|
2580
|
+
}, sessionId, signal), "typed element response");
|
|
2581
|
+
const after = asRecord(asRecord(afterResponse["result"], "typed result")["value"], "typed state");
|
|
2582
|
+
if (after["active"] !== true) {
|
|
2583
|
+
throw new Error("Focus changed while typing; input result could not be verified");
|
|
2584
|
+
}
|
|
2585
|
+
const tag = typeof focusState["tag"] === "string" ? focusState["tag"] : "ELEMENT";
|
|
2586
|
+
if (after["changed"] !== true) {
|
|
2587
|
+
throw new Error(`Input.insertText completed but referenced <${tag}> did not change`);
|
|
2588
|
+
}
|
|
2589
|
+
return `Typed ${text.length} characters into referenced <${tag}>`;
|
|
2590
|
+
}, signal);
|
|
2591
|
+
}
|
|
2592
|
+
|
|
2593
|
+
// packages/browser/src/cdp/actions/wait.ts
|
|
2594
|
+
var POLL_INTERVAL_MS = 100;
|
|
2595
|
+
var SUMMARY_LENGTH = 120;
|
|
2596
|
+
var NAVIGATION_CONTEXT_ERRORS = [
|
|
2597
|
+
/(?:^|: )Execution context was destroyed\b/i,
|
|
2598
|
+
/(?:^|: )Cannot find context with specified id\b/i,
|
|
2599
|
+
/(?:^|: )Cannot find (?:default )?execution context\b/i,
|
|
2600
|
+
/(?:^|: )No execution context with given id\b/i
|
|
2601
|
+
];
|
|
2602
|
+
function conditionDetails(condition) {
|
|
2603
|
+
if ("selector" in condition) {
|
|
2604
|
+
return {
|
|
2605
|
+
expression: `document.querySelector(${JSON.stringify(condition.selector)}) !== null`,
|
|
2606
|
+
label: `selector ${summary(condition.selector)}`,
|
|
2607
|
+
matched: `Matched selector ${summary(condition.selector)}`
|
|
2608
|
+
};
|
|
2609
|
+
}
|
|
2610
|
+
if ("text" in condition) {
|
|
2611
|
+
return {
|
|
2612
|
+
expression: `document.body?.innerText.includes(${JSON.stringify(condition.text)}) ?? false`,
|
|
2613
|
+
label: `text ${summary(condition.text)}`,
|
|
2614
|
+
matched: `Matched text ${summary(condition.text)}`
|
|
2615
|
+
};
|
|
2616
|
+
}
|
|
2617
|
+
return {
|
|
2618
|
+
expression: `location.href.includes(${JSON.stringify(condition.url_includes)})`,
|
|
2619
|
+
label: `URL containing ${summary(condition.url_includes)}`,
|
|
2620
|
+
matched: `Matched URL containing ${summary(condition.url_includes)}`
|
|
2621
|
+
};
|
|
2622
|
+
}
|
|
2623
|
+
function summary(value) {
|
|
2624
|
+
const normalized = value.replace(/\s+/g, " ").trim();
|
|
2625
|
+
const bounded = normalized.length > SUMMARY_LENGTH ? `${normalized.slice(0, SUMMARY_LENGTH - 3)}...` : normalized;
|
|
2626
|
+
return JSON.stringify(bounded);
|
|
2627
|
+
}
|
|
2628
|
+
function isNavigationContextError(error) {
|
|
2629
|
+
const message = errorMessage(error);
|
|
2630
|
+
return NAVIGATION_CONTEXT_ERRORS.some((pattern) => pattern.test(message));
|
|
2631
|
+
}
|
|
2632
|
+
async function waitForCondition(cdp, sessionId, condition, timeoutMs, signal) {
|
|
2633
|
+
const details = conditionDetails(condition);
|
|
2634
|
+
const timeoutError = new Error(`Timed out after ${timeoutMs}ms waiting for ${details.label}`);
|
|
2635
|
+
const deadline = Date.now() + timeoutMs;
|
|
2636
|
+
const controller = new AbortController;
|
|
2637
|
+
let timedOut = false;
|
|
2638
|
+
const abort = () => {
|
|
2639
|
+
controller.abort(signal?.reason ?? new Error("Wait aborted"));
|
|
2640
|
+
};
|
|
2641
|
+
if (signal?.aborted) {
|
|
2642
|
+
abort();
|
|
2643
|
+
} else {
|
|
2644
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
2645
|
+
}
|
|
2646
|
+
const timer = setTimeout(() => {
|
|
2647
|
+
timedOut = true;
|
|
2648
|
+
controller.abort(timeoutError);
|
|
2649
|
+
}, timeoutMs);
|
|
2650
|
+
try {
|
|
2651
|
+
while (Date.now() < deadline) {
|
|
2652
|
+
try {
|
|
2653
|
+
const matched = await evaluate(cdp, sessionId, details.expression, controller.signal);
|
|
2654
|
+
if (matched === true)
|
|
2655
|
+
return details.matched;
|
|
2656
|
+
if (matched !== false) {
|
|
2657
|
+
throw new Error("Wait condition returned a non-boolean result");
|
|
2658
|
+
}
|
|
2659
|
+
} catch (error) {
|
|
2660
|
+
if (controller.signal.aborted)
|
|
2661
|
+
throw controller.signal.reason;
|
|
2662
|
+
if (!isNavigationContextError(error))
|
|
2663
|
+
throw error;
|
|
2664
|
+
}
|
|
2665
|
+
const remaining = deadline - Date.now();
|
|
2666
|
+
if (remaining <= 0)
|
|
2667
|
+
break;
|
|
2668
|
+
await sleep(Math.min(POLL_INTERVAL_MS, remaining), controller.signal);
|
|
2669
|
+
}
|
|
2670
|
+
throw timeoutError;
|
|
2671
|
+
} catch (error) {
|
|
2672
|
+
if (timedOut)
|
|
2673
|
+
throw timeoutError;
|
|
2674
|
+
throw error;
|
|
2675
|
+
} finally {
|
|
2676
|
+
clearTimeout(timer);
|
|
2677
|
+
signal?.removeEventListener("abort", abort);
|
|
2678
|
+
}
|
|
2679
|
+
}
|
|
2680
|
+
|
|
2681
|
+
// packages/browser/src/cdp/accessibility-snapshot.ts
|
|
2682
|
+
var INTERACTIVE_ROLES = new Set([
|
|
2683
|
+
"button",
|
|
2684
|
+
"checkbox",
|
|
2685
|
+
"combobox",
|
|
2686
|
+
"link",
|
|
2687
|
+
"listbox",
|
|
2688
|
+
"menuitem",
|
|
2689
|
+
"option",
|
|
2690
|
+
"menuitemcheckbox",
|
|
2691
|
+
"menuitemradio",
|
|
2692
|
+
"radio",
|
|
2693
|
+
"searchbox",
|
|
2694
|
+
"slider",
|
|
2695
|
+
"spinbutton",
|
|
2696
|
+
"switch",
|
|
2697
|
+
"tab",
|
|
2698
|
+
"textbox",
|
|
2699
|
+
"treeitem"
|
|
2700
|
+
]);
|
|
2701
|
+
var NEXT_ELEMENT_IDS = new WeakMap;
|
|
2702
|
+
function axProperty(value) {
|
|
2703
|
+
const record = asRecord(value, "accessibility property");
|
|
2704
|
+
if (typeof record["name"] !== "string") {
|
|
2705
|
+
throw new Error("Accessibility property has no name");
|
|
2706
|
+
}
|
|
2707
|
+
return {
|
|
2708
|
+
name: record["name"],
|
|
2709
|
+
...record["value"] ? { value: asRecord(record["value"]) } : {}
|
|
2710
|
+
};
|
|
2711
|
+
}
|
|
2712
|
+
function axNode(value) {
|
|
2713
|
+
const record = asRecord(value, "accessibility node");
|
|
2714
|
+
if (typeof record["nodeId"] !== "string") {
|
|
2715
|
+
throw new Error("Accessibility node has no nodeId");
|
|
2716
|
+
}
|
|
2717
|
+
return {
|
|
2718
|
+
nodeId: record["nodeId"],
|
|
2719
|
+
...typeof record["parentId"] === "string" ? { parentId: record["parentId"] } : {},
|
|
2720
|
+
...Array.isArray(record["childIds"]) ? {
|
|
2721
|
+
childIds: record["childIds"].filter((id) => typeof id === "string")
|
|
2722
|
+
} : {},
|
|
2723
|
+
...typeof record["backendDOMNodeId"] === "number" ? { backendDOMNodeId: record["backendDOMNodeId"] } : {},
|
|
2724
|
+
...typeof record["ignored"] === "boolean" ? { ignored: record["ignored"] } : {},
|
|
2725
|
+
...record["role"] ? { role: asRecord(record["role"]) } : {},
|
|
2726
|
+
...record["name"] ? { name: asRecord(record["name"]) } : {},
|
|
2727
|
+
...record["value"] ? { value: asRecord(record["value"]) } : {},
|
|
2728
|
+
...Array.isArray(record["properties"]) ? { properties: record["properties"].map(axProperty) } : {}
|
|
2729
|
+
};
|
|
2730
|
+
}
|
|
2731
|
+
function shouldShow(node) {
|
|
2732
|
+
const role = String(node.role?.value ?? "");
|
|
2733
|
+
const name = node.name?.value ?? "";
|
|
2734
|
+
const value = node.value?.value;
|
|
2735
|
+
if (role === "InlineTextBox")
|
|
2736
|
+
return false;
|
|
2737
|
+
if (INTERACTIVE_ROLES.has(role))
|
|
2738
|
+
return true;
|
|
2739
|
+
return role !== "none" && role !== "generic" && !(name === "" && (value === "" || value == null));
|
|
2740
|
+
}
|
|
2741
|
+
function orderedChildren(node, nodesById, childrenByParent) {
|
|
2742
|
+
const children = [];
|
|
2743
|
+
const seen = new Set;
|
|
2744
|
+
for (const childId of node.childIds ?? []) {
|
|
2745
|
+
const child = nodesById.get(childId);
|
|
2746
|
+
if (child && !seen.has(child.nodeId)) {
|
|
2747
|
+
seen.add(child.nodeId);
|
|
2748
|
+
children.push(child);
|
|
2749
|
+
}
|
|
2750
|
+
}
|
|
2751
|
+
for (const child of childrenByParent.get(node.nodeId) ?? []) {
|
|
2752
|
+
if (!seen.has(child.nodeId)) {
|
|
2753
|
+
seen.add(child.nodeId);
|
|
2754
|
+
children.push(child);
|
|
2755
|
+
}
|
|
2756
|
+
}
|
|
2757
|
+
return children;
|
|
2758
|
+
}
|
|
2759
|
+
function normalizeText(value) {
|
|
2760
|
+
return String(value ?? "").replace(/\s+/g, " ").trim();
|
|
2761
|
+
}
|
|
2762
|
+
function splitText(value, max = 700) {
|
|
2763
|
+
const text = normalizeText(value);
|
|
2764
|
+
if (!text)
|
|
2765
|
+
return [];
|
|
2766
|
+
const parts = [];
|
|
2767
|
+
for (let start = 0;start < text.length; start += max) {
|
|
2768
|
+
parts.push(text.slice(start, start + max));
|
|
2769
|
+
}
|
|
2770
|
+
return parts;
|
|
2771
|
+
}
|
|
2772
|
+
function interactiveState(node) {
|
|
2773
|
+
const values = new Map((node.properties ?? []).map((property) => [
|
|
2774
|
+
property.name,
|
|
2775
|
+
property.value?.value
|
|
2776
|
+
]));
|
|
2777
|
+
const checkedValue = values.get("checked");
|
|
2778
|
+
const checked = checkedValue === "true" ? true : checkedValue === "false" ? false : typeof checkedValue === "boolean" || checkedValue === "mixed" ? checkedValue : undefined;
|
|
2779
|
+
const selected = values.get("selected");
|
|
2780
|
+
const expanded = values.get("expanded");
|
|
2781
|
+
const disabled = values.get("disabled");
|
|
2782
|
+
return {
|
|
2783
|
+
...checked === undefined ? {} : { checked },
|
|
2784
|
+
...typeof selected === "boolean" ? { selected } : {},
|
|
2785
|
+
...typeof expanded === "boolean" ? { expanded } : {},
|
|
2786
|
+
...typeof disabled === "boolean" ? { disabled } : {}
|
|
2787
|
+
};
|
|
2788
|
+
}
|
|
2789
|
+
function interactiveText(role, name, value, state) {
|
|
2790
|
+
const states = [
|
|
2791
|
+
state.checked === undefined ? undefined : `checked=${state.checked}`,
|
|
2792
|
+
state.selected === undefined ? undefined : `selected=${state.selected}`,
|
|
2793
|
+
state.expanded === undefined ? undefined : `expanded=${state.expanded}`,
|
|
2794
|
+
state.disabled === undefined ? undefined : `disabled=${state.disabled}`
|
|
2795
|
+
].filter((entry) => entry !== undefined);
|
|
2796
|
+
return `${role}${name ? ` ${name}` : ""}${value === "" || value == null ? "" : ` = ${JSON.stringify(value)}`}${states.length > 0 ? ` [${states.join(", ")}]` : ""}`;
|
|
2797
|
+
}
|
|
2798
|
+
function renderAccessibilityTree(values, elementRefs) {
|
|
2799
|
+
const nodes = values.map(axNode);
|
|
2800
|
+
const nodesById = new Map(nodes.map((node) => [node.nodeId, node]));
|
|
2801
|
+
const childrenByParent = new Map;
|
|
2802
|
+
for (const node of nodes) {
|
|
2803
|
+
if (!node.parentId)
|
|
2804
|
+
continue;
|
|
2805
|
+
const children = childrenByParent.get(node.parentId) ?? [];
|
|
2806
|
+
children.push(node);
|
|
2807
|
+
childrenByParent.set(node.parentId, children);
|
|
2808
|
+
}
|
|
2809
|
+
elementRefs.clear();
|
|
2810
|
+
const lines = [];
|
|
2811
|
+
const elements = [];
|
|
2812
|
+
const visited = new Set;
|
|
2813
|
+
const nextElementId = () => {
|
|
2814
|
+
const id = NEXT_ELEMENT_IDS.get(elementRefs) ?? 1;
|
|
2815
|
+
if (!Number.isSafeInteger(id)) {
|
|
2816
|
+
throw new Error("Element id limit reached; restart the tab bridge");
|
|
2817
|
+
}
|
|
2818
|
+
NEXT_ELEMENT_IDS.set(elementRefs, id + 1);
|
|
2819
|
+
return id;
|
|
2820
|
+
};
|
|
2821
|
+
const addLine = (text, element, kind = "text") => {
|
|
2822
|
+
for (const part of splitText(text)) {
|
|
2823
|
+
lines.push({
|
|
2824
|
+
line: lines.length + 1,
|
|
2825
|
+
text: part,
|
|
2826
|
+
kind,
|
|
2827
|
+
...element ? { element_id: element.id } : {}
|
|
2828
|
+
});
|
|
2829
|
+
}
|
|
2830
|
+
};
|
|
2831
|
+
const addStaticText = (text) => {
|
|
2832
|
+
const normalized = normalizeText(text);
|
|
2833
|
+
if (!normalized)
|
|
2834
|
+
return;
|
|
2835
|
+
const previous = lines.at(-1);
|
|
2836
|
+
if (previous?.kind === "text" && previous.text.length + normalized.length + 1 <= 700) {
|
|
2837
|
+
previous.text += ` ${normalized}`;
|
|
2838
|
+
return;
|
|
2839
|
+
}
|
|
2840
|
+
addLine(normalized);
|
|
2841
|
+
};
|
|
2842
|
+
const visit = (node, parentName = "") => {
|
|
2843
|
+
if (!node || visited.has(node.nodeId))
|
|
2844
|
+
return;
|
|
2845
|
+
visited.add(node.nodeId);
|
|
2846
|
+
const role = String(node.role?.value ?? "");
|
|
2847
|
+
const name = normalizeText(node.name?.value ?? "");
|
|
2848
|
+
const value = node.value?.value;
|
|
2849
|
+
let renderedName = parentName;
|
|
2850
|
+
if (!node.ignored && shouldShow(node)) {
|
|
2851
|
+
if (INTERACTIVE_ROLES.has(role)) {
|
|
2852
|
+
const state = interactiveState(node);
|
|
2853
|
+
const text = interactiveText(role, name, value, state);
|
|
2854
|
+
if (!node.backendDOMNodeId) {
|
|
2855
|
+
addLine(text, undefined, "interactive");
|
|
2856
|
+
renderedName = name;
|
|
2857
|
+
} else {
|
|
2858
|
+
const href = role === "link" ? node.properties?.find((property) => property.name === "url")?.value?.value : undefined;
|
|
2859
|
+
const element = {
|
|
2860
|
+
id: nextElementId(),
|
|
2861
|
+
role,
|
|
2862
|
+
...name ? { name } : {},
|
|
2863
|
+
...typeof href === "string" && href ? { href } : {},
|
|
2864
|
+
...value === "" || value == null ? {} : { value },
|
|
2865
|
+
...state
|
|
2866
|
+
};
|
|
2867
|
+
elementRefs.set(element.id, node.backendDOMNodeId);
|
|
2868
|
+
elements.push(element);
|
|
2869
|
+
addLine(`[${element.id}] ${text}`, element, "interactive");
|
|
2870
|
+
renderedName = name;
|
|
2871
|
+
}
|
|
2872
|
+
} else if (role === "StaticText") {
|
|
2873
|
+
if (name && name !== parentName)
|
|
2874
|
+
addStaticText(name);
|
|
2875
|
+
} else if (role === "heading" || role === "image") {
|
|
2876
|
+
if (name)
|
|
2877
|
+
addLine(`${role}: ${name}`, undefined, role);
|
|
2878
|
+
renderedName = name || parentName;
|
|
2879
|
+
}
|
|
2880
|
+
}
|
|
2881
|
+
for (const child of orderedChildren(node, nodesById, childrenByParent)) {
|
|
2882
|
+
visit(child, renderedName);
|
|
2883
|
+
}
|
|
2884
|
+
};
|
|
2885
|
+
for (const root of nodes.filter((node) => !node.parentId || !nodesById.has(node.parentId))) {
|
|
2886
|
+
visit(root);
|
|
2887
|
+
}
|
|
2888
|
+
for (const node of nodes)
|
|
2889
|
+
visit(node);
|
|
2890
|
+
return { lines, elements };
|
|
2891
|
+
}
|
|
2892
|
+
|
|
2893
|
+
// packages/browser/src/cdp/snapshot.ts
|
|
2894
|
+
async function snapshotData(cdp, sessionId, elementRefs, options = {}) {
|
|
2895
|
+
const lineno = positiveInteger(options.lineno ?? 1, "line cursor");
|
|
2896
|
+
const responseLength = snapshotResponseLength(options.responseLength);
|
|
2897
|
+
const response = asRecord(await cdp.send("Accessibility.getFullAXTree", {}, sessionId, options.signal), "Accessibility response");
|
|
2898
|
+
if (!Array.isArray(response["nodes"])) {
|
|
2899
|
+
throw new Error("Accessibility response has no nodes");
|
|
2900
|
+
}
|
|
2901
|
+
const { lines, elements } = renderAccessibilityTree(response["nodes"], elementRefs);
|
|
2902
|
+
const metadata = asRecord(await evaluate(cdp, sessionId, "({title: document.title, url: location.href})", options.signal), "page metadata");
|
|
2903
|
+
const pattern = options.pattern?.toLowerCase();
|
|
2904
|
+
const matching = pattern ? lines.filter((line) => line.text.toLowerCase().includes(pattern)) : lines;
|
|
2905
|
+
const start = lineno - 1;
|
|
2906
|
+
const content = matching.slice(start, start + SNAPSHOT_LIMITS[responseLength]).map(({ kind: _kind, ...line }) => line);
|
|
2907
|
+
const visibleIds = new Set(content.flatMap((line) => line.element_id === undefined ? [] : [line.element_id]));
|
|
2908
|
+
const hasMore = start + content.length < matching.length;
|
|
2909
|
+
return {
|
|
2910
|
+
...options.refId ? { ref_id: options.refId } : {},
|
|
2911
|
+
title: typeof metadata["title"] === "string" ? metadata["title"] : "",
|
|
2912
|
+
url: typeof metadata["url"] === "string" ? metadata["url"] : "",
|
|
2913
|
+
lineno: start + 1,
|
|
2914
|
+
content,
|
|
2915
|
+
elements: elements.filter((element) => visibleIds.has(element.id)),
|
|
2916
|
+
...options.pattern ? { pattern: options.pattern } : {},
|
|
2917
|
+
...hasMore ? { next_lineno: start + content.length + 1 } : {}
|
|
2918
|
+
};
|
|
2919
|
+
}
|
|
2920
|
+
|
|
2921
|
+
// packages/browser/src/browser/bounds.ts
|
|
2922
|
+
import { StringDecoder as StringDecoder2 } from "node:string_decoder";
|
|
2923
|
+
var OUTPUT_BUDGET_BYTES = 38000;
|
|
2924
|
+
var SNAPSHOT_TITLE_BYTES = 1000;
|
|
2925
|
+
var SNAPSHOT_URL_BYTES = 8000;
|
|
2926
|
+
var SNAPSHOT_PATTERN_BYTES = 2000;
|
|
2927
|
+
var SNAPSHOT_ELEMENT_NAME_BYTES = 2000;
|
|
2928
|
+
var SNAPSHOT_ELEMENT_VALUE_BYTES = 4000;
|
|
2929
|
+
function byteLength(value) {
|
|
2930
|
+
return Buffer.byteLength(JSON.stringify(value));
|
|
2931
|
+
}
|
|
2932
|
+
function truncateUtf8(value, maxBytes) {
|
|
2933
|
+
const bytes = Buffer.from(value);
|
|
2934
|
+
if (bytes.length <= maxBytes)
|
|
2935
|
+
return value;
|
|
2936
|
+
return new StringDecoder2("utf8").write(bytes.subarray(0, maxBytes));
|
|
2937
|
+
}
|
|
2938
|
+
function boundedElement(element) {
|
|
2939
|
+
const { href, ...rest } = element;
|
|
2940
|
+
let value = element.value;
|
|
2941
|
+
if (typeof value === "string") {
|
|
2942
|
+
value = truncateUtf8(value, SNAPSHOT_ELEMENT_VALUE_BYTES);
|
|
2943
|
+
} else if (value !== undefined) {
|
|
2944
|
+
const serialized = JSON.stringify(value);
|
|
2945
|
+
if (serialized && Buffer.byteLength(serialized) > SNAPSHOT_ELEMENT_VALUE_BYTES) {
|
|
2946
|
+
value = truncateUtf8(serialized, SNAPSHOT_ELEMENT_VALUE_BYTES);
|
|
2947
|
+
}
|
|
2948
|
+
}
|
|
2949
|
+
return {
|
|
2950
|
+
...rest,
|
|
2951
|
+
...href === undefined ? {} : Buffer.byteLength(href) > SNAPSHOT_URL_BYTES ? { href_omitted: true } : { href },
|
|
2952
|
+
role: truncateUtf8(element.role, 128),
|
|
2953
|
+
...element.name === undefined ? {} : { name: truncateUtf8(element.name, SNAPSHOT_ELEMENT_NAME_BYTES) },
|
|
2954
|
+
...value === undefined ? {} : { value }
|
|
2955
|
+
};
|
|
2956
|
+
}
|
|
2957
|
+
function boundTabs(pages, query, offset, ownedOnly = false) {
|
|
2958
|
+
const prefixLength = getDisplayPrefixLength(pages.map((page) => page.targetId));
|
|
2959
|
+
let filtered = ownedOnly ? pages.filter((page) => page.owned === true) : pages;
|
|
2960
|
+
if (query) {
|
|
2961
|
+
const normalized = query.toLowerCase();
|
|
2962
|
+
filtered = filtered.filter((page) => `${page.title}
|
|
2963
|
+
${page.url}`.toLowerCase().includes(normalized));
|
|
2964
|
+
}
|
|
2965
|
+
if (offset > filtered.length) {
|
|
2966
|
+
throw new Error(`offset ${offset} exceeds tab count ${filtered.length}`);
|
|
2967
|
+
}
|
|
2968
|
+
const tabs = [];
|
|
2969
|
+
for (const page of filtered.slice(offset)) {
|
|
2970
|
+
const compact = {
|
|
2971
|
+
ref_id: page.targetId.slice(0, prefixLength),
|
|
2972
|
+
title: page.title.slice(0, 500),
|
|
2973
|
+
url: page.url.slice(0, 8000),
|
|
2974
|
+
owned: page.owned === true
|
|
2975
|
+
};
|
|
2976
|
+
if (byteLength({ tabs: [...tabs, compact] }) > OUTPUT_BUDGET_BYTES) {
|
|
2977
|
+
break;
|
|
2978
|
+
}
|
|
2979
|
+
tabs.push(compact);
|
|
2980
|
+
}
|
|
2981
|
+
const remaining = filtered.length - offset - tabs.length;
|
|
2982
|
+
return {
|
|
2983
|
+
offset,
|
|
2984
|
+
tabs,
|
|
2985
|
+
...remaining > 0 ? {
|
|
2986
|
+
truncated: true,
|
|
2987
|
+
omitted_tabs: remaining,
|
|
2988
|
+
next_offset: offset + tabs.length
|
|
2989
|
+
} : {}
|
|
2990
|
+
};
|
|
2991
|
+
}
|
|
2992
|
+
function boundSnapshot(page) {
|
|
2993
|
+
const base = {
|
|
2994
|
+
ref_id: page.ref_id === undefined ? undefined : truncateUtf8(page.ref_id, 512),
|
|
2995
|
+
title: truncateUtf8(page.title, SNAPSHOT_TITLE_BYTES),
|
|
2996
|
+
url: truncateUtf8(page.url, SNAPSHOT_URL_BYTES),
|
|
2997
|
+
lineno: page.lineno,
|
|
2998
|
+
...page.pattern ? { pattern: truncateUtf8(page.pattern, SNAPSHOT_PATTERN_BYTES) } : {}
|
|
2999
|
+
};
|
|
3000
|
+
const elements = new Map(page.elements.map((element) => [element.id, boundedElement(element)]));
|
|
3001
|
+
const content = [];
|
|
3002
|
+
const includedElements = [];
|
|
3003
|
+
const includedIds = new Set;
|
|
3004
|
+
for (const line of page.content) {
|
|
3005
|
+
const nextContent = [...content, line];
|
|
3006
|
+
const nextElements = [...includedElements];
|
|
3007
|
+
if (line.element_id !== undefined && !includedIds.has(line.element_id) && elements.has(line.element_id)) {
|
|
3008
|
+
const element = elements.get(line.element_id);
|
|
3009
|
+
if (element)
|
|
3010
|
+
nextElements.push(element);
|
|
3011
|
+
}
|
|
3012
|
+
if (byteLength({
|
|
3013
|
+
...base,
|
|
3014
|
+
content: nextContent,
|
|
3015
|
+
elements: nextElements
|
|
3016
|
+
}) > OUTPUT_BUDGET_BYTES) {
|
|
3017
|
+
break;
|
|
3018
|
+
}
|
|
3019
|
+
content.push(line);
|
|
3020
|
+
if (line.element_id !== undefined && !includedIds.has(line.element_id) && elements.has(line.element_id)) {
|
|
3021
|
+
includedIds.add(line.element_id);
|
|
3022
|
+
const element = elements.get(line.element_id);
|
|
3023
|
+
if (element)
|
|
3024
|
+
includedElements.push(element);
|
|
3025
|
+
}
|
|
3026
|
+
}
|
|
3027
|
+
const omitted = content.length < page.content.length;
|
|
3028
|
+
return {
|
|
3029
|
+
...base,
|
|
3030
|
+
content,
|
|
3031
|
+
elements: includedElements,
|
|
3032
|
+
...omitted || page.next_lineno ? {
|
|
3033
|
+
truncated: true,
|
|
3034
|
+
next_lineno: omitted ? page.lineno + content.length : page.next_lineno
|
|
3035
|
+
} : {}
|
|
3036
|
+
};
|
|
3037
|
+
}
|
|
3038
|
+
|
|
3039
|
+
// packages/browser/src/browser/launcher.ts
|
|
3040
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
3041
|
+
var BROWSER_START_TIMEOUT_MS = 1e4;
|
|
3042
|
+
var BROWSER_UNIT = "chrome-cdp-browser.service";
|
|
3043
|
+
var PROCESS_OUTPUT_LIMIT = 1 * 1024 * 1024;
|
|
3044
|
+
function abortReason(signal) {
|
|
3045
|
+
return signal.reason instanceof Error ? signal.reason : new Error("Browser launch aborted");
|
|
3046
|
+
}
|
|
3047
|
+
function runProcess(command, args, signal) {
|
|
3048
|
+
if (signal?.aborted)
|
|
3049
|
+
return Promise.reject(abortReason(signal));
|
|
3050
|
+
return new Promise((resolveValue, reject) => {
|
|
3051
|
+
const child = spawn2(command, args, {
|
|
3052
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
3053
|
+
});
|
|
3054
|
+
let stdout = "";
|
|
3055
|
+
let stderr = "";
|
|
3056
|
+
let bytes = 0;
|
|
3057
|
+
let settled = false;
|
|
3058
|
+
let failure;
|
|
3059
|
+
let killTimer;
|
|
3060
|
+
const cleanup = () => {
|
|
3061
|
+
if (killTimer)
|
|
3062
|
+
clearTimeout(killTimer);
|
|
3063
|
+
signal?.removeEventListener("abort", abort);
|
|
3064
|
+
};
|
|
3065
|
+
const finish = (action) => {
|
|
3066
|
+
if (settled)
|
|
3067
|
+
return;
|
|
3068
|
+
settled = true;
|
|
3069
|
+
cleanup();
|
|
3070
|
+
action();
|
|
3071
|
+
};
|
|
3072
|
+
const running = () => child.exitCode === null && child.signalCode === null;
|
|
3073
|
+
const abort = () => {
|
|
3074
|
+
if (running())
|
|
3075
|
+
child.kill("SIGTERM");
|
|
3076
|
+
killTimer = setTimeout(() => {
|
|
3077
|
+
if (running())
|
|
3078
|
+
child.kill("SIGKILL");
|
|
3079
|
+
}, 1000);
|
|
3080
|
+
killTimer.unref?.();
|
|
3081
|
+
};
|
|
3082
|
+
const append = (target, chunk) => {
|
|
3083
|
+
if (failure)
|
|
3084
|
+
return;
|
|
3085
|
+
bytes += chunk.length;
|
|
3086
|
+
if (bytes > PROCESS_OUTPUT_LIMIT) {
|
|
3087
|
+
if (running())
|
|
3088
|
+
child.kill("SIGKILL");
|
|
3089
|
+
failure = new Error("Browser launch output exceeded 1 MiB");
|
|
3090
|
+
return;
|
|
3091
|
+
}
|
|
3092
|
+
if (target === "stdout")
|
|
3093
|
+
stdout += chunk.toString("utf8");
|
|
3094
|
+
else
|
|
3095
|
+
stderr += chunk.toString("utf8");
|
|
3096
|
+
};
|
|
3097
|
+
child.stdout.on("data", (chunk) => append("stdout", chunk));
|
|
3098
|
+
child.stderr.on("data", (chunk) => append("stderr", chunk));
|
|
3099
|
+
child.on("error", (error) => finish(() => reject(error)));
|
|
3100
|
+
child.on("close", (code) => finish(() => {
|
|
3101
|
+
if (failure) {
|
|
3102
|
+
reject(failure);
|
|
3103
|
+
return;
|
|
3104
|
+
}
|
|
3105
|
+
if (signal?.aborted) {
|
|
3106
|
+
reject(abortReason(signal));
|
|
3107
|
+
return;
|
|
3108
|
+
}
|
|
3109
|
+
resolveValue({
|
|
3110
|
+
code: code ?? 1,
|
|
3111
|
+
stdout: stdout.trim(),
|
|
3112
|
+
stderr: stderr.trim()
|
|
3113
|
+
});
|
|
3114
|
+
}));
|
|
3115
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
3116
|
+
});
|
|
3117
|
+
}
|
|
3118
|
+
function endpoint() {
|
|
3119
|
+
return {
|
|
3120
|
+
port: process.env["CDP_PORT"] ?? "9222",
|
|
3121
|
+
host: process.env["CDP_HOST"] ?? "127.0.0.1"
|
|
3122
|
+
};
|
|
3123
|
+
}
|
|
3124
|
+
async function waitForDebugEndpoint(signal, timeout = BROWSER_START_TIMEOUT_MS) {
|
|
3125
|
+
const { port, host } = endpoint();
|
|
3126
|
+
const deadline = Date.now() + timeout;
|
|
3127
|
+
let lastError;
|
|
3128
|
+
while (Date.now() < deadline) {
|
|
3129
|
+
try {
|
|
3130
|
+
await probeDebugPort(port, host, signal);
|
|
3131
|
+
return;
|
|
3132
|
+
} catch (error) {
|
|
3133
|
+
lastError = error;
|
|
3134
|
+
}
|
|
3135
|
+
await sleep(100, signal);
|
|
3136
|
+
}
|
|
3137
|
+
throw new Error(`Browser did not expose CDP at ${host}:${port} within ${timeout}ms${lastError instanceof Error ? ` (${lastError.message})` : ""}`);
|
|
3138
|
+
}
|
|
3139
|
+
async function unitExists(systemctl, signal) {
|
|
3140
|
+
const result = await runProcess(systemctl, ["--user", "show", BROWSER_UNIT, "--property=LoadState", "--value"], signal);
|
|
3141
|
+
return result.code === 0 && result.stdout !== "not-found";
|
|
3142
|
+
}
|
|
3143
|
+
async function waitForBrowserOrUnitRemoval(systemctl, signal) {
|
|
3144
|
+
const { port, host } = endpoint();
|
|
3145
|
+
const deadline = Date.now() + BROWSER_START_TIMEOUT_MS;
|
|
3146
|
+
while (Date.now() < deadline) {
|
|
3147
|
+
try {
|
|
3148
|
+
await probeDebugPort(port, host, signal);
|
|
3149
|
+
return "browser";
|
|
3150
|
+
} catch {}
|
|
3151
|
+
if (!await unitExists(systemctl, signal))
|
|
3152
|
+
return "removed";
|
|
3153
|
+
await sleep(100, signal);
|
|
3154
|
+
}
|
|
3155
|
+
return "timeout";
|
|
3156
|
+
}
|
|
3157
|
+
async function startBrowser(signal) {
|
|
3158
|
+
const { port, host } = endpoint();
|
|
3159
|
+
try {
|
|
3160
|
+
await probeDebugPort(port, host, signal);
|
|
3161
|
+
return `Browser already running with CDP at ${host}:${port}`;
|
|
3162
|
+
} catch {}
|
|
3163
|
+
if (process.platform !== "linux") {
|
|
3164
|
+
throw new Error("Automatic browser launch requires a Linux systemd user session. Start the authenticated browser normally with remote debugging enabled.");
|
|
3165
|
+
}
|
|
3166
|
+
const systemctl = process.env["CDP_SYSTEMCTL"] ?? "/usr/bin/systemctl";
|
|
3167
|
+
const systemdRun = process.env["CDP_SYSTEMD_RUN"] ?? "/usr/bin/systemd-run";
|
|
3168
|
+
const browser = process.env["CDP_BROWSER"] ?? "/usr/bin/chromium";
|
|
3169
|
+
let lastLaunchError = "";
|
|
3170
|
+
for (let attempt = 0;attempt < 3; attempt++) {
|
|
3171
|
+
const state = await waitForBrowserOrUnitRemoval(systemctl, signal);
|
|
3172
|
+
if (state === "browser") {
|
|
3173
|
+
return `Browser already running with CDP at ${host}:${port}`;
|
|
3174
|
+
}
|
|
3175
|
+
if (state === "timeout") {
|
|
3176
|
+
throw new Error(`Browser unit ${BROWSER_UNIT} remained loaded without exposing CDP at ${host}:${port}`);
|
|
3177
|
+
}
|
|
3178
|
+
await runProcess(systemctl, ["--user", "reset-failed", BROWSER_UNIT], signal);
|
|
3179
|
+
const browserArgs = [
|
|
3180
|
+
`--remote-debugging-address=${host}`,
|
|
3181
|
+
`--remote-debugging-port=${port}`
|
|
3182
|
+
];
|
|
3183
|
+
const profile = process.env["CDP_PROFILE_DIRECTORY"];
|
|
3184
|
+
if (profile) {
|
|
3185
|
+
browserArgs.push(`--profile-directory=${profile}`);
|
|
3186
|
+
}
|
|
3187
|
+
browserArgs.push("about:blank");
|
|
3188
|
+
const launched = await runProcess(systemdRun, [
|
|
3189
|
+
"--user",
|
|
3190
|
+
"--unit=chrome-cdp-browser",
|
|
3191
|
+
"--collect",
|
|
3192
|
+
"--property=Type=exec",
|
|
3193
|
+
"--property=Restart=no",
|
|
3194
|
+
browser,
|
|
3195
|
+
...browserArgs
|
|
3196
|
+
], signal);
|
|
3197
|
+
if (launched.code === 0) {
|
|
3198
|
+
await waitForDebugEndpoint(signal);
|
|
3199
|
+
return `Started authenticated browser with CDP at ${host}:${port}`;
|
|
3200
|
+
}
|
|
3201
|
+
lastLaunchError = launched.stderr || launched.stdout || `exit ${launched.code}`;
|
|
3202
|
+
}
|
|
3203
|
+
throw new Error(`Could not launch the browser through the graphical user session: ${lastLaunchError}`);
|
|
3204
|
+
}
|
|
3205
|
+
|
|
3206
|
+
// packages/browser/src/browser/operation-executor.ts
|
|
3207
|
+
class BrowserOperationExecutor {
|
|
3208
|
+
cdp;
|
|
3209
|
+
start;
|
|
3210
|
+
constructor(cdp, start = startBrowser) {
|
|
3211
|
+
this.start = start;
|
|
3212
|
+
this.cdp = cdp;
|
|
3213
|
+
}
|
|
3214
|
+
async execute(operation, signal, artifacts) {
|
|
3215
|
+
switch (operation.action) {
|
|
3216
|
+
case "start":
|
|
3217
|
+
return { result: await this.start(signal) };
|
|
3218
|
+
case "tabs":
|
|
3219
|
+
return boundTabs(await this.cdp.pages(signal), operation.query, operation.offset, operation.owned_only);
|
|
3220
|
+
case "open":
|
|
3221
|
+
if ("url" in operation) {
|
|
3222
|
+
const opened = await this.cdp.open(operation.url, signal);
|
|
3223
|
+
return {
|
|
3224
|
+
ref_id: opened.refId,
|
|
3225
|
+
url: operation.url,
|
|
3226
|
+
owned: true
|
|
3227
|
+
};
|
|
3228
|
+
}
|
|
3229
|
+
return this.cdp.withTab(operation.ref_id, signal, async (tab) => boundSnapshot(await snapshotData(tab.cdp, tab.sessionId, tab.elementRefs, {
|
|
3230
|
+
refId: tab.refId,
|
|
3231
|
+
lineno: operation.lineno,
|
|
3232
|
+
responseLength: operation.response_length,
|
|
3233
|
+
signal
|
|
3234
|
+
})));
|
|
3235
|
+
case "find":
|
|
3236
|
+
return this.cdp.withTab(operation.ref_id, signal, async (tab) => boundSnapshot(await snapshotData(tab.cdp, tab.sessionId, tab.elementRefs, {
|
|
3237
|
+
refId: tab.refId,
|
|
3238
|
+
pattern: operation.pattern,
|
|
3239
|
+
lineno: operation.lineno,
|
|
3240
|
+
responseLength: operation.response_length,
|
|
3241
|
+
signal
|
|
3242
|
+
})));
|
|
3243
|
+
case "show":
|
|
3244
|
+
return { shown: await this.cdp.show(operation.ref_id, signal) };
|
|
3245
|
+
case "close":
|
|
3246
|
+
return { closed: await this.cdp.closeTab(operation.ref_id, signal) };
|
|
3247
|
+
case "read_result":
|
|
3248
|
+
return artifacts.readCachedResult(operation);
|
|
3249
|
+
case "discard_result":
|
|
3250
|
+
return artifacts.discardCachedResult(operation.handle);
|
|
3251
|
+
case "stop":
|
|
3252
|
+
await this.cdp.stop(operation.ref_id);
|
|
3253
|
+
return {
|
|
3254
|
+
stopped: operation.ref_id ?? "all tab daemons"
|
|
3255
|
+
};
|
|
3256
|
+
case "screenshot":
|
|
3257
|
+
return this.screenshot(operation, signal, artifacts);
|
|
3258
|
+
case "evaluate":
|
|
3259
|
+
return this.cdp.withTab(operation.ref_id, signal, async (tab) => artifacts.limitedText({ ref_id: tab.refId }, "value", await evaluateText(tab.cdp, tab.sessionId, operation.expression, signal)));
|
|
3260
|
+
case "html":
|
|
3261
|
+
return this.cdp.withTab(operation.ref_id, signal, async (tab) => artifacts.limitedText({ ref_id: tab.refId }, "html", operation.id === undefined ? await html(tab.cdp, tab.sessionId, operation.selector, signal) : await htmlRef(tab.cdp, tab.sessionId, tab.elementRefs, operation.id, signal)));
|
|
3262
|
+
case "network":
|
|
3263
|
+
return this.cdp.withTab(operation.ref_id, signal, async (tab) => artifacts.limitedText({ ref_id: tab.refId }, "entries", await networkEntries(tab.cdp, tab.sessionId, signal)));
|
|
3264
|
+
case "raw":
|
|
3265
|
+
return this.cdp.withTab(operation.ref_id, signal, async (tab) => artifacts.limitedText({ ref_id: tab.refId }, "result", await rawCommand(tab.cdp, tab.sessionId, operation.method, operation.params, signal)));
|
|
3266
|
+
case "navigate":
|
|
3267
|
+
return this.tabResult(operation.ref_id, signal, (tab) => navigate(tab.cdp, tab.sessionId, operation.url, signal));
|
|
3268
|
+
case "click":
|
|
3269
|
+
return this.tabResult(operation.ref_id, signal, (tab) => {
|
|
3270
|
+
if (operation.id !== undefined) {
|
|
3271
|
+
return clickRef(tab.cdp, tab.sessionId, tab.elementRefs, operation.id, signal);
|
|
3272
|
+
}
|
|
3273
|
+
if (operation.selector) {
|
|
3274
|
+
return clickSelector(tab.cdp, tab.sessionId, operation.selector, signal);
|
|
3275
|
+
}
|
|
3276
|
+
if (operation.x === undefined || operation.y === undefined) {
|
|
3277
|
+
throw new Error("click requires id, selector, or x+y");
|
|
3278
|
+
}
|
|
3279
|
+
return clickCoordinates(tab.cdp, tab.sessionId, operation.x, operation.y, signal);
|
|
3280
|
+
});
|
|
3281
|
+
case "type":
|
|
3282
|
+
return this.tabResult(operation.ref_id, signal, (tab) => operation.id === undefined ? typeAtFocus(tab.cdp, tab.sessionId, operation.text, signal) : typeRef(tab.cdp, tab.sessionId, tab.elementRefs, operation.id, operation.text, signal));
|
|
3283
|
+
case "load_all":
|
|
3284
|
+
return this.tabResult(operation.ref_id, signal, (tab) => loadAll(tab.cdp, tab.sessionId, operation.selector, operation.interval_ms, signal));
|
|
3285
|
+
case "fill":
|
|
3286
|
+
return this.tabResult(operation.ref_id, signal, (tab) => fillElement(tab.cdp, tab.sessionId, tab.elementRefs, operation, operation.value, signal));
|
|
3287
|
+
case "press":
|
|
3288
|
+
return this.tabResult(operation.ref_id, signal, (tab) => pressKey(tab.cdp, tab.sessionId, operation.key, signal));
|
|
3289
|
+
case "wait":
|
|
3290
|
+
return this.tabResult(operation.ref_id, signal, (tab) => waitForCondition(tab.cdp, tab.sessionId, operation, operation.timeout_ms, signal));
|
|
3291
|
+
}
|
|
3292
|
+
}
|
|
3293
|
+
async screenshot(operation, signal, artifacts) {
|
|
3294
|
+
const file = artifacts.screenshotTarget(operation);
|
|
3295
|
+
return this.cdp.withTab(operation.ref_id, signal, async (tab) => {
|
|
3296
|
+
const capture = operation.id !== undefined ? await captureRef(tab.cdp, tab.sessionId, tab.elementRefs, operation.id, file, signal) : operation.selector ? await captureSelector(tab.cdp, tab.sessionId, operation.selector, file, signal) : await captureViewport(tab.cdp, tab.sessionId, file, signal);
|
|
3297
|
+
return {
|
|
3298
|
+
ref_id: tab.refId,
|
|
3299
|
+
...operation.id === undefined ? {} : { id: operation.id },
|
|
3300
|
+
...operation.selector ? { selector: operation.selector } : {},
|
|
3301
|
+
file: capture.file,
|
|
3302
|
+
dpr: capture.dpr,
|
|
3303
|
+
coordinates: "CSS pixels; screenshot pixels / DPR"
|
|
3304
|
+
};
|
|
3305
|
+
}, "foreground");
|
|
3306
|
+
}
|
|
3307
|
+
async tabResult(refId, signal, action) {
|
|
3308
|
+
return this.cdp.withTab(refId, signal, async (tab) => ({
|
|
3309
|
+
ref_id: tab.refId,
|
|
3310
|
+
result: await action(tab) || "ok"
|
|
3311
|
+
}));
|
|
3312
|
+
}
|
|
3313
|
+
}
|
|
3314
|
+
|
|
3315
|
+
// packages/browser/src/browser/remote.ts
|
|
3316
|
+
import { mkdir as mkdir4, mkdtemp, readFile as readFile3, rm as rm4 } from "node:fs/promises";
|
|
3317
|
+
import { join as join4 } from "node:path";
|
|
3318
|
+
|
|
3319
|
+
// packages/browser/src/browser/remote-helper.ts
|
|
3320
|
+
import { readFile as readFile2 } from "node:fs/promises";
|
|
3321
|
+
import { fileURLToPath } from "node:url";
|
|
3322
|
+
|
|
3323
|
+
// packages/browser/src/browser/remote-process.ts
|
|
3324
|
+
import { spawn as spawn3 } from "node:child_process";
|
|
3325
|
+
import { StringDecoder as StringDecoder3 } from "node:string_decoder";
|
|
3326
|
+
var OUTPUT_LIMIT_BYTES = 8 * 1024 * 1024;
|
|
3327
|
+
function abortReason2(signal) {
|
|
3328
|
+
return signal.reason instanceof Error ? signal.reason : new Error("Remote browser operation aborted");
|
|
3329
|
+
}
|
|
3330
|
+
function runProgram(command, args, input, signal) {
|
|
3331
|
+
if (signal?.aborted)
|
|
3332
|
+
return Promise.reject(abortReason2(signal));
|
|
3333
|
+
return new Promise((resolveValue, reject) => {
|
|
3334
|
+
const child = spawn3(command, args, {
|
|
3335
|
+
stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"]
|
|
3336
|
+
});
|
|
3337
|
+
let stdout = "";
|
|
3338
|
+
let stderr = "";
|
|
3339
|
+
const stdoutDecoder = new StringDecoder3("utf8");
|
|
3340
|
+
const stderrDecoder = new StringDecoder3("utf8");
|
|
3341
|
+
let bytes = 0;
|
|
3342
|
+
let settled = false;
|
|
3343
|
+
let failure;
|
|
3344
|
+
let killTimer;
|
|
3345
|
+
const running = () => child.exitCode === null && child.signalCode === null;
|
|
3346
|
+
const cleanup = () => {
|
|
3347
|
+
if (killTimer)
|
|
3348
|
+
clearTimeout(killTimer);
|
|
3349
|
+
signal?.removeEventListener("abort", abort);
|
|
3350
|
+
};
|
|
3351
|
+
const finish = (action) => {
|
|
3352
|
+
if (settled)
|
|
3353
|
+
return;
|
|
3354
|
+
settled = true;
|
|
3355
|
+
cleanup();
|
|
3356
|
+
action();
|
|
3357
|
+
};
|
|
3358
|
+
const abort = () => {
|
|
3359
|
+
if (running())
|
|
3360
|
+
child.kill("SIGTERM");
|
|
3361
|
+
killTimer = setTimeout(() => {
|
|
3362
|
+
if (running())
|
|
3363
|
+
child.kill("SIGKILL");
|
|
3364
|
+
}, 1000);
|
|
3365
|
+
killTimer.unref?.();
|
|
3366
|
+
};
|
|
3367
|
+
const append = (target, chunk) => {
|
|
3368
|
+
if (failure)
|
|
3369
|
+
return;
|
|
3370
|
+
bytes += chunk.length;
|
|
3371
|
+
if (bytes > OUTPUT_LIMIT_BYTES) {
|
|
3372
|
+
if (running())
|
|
3373
|
+
child.kill("SIGKILL");
|
|
3374
|
+
failure = new Error("Remote browser output exceeded 8 MiB");
|
|
3375
|
+
return;
|
|
3376
|
+
}
|
|
3377
|
+
if (target === "stdout")
|
|
3378
|
+
stdout += stdoutDecoder.write(chunk);
|
|
3379
|
+
else
|
|
3380
|
+
stderr += stderrDecoder.write(chunk);
|
|
3381
|
+
};
|
|
3382
|
+
child.stdout?.on("data", (chunk) => append("stdout", chunk));
|
|
3383
|
+
child.stderr?.on("data", (chunk) => append("stderr", chunk));
|
|
3384
|
+
child.on("error", (error) => finish(() => reject(error)));
|
|
3385
|
+
child.on("close", (code) => finish(() => {
|
|
3386
|
+
stdout += stdoutDecoder.end();
|
|
3387
|
+
stderr += stderrDecoder.end();
|
|
3388
|
+
if (failure) {
|
|
3389
|
+
reject(failure);
|
|
3390
|
+
return;
|
|
3391
|
+
}
|
|
3392
|
+
if (signal?.aborted) {
|
|
3393
|
+
reject(abortReason2(signal));
|
|
3394
|
+
return;
|
|
3395
|
+
}
|
|
3396
|
+
resolveValue({
|
|
3397
|
+
code: code ?? 1,
|
|
3398
|
+
stderr: stderr.trim(),
|
|
3399
|
+
stdout: stdout.trim()
|
|
3400
|
+
});
|
|
3401
|
+
}));
|
|
3402
|
+
child.stdin?.on("error", (error) => {
|
|
3403
|
+
failure = error;
|
|
3404
|
+
if (running())
|
|
3405
|
+
child.kill("SIGKILL");
|
|
3406
|
+
});
|
|
3407
|
+
if (input !== undefined)
|
|
3408
|
+
child.stdin?.end(input);
|
|
3409
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
3410
|
+
});
|
|
3411
|
+
}
|
|
3412
|
+
|
|
3413
|
+
// packages/browser/src/browser/remote-helper.ts
|
|
3414
|
+
var DEPLOY_TIMEOUT_MS = 20000;
|
|
3415
|
+
var REMOTE_HELPER = "~/.cache/pi-durable-browser/worker.mjs";
|
|
3416
|
+
var BROWSER_WORKER_MARKER = "// @howaboua/pi-durable-browser managed worker";
|
|
3417
|
+
var deployments = new Set;
|
|
3418
|
+
var helperSourcePromise;
|
|
3419
|
+
var DEPLOY_SOURCE = String.raw`
|
|
3420
|
+
const { randomUUID } = require("node:crypto");
|
|
3421
|
+
const { mkdir, readFile, rename, unlink, writeFile } = require("node:fs/promises");
|
|
3422
|
+
const { homedir } = require("node:os");
|
|
3423
|
+
const { dirname, join } = require("node:path");
|
|
3424
|
+
const targetValue = process.argv[1];
|
|
3425
|
+
const marker = ${JSON.stringify(BROWSER_WORKER_MARKER)};
|
|
3426
|
+
const target = targetValue === "~" ? homedir() : targetValue.startsWith("~/") ? join(homedir(), targetValue.slice(2)) : targetValue;
|
|
3427
|
+
const chunks = [];
|
|
3428
|
+
let size = 0;
|
|
3429
|
+
process.stdin.on("data", chunk => { size += chunk.length; if (size > 4 * 1024 * 1024) { process.stderr.write("worker source is too large\n"); process.exit(1); } chunks.push(chunk); });
|
|
3430
|
+
process.stdin.on("end", () => { void (async () => {
|
|
3431
|
+
const source = Buffer.concat(chunks);
|
|
3432
|
+
if (!source.toString("utf8", 0, 512).includes(marker)) throw new Error("worker source has no pi-durable-browser ownership marker");
|
|
3433
|
+
let existing;
|
|
3434
|
+
try { existing = await readFile(target); } catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
3435
|
+
if (existing) {
|
|
3436
|
+
if (existing.equals(source)) { process.stdout.write(JSON.stringify({ updated: false, path: target }) + "\n"); return; }
|
|
3437
|
+
if (!existing.toString("utf8", 0, 512).includes(marker)) throw new Error(target + " is not owned by pi-durable-browser");
|
|
3438
|
+
}
|
|
3439
|
+
await mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
|
3440
|
+
const temporary = target + "." + process.pid + "." + randomUUID() + ".tmp";
|
|
3441
|
+
try {
|
|
3442
|
+
await writeFile(temporary, source, { mode: 0o600, flag: "wx" });
|
|
3443
|
+
await rename(temporary, target);
|
|
3444
|
+
} catch (error) {
|
|
3445
|
+
await unlink(temporary).catch(() => undefined);
|
|
3446
|
+
throw error;
|
|
3447
|
+
}
|
|
3448
|
+
process.stdout.write(JSON.stringify({ updated: true, path: target }) + "\n");
|
|
3449
|
+
})().catch(error => { process.stderr.write(error.message + "\n"); process.exit(1); }); });
|
|
3450
|
+
`;
|
|
3451
|
+
function remoteNodeCommand(command) {
|
|
3452
|
+
return `${command.nodePath} --preserve-symlinks-main "$HOME"/.cache/pi-durable-browser/worker.mjs`;
|
|
3453
|
+
}
|
|
3454
|
+
function shellQuote(value) {
|
|
3455
|
+
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
3456
|
+
}
|
|
3457
|
+
async function readHelperSource() {
|
|
3458
|
+
const candidates = [
|
|
3459
|
+
fileURLToPath(new URL("./remote-worker.js", import.meta.url)),
|
|
3460
|
+
fileURLToPath(new URL("../../dist/remote-worker.js", import.meta.url))
|
|
3461
|
+
];
|
|
3462
|
+
let lastError;
|
|
3463
|
+
for (const path of candidates) {
|
|
3464
|
+
try {
|
|
3465
|
+
return await readFile2(path, "utf8");
|
|
3466
|
+
} catch (error) {
|
|
3467
|
+
lastError = error;
|
|
3468
|
+
}
|
|
3469
|
+
}
|
|
3470
|
+
throw new Error(`Could not read bundled browser worker: ${lastError instanceof Error ? lastError.message : String(lastError)}`);
|
|
3471
|
+
}
|
|
3472
|
+
async function deployRemoteHelper(host, command, signal) {
|
|
3473
|
+
helperSourcePromise ??= readHelperSource();
|
|
3474
|
+
let source;
|
|
3475
|
+
try {
|
|
3476
|
+
source = await helperSourcePromise;
|
|
3477
|
+
} catch (error) {
|
|
3478
|
+
helperSourcePromise = undefined;
|
|
3479
|
+
throw error;
|
|
3480
|
+
}
|
|
3481
|
+
const deployment = await runProgram("ssh", [
|
|
3482
|
+
host,
|
|
3483
|
+
`${command.nodePath} -e ${shellQuote(DEPLOY_SOURCE)} ${shellQuote(REMOTE_HELPER)}`
|
|
3484
|
+
], source, signal ? AbortSignal.any([signal, AbortSignal.timeout(DEPLOY_TIMEOUT_MS)]) : AbortSignal.timeout(DEPLOY_TIMEOUT_MS));
|
|
3485
|
+
if (deployment.code !== 0) {
|
|
3486
|
+
throw new Error(deployment.stderr || deployment.stdout || "could not deploy remote browser worker");
|
|
3487
|
+
}
|
|
3488
|
+
}
|
|
3489
|
+
async function ensureRemoteHelper(host, command, signal) {
|
|
3490
|
+
const key = `${host}\x00${command.nodePath}`;
|
|
3491
|
+
if (deployments.has(key))
|
|
3492
|
+
return;
|
|
3493
|
+
await deployRemoteHelper(host, command, signal);
|
|
3494
|
+
deployments.add(key);
|
|
3495
|
+
}
|
|
3496
|
+
|
|
3497
|
+
// packages/browser/src/browser/remote.ts
|
|
3498
|
+
var SAFE_REMOTE_FILE = /^\/[A-Za-z0-9_./-]+$/;
|
|
3499
|
+
function isRecord(value) {
|
|
3500
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
3501
|
+
}
|
|
3502
|
+
async function copyRemoteArtifact(host, remoteFile, signal, artifacts, stateDirectory) {
|
|
3503
|
+
if (!SAFE_REMOTE_FILE.test(remoteFile)) {
|
|
3504
|
+
throw new Error(`remote browser returned an unsafe artifact path: ${remoteFile}`);
|
|
3505
|
+
}
|
|
3506
|
+
await mkdir4(stateDirectory, { recursive: true, mode: 448 });
|
|
3507
|
+
const staging = await mkdtemp(join4(stateDirectory, "scp-"));
|
|
3508
|
+
const localFile = join4(staging, "screenshot.png");
|
|
3509
|
+
try {
|
|
3510
|
+
const copied = await runProgram("scp", ["-q", `${host}:${remoteFile}`, localFile], undefined, signal);
|
|
3511
|
+
if (copied.code !== 0) {
|
|
3512
|
+
throw new Error(copied.stderr || copied.stdout || "could not copy remote screenshot");
|
|
3513
|
+
}
|
|
3514
|
+
const removed = await runProgram("ssh", [host, `/usr/bin/rm -- ${remoteFile}`], undefined, signal);
|
|
3515
|
+
if (removed.code !== 0) {
|
|
3516
|
+
throw new Error(removed.stderr || removed.stdout || "copied screenshot but could not remove remote artifact");
|
|
3517
|
+
}
|
|
3518
|
+
const target = artifacts.screenshotTarget({ ref_id: host });
|
|
3519
|
+
await target.write(await readFile3(localFile));
|
|
3520
|
+
return target.file;
|
|
3521
|
+
} finally {
|
|
3522
|
+
await rm4(staging, { recursive: true, force: true });
|
|
3523
|
+
}
|
|
3524
|
+
}
|
|
3525
|
+
async function localizeScreenshots(host, operations, result, signal, artifacts, stateDirectory) {
|
|
3526
|
+
for (const [index, operation] of operations.entries()) {
|
|
3527
|
+
if (operation.action !== "screenshot")
|
|
3528
|
+
continue;
|
|
3529
|
+
const item = operations.length === 1 ? result : Array.isArray(result["results"]) ? result["results"][index] : undefined;
|
|
3530
|
+
if (!isRecord(item) || typeof item["file"] !== "string") {
|
|
3531
|
+
throw new Error(`remote screenshot result ${index} has no file path`);
|
|
3532
|
+
}
|
|
3533
|
+
item["file"] = await copyRemoteArtifact(host, item["file"], signal, artifacts, stateDirectory);
|
|
3534
|
+
}
|
|
3535
|
+
}
|
|
3536
|
+
async function executeRemoteBrowser(route, operations, ownerId, signal, artifacts, stateDirectory) {
|
|
3537
|
+
if (!route.remote) {
|
|
3538
|
+
throw new Error(`Browser host ${route.name} has no remote command`);
|
|
3539
|
+
}
|
|
3540
|
+
await ensureRemoteHelper(route.name, route.remote, signal);
|
|
3541
|
+
const executed = await runProgram("ssh", [route.name, remoteNodeCommand(route.remote)], JSON.stringify({ owner_id: ownerId, operations }), signal);
|
|
3542
|
+
if (executed.code !== 0) {
|
|
3543
|
+
throw new Error(executed.stderr || executed.stdout || `remote browser exited with code ${executed.code}`);
|
|
3544
|
+
}
|
|
3545
|
+
let value;
|
|
3546
|
+
try {
|
|
3547
|
+
value = JSON.parse(executed.stdout);
|
|
3548
|
+
} catch (error) {
|
|
3549
|
+
throw new Error(`remote browser returned invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
3550
|
+
}
|
|
3551
|
+
if (!isRecord(value)) {
|
|
3552
|
+
throw new Error("remote browser result is not an object");
|
|
3553
|
+
}
|
|
3554
|
+
await localizeScreenshots(route.name, operations, value, signal, artifacts, stateDirectory);
|
|
3555
|
+
return value;
|
|
3556
|
+
}
|
|
3557
|
+
|
|
3558
|
+
// packages/browser/src/browser/runtime.ts
|
|
3559
|
+
var LOCAL_SESSION_IDLE_MS = 20 * 60 * 1000;
|
|
3560
|
+
|
|
3561
|
+
class BrowserRuntime {
|
|
3562
|
+
hosts;
|
|
3563
|
+
defaultOwnerId = randomUUID();
|
|
3564
|
+
lifetime = new AbortController;
|
|
3565
|
+
closing;
|
|
3566
|
+
localSessions = new Map;
|
|
3567
|
+
routes;
|
|
3568
|
+
active = new Set;
|
|
3569
|
+
config;
|
|
3570
|
+
constructor(config) {
|
|
3571
|
+
this.config = config;
|
|
3572
|
+
if (!isAbsolute2(config.stateDirectory))
|
|
3573
|
+
throw new Error("Native browser stateDirectory must be absolute");
|
|
3574
|
+
this.routes = config.routes ?? new BrowserRoutes;
|
|
3575
|
+
this.hosts = this.routes.names;
|
|
3576
|
+
}
|
|
3577
|
+
execute(request, options = {}) {
|
|
3578
|
+
const pending = this.run(request, options);
|
|
3579
|
+
this.active.add(pending);
|
|
3580
|
+
pending.then(() => this.active.delete(pending), () => this.active.delete(pending));
|
|
3581
|
+
return pending;
|
|
3582
|
+
}
|
|
3583
|
+
async run(request, options = {}) {
|
|
3584
|
+
options = {
|
|
3585
|
+
...options,
|
|
3586
|
+
signal: options.signal ? AbortSignal.any([options.signal, this.lifetime.signal]) : this.lifetime.signal
|
|
3587
|
+
};
|
|
3588
|
+
options.signal?.throwIfAborted();
|
|
3589
|
+
await waitForTurn(this.pruneLocalSessions(), options.signal);
|
|
3590
|
+
const artifacts = new BrowserArtifacts(options.artifacts ?? this.config.artifacts);
|
|
3591
|
+
await artifacts.prune();
|
|
3592
|
+
options.signal?.throwIfAborted();
|
|
3593
|
+
if ("help" in request)
|
|
3594
|
+
return browserHelp(this.hosts);
|
|
3595
|
+
const ownerId = options.ownerId ?? this.defaultOwnerId;
|
|
3596
|
+
if (request.host) {
|
|
3597
|
+
const route = this.routes.resolve(request.host);
|
|
3598
|
+
if (!route.local) {
|
|
3599
|
+
const first = request.operations[0];
|
|
3600
|
+
if (first) {
|
|
3601
|
+
await options.onOperation?.(first, 0, request.operations.length);
|
|
3602
|
+
}
|
|
3603
|
+
const result = await executeRemoteBrowser(route, request.operations, ownerId, options.signal, artifacts, this.config.stateDirectory);
|
|
3604
|
+
return { host: request.host, ...result };
|
|
3605
|
+
}
|
|
3606
|
+
}
|
|
3607
|
+
const result = await this.executeLocal(request.operations, ownerId, options, artifacts);
|
|
3608
|
+
return request.host ? { host: request.host, ...result } : result;
|
|
3609
|
+
}
|
|
3610
|
+
close() {
|
|
3611
|
+
if (this.closing)
|
|
3612
|
+
return this.closing;
|
|
3613
|
+
this.lifetime.abort(new Error("Browser runtime closed"));
|
|
3614
|
+
const closing = [...this.localSessions.values()].map((session) => session.cdp.close());
|
|
3615
|
+
this.localSessions.clear();
|
|
3616
|
+
this.closing = Promise.all([
|
|
3617
|
+
...closing,
|
|
3618
|
+
...[...this.active].map((pending) => pending.then(() => {
|
|
3619
|
+
return;
|
|
3620
|
+
}, () => {
|
|
3621
|
+
return;
|
|
3622
|
+
}))
|
|
3623
|
+
]).then(() => {
|
|
3624
|
+
return;
|
|
3625
|
+
});
|
|
3626
|
+
return this.closing;
|
|
3627
|
+
}
|
|
3628
|
+
async executeLocal(operations, ownerId, options, artifacts) {
|
|
3629
|
+
let pendingClose = this.localSessions.get(ownerId)?.closing;
|
|
3630
|
+
while (pendingClose) {
|
|
3631
|
+
await waitForTurn(pendingClose, options.signal);
|
|
3632
|
+
pendingClose = this.localSessions.get(ownerId)?.closing;
|
|
3633
|
+
}
|
|
3634
|
+
options.signal?.throwIfAborted();
|
|
3635
|
+
const session = this.localSession(ownerId);
|
|
3636
|
+
session.activeCalls++;
|
|
3637
|
+
try {
|
|
3638
|
+
const results = [];
|
|
3639
|
+
for (const [index, operation] of operations.entries()) {
|
|
3640
|
+
try {
|
|
3641
|
+
options.signal?.throwIfAborted();
|
|
3642
|
+
await options.onOperation?.(operation, index, operations.length);
|
|
3643
|
+
results.push(await session.operations.execute(operation, options.signal, artifacts));
|
|
3644
|
+
} catch (error) {
|
|
3645
|
+
throw new Error(`batch failed at ${operation.action}[${index}] after ${results.length} completed operation(s): ${error instanceof Error ? error.message : String(error)}`);
|
|
3646
|
+
}
|
|
3647
|
+
}
|
|
3648
|
+
const first = results[0];
|
|
3649
|
+
if (results.length === 1 && first)
|
|
3650
|
+
return first;
|
|
3651
|
+
return {
|
|
3652
|
+
results: results.map((result, index) => ({
|
|
3653
|
+
operation: operations[index]?.action ?? "unknown",
|
|
3654
|
+
index,
|
|
3655
|
+
...result
|
|
3656
|
+
}))
|
|
3657
|
+
};
|
|
3658
|
+
} finally {
|
|
3659
|
+
session.activeCalls--;
|
|
3660
|
+
session.lastUsed = Date.now();
|
|
3661
|
+
}
|
|
3662
|
+
}
|
|
3663
|
+
localSession(ownerId) {
|
|
3664
|
+
let session = this.localSessions.get(ownerId);
|
|
3665
|
+
if (session)
|
|
3666
|
+
return session;
|
|
3667
|
+
const cdp = new BrowserCdpSession(ownerId, join5(this.config.stateDirectory, "tabs"), this.config.discover);
|
|
3668
|
+
session = {
|
|
3669
|
+
activeCalls: 0,
|
|
3670
|
+
cdp,
|
|
3671
|
+
lastUsed: Date.now(),
|
|
3672
|
+
operations: new BrowserOperationExecutor(cdp, this.config.start)
|
|
3673
|
+
};
|
|
3674
|
+
this.localSessions.set(ownerId, session);
|
|
3675
|
+
return session;
|
|
3676
|
+
}
|
|
3677
|
+
async pruneLocalSessions(now = Date.now()) {
|
|
3678
|
+
const closing = [];
|
|
3679
|
+
for (const [ownerId, session] of this.localSessions) {
|
|
3680
|
+
if (!session.closing && session.activeCalls === 0 && now - session.lastUsed >= LOCAL_SESSION_IDLE_MS) {
|
|
3681
|
+
session.closing = session.cdp.close().finally(() => {
|
|
3682
|
+
if (this.localSessions.get(ownerId) === session) {
|
|
3683
|
+
this.localSessions.delete(ownerId);
|
|
3684
|
+
}
|
|
3685
|
+
});
|
|
3686
|
+
}
|
|
3687
|
+
if (session.closing)
|
|
3688
|
+
closing.push(session.closing);
|
|
3689
|
+
}
|
|
3690
|
+
await Promise.all(closing);
|
|
3691
|
+
}
|
|
3692
|
+
}
|
|
3693
|
+
|
|
3694
|
+
// packages/browser/src/browser/worker-server.ts
|
|
3695
|
+
var IDLE_TIMEOUT_MS = 20 * 60 * 1000;
|
|
3696
|
+
var IS_WINDOWS4 = process.platform === "win32";
|
|
3697
|
+
function parseWorkerRequest(input) {
|
|
3698
|
+
let value;
|
|
3699
|
+
try {
|
|
3700
|
+
value = JSON.parse(input);
|
|
3701
|
+
} catch (error) {
|
|
3702
|
+
throw new Error(`worker input must be valid JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
3703
|
+
}
|
|
3704
|
+
if (!isRecordValue(value))
|
|
3705
|
+
throw new Error("worker input must be an object");
|
|
3706
|
+
const unknown = Object.keys(value).filter((key) => key !== "owner_id" && key !== "operations");
|
|
3707
|
+
if (unknown.length > 0) {
|
|
3708
|
+
throw new Error(`unknown worker field(s): ${unknown.join(", ")}`);
|
|
3709
|
+
}
|
|
3710
|
+
if (typeof value["owner_id"] !== "string" || value["owner_id"].length === 0 || value["owner_id"].length > 256) {
|
|
3711
|
+
throw new Error("worker owner_id must be a non-empty string no longer than 256 characters");
|
|
3712
|
+
}
|
|
3713
|
+
if (!Array.isArray(value["operations"]) || value["operations"].length === 0) {
|
|
3714
|
+
throw new Error("worker operations must be a non-empty array");
|
|
3715
|
+
}
|
|
3716
|
+
const operations = value["operations"].map((operation, index) => {
|
|
3717
|
+
if (!isRecordValue(operation)) {
|
|
3718
|
+
throw new Error(`worker operations[${index}] must be an object`);
|
|
3719
|
+
}
|
|
3720
|
+
const parsed = parseActionRequest(operation);
|
|
3721
|
+
if (parsed.action === "help") {
|
|
3722
|
+
throw new Error("help is not a worker operation");
|
|
3723
|
+
}
|
|
3724
|
+
return parsed;
|
|
3725
|
+
});
|
|
3726
|
+
return { operations, ownerId: value["owner_id"] };
|
|
3727
|
+
}
|
|
3728
|
+
async function handleConnection(socket, runtime) {
|
|
3729
|
+
const controller = new AbortController;
|
|
3730
|
+
const abort = () => controller.abort(new Error("Browser worker requester disconnected"));
|
|
3731
|
+
socket.once("close", abort);
|
|
3732
|
+
socket.once("error", abort);
|
|
3733
|
+
let response;
|
|
3734
|
+
try {
|
|
3735
|
+
const request = parseWorkerRequest(await readLine(socket));
|
|
3736
|
+
response = {
|
|
3737
|
+
ok: true,
|
|
3738
|
+
result: await runtime.execute({ operations: request.operations }, { ownerId: request.ownerId, signal: controller.signal })
|
|
3739
|
+
};
|
|
3740
|
+
} catch (error) {
|
|
3741
|
+
response = {
|
|
3742
|
+
ok: false,
|
|
3743
|
+
error: error instanceof Error ? error.message : String(error)
|
|
3744
|
+
};
|
|
3745
|
+
}
|
|
3746
|
+
socket.off("close", abort);
|
|
3747
|
+
socket.off("error", abort);
|
|
3748
|
+
if (!socket.destroyed)
|
|
3749
|
+
socket.end(`${JSON.stringify(response)}
|
|
3750
|
+
`);
|
|
3751
|
+
}
|
|
3752
|
+
async function serveBrowserWorker(workerId) {
|
|
3753
|
+
const path = workerSocketPath(workerId);
|
|
3754
|
+
await ensureWorkerSocketDirectory(workerId);
|
|
3755
|
+
const directory = dirname2(path);
|
|
3756
|
+
const runtime = new BrowserRuntime({
|
|
3757
|
+
routes: new BrowserRoutes,
|
|
3758
|
+
stateDirectory: directory,
|
|
3759
|
+
artifacts: nodeArtifactStore(directory)
|
|
3760
|
+
});
|
|
3761
|
+
let ownsSocket = false;
|
|
3762
|
+
let closed = false;
|
|
3763
|
+
const sockets = new Set;
|
|
3764
|
+
const server = createServer((socket) => {
|
|
3765
|
+
sockets.add(socket);
|
|
3766
|
+
socket.once("close", () => sockets.delete(socket));
|
|
3767
|
+
resetIdle();
|
|
3768
|
+
handleConnection(socket, runtime).finally(resetIdle);
|
|
3769
|
+
});
|
|
3770
|
+
let idleTimer;
|
|
3771
|
+
const close = () => {
|
|
3772
|
+
if (closed)
|
|
3773
|
+
return;
|
|
3774
|
+
closed = true;
|
|
3775
|
+
runtime.close();
|
|
3776
|
+
for (const socket of sockets)
|
|
3777
|
+
socket.destroy();
|
|
3778
|
+
server.close();
|
|
3779
|
+
};
|
|
3780
|
+
const resetIdle = () => {
|
|
3781
|
+
if (closed)
|
|
3782
|
+
return;
|
|
3783
|
+
if (idleTimer)
|
|
3784
|
+
clearTimeout(idleTimer);
|
|
3785
|
+
idleTimer = setTimeout(close, IDLE_TIMEOUT_MS);
|
|
3786
|
+
idleTimer.unref?.();
|
|
3787
|
+
};
|
|
3788
|
+
process.once("SIGINT", close);
|
|
3789
|
+
process.once("SIGTERM", close);
|
|
3790
|
+
try {
|
|
3791
|
+
await new Promise((resolveValue, reject) => {
|
|
3792
|
+
server.once("error", reject);
|
|
3793
|
+
server.listen(path, () => {
|
|
3794
|
+
ownsSocket = true;
|
|
3795
|
+
server.off("error", reject);
|
|
3796
|
+
resetIdle();
|
|
3797
|
+
});
|
|
3798
|
+
server.once("close", resolveValue);
|
|
3799
|
+
});
|
|
3800
|
+
} finally {
|
|
3801
|
+
if (idleTimer)
|
|
3802
|
+
clearTimeout(idleTimer);
|
|
3803
|
+
process.removeListener("SIGINT", close);
|
|
3804
|
+
process.removeListener("SIGTERM", close);
|
|
3805
|
+
await runtime.close();
|
|
3806
|
+
if (!IS_WINDOWS4 && ownsSocket)
|
|
3807
|
+
await rm5(path, { force: true });
|
|
3808
|
+
}
|
|
3809
|
+
}
|
|
3810
|
+
|
|
3811
|
+
// packages/browser/src/remote-worker.ts
|
|
3812
|
+
async function readStdin() {
|
|
3813
|
+
let input = "";
|
|
3814
|
+
let bytes = 0;
|
|
3815
|
+
process.stdin.setEncoding("utf8");
|
|
3816
|
+
for await (const chunk of process.stdin) {
|
|
3817
|
+
bytes += Buffer.byteLength(chunk);
|
|
3818
|
+
if (bytes > 8 * 1024 * 1024)
|
|
3819
|
+
throw new Error("Browser worker input exceeded 8 MiB");
|
|
3820
|
+
input += chunk;
|
|
3821
|
+
}
|
|
3822
|
+
return input;
|
|
3823
|
+
}
|
|
3824
|
+
async function main() {
|
|
3825
|
+
const entryPath = fileURLToPath2(import.meta.url);
|
|
3826
|
+
const workerId = createHash2("sha256").update(readFileSync2(entryPath)).digest("hex").slice(0, 12);
|
|
3827
|
+
if (process.argv.includes("--daemon")) {
|
|
3828
|
+
await serveBrowserWorker(workerId);
|
|
3829
|
+
return;
|
|
3830
|
+
}
|
|
3831
|
+
const controller = new AbortController;
|
|
3832
|
+
const abort = () => controller.abort(new Error("Remote browser interrupted"));
|
|
3833
|
+
process.once("SIGINT", abort);
|
|
3834
|
+
process.once("SIGTERM", abort);
|
|
3835
|
+
try {
|
|
3836
|
+
const result = await requestBrowserWorker(await readStdin(), entryPath, workerId, controller.signal);
|
|
3837
|
+
process.stdout.write(`${JSON.stringify(result)}
|
|
3838
|
+
`);
|
|
3839
|
+
} finally {
|
|
3840
|
+
process.removeListener("SIGINT", abort);
|
|
3841
|
+
process.removeListener("SIGTERM", abort);
|
|
3842
|
+
}
|
|
3843
|
+
}
|
|
3844
|
+
if (process.argv[1] && realpathSync(fileURLToPath2(import.meta.url)) === realpathSync(resolve2(process.argv[1]))) {
|
|
3845
|
+
main().catch((error) => {
|
|
3846
|
+
process.stderr.write(`pi-durable-browser-worker: ${error instanceof Error ? error.message : String(error)}
|
|
3847
|
+
`);
|
|
3848
|
+
process.exitCode = 1;
|
|
3849
|
+
});
|
|
3850
|
+
}
|