@howaboua/pi-browser 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/LICENSE +22 -0
- package/README.md +47 -0
- package/biome.json +31 -0
- package/changelog.ts +337 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +82 -0
- package/dist/remote-worker.d.ts +2 -0
- package/dist/remote-worker.js +3005 -0
- package/dist/src/browser/artifacts.d.ts +13 -0
- package/dist/src/browser/artifacts.js +133 -0
- package/dist/src/browser/bounds.d.ts +4 -0
- package/dist/src/browser/bounds.js +129 -0
- package/dist/src/browser/config.d.ts +11 -0
- package/dist/src/browser/config.js +106 -0
- package/dist/src/browser/help.d.ts +1 -0
- package/dist/src/browser/help.js +27 -0
- package/dist/src/browser/launcher.d.ts +8 -0
- package/dist/src/browser/launcher.js +169 -0
- package/dist/src/browser/operation-executor.d.ts +9 -0
- package/dist/src/browser/operation-executor.js +112 -0
- package/dist/src/browser/operation.d.ts +92 -0
- package/dist/src/browser/operation.js +20 -0
- package/dist/src/browser/parse-operation.d.ts +6 -0
- package/dist/src/browser/parse-operation.js +248 -0
- package/dist/src/browser/remote-helper.d.ts +3 -0
- package/dist/src/browser/remote-helper.js +114 -0
- package/dist/src/browser/remote-process.d.ts +7 -0
- package/dist/src/browser/remote-process.js +78 -0
- package/dist/src/browser/remote.d.ts +4 -0
- package/dist/src/browser/remote.js +73 -0
- package/dist/src/browser/request.d.ts +8 -0
- package/dist/src/browser/request.js +80 -0
- package/dist/src/browser/routes.d.ts +16 -0
- package/dist/src/browser/routes.js +40 -0
- package/dist/src/browser/runtime.d.ts +17 -0
- package/dist/src/browser/runtime.js +61 -0
- package/dist/src/browser/settings.d.ts +2 -0
- package/dist/src/browser/settings.js +164 -0
- package/dist/src/browser/worker-server.d.ts +2 -0
- package/dist/src/browser/worker-server.js +241 -0
- package/dist/src/browser-parameters.d.ts +42 -0
- package/dist/src/browser-parameters.js +113 -0
- package/dist/src/browser-tool.d.ts +48 -0
- package/dist/src/browser-tool.js +71 -0
- package/dist/src/cdp/actions/click.d.ts +4 -0
- package/dist/src/cdp/actions/click.js +56 -0
- package/dist/src/cdp/actions/element.d.ts +22 -0
- package/dist/src/cdp/actions/element.js +126 -0
- package/dist/src/cdp/actions/page.d.ts +7 -0
- package/dist/src/cdp/actions/page.js +127 -0
- package/dist/src/cdp/actions/screenshot.d.ts +10 -0
- package/dist/src/cdp/actions/screenshot.js +96 -0
- package/dist/src/cdp/actions/selector.d.ts +2 -0
- package/dist/src/cdp/actions/selector.js +41 -0
- package/dist/src/cdp/actions/type.d.ts +3 -0
- package/dist/src/cdp/actions/type.js +138 -0
- package/dist/src/cdp/client.d.ts +20 -0
- package/dist/src/cdp/client.js +248 -0
- package/dist/src/cdp/discovery.d.ts +7 -0
- package/dist/src/cdp/discovery.js +153 -0
- package/dist/src/cdp/evaluate.d.ts +3 -0
- package/dist/src/cdp/evaluate.js +31 -0
- package/dist/src/cdp/pages.d.ts +3 -0
- package/dist/src/cdp/pages.js +40 -0
- package/dist/src/cdp/serial.d.ts +1 -0
- package/dist/src/cdp/serial.js +18 -0
- package/dist/src/cdp/session.d.ts +25 -0
- package/dist/src/cdp/session.js +246 -0
- package/dist/src/cdp/snapshot-contract.d.ts +32 -0
- package/dist/src/cdp/snapshot-contract.js +23 -0
- package/dist/src/cdp/snapshot.d.ts +3 -0
- package/dist/src/cdp/snapshot.js +205 -0
- package/dist/src/cdp/types.d.ts +20 -0
- package/dist/src/cdp/types.js +14 -0
- package/dist/src/cdp/url.d.ts +1 -0
- package/dist/src/cdp/url.js +12 -0
- package/index.ts +115 -0
- package/package.json +93 -0
- package/remote-worker.ts +58 -0
- package/src/browser/artifacts.ts +178 -0
- package/src/browser/bounds.ts +159 -0
- package/src/browser/config.ts +162 -0
- package/src/browser/help.ts +30 -0
- package/src/browser/launcher.ts +208 -0
- package/src/browser/operation-executor.ts +251 -0
- package/src/browser/operation.ts +105 -0
- package/src/browser/parse-operation.ts +272 -0
- package/src/browser/remote-helper.ts +137 -0
- package/src/browser/remote-process.ts +85 -0
- package/src/browser/remote.ts +120 -0
- package/src/browser/request.ts +95 -0
- package/src/browser/routes.ts +69 -0
- package/src/browser/runtime.ts +84 -0
- package/src/browser/settings.ts +219 -0
- package/src/browser/worker-server.ts +274 -0
- package/src/browser-parameters.ts +118 -0
- package/src/browser-tool.ts +88 -0
- package/src/cdp/actions/click.ts +126 -0
- package/src/cdp/actions/element.ts +234 -0
- package/src/cdp/actions/page.ts +219 -0
- package/src/cdp/actions/screenshot.ts +176 -0
- package/src/cdp/actions/selector.ts +63 -0
- package/src/cdp/actions/type.ts +224 -0
- package/src/cdp/client.ts +286 -0
- package/src/cdp/discovery.ts +198 -0
- package/src/cdp/evaluate.ts +55 -0
- package/src/cdp/pages.ts +60 -0
- package/src/cdp/serial.ts +23 -0
- package/src/cdp/session.ts +345 -0
- package/src/cdp/snapshot-contract.ts +63 -0
- package/src/cdp/snapshot.ts +273 -0
- package/src/cdp/types.ts +49 -0
- package/src/cdp/url.ts +11 -0
- package/tsconfig.json +7 -0
|
@@ -0,0 +1,3005 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// @howaboua/pi-browser managed worker
|
|
3
|
+
|
|
4
|
+
// remote-worker.ts
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { readFileSync as readFileSync3, realpathSync } from "node:fs";
|
|
7
|
+
import { resolve as resolve2 } from "node:path";
|
|
8
|
+
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
9
|
+
|
|
10
|
+
// src/browser/worker-server.ts
|
|
11
|
+
import { spawn as spawn3 } from "node:child_process";
|
|
12
|
+
import { chmod, lstat, mkdir as mkdir3, rm as rm3 } from "node:fs/promises";
|
|
13
|
+
import { createConnection, createServer } from "node:net";
|
|
14
|
+
import { tmpdir as tmpdir2 } from "node:os";
|
|
15
|
+
import { dirname as dirname2, join as join4 } from "node:path";
|
|
16
|
+
import { StringDecoder as StringDecoder3 } from "node:string_decoder";
|
|
17
|
+
|
|
18
|
+
// src/browser/operation.ts
|
|
19
|
+
var BROWSER_ACTIONS = [
|
|
20
|
+
"help",
|
|
21
|
+
"start",
|
|
22
|
+
"tabs",
|
|
23
|
+
"open",
|
|
24
|
+
"find",
|
|
25
|
+
"click",
|
|
26
|
+
"type",
|
|
27
|
+
"screenshot",
|
|
28
|
+
"html",
|
|
29
|
+
"navigate",
|
|
30
|
+
"evaluate",
|
|
31
|
+
"network",
|
|
32
|
+
"load_all",
|
|
33
|
+
"raw",
|
|
34
|
+
"read_result",
|
|
35
|
+
"discard_result",
|
|
36
|
+
"stop"
|
|
37
|
+
];
|
|
38
|
+
var OPERATION_ORDER = BROWSER_ACTIONS.filter((action) => action !== "help");
|
|
39
|
+
|
|
40
|
+
// src/browser/parse-operation.ts
|
|
41
|
+
var fields = (...names) => new Set(["action", ...names]);
|
|
42
|
+
var ACTION_FIELDS = {
|
|
43
|
+
help: fields(),
|
|
44
|
+
start: fields(),
|
|
45
|
+
tabs: fields("query", "offset"),
|
|
46
|
+
open: fields("ref_id", "url", "lineno", "response_length"),
|
|
47
|
+
find: fields("ref_id", "pattern", "lineno", "response_length"),
|
|
48
|
+
click: fields("ref_id", "id", "selector", "x", "y"),
|
|
49
|
+
type: fields("ref_id", "id", "text"),
|
|
50
|
+
screenshot: fields("ref_id", "id", "selector"),
|
|
51
|
+
html: fields("ref_id", "id", "selector"),
|
|
52
|
+
navigate: fields("ref_id", "url"),
|
|
53
|
+
evaluate: fields("ref_id", "expression"),
|
|
54
|
+
network: fields("ref_id"),
|
|
55
|
+
load_all: fields("ref_id", "selector", "interval_ms"),
|
|
56
|
+
raw: fields("ref_id", "method", "params"),
|
|
57
|
+
read_result: fields("handle", "offset"),
|
|
58
|
+
discard_result: fields("handle"),
|
|
59
|
+
stop: fields("ref_id")
|
|
60
|
+
};
|
|
61
|
+
function isRecord(value) {
|
|
62
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
63
|
+
}
|
|
64
|
+
function requiredString(value, field) {
|
|
65
|
+
if (typeof value !== "string" || !value.trim()) {
|
|
66
|
+
throw new Error(`${field} must be a non-empty string`);
|
|
67
|
+
}
|
|
68
|
+
return value.trim();
|
|
69
|
+
}
|
|
70
|
+
function optionalString(value, field) {
|
|
71
|
+
if (value === undefined)
|
|
72
|
+
return;
|
|
73
|
+
return requiredString(value, field);
|
|
74
|
+
}
|
|
75
|
+
function requiredRef(value, action) {
|
|
76
|
+
if (typeof value !== "string" || !value.trim()) {
|
|
77
|
+
throw new Error(`${action} requires a ref_id returned by tabs; call tabs first`);
|
|
78
|
+
}
|
|
79
|
+
return value.trim();
|
|
80
|
+
}
|
|
81
|
+
function offset(value, field = "offset", fallback = 0) {
|
|
82
|
+
if (value === undefined)
|
|
83
|
+
return fallback;
|
|
84
|
+
if (!Number.isInteger(value) || Number(value) < 0) {
|
|
85
|
+
throw new Error(`${field} must be a non-negative integer`);
|
|
86
|
+
}
|
|
87
|
+
return Number(value);
|
|
88
|
+
}
|
|
89
|
+
function line(value) {
|
|
90
|
+
const parsed = offset(value, "lineno", 1);
|
|
91
|
+
if (parsed < 1)
|
|
92
|
+
throw new Error("lineno must be at least 1");
|
|
93
|
+
return parsed;
|
|
94
|
+
}
|
|
95
|
+
function elementId(value) {
|
|
96
|
+
if (value === undefined)
|
|
97
|
+
return;
|
|
98
|
+
if (!Number.isInteger(value) || Number(value) < 1) {
|
|
99
|
+
throw new Error("id must be a positive integer from open/find");
|
|
100
|
+
}
|
|
101
|
+
return Number(value);
|
|
102
|
+
}
|
|
103
|
+
function responseLength(value) {
|
|
104
|
+
if (value === undefined)
|
|
105
|
+
return "medium";
|
|
106
|
+
if (value !== "short" && value !== "medium" && value !== "long") {
|
|
107
|
+
throw new Error("response_length must be one of: short, medium, long");
|
|
108
|
+
}
|
|
109
|
+
return value;
|
|
110
|
+
}
|
|
111
|
+
function resultHandle(value) {
|
|
112
|
+
const handle = requiredString(value, "handle");
|
|
113
|
+
if (!/^[a-f0-9-]{36}$/.test(handle)) {
|
|
114
|
+
throw new Error("handle is invalid");
|
|
115
|
+
}
|
|
116
|
+
return handle;
|
|
117
|
+
}
|
|
118
|
+
function browserAction(value) {
|
|
119
|
+
if (typeof value !== "string" || !BROWSER_ACTIONS.includes(value)) {
|
|
120
|
+
throw new Error(`action must be one of: ${BROWSER_ACTIONS.join(", ")}`);
|
|
121
|
+
}
|
|
122
|
+
return value;
|
|
123
|
+
}
|
|
124
|
+
function parseActionRequest(value) {
|
|
125
|
+
if (!isRecord(value))
|
|
126
|
+
throw new Error("input must be a JSON object");
|
|
127
|
+
const action = browserAction(value["action"]);
|
|
128
|
+
const unknown = Object.keys(value).filter((key) => !ACTION_FIELDS[action].has(key));
|
|
129
|
+
if (unknown.length > 0) {
|
|
130
|
+
throw new Error(`unknown ${action} field(s): ${unknown.join(", ")}`);
|
|
131
|
+
}
|
|
132
|
+
if (action === "help" || action === "start")
|
|
133
|
+
return { action };
|
|
134
|
+
if (action === "tabs") {
|
|
135
|
+
const query = optionalString(value["query"], "query");
|
|
136
|
+
return {
|
|
137
|
+
action,
|
|
138
|
+
...query ? { query } : {},
|
|
139
|
+
offset: offset(value["offset"])
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
if (action === "open") {
|
|
143
|
+
const refId2 = optionalString(value["ref_id"], "ref_id");
|
|
144
|
+
const url = optionalString(value["url"], "url");
|
|
145
|
+
if (Boolean(refId2) === Boolean(url)) {
|
|
146
|
+
throw new Error("open requires exactly one of ref_id or url");
|
|
147
|
+
}
|
|
148
|
+
if (url)
|
|
149
|
+
return { action, url };
|
|
150
|
+
if (!refId2)
|
|
151
|
+
throw new Error("open requires ref_id or url");
|
|
152
|
+
return {
|
|
153
|
+
action,
|
|
154
|
+
ref_id: refId2,
|
|
155
|
+
lineno: line(value["lineno"]),
|
|
156
|
+
response_length: responseLength(value["response_length"])
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
if (action === "find") {
|
|
160
|
+
return {
|
|
161
|
+
action,
|
|
162
|
+
ref_id: requiredRef(value["ref_id"], action),
|
|
163
|
+
pattern: requiredString(value["pattern"], "pattern"),
|
|
164
|
+
lineno: line(value["lineno"]),
|
|
165
|
+
response_length: responseLength(value["response_length"])
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
if (action === "read_result") {
|
|
169
|
+
return {
|
|
170
|
+
action,
|
|
171
|
+
handle: resultHandle(value["handle"]),
|
|
172
|
+
offset: offset(value["offset"])
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
if (action === "discard_result") {
|
|
176
|
+
return { action, handle: resultHandle(value["handle"]) };
|
|
177
|
+
}
|
|
178
|
+
if (action === "stop") {
|
|
179
|
+
const refId2 = optionalString(value["ref_id"], "ref_id");
|
|
180
|
+
return { action, ...refId2 ? { ref_id: refId2 } : {} };
|
|
181
|
+
}
|
|
182
|
+
const refId = requiredRef(value["ref_id"], action);
|
|
183
|
+
if (action === "network")
|
|
184
|
+
return { action, ref_id: refId };
|
|
185
|
+
if (action === "navigate") {
|
|
186
|
+
return {
|
|
187
|
+
action,
|
|
188
|
+
ref_id: refId,
|
|
189
|
+
url: requiredString(value["url"], "url")
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
if (action === "evaluate") {
|
|
193
|
+
return {
|
|
194
|
+
action,
|
|
195
|
+
ref_id: refId,
|
|
196
|
+
expression: requiredString(value["expression"], "expression")
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
if (action === "click") {
|
|
200
|
+
const id = elementId(value["id"]);
|
|
201
|
+
const selector = optionalString(value["selector"], "selector");
|
|
202
|
+
const hasX = value["x"] !== undefined;
|
|
203
|
+
const hasY = value["y"] !== undefined;
|
|
204
|
+
let coordinates;
|
|
205
|
+
if (hasX !== hasY) {
|
|
206
|
+
throw new Error("click coordinates require both x and y");
|
|
207
|
+
}
|
|
208
|
+
if (hasX && (typeof value["x"] !== "number" || !Number.isFinite(value["x"]) || typeof value["y"] !== "number" || !Number.isFinite(value["y"]))) {
|
|
209
|
+
throw new Error("x and y must be finite CSS-pixel numbers");
|
|
210
|
+
}
|
|
211
|
+
if (typeof value["x"] === "number" && typeof value["y"] === "number") {
|
|
212
|
+
coordinates = { x: value["x"], y: value["y"] };
|
|
213
|
+
}
|
|
214
|
+
if (Number(id !== undefined) + Number(Boolean(selector)) + Number(hasX) !== 1) {
|
|
215
|
+
throw new Error("click requires exactly one of id, selector, or x+y");
|
|
216
|
+
}
|
|
217
|
+
if (id !== undefined)
|
|
218
|
+
return { action, ref_id: refId, id };
|
|
219
|
+
if (selector)
|
|
220
|
+
return { action, ref_id: refId, selector };
|
|
221
|
+
if (coordinates) {
|
|
222
|
+
return { action, ref_id: refId, ...coordinates };
|
|
223
|
+
}
|
|
224
|
+
throw new Error("click requires id, selector, or x+y");
|
|
225
|
+
}
|
|
226
|
+
if (action === "type") {
|
|
227
|
+
if (typeof value["text"] !== "string" || value["text"].length === 0) {
|
|
228
|
+
throw new Error("text must be a non-empty string");
|
|
229
|
+
}
|
|
230
|
+
const id = elementId(value["id"]);
|
|
231
|
+
return {
|
|
232
|
+
action,
|
|
233
|
+
ref_id: refId,
|
|
234
|
+
...id === undefined ? {} : { id },
|
|
235
|
+
text: value["text"]
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
if (action === "screenshot" || action === "html") {
|
|
239
|
+
const id = elementId(value["id"]);
|
|
240
|
+
const selector = optionalString(value["selector"], "selector");
|
|
241
|
+
if (id !== undefined && selector) {
|
|
242
|
+
throw new Error(`${action} accepts id or selector, not both`);
|
|
243
|
+
}
|
|
244
|
+
return {
|
|
245
|
+
action,
|
|
246
|
+
ref_id: refId,
|
|
247
|
+
...id === undefined ? {} : { id },
|
|
248
|
+
...selector ? { selector } : {}
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
if (action === "load_all") {
|
|
252
|
+
const interval = value["interval_ms"] ?? 1500;
|
|
253
|
+
if (!Number.isInteger(interval) || Number(interval) < 0 || Number(interval) > 60000) {
|
|
254
|
+
throw new Error("interval_ms must be an integer from 0 to 60000");
|
|
255
|
+
}
|
|
256
|
+
return {
|
|
257
|
+
action,
|
|
258
|
+
ref_id: refId,
|
|
259
|
+
selector: requiredString(value["selector"], "selector"),
|
|
260
|
+
interval_ms: Number(interval)
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
if (action === "raw") {
|
|
264
|
+
const params = value["params"] ?? {};
|
|
265
|
+
if (!isRecord(params)) {
|
|
266
|
+
throw new Error("params must be an object when provided");
|
|
267
|
+
}
|
|
268
|
+
return {
|
|
269
|
+
action,
|
|
270
|
+
ref_id: refId,
|
|
271
|
+
method: requiredString(value["method"], "method"),
|
|
272
|
+
params
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
throw new Error(`unsupported action: ${action}`);
|
|
276
|
+
}
|
|
277
|
+
function isRecordValue(value) {
|
|
278
|
+
return isRecord(value);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// src/browser/routes.ts
|
|
282
|
+
import { hostname } from "node:os";
|
|
283
|
+
|
|
284
|
+
// src/browser/config.ts
|
|
285
|
+
import {
|
|
286
|
+
mkdirSync,
|
|
287
|
+
readFileSync,
|
|
288
|
+
renameSync,
|
|
289
|
+
rmSync,
|
|
290
|
+
writeFileSync
|
|
291
|
+
} from "node:fs";
|
|
292
|
+
import { homedir } from "node:os";
|
|
293
|
+
import { basename, dirname, join } from "node:path";
|
|
294
|
+
var DEFAULT_REMOTE_NODE_PATH = "node";
|
|
295
|
+
var ROUTE_NAME = /^[A-Za-z0-9_.-]+$/;
|
|
296
|
+
var REMOTE_WORD = /^[A-Za-z0-9_./:$@=+-]+$/;
|
|
297
|
+
function browserConfigPath() {
|
|
298
|
+
const agentDir = process.env["PI_CODING_AGENT_DIR"]?.trim() || join(homedir(), ".pi", "agent");
|
|
299
|
+
return process.env["PI_BROWSER_CONFIG"]?.trim() || join(agentDir, "pi-browser.json");
|
|
300
|
+
}
|
|
301
|
+
function defaultBrowserRouteConfig() {
|
|
302
|
+
return {
|
|
303
|
+
aliases: {},
|
|
304
|
+
hosts: [],
|
|
305
|
+
remoteNodePath: DEFAULT_REMOTE_NODE_PATH
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
function normalizeBrowserHostName(value, field = "browser host") {
|
|
309
|
+
if (typeof value !== "string" || !ROUTE_NAME.test(value)) {
|
|
310
|
+
throw new Error(`${field} must contain only letters, digits, dot, dash or underscore`);
|
|
311
|
+
}
|
|
312
|
+
return value;
|
|
313
|
+
}
|
|
314
|
+
function remoteWord(value, field) {
|
|
315
|
+
if (typeof value !== "string" || !value || !REMOTE_WORD.test(value)) {
|
|
316
|
+
throw new Error(`${field} contains unsupported shell characters`);
|
|
317
|
+
}
|
|
318
|
+
return value;
|
|
319
|
+
}
|
|
320
|
+
function normalizeBrowserRouteConfig(value) {
|
|
321
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
322
|
+
throw new Error("pi-browser config must be an object");
|
|
323
|
+
}
|
|
324
|
+
const input = value;
|
|
325
|
+
const rawHosts = input.hosts ?? [];
|
|
326
|
+
if (!Array.isArray(rawHosts)) {
|
|
327
|
+
throw new Error("pi-browser config hosts must be an array");
|
|
328
|
+
}
|
|
329
|
+
const hosts = rawHosts.map((name) => normalizeBrowserHostName(name, "pi-browser host name"));
|
|
330
|
+
if (new Set(hosts).size !== hosts.length) {
|
|
331
|
+
throw new Error("pi-browser config hosts must be unique");
|
|
332
|
+
}
|
|
333
|
+
const rawAliases = input.aliases ?? {};
|
|
334
|
+
if (typeof rawAliases !== "object" || Array.isArray(rawAliases)) {
|
|
335
|
+
throw new Error("pi-browser config aliases must be an object");
|
|
336
|
+
}
|
|
337
|
+
const aliases = {};
|
|
338
|
+
for (const [rawAlias, rawTarget] of Object.entries(rawAliases)) {
|
|
339
|
+
const alias = normalizeBrowserHostName(rawAlias, "pi-browser alias");
|
|
340
|
+
const target = normalizeBrowserHostName(rawTarget, `pi-browser alias ${alias}`);
|
|
341
|
+
if (!hosts.includes(target)) {
|
|
342
|
+
throw new Error(`pi-browser alias ${alias} targets unknown host ${target}`);
|
|
343
|
+
}
|
|
344
|
+
aliases[alias] = target;
|
|
345
|
+
}
|
|
346
|
+
return {
|
|
347
|
+
aliases,
|
|
348
|
+
hosts,
|
|
349
|
+
remoteNodePath: remoteWord(input.remoteNodePath ?? DEFAULT_REMOTE_NODE_PATH, "pi-browser remoteNodePath")
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
function readBrowserRouteConfig(path = browserConfigPath()) {
|
|
353
|
+
let source;
|
|
354
|
+
try {
|
|
355
|
+
source = readFileSync(path, "utf8");
|
|
356
|
+
} catch (error) {
|
|
357
|
+
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
|
|
358
|
+
return defaultBrowserRouteConfig();
|
|
359
|
+
}
|
|
360
|
+
throw error;
|
|
361
|
+
}
|
|
362
|
+
try {
|
|
363
|
+
return normalizeBrowserRouteConfig(JSON.parse(source));
|
|
364
|
+
} catch (error) {
|
|
365
|
+
throw new Error(`Invalid pi-browser config at ${path}: ${error instanceof Error ? error.message : String(error)}`);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// src/browser/routes.ts
|
|
370
|
+
class BrowserRoutes {
|
|
371
|
+
names;
|
|
372
|
+
routes;
|
|
373
|
+
constructor(routes = new Map) {
|
|
374
|
+
this.routes = routes;
|
|
375
|
+
this.names = [...routes.keys()];
|
|
376
|
+
}
|
|
377
|
+
resolve(name) {
|
|
378
|
+
const route = this.routes.get(name);
|
|
379
|
+
if (route)
|
|
380
|
+
return route;
|
|
381
|
+
if (this.names.length === 0) {
|
|
382
|
+
throw new Error("Browser host routing is disabled");
|
|
383
|
+
}
|
|
384
|
+
throw new Error(`browser host must be one of: ${this.names.join(", ")}`);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
function routesFromConfig(config, currentHostname) {
|
|
388
|
+
const shortHostname = currentHostname.split(".")[0] ?? currentHostname;
|
|
389
|
+
const currentName = config.aliases[currentHostname] ?? config.aliases[shortHostname] ?? shortHostname;
|
|
390
|
+
const remote = {
|
|
391
|
+
nodePath: config.remoteNodePath
|
|
392
|
+
};
|
|
393
|
+
const routes = new Map;
|
|
394
|
+
for (const name of config.hosts) {
|
|
395
|
+
const local = currentName === name;
|
|
396
|
+
routes.set(name, local ? { name, local } : { name, local, remote });
|
|
397
|
+
}
|
|
398
|
+
return new BrowserRoutes(routes);
|
|
399
|
+
}
|
|
400
|
+
function loadBrowserRoutes(path, currentHostname = hostname()) {
|
|
401
|
+
return routesFromConfig(readBrowserRouteConfig(path), currentHostname);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// src/cdp/discovery.ts
|
|
405
|
+
import { existsSync, readFileSync as readFileSync2 } from "node:fs";
|
|
406
|
+
import http from "node:http";
|
|
407
|
+
import { homedir as homedir2 } from "node:os";
|
|
408
|
+
import { resolve } from "node:path";
|
|
409
|
+
|
|
410
|
+
// src/cdp/types.ts
|
|
411
|
+
function asRecord(value, label = "CDP response") {
|
|
412
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
413
|
+
throw new Error(`${label} is not an object`);
|
|
414
|
+
}
|
|
415
|
+
return value;
|
|
416
|
+
}
|
|
417
|
+
function asString(value, label) {
|
|
418
|
+
if (typeof value !== "string")
|
|
419
|
+
throw new Error(`${label} is not a string`);
|
|
420
|
+
return value;
|
|
421
|
+
}
|
|
422
|
+
function errorMessage(error) {
|
|
423
|
+
return error instanceof Error ? error.message : String(error);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
// src/cdp/discovery.ts
|
|
427
|
+
var CDP_TIMEOUT_MS = 15000;
|
|
428
|
+
var NAVIGATION_TIMEOUT_MS = 30000;
|
|
429
|
+
var MIN_TARGET_PREFIX_LENGTH = 8;
|
|
430
|
+
var IS_WINDOWS = process.platform === "win32";
|
|
431
|
+
function getJson(url, timeout = 2000) {
|
|
432
|
+
return new Promise((resolveValue, reject) => {
|
|
433
|
+
const request = http.get(url, { timeout }, (response) => {
|
|
434
|
+
let body = "";
|
|
435
|
+
response.setEncoding("utf8");
|
|
436
|
+
response.on("data", (chunk) => {
|
|
437
|
+
body += chunk;
|
|
438
|
+
});
|
|
439
|
+
response.on("end", () => {
|
|
440
|
+
const status = response.statusCode ?? 0;
|
|
441
|
+
if (status < 200 || status >= 300) {
|
|
442
|
+
reject(new Error(`HTTP ${status} from ${url}`));
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
try {
|
|
446
|
+
resolveValue(JSON.parse(body));
|
|
447
|
+
} catch (error) {
|
|
448
|
+
reject(error);
|
|
449
|
+
}
|
|
450
|
+
});
|
|
451
|
+
});
|
|
452
|
+
request.on("timeout", () => request.destroy(new Error(`Timeout fetching ${url}`)));
|
|
453
|
+
request.on("error", reject);
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
async function probeDebugPort(port, host = process.env["CDP_HOST"] ?? "127.0.0.1") {
|
|
457
|
+
const version = asRecord(await getJson(`http://${host}:${port}/json/version`), "CDP version response");
|
|
458
|
+
return asString(version["webSocketDebuggerUrl"], "CDP webSocketDebuggerUrl");
|
|
459
|
+
}
|
|
460
|
+
async function getWebSocketUrl(recovery = "Enable remote debugging or set CDP_PORT/CDP_PORT_FILE.") {
|
|
461
|
+
const home = homedir2();
|
|
462
|
+
const macBrowsers = [
|
|
463
|
+
"Google/Chrome",
|
|
464
|
+
"Google/Chrome Beta",
|
|
465
|
+
"Google/Chrome for Testing",
|
|
466
|
+
"Chromium",
|
|
467
|
+
"BraveSoftware/Brave-Browser",
|
|
468
|
+
"Microsoft Edge"
|
|
469
|
+
];
|
|
470
|
+
const linuxBrowsers = [
|
|
471
|
+
"google-chrome",
|
|
472
|
+
"google-chrome-beta",
|
|
473
|
+
"chromium",
|
|
474
|
+
"vivaldi",
|
|
475
|
+
"vivaldi-snapshot",
|
|
476
|
+
"BraveSoftware/Brave-Browser",
|
|
477
|
+
"microsoft-edge"
|
|
478
|
+
];
|
|
479
|
+
const flatpakBrowsers = [
|
|
480
|
+
["org.chromium.Chromium", "chromium"],
|
|
481
|
+
["com.google.Chrome", "google-chrome"],
|
|
482
|
+
["com.brave.Browser", "BraveSoftware/Brave-Browser"],
|
|
483
|
+
["com.microsoft.Edge", "microsoft-edge"],
|
|
484
|
+
["com.vivaldi.Vivaldi", "vivaldi"]
|
|
485
|
+
];
|
|
486
|
+
const candidates = [
|
|
487
|
+
process.env["CDP_PORT_FILE"],
|
|
488
|
+
...macBrowsers.flatMap((browser) => [
|
|
489
|
+
resolve(home, "Library/Application Support", browser, "DevToolsActivePort"),
|
|
490
|
+
resolve(home, "Library/Application Support", browser, "Default/DevToolsActivePort")
|
|
491
|
+
]),
|
|
492
|
+
...linuxBrowsers.flatMap((browser) => [
|
|
493
|
+
resolve(home, ".config", browser, "DevToolsActivePort"),
|
|
494
|
+
resolve(home, ".config", browser, "Default/DevToolsActivePort")
|
|
495
|
+
]),
|
|
496
|
+
...flatpakBrowsers.flatMap(([appId, browser]) => [
|
|
497
|
+
resolve(home, ".var/app", appId, "config", browser, "DevToolsActivePort"),
|
|
498
|
+
resolve(home, ".var/app", appId, "config", browser, "Default/DevToolsActivePort")
|
|
499
|
+
]),
|
|
500
|
+
...IS_WINDOWS ? [
|
|
501
|
+
"Google/Chrome",
|
|
502
|
+
"BraveSoftware/Brave-Browser",
|
|
503
|
+
"Microsoft/Edge"
|
|
504
|
+
].flatMap((browser) => {
|
|
505
|
+
const base = process.env["LOCALAPPDATA"] ?? resolve(home, "AppData/Local");
|
|
506
|
+
return [
|
|
507
|
+
resolve(base, browser, "User Data", "DevToolsActivePort"),
|
|
508
|
+
resolve(base, browser, "User Data", "Default/DevToolsActivePort")
|
|
509
|
+
];
|
|
510
|
+
}) : []
|
|
511
|
+
].filter((candidate) => Boolean(candidate));
|
|
512
|
+
const host = process.env["CDP_HOST"] ?? "127.0.0.1";
|
|
513
|
+
const port = process.env["CDP_PORT"] ?? "9222";
|
|
514
|
+
try {
|
|
515
|
+
return await probeDebugPort(port, host);
|
|
516
|
+
} catch (error) {
|
|
517
|
+
const portFile = candidates.find((candidate) => existsSync(candidate));
|
|
518
|
+
if (portFile) {
|
|
519
|
+
const lines = readFileSync2(portFile, "utf8").trim().split(`
|
|
520
|
+
`);
|
|
521
|
+
if (!lines[0] || !lines[1]) {
|
|
522
|
+
throw new Error(`Invalid DevToolsActivePort file: ${portFile}`);
|
|
523
|
+
}
|
|
524
|
+
return `ws://${host}:${lines[0]}${lines[1]}`;
|
|
525
|
+
}
|
|
526
|
+
throw new Error(`CDP HTTP discovery failed and no DevToolsActivePort found. ${recovery} Tried: ${host}:${port} ${errorMessage(error)}`);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
function sleep(ms, signal) {
|
|
530
|
+
if (signal?.aborted) {
|
|
531
|
+
return Promise.reject(signal.reason ?? new Error("Operation aborted"));
|
|
532
|
+
}
|
|
533
|
+
return new Promise((resolveValue, reject) => {
|
|
534
|
+
const cleanup = () => signal?.removeEventListener("abort", abort);
|
|
535
|
+
const timer = setTimeout(() => {
|
|
536
|
+
cleanup();
|
|
537
|
+
resolveValue();
|
|
538
|
+
}, ms);
|
|
539
|
+
const abort = () => {
|
|
540
|
+
clearTimeout(timer);
|
|
541
|
+
cleanup();
|
|
542
|
+
reject(signal?.reason ?? new Error("Operation aborted"));
|
|
543
|
+
};
|
|
544
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
function resolvePrefix(prefix, candidates, noun = "target", missingHint = "") {
|
|
548
|
+
const upper = prefix.toUpperCase();
|
|
549
|
+
const matches = candidates.filter((candidate) => candidate.toUpperCase().startsWith(upper));
|
|
550
|
+
if (matches.length === 0) {
|
|
551
|
+
throw new Error(`No ${noun} matching prefix "${prefix}".${missingHint ? ` ${missingHint}` : ""}`);
|
|
552
|
+
}
|
|
553
|
+
if (matches.length > 1) {
|
|
554
|
+
throw new Error(`Ambiguous prefix "${prefix}" matches ${matches.length} ${noun}s. Use more characters.`);
|
|
555
|
+
}
|
|
556
|
+
const match = matches[0];
|
|
557
|
+
if (!match)
|
|
558
|
+
throw new Error(`No ${noun} matching prefix "${prefix}".`);
|
|
559
|
+
return match;
|
|
560
|
+
}
|
|
561
|
+
function getDisplayPrefixLength(targetIds) {
|
|
562
|
+
if (targetIds.length === 0)
|
|
563
|
+
return MIN_TARGET_PREFIX_LENGTH;
|
|
564
|
+
const maxLength = Math.max(...targetIds.map((id) => id.length));
|
|
565
|
+
for (let length = MIN_TARGET_PREFIX_LENGTH;length <= maxLength; length++) {
|
|
566
|
+
const prefixes = new Set(targetIds.map((id) => id.slice(0, length).toUpperCase()));
|
|
567
|
+
if (prefixes.size === targetIds.length)
|
|
568
|
+
return length;
|
|
569
|
+
}
|
|
570
|
+
return maxLength;
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
// src/cdp/client.ts
|
|
574
|
+
var RETRYABLE_TIMEOUT_METHODS = new Set([
|
|
575
|
+
"Accessibility.getFullAXTree",
|
|
576
|
+
"Page.captureScreenshot",
|
|
577
|
+
"Runtime.enable"
|
|
578
|
+
]);
|
|
579
|
+
|
|
580
|
+
class CdpTimeoutError extends Error {
|
|
581
|
+
}
|
|
582
|
+
function cdpTimeoutAttempts(method) {
|
|
583
|
+
return RETRYABLE_TIMEOUT_METHODS.has(method) ? 2 : 1;
|
|
584
|
+
}
|
|
585
|
+
function timeoutError(method, attempts) {
|
|
586
|
+
const seconds = CDP_TIMEOUT_MS / 1000;
|
|
587
|
+
if (attempts > 1) {
|
|
588
|
+
return new Error(`Chrome did not answer ${method} after two ${seconds}s attempts. The tab may be unresponsive or suspended.`);
|
|
589
|
+
}
|
|
590
|
+
if (method === "Runtime.evaluate") {
|
|
591
|
+
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.`);
|
|
592
|
+
}
|
|
593
|
+
return new Error(`Chrome did not answer ${method} within ${seconds}s.`);
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
class CdpClient {
|
|
597
|
+
socket;
|
|
598
|
+
nextId = 0;
|
|
599
|
+
pending = new Map;
|
|
600
|
+
eventHandlers = new Map;
|
|
601
|
+
closeHandlers = new Set;
|
|
602
|
+
async connect(url, signal) {
|
|
603
|
+
if (signal?.aborted) {
|
|
604
|
+
throw signal.reason ?? new Error("CDP connection aborted");
|
|
605
|
+
}
|
|
606
|
+
await new Promise((resolveValue, reject) => {
|
|
607
|
+
const socket = new WebSocket(url);
|
|
608
|
+
this.socket = socket;
|
|
609
|
+
let settled = false;
|
|
610
|
+
const cleanup = () => signal?.removeEventListener("abort", abort);
|
|
611
|
+
const fail = (error) => {
|
|
612
|
+
if (settled)
|
|
613
|
+
return;
|
|
614
|
+
settled = true;
|
|
615
|
+
cleanup();
|
|
616
|
+
reject(error);
|
|
617
|
+
};
|
|
618
|
+
const abort = () => {
|
|
619
|
+
socket.close();
|
|
620
|
+
fail(signal?.reason ?? new Error("CDP connection aborted"));
|
|
621
|
+
};
|
|
622
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
623
|
+
socket.onopen = () => {
|
|
624
|
+
if (settled)
|
|
625
|
+
return;
|
|
626
|
+
settled = true;
|
|
627
|
+
cleanup();
|
|
628
|
+
resolveValue();
|
|
629
|
+
};
|
|
630
|
+
socket.onerror = (event) => fail(new Error(`WebSocket error: ${"message" in event ? String(event.message) : event.type}`));
|
|
631
|
+
socket.onmessage = (event) => this.handleMessage(event.data);
|
|
632
|
+
socket.onclose = () => this.handleClose();
|
|
633
|
+
});
|
|
634
|
+
}
|
|
635
|
+
async send(method, params = {}, sessionId, signal) {
|
|
636
|
+
const attempts = cdpTimeoutAttempts(method);
|
|
637
|
+
for (let attempt = 1;attempt <= attempts; attempt++) {
|
|
638
|
+
try {
|
|
639
|
+
return await this.sendOnce(method, params, sessionId, signal);
|
|
640
|
+
} catch (error) {
|
|
641
|
+
if (!(error instanceof CdpTimeoutError))
|
|
642
|
+
throw error;
|
|
643
|
+
if (attempt === attempts)
|
|
644
|
+
throw timeoutError(method, attempts);
|
|
645
|
+
await sleep(100, signal);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
throw new Error(`Could not send ${method}`);
|
|
649
|
+
}
|
|
650
|
+
onEvent(method, handler) {
|
|
651
|
+
const handlers = this.eventHandlers.get(method) ?? new Set;
|
|
652
|
+
handlers.add(handler);
|
|
653
|
+
this.eventHandlers.set(method, handlers);
|
|
654
|
+
return () => {
|
|
655
|
+
handlers.delete(handler);
|
|
656
|
+
if (handlers.size === 0)
|
|
657
|
+
this.eventHandlers.delete(method);
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
waitForEvent(method, timeout = CDP_TIMEOUT_MS, signal) {
|
|
661
|
+
if (signal?.aborted) {
|
|
662
|
+
return {
|
|
663
|
+
promise: Promise.reject(signal.reason ?? new Error("Operation aborted")),
|
|
664
|
+
cancel() {}
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
let settled = false;
|
|
668
|
+
let timer;
|
|
669
|
+
let off;
|
|
670
|
+
let abort;
|
|
671
|
+
const cleanup = () => {
|
|
672
|
+
if (timer)
|
|
673
|
+
clearTimeout(timer);
|
|
674
|
+
off?.();
|
|
675
|
+
if (abort)
|
|
676
|
+
signal?.removeEventListener("abort", abort);
|
|
677
|
+
};
|
|
678
|
+
const promise = new Promise((resolveValue, reject) => {
|
|
679
|
+
off = this.onEvent(method, (params) => {
|
|
680
|
+
if (settled)
|
|
681
|
+
return;
|
|
682
|
+
settled = true;
|
|
683
|
+
cleanup();
|
|
684
|
+
resolveValue(params);
|
|
685
|
+
});
|
|
686
|
+
timer = setTimeout(() => {
|
|
687
|
+
if (settled)
|
|
688
|
+
return;
|
|
689
|
+
settled = true;
|
|
690
|
+
cleanup();
|
|
691
|
+
reject(new Error(`Timeout waiting for event: ${method}`));
|
|
692
|
+
}, timeout);
|
|
693
|
+
abort = () => {
|
|
694
|
+
if (settled)
|
|
695
|
+
return;
|
|
696
|
+
settled = true;
|
|
697
|
+
cleanup();
|
|
698
|
+
reject(signal?.reason ?? new Error("Operation aborted"));
|
|
699
|
+
};
|
|
700
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
701
|
+
});
|
|
702
|
+
return {
|
|
703
|
+
promise,
|
|
704
|
+
cancel() {
|
|
705
|
+
if (settled)
|
|
706
|
+
return;
|
|
707
|
+
settled = true;
|
|
708
|
+
cleanup();
|
|
709
|
+
}
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
onClose(handler) {
|
|
713
|
+
this.closeHandlers.add(handler);
|
|
714
|
+
return () => this.closeHandlers.delete(handler);
|
|
715
|
+
}
|
|
716
|
+
close() {
|
|
717
|
+
this.socket?.close();
|
|
718
|
+
this.socket = undefined;
|
|
719
|
+
}
|
|
720
|
+
sendOnce(method, params, sessionId, signal) {
|
|
721
|
+
if (signal?.aborted) {
|
|
722
|
+
return Promise.reject(signal.reason ?? new Error(`${method} aborted`));
|
|
723
|
+
}
|
|
724
|
+
const socket = this.socket;
|
|
725
|
+
if (!socket || socket.readyState !== WebSocket.OPEN) {
|
|
726
|
+
return Promise.reject(new Error("CDP is not connected"));
|
|
727
|
+
}
|
|
728
|
+
const id = ++this.nextId;
|
|
729
|
+
return new Promise((resolveValue, reject) => {
|
|
730
|
+
const timer = setTimeout(() => {
|
|
731
|
+
this.finishPending(id)?.reject(new CdpTimeoutError(method));
|
|
732
|
+
}, CDP_TIMEOUT_MS);
|
|
733
|
+
const abort = () => {
|
|
734
|
+
const pending = this.pending.get(id);
|
|
735
|
+
if (!pending)
|
|
736
|
+
return;
|
|
737
|
+
this.pending.delete(id);
|
|
738
|
+
clearTimeout(pending.timer);
|
|
739
|
+
reject(signal?.reason ?? new Error(`${method} aborted`));
|
|
740
|
+
};
|
|
741
|
+
this.pending.set(id, {
|
|
742
|
+
resolve: resolveValue,
|
|
743
|
+
reject,
|
|
744
|
+
timer,
|
|
745
|
+
...signal ? { signal, abort } : {}
|
|
746
|
+
});
|
|
747
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
748
|
+
try {
|
|
749
|
+
socket.send(JSON.stringify({
|
|
750
|
+
id,
|
|
751
|
+
method,
|
|
752
|
+
params,
|
|
753
|
+
...sessionId ? { sessionId } : {}
|
|
754
|
+
}));
|
|
755
|
+
} catch (error) {
|
|
756
|
+
this.finishPending(id);
|
|
757
|
+
reject(error);
|
|
758
|
+
}
|
|
759
|
+
});
|
|
760
|
+
}
|
|
761
|
+
handleMessage(data) {
|
|
762
|
+
let message;
|
|
763
|
+
try {
|
|
764
|
+
message = asRecord(JSON.parse(String(data)), "CDP message");
|
|
765
|
+
} catch {
|
|
766
|
+
return;
|
|
767
|
+
}
|
|
768
|
+
const id = message["id"];
|
|
769
|
+
if (typeof id === "number" && this.pending.has(id)) {
|
|
770
|
+
const pending = this.finishPending(id);
|
|
771
|
+
if (!pending)
|
|
772
|
+
return;
|
|
773
|
+
const error = message["error"];
|
|
774
|
+
if (error) {
|
|
775
|
+
const record = asRecord(error, "CDP error");
|
|
776
|
+
pending.reject(new Error(typeof record["message"] === "string" ? record["message"] : "Unknown CDP error"));
|
|
777
|
+
} else {
|
|
778
|
+
pending.resolve(message["result"]);
|
|
779
|
+
}
|
|
780
|
+
return;
|
|
781
|
+
}
|
|
782
|
+
const method = message["method"];
|
|
783
|
+
if (typeof method !== "string")
|
|
784
|
+
return;
|
|
785
|
+
for (const handler of this.eventHandlers.get(method) ?? []) {
|
|
786
|
+
handler(message["params"] ?? {});
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
finishPending(id) {
|
|
790
|
+
const pending = this.pending.get(id);
|
|
791
|
+
if (!pending)
|
|
792
|
+
return;
|
|
793
|
+
this.pending.delete(id);
|
|
794
|
+
clearTimeout(pending.timer);
|
|
795
|
+
if (pending.abort) {
|
|
796
|
+
pending.signal?.removeEventListener("abort", pending.abort);
|
|
797
|
+
}
|
|
798
|
+
return pending;
|
|
799
|
+
}
|
|
800
|
+
handleClose() {
|
|
801
|
+
this.socket = undefined;
|
|
802
|
+
for (const [id, pending] of this.pending) {
|
|
803
|
+
this.finishPending(id);
|
|
804
|
+
pending.reject(new Error("Chrome disconnected"));
|
|
805
|
+
}
|
|
806
|
+
for (const handler of this.closeHandlers) {
|
|
807
|
+
try {
|
|
808
|
+
handler();
|
|
809
|
+
} catch (error) {
|
|
810
|
+
process.stderr.write(`Browser close handler failed: ${errorMessage(error)}
|
|
811
|
+
`);
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
// src/cdp/pages.ts
|
|
818
|
+
function pageInfo(value) {
|
|
819
|
+
const record = asRecord(value, "CDP target");
|
|
820
|
+
return {
|
|
821
|
+
targetId: asString(record["targetId"], "targetId"),
|
|
822
|
+
title: typeof record["title"] === "string" ? record["title"] : "",
|
|
823
|
+
url: asString(record["url"], "target URL"),
|
|
824
|
+
...typeof record["type"] === "string" ? { type: record["type"] } : {}
|
|
825
|
+
};
|
|
826
|
+
}
|
|
827
|
+
async function getPages(cdp, signal) {
|
|
828
|
+
const response = asRecord(await cdp.send("Target.getTargets", {}, undefined, signal), "Target.getTargets response");
|
|
829
|
+
const targetInfos = response["targetInfos"];
|
|
830
|
+
if (!Array.isArray(targetInfos)) {
|
|
831
|
+
throw new Error("Target.getTargets response has no targetInfos");
|
|
832
|
+
}
|
|
833
|
+
return targetInfos.map(pageInfo).filter((target) => target.type === "page" && !target.url.startsWith("chrome://"));
|
|
834
|
+
}
|
|
835
|
+
async function waitForOpenedTarget(cdp, targetId, requestedUrl, timeout = 5000, signal) {
|
|
836
|
+
if (requestedUrl === "about:blank") {
|
|
837
|
+
return {
|
|
838
|
+
targetId,
|
|
839
|
+
title: requestedUrl,
|
|
840
|
+
url: requestedUrl,
|
|
841
|
+
type: "page"
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
const deadline = Date.now() + timeout;
|
|
845
|
+
while (Date.now() < deadline) {
|
|
846
|
+
const response = asRecord(await cdp.send("Target.getTargetInfo", { targetId }, undefined, signal), "Target.getTargetInfo response");
|
|
847
|
+
const target = pageInfo(response["targetInfo"]);
|
|
848
|
+
if (target.url && target.url !== "about:blank")
|
|
849
|
+
return target;
|
|
850
|
+
await sleep(100, signal);
|
|
851
|
+
}
|
|
852
|
+
throw new Error(`New tab did not begin navigating to ${requestedUrl}`);
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
// src/cdp/serial.ts
|
|
856
|
+
function waitForTurn(promise, signal) {
|
|
857
|
+
if (!signal)
|
|
858
|
+
return promise;
|
|
859
|
+
if (signal.aborted) {
|
|
860
|
+
return Promise.reject(signal.reason ?? new Error("Operation aborted"));
|
|
861
|
+
}
|
|
862
|
+
return new Promise((resolveValue, reject) => {
|
|
863
|
+
const abort = () => reject(signal.reason ?? new Error("Operation aborted"));
|
|
864
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
865
|
+
promise.then((value) => {
|
|
866
|
+
signal.removeEventListener("abort", abort);
|
|
867
|
+
resolveValue(value);
|
|
868
|
+
}, (error) => {
|
|
869
|
+
signal.removeEventListener("abort", abort);
|
|
870
|
+
reject(error);
|
|
871
|
+
});
|
|
872
|
+
});
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
// src/cdp/url.ts
|
|
876
|
+
function assertHttpUrl(value) {
|
|
877
|
+
let parsed;
|
|
878
|
+
try {
|
|
879
|
+
parsed = new URL(value);
|
|
880
|
+
} catch {
|
|
881
|
+
throw new Error(`Invalid URL: ${value}`);
|
|
882
|
+
}
|
|
883
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
884
|
+
throw new Error(`Only http/https URLs allowed, got: ${value}`);
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
// src/cdp/session.ts
|
|
889
|
+
var TAB_IDLE_MS = 20 * 60 * 1000;
|
|
890
|
+
|
|
891
|
+
class TabBridge {
|
|
892
|
+
elementRefs = new Map;
|
|
893
|
+
targetId;
|
|
894
|
+
cdp;
|
|
895
|
+
sessionId;
|
|
896
|
+
tail = Promise.resolve();
|
|
897
|
+
idleTimer;
|
|
898
|
+
closed = false;
|
|
899
|
+
onClose;
|
|
900
|
+
constructor(targetId, cdp, sessionId, onClose) {
|
|
901
|
+
this.targetId = targetId;
|
|
902
|
+
this.cdp = cdp;
|
|
903
|
+
this.sessionId = sessionId;
|
|
904
|
+
this.onClose = onClose;
|
|
905
|
+
this.resetIdle();
|
|
906
|
+
cdp.onEvent("Target.targetDestroyed", (value) => {
|
|
907
|
+
const event = asRecord(value, "target destroyed event");
|
|
908
|
+
if (event["targetId"] === targetId)
|
|
909
|
+
this.close(false);
|
|
910
|
+
});
|
|
911
|
+
cdp.onEvent("Target.detachedFromTarget", (value) => {
|
|
912
|
+
const event = asRecord(value, "target detached event");
|
|
913
|
+
if (event["sessionId"] === sessionId)
|
|
914
|
+
this.close(false);
|
|
915
|
+
});
|
|
916
|
+
cdp.onClose(() => this.close(false));
|
|
917
|
+
}
|
|
918
|
+
static async connect(targetId, onClose, signal) {
|
|
919
|
+
const cdp = new CdpClient;
|
|
920
|
+
try {
|
|
921
|
+
await cdp.connect(await getWebSocketUrl(), signal);
|
|
922
|
+
const response = asRecord(await cdp.send("Target.attachToTarget", { targetId, flatten: true }, undefined, signal), "Target.attachToTarget response");
|
|
923
|
+
if (typeof response["sessionId"] !== "string") {
|
|
924
|
+
throw new Error("Chrome did not return a tab session");
|
|
925
|
+
}
|
|
926
|
+
return new TabBridge(targetId, cdp, response["sessionId"], onClose);
|
|
927
|
+
} catch (error) {
|
|
928
|
+
cdp.close();
|
|
929
|
+
throw error;
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
async run(refId, signal, action) {
|
|
933
|
+
if (this.closed)
|
|
934
|
+
throw new Error("Tab bridge is closed");
|
|
935
|
+
let release;
|
|
936
|
+
const turn = new Promise((resolveValue) => {
|
|
937
|
+
release = resolveValue;
|
|
938
|
+
});
|
|
939
|
+
const previous = this.tail;
|
|
940
|
+
this.tail = previous.then(() => turn, () => turn);
|
|
941
|
+
try {
|
|
942
|
+
await waitForTurn(previous, signal);
|
|
943
|
+
if (this.closed)
|
|
944
|
+
throw new Error("Tab bridge is closed");
|
|
945
|
+
this.resetIdle();
|
|
946
|
+
return await action({
|
|
947
|
+
cdp: this.cdp,
|
|
948
|
+
sessionId: this.sessionId,
|
|
949
|
+
elementRefs: this.elementRefs,
|
|
950
|
+
refId
|
|
951
|
+
});
|
|
952
|
+
} finally {
|
|
953
|
+
release();
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
close(detach = true) {
|
|
957
|
+
if (this.closed)
|
|
958
|
+
return;
|
|
959
|
+
this.closed = true;
|
|
960
|
+
if (this.idleTimer)
|
|
961
|
+
clearTimeout(this.idleTimer);
|
|
962
|
+
this.elementRefs.clear();
|
|
963
|
+
if (detach) {
|
|
964
|
+
this.cdp.send("Target.detachFromTarget", { sessionId: this.sessionId }, undefined, undefined).catch(() => {
|
|
965
|
+
return;
|
|
966
|
+
}).finally(() => this.cdp.close());
|
|
967
|
+
} else {
|
|
968
|
+
this.cdp.close();
|
|
969
|
+
}
|
|
970
|
+
this.onClose();
|
|
971
|
+
}
|
|
972
|
+
resetIdle() {
|
|
973
|
+
if (this.idleTimer)
|
|
974
|
+
clearTimeout(this.idleTimer);
|
|
975
|
+
this.idleTimer = setTimeout(() => this.close(), TAB_IDLE_MS);
|
|
976
|
+
this.idleTimer.unref?.();
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
class BrowserCdpSession {
|
|
981
|
+
root;
|
|
982
|
+
rootPending;
|
|
983
|
+
tabs = new Map;
|
|
984
|
+
tabPromises = new Map;
|
|
985
|
+
async pages(signal) {
|
|
986
|
+
return getPages(await this.rootConnection(signal), signal);
|
|
987
|
+
}
|
|
988
|
+
async open(url, signal) {
|
|
989
|
+
assertHttpUrl(url);
|
|
990
|
+
const root = await this.rootConnection(signal);
|
|
991
|
+
const response = asRecord(await root.send("Target.createTarget", { url }, undefined, signal), "Target.createTarget response");
|
|
992
|
+
if (typeof response["targetId"] !== "string") {
|
|
993
|
+
throw new Error("Chrome did not return a new tab target");
|
|
994
|
+
}
|
|
995
|
+
const page = await waitForOpenedTarget(root, response["targetId"], url, 5000, signal);
|
|
996
|
+
const pages = await getPages(root, signal);
|
|
997
|
+
if (!pages.some((candidate) => candidate.targetId === page.targetId)) {
|
|
998
|
+
pages.push(page);
|
|
999
|
+
}
|
|
1000
|
+
const prefixLength = getDisplayPrefixLength(pages.map((candidate) => candidate.targetId));
|
|
1001
|
+
return {
|
|
1002
|
+
refId: page.targetId.slice(0, prefixLength)
|
|
1003
|
+
};
|
|
1004
|
+
}
|
|
1005
|
+
async withTab(refId, signal, action) {
|
|
1006
|
+
const pages = await this.pages(signal);
|
|
1007
|
+
const targetId = resolvePrefix(refId, pages.map((page) => page.targetId), "target", "Run tabs.");
|
|
1008
|
+
let bridge = this.tabs.get(targetId);
|
|
1009
|
+
if (!bridge) {
|
|
1010
|
+
let pending = this.tabPromises.get(targetId);
|
|
1011
|
+
if (!pending) {
|
|
1012
|
+
const controller = new AbortController;
|
|
1013
|
+
const promise = this.connectTab(targetId, controller.signal);
|
|
1014
|
+
pending = { controller, promise };
|
|
1015
|
+
this.tabPromises.set(targetId, pending);
|
|
1016
|
+
promise.then((value) => {
|
|
1017
|
+
pending.value = value;
|
|
1018
|
+
}, () => {
|
|
1019
|
+
if (this.tabPromises.get(targetId) === pending) {
|
|
1020
|
+
this.tabPromises.delete(targetId);
|
|
1021
|
+
}
|
|
1022
|
+
});
|
|
1023
|
+
}
|
|
1024
|
+
const connected = await waitForTurn(pending.promise, signal);
|
|
1025
|
+
bridge = this.tabs.get(targetId);
|
|
1026
|
+
if (!bridge) {
|
|
1027
|
+
if (this.tabPromises.get(targetId) !== pending) {
|
|
1028
|
+
connected.close();
|
|
1029
|
+
throw new Error("Tab bridge was stopped while connecting");
|
|
1030
|
+
}
|
|
1031
|
+
this.tabPromises.delete(targetId);
|
|
1032
|
+
this.tabs.set(targetId, connected);
|
|
1033
|
+
bridge = connected;
|
|
1034
|
+
} else if (bridge !== connected) {
|
|
1035
|
+
connected.close();
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
const prefixLength = getDisplayPrefixLength(pages.map((page) => page.targetId));
|
|
1039
|
+
return bridge.run(targetId.slice(0, prefixLength), signal, action);
|
|
1040
|
+
}
|
|
1041
|
+
async stop(refId) {
|
|
1042
|
+
if (!refId) {
|
|
1043
|
+
for (const targetId2 of this.tabPromises.keys()) {
|
|
1044
|
+
this.stopPendingTab(targetId2, "All tab bridges were stopped");
|
|
1045
|
+
}
|
|
1046
|
+
for (const bridge of this.tabs.values())
|
|
1047
|
+
bridge.close();
|
|
1048
|
+
this.tabs.clear();
|
|
1049
|
+
return;
|
|
1050
|
+
}
|
|
1051
|
+
const pages = await this.pages();
|
|
1052
|
+
const targetId = resolvePrefix(refId, pages.map((page) => page.targetId), "target");
|
|
1053
|
+
this.stopPendingTab(targetId, "Tab bridge " + refId + " was stopped");
|
|
1054
|
+
this.tabs.get(targetId)?.close();
|
|
1055
|
+
this.tabs.delete(targetId);
|
|
1056
|
+
}
|
|
1057
|
+
close() {
|
|
1058
|
+
for (const targetId of this.tabPromises.keys()) {
|
|
1059
|
+
this.stopPendingTab(targetId, "Browser session closed");
|
|
1060
|
+
}
|
|
1061
|
+
for (const bridge of this.tabs.values())
|
|
1062
|
+
bridge.close();
|
|
1063
|
+
this.tabs.clear();
|
|
1064
|
+
const rootPending = this.rootPending;
|
|
1065
|
+
this.rootPending = undefined;
|
|
1066
|
+
if (rootPending) {
|
|
1067
|
+
rootPending.controller.abort(new Error("Browser session closed"));
|
|
1068
|
+
rootPending.promise.then((client) => client.close(), () => {
|
|
1069
|
+
return;
|
|
1070
|
+
});
|
|
1071
|
+
}
|
|
1072
|
+
this.root?.close();
|
|
1073
|
+
this.root = undefined;
|
|
1074
|
+
}
|
|
1075
|
+
async rootConnection(signal) {
|
|
1076
|
+
if (this.root)
|
|
1077
|
+
return this.root;
|
|
1078
|
+
let pending = this.rootPending;
|
|
1079
|
+
if (!pending) {
|
|
1080
|
+
const controller = new AbortController;
|
|
1081
|
+
const promise = this.connectRoot(controller.signal);
|
|
1082
|
+
pending = { controller, promise };
|
|
1083
|
+
this.rootPending = pending;
|
|
1084
|
+
promise.then((value) => {
|
|
1085
|
+
pending.value = value;
|
|
1086
|
+
if (this.rootPending === pending)
|
|
1087
|
+
this.rootPending = undefined;
|
|
1088
|
+
}, () => {
|
|
1089
|
+
if (this.rootPending === pending)
|
|
1090
|
+
this.rootPending = undefined;
|
|
1091
|
+
});
|
|
1092
|
+
}
|
|
1093
|
+
return waitForTurn(pending.promise, signal);
|
|
1094
|
+
}
|
|
1095
|
+
async connectTab(targetId, signal) {
|
|
1096
|
+
let bridge;
|
|
1097
|
+
bridge = await TabBridge.connect(targetId, () => {
|
|
1098
|
+
if (bridge && this.tabs.get(targetId) === bridge) {
|
|
1099
|
+
this.tabs.delete(targetId);
|
|
1100
|
+
}
|
|
1101
|
+
const pending = this.tabPromises.get(targetId);
|
|
1102
|
+
if (bridge && pending?.value === bridge) {
|
|
1103
|
+
this.tabPromises.delete(targetId);
|
|
1104
|
+
}
|
|
1105
|
+
}, signal);
|
|
1106
|
+
return bridge;
|
|
1107
|
+
}
|
|
1108
|
+
stopPendingTab(targetId, message) {
|
|
1109
|
+
const pending = this.tabPromises.get(targetId);
|
|
1110
|
+
if (!pending)
|
|
1111
|
+
return;
|
|
1112
|
+
this.tabPromises.delete(targetId);
|
|
1113
|
+
pending.controller.abort(new Error(message));
|
|
1114
|
+
pending.promise.then((bridge) => bridge.close(), () => {
|
|
1115
|
+
return;
|
|
1116
|
+
});
|
|
1117
|
+
}
|
|
1118
|
+
async connectRoot(signal) {
|
|
1119
|
+
const client = new CdpClient;
|
|
1120
|
+
await client.connect(await getWebSocketUrl(), signal);
|
|
1121
|
+
this.root = client;
|
|
1122
|
+
client.onClose(() => {
|
|
1123
|
+
if (this.root !== client)
|
|
1124
|
+
return;
|
|
1125
|
+
this.root = undefined;
|
|
1126
|
+
});
|
|
1127
|
+
return client;
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
// src/browser/artifacts.ts
|
|
1132
|
+
import {
|
|
1133
|
+
mkdir,
|
|
1134
|
+
readdir,
|
|
1135
|
+
readFile,
|
|
1136
|
+
rm,
|
|
1137
|
+
stat,
|
|
1138
|
+
writeFile
|
|
1139
|
+
} from "node:fs/promises";
|
|
1140
|
+
import { tmpdir } from "node:os";
|
|
1141
|
+
import { join as join2 } from "node:path";
|
|
1142
|
+
var RESULT_TTL_MS = 60 * 60 * 1000;
|
|
1143
|
+
var SCREENSHOT_TTL_MS = 24 * 60 * 60 * 1000;
|
|
1144
|
+
var TEXT_BUDGET_BYTES = 32000;
|
|
1145
|
+
function artifactDirectory() {
|
|
1146
|
+
return process.env["XDG_RUNTIME_DIR"] ? join2(process.env["XDG_RUNTIME_DIR"], "browser-tool") : join2(tmpdir(), `browser-tool-${process.getuid?.() ?? "user"}`);
|
|
1147
|
+
}
|
|
1148
|
+
function resultPath(handle) {
|
|
1149
|
+
return join2(artifactDirectory(), `result-${handle}.txt`);
|
|
1150
|
+
}
|
|
1151
|
+
async function screenshotPath(request) {
|
|
1152
|
+
await mkdir(artifactDirectory(), {
|
|
1153
|
+
recursive: true,
|
|
1154
|
+
mode: 448
|
|
1155
|
+
});
|
|
1156
|
+
const suffix = request.id !== undefined ? `-element-${request.id}` : request.selector ? "-element" : "";
|
|
1157
|
+
const safeRef = request.ref_id.slice(0, 12).replace(/[^A-Za-z0-9_-]/g, "_");
|
|
1158
|
+
return join2(artifactDirectory(), `browser-${safeRef}${suffix}-${crypto.randomUUID()}.png`);
|
|
1159
|
+
}
|
|
1160
|
+
async function pruneArtifacts(now = Date.now()) {
|
|
1161
|
+
let names;
|
|
1162
|
+
try {
|
|
1163
|
+
names = await readdir(artifactDirectory());
|
|
1164
|
+
} catch (error) {
|
|
1165
|
+
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
|
|
1166
|
+
return 0;
|
|
1167
|
+
}
|
|
1168
|
+
throw error;
|
|
1169
|
+
}
|
|
1170
|
+
let removed = 0;
|
|
1171
|
+
for (const name of names.filter((candidate) => /^(?:result-[a-f0-9-]{36}\.txt|browser-.*\.png)$/.test(candidate))) {
|
|
1172
|
+
const path = join2(artifactDirectory(), name);
|
|
1173
|
+
try {
|
|
1174
|
+
const maxAge = name.startsWith("result-") ? RESULT_TTL_MS : SCREENSHOT_TTL_MS;
|
|
1175
|
+
if (now - (await stat(path)).mtimeMs > maxAge) {
|
|
1176
|
+
await rm(path, { force: true });
|
|
1177
|
+
removed++;
|
|
1178
|
+
}
|
|
1179
|
+
} catch (error) {
|
|
1180
|
+
if (!error || typeof error !== "object" || !("code" in error) || error.code !== "ENOENT") {
|
|
1181
|
+
throw error;
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
return removed;
|
|
1186
|
+
}
|
|
1187
|
+
function chunkForJson(value, offset2 = 0, budget = TEXT_BUDGET_BYTES) {
|
|
1188
|
+
let bytes = 2;
|
|
1189
|
+
let end = offset2;
|
|
1190
|
+
for (const character of value.slice(offset2)) {
|
|
1191
|
+
const next = Buffer.byteLength(JSON.stringify(character)) - 2;
|
|
1192
|
+
if (bytes + next > budget)
|
|
1193
|
+
break;
|
|
1194
|
+
bytes += next;
|
|
1195
|
+
end += character.length;
|
|
1196
|
+
}
|
|
1197
|
+
return { text: value.slice(offset2, end), end };
|
|
1198
|
+
}
|
|
1199
|
+
async function cacheResult(value) {
|
|
1200
|
+
const handle = crypto.randomUUID();
|
|
1201
|
+
await mkdir(artifactDirectory(), {
|
|
1202
|
+
recursive: true,
|
|
1203
|
+
mode: 448
|
|
1204
|
+
});
|
|
1205
|
+
await writeFile(resultPath(handle), value, { mode: 384 });
|
|
1206
|
+
return handle;
|
|
1207
|
+
}
|
|
1208
|
+
async function limitedText(base, field, value) {
|
|
1209
|
+
const chunk = chunkForJson(value);
|
|
1210
|
+
if (chunk.end >= value.length)
|
|
1211
|
+
return { ...base, [field]: value };
|
|
1212
|
+
const handle = await cacheResult(value);
|
|
1213
|
+
return {
|
|
1214
|
+
...base,
|
|
1215
|
+
[field]: chunk.text,
|
|
1216
|
+
truncated: true,
|
|
1217
|
+
omitted_chars: value.length - chunk.end,
|
|
1218
|
+
result_handle: handle,
|
|
1219
|
+
next_offset: chunk.end
|
|
1220
|
+
};
|
|
1221
|
+
}
|
|
1222
|
+
async function readCachedResult(request) {
|
|
1223
|
+
let value;
|
|
1224
|
+
try {
|
|
1225
|
+
value = await readFile(resultPath(request.handle), "utf8");
|
|
1226
|
+
} catch (error) {
|
|
1227
|
+
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
|
|
1228
|
+
throw new Error(`result handle not found: ${request.handle}; check the host or rerun the original action`);
|
|
1229
|
+
}
|
|
1230
|
+
throw error;
|
|
1231
|
+
}
|
|
1232
|
+
if (request.offset > value.length) {
|
|
1233
|
+
throw new Error(`offset ${request.offset} exceeds result length ${value.length}`);
|
|
1234
|
+
}
|
|
1235
|
+
const chunk = chunkForJson(value, request.offset);
|
|
1236
|
+
const complete = chunk.end >= value.length;
|
|
1237
|
+
if (complete) {
|
|
1238
|
+
await rm(resultPath(request.handle), { force: true });
|
|
1239
|
+
}
|
|
1240
|
+
return {
|
|
1241
|
+
handle: request.handle,
|
|
1242
|
+
offset: request.offset,
|
|
1243
|
+
text: chunk.text,
|
|
1244
|
+
complete,
|
|
1245
|
+
...complete ? {} : { next_offset: chunk.end }
|
|
1246
|
+
};
|
|
1247
|
+
}
|
|
1248
|
+
async function discardCachedResult(handle) {
|
|
1249
|
+
await rm(resultPath(handle), { force: true });
|
|
1250
|
+
return { discarded: handle };
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
// src/browser/help.ts
|
|
1254
|
+
function browserHelp(hosts = []) {
|
|
1255
|
+
const routed = hosts.length > 0;
|
|
1256
|
+
return {
|
|
1257
|
+
input: "Code=JSON.stringify(request); normal=request",
|
|
1258
|
+
...routed ? { host: `${hosts.join("|")} optional` } : {},
|
|
1259
|
+
batch: "top-level nonempty action arrays; items omit action/host/response_length; independent only",
|
|
1260
|
+
actions: {
|
|
1261
|
+
tabs: "query? offset? -> ref_id title url",
|
|
1262
|
+
open: "ref_id lineno? response_length? | url",
|
|
1263
|
+
find: "ref_id pattern lineno? response_length?",
|
|
1264
|
+
click: "ref_id id|selector|x+y",
|
|
1265
|
+
type: "ref_id text id?; id focuses",
|
|
1266
|
+
screenshot: "ref_id id?|selector? -> file",
|
|
1267
|
+
navigate: "ref_id url",
|
|
1268
|
+
html: "ref_id id?|selector?",
|
|
1269
|
+
evaluate: "ref_id expression",
|
|
1270
|
+
network: "ref_id",
|
|
1271
|
+
load_all: "ref_id selector interval_ms?",
|
|
1272
|
+
raw: "ref_id method params?",
|
|
1273
|
+
start: "",
|
|
1274
|
+
stop: "ref_id?",
|
|
1275
|
+
read_result: `handle offset${routed ? "; same host" : ""}`,
|
|
1276
|
+
discard_result: `handle${routed ? "; same host" : ""}`
|
|
1277
|
+
},
|
|
1278
|
+
continue: "next_lineno/next_offset; response_length=short|medium|long"
|
|
1279
|
+
};
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1282
|
+
// src/cdp/snapshot-contract.ts
|
|
1283
|
+
var SNAPSHOT_LIMITS = {
|
|
1284
|
+
short: 60,
|
|
1285
|
+
medium: 140,
|
|
1286
|
+
long: 300
|
|
1287
|
+
};
|
|
1288
|
+
function positiveInteger(value, label) {
|
|
1289
|
+
const source = String(value);
|
|
1290
|
+
if (!/^[1-9]\d*$/.test(source)) {
|
|
1291
|
+
throw new Error(`${label} must be a positive integer`);
|
|
1292
|
+
}
|
|
1293
|
+
const parsed = Number(source);
|
|
1294
|
+
if (!Number.isSafeInteger(parsed)) {
|
|
1295
|
+
throw new Error(`${label} must be a safe positive integer`);
|
|
1296
|
+
}
|
|
1297
|
+
return parsed;
|
|
1298
|
+
}
|
|
1299
|
+
function snapshotResponseLength(value) {
|
|
1300
|
+
const resolved = value ?? "medium";
|
|
1301
|
+
if (resolved !== "short" && resolved !== "medium" && resolved !== "long") {
|
|
1302
|
+
throw new Error(`response length must be one of: ${Object.keys(SNAPSHOT_LIMITS).join(", ")}`);
|
|
1303
|
+
}
|
|
1304
|
+
return resolved;
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
// src/cdp/actions/element.ts
|
|
1308
|
+
function requireElementRef(elementRefs, id) {
|
|
1309
|
+
const parsed = positiveInteger(id, "element id");
|
|
1310
|
+
const backendNodeId = elementRefs.get(parsed);
|
|
1311
|
+
if (!backendNodeId) {
|
|
1312
|
+
throw new Error(`Unknown element id ${id}; run open again and use a current element id`);
|
|
1313
|
+
}
|
|
1314
|
+
return { id: parsed, backendNodeId };
|
|
1315
|
+
}
|
|
1316
|
+
async function resolveBackendObject(cdp, sessionId, backendNodeId, signal) {
|
|
1317
|
+
const response = asRecord(await cdp.send("DOM.resolveNode", { backendNodeId }, sessionId, signal), "DOM.resolveNode response");
|
|
1318
|
+
const object = asRecord(response["object"], "resolved DOM object");
|
|
1319
|
+
if (typeof object["objectId"] !== "string") {
|
|
1320
|
+
throw new Error("Element is no longer available; run open again");
|
|
1321
|
+
}
|
|
1322
|
+
return object["objectId"];
|
|
1323
|
+
}
|
|
1324
|
+
async function withBackendObject(cdp, sessionId, backendNodeId, action, signal) {
|
|
1325
|
+
const objectId = await resolveBackendObject(cdp, sessionId, backendNodeId, signal);
|
|
1326
|
+
try {
|
|
1327
|
+
return await action(objectId);
|
|
1328
|
+
} finally {
|
|
1329
|
+
await cdp.send("Runtime.releaseObject", { objectId }, sessionId, undefined).catch(() => {
|
|
1330
|
+
return;
|
|
1331
|
+
});
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
async function scrollBackendIntoView(cdp, sessionId, backendNodeId, signal) {
|
|
1335
|
+
await withBackendObject(cdp, sessionId, backendNodeId, (objectId) => cdp.send("Runtime.callFunctionOn", {
|
|
1336
|
+
objectId,
|
|
1337
|
+
functionDeclaration: 'function() { this.scrollIntoView({block: "center", inline: "center"}); }'
|
|
1338
|
+
}, sessionId, signal), signal);
|
|
1339
|
+
await sleep(50, signal);
|
|
1340
|
+
}
|
|
1341
|
+
async function backendCenter(cdp, sessionId, backendNodeId, scroll = true, signal) {
|
|
1342
|
+
if (scroll) {
|
|
1343
|
+
await scrollBackendIntoView(cdp, sessionId, backendNodeId, signal);
|
|
1344
|
+
}
|
|
1345
|
+
const response = await withBackendObject(cdp, sessionId, backendNodeId, (objectId) => cdp.send("Runtime.callFunctionOn", {
|
|
1346
|
+
objectId,
|
|
1347
|
+
functionDeclaration: `function() {
|
|
1348
|
+
const rect = this.getBoundingClientRect();
|
|
1349
|
+
const style = getComputedStyle(this);
|
|
1350
|
+
const disabled = this.matches(':disabled') ||
|
|
1351
|
+
this.getAttribute('aria-disabled') === 'true';
|
|
1352
|
+
const hidden = rect.width <= 0 || rect.height <= 0 ||
|
|
1353
|
+
style.display === 'none' || style.visibility === 'hidden' ||
|
|
1354
|
+
style.visibility === 'collapse' || style.pointerEvents === 'none' ||
|
|
1355
|
+
Number(style.opacity) === 0 || this.closest('[inert]') !== null;
|
|
1356
|
+
if (hidden) return { ok: false, error: 'Element is not visible or interactable' };
|
|
1357
|
+
if (disabled) return { ok: false, error: 'Element is disabled' };
|
|
1358
|
+
const x = rect.left + rect.width / 2;
|
|
1359
|
+
const y = rect.top + rect.height / 2;
|
|
1360
|
+
const root = this.getRootNode();
|
|
1361
|
+
const hit = root && typeof root.elementFromPoint === 'function'
|
|
1362
|
+
? root.elementFromPoint(x, y)
|
|
1363
|
+
: this.ownerDocument.elementFromPoint(x, y);
|
|
1364
|
+
if (!hit || (hit !== this && !this.contains(hit))) {
|
|
1365
|
+
const blocker = hit ? '<' + hit.tagName.toLowerCase() + '>' : 'no element';
|
|
1366
|
+
return { ok: false, error: 'Element center is covered by ' + blocker };
|
|
1367
|
+
}
|
|
1368
|
+
return {
|
|
1369
|
+
ok: true,
|
|
1370
|
+
x,
|
|
1371
|
+
y,
|
|
1372
|
+
tag: this.tagName,
|
|
1373
|
+
text: (this.textContent || '').trim().substring(0, 80)
|
|
1374
|
+
};
|
|
1375
|
+
}`,
|
|
1376
|
+
returnByValue: true
|
|
1377
|
+
}, sessionId, signal), signal);
|
|
1378
|
+
const result = asRecord(response, "element center response");
|
|
1379
|
+
const point = asRecord(asRecord(result["result"], "element center result")["value"], "element center");
|
|
1380
|
+
if (point["ok"] !== true) {
|
|
1381
|
+
throw new Error(typeof point["error"] === "string" ? point["error"] : "Element has no clickable box");
|
|
1382
|
+
}
|
|
1383
|
+
if (typeof point["x"] !== "number" || typeof point["y"] !== "number") {
|
|
1384
|
+
throw new Error("Element center has invalid coordinates");
|
|
1385
|
+
}
|
|
1386
|
+
return {
|
|
1387
|
+
x: point["x"],
|
|
1388
|
+
y: point["y"],
|
|
1389
|
+
tag: typeof point["tag"] === "string" ? point["tag"] : "ELEMENT",
|
|
1390
|
+
text: typeof point["text"] === "string" ? point["text"] : ""
|
|
1391
|
+
};
|
|
1392
|
+
}
|
|
1393
|
+
async function visibleElementClip(cdp, sessionId, quad, padding = 10, signal) {
|
|
1394
|
+
const response = asRecord(await cdp.send("Page.getLayoutMetrics", {}, sessionId, signal), "layout metrics");
|
|
1395
|
+
const viewportValue = response["cssVisualViewport"] ?? response["visualViewport"] ?? response["cssLayoutViewport"] ?? response["layoutViewport"];
|
|
1396
|
+
const viewport = asRecord(viewportValue, "layout viewport");
|
|
1397
|
+
if (typeof viewport["clientWidth"] !== "number" || typeof viewport["clientHeight"] !== "number" || viewport["clientWidth"] <= 0 || viewport["clientHeight"] <= 0) {
|
|
1398
|
+
throw new Error("Could not determine a bounded screenshot viewport");
|
|
1399
|
+
}
|
|
1400
|
+
const pageX = typeof viewport["pageX"] === "number" ? viewport["pageX"] : 0;
|
|
1401
|
+
const pageY = typeof viewport["pageY"] === "number" ? viewport["pageY"] : 0;
|
|
1402
|
+
const xs = [quad[0], quad[2], quad[4], quad[6]].filter((value) => typeof value === "number");
|
|
1403
|
+
const ys = [quad[1], quad[3], quad[5], quad[7]].filter((value) => typeof value === "number");
|
|
1404
|
+
if (xs.length !== 4 || ys.length !== 4) {
|
|
1405
|
+
throw new Error("Element has an invalid screenshot box");
|
|
1406
|
+
}
|
|
1407
|
+
const x = Math.max(pageX, Math.min(...xs) - padding);
|
|
1408
|
+
const y = Math.max(pageY, Math.min(...ys) - padding);
|
|
1409
|
+
const right = Math.min(pageX + viewport["clientWidth"], Math.max(...xs) + padding);
|
|
1410
|
+
const bottom = Math.min(pageY + viewport["clientHeight"], Math.max(...ys) + padding);
|
|
1411
|
+
if (right <= x || bottom <= y) {
|
|
1412
|
+
throw new Error("Element has no visible screenshot box");
|
|
1413
|
+
}
|
|
1414
|
+
return {
|
|
1415
|
+
x,
|
|
1416
|
+
y,
|
|
1417
|
+
width: right - x,
|
|
1418
|
+
height: bottom - y,
|
|
1419
|
+
scale: 1
|
|
1420
|
+
};
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
// src/cdp/actions/selector.ts
|
|
1424
|
+
async function selectorBackendNode(cdp, sessionId, selector, signal) {
|
|
1425
|
+
await cdp.send("Runtime.enable", {}, sessionId, signal);
|
|
1426
|
+
const selected = asRecord(await cdp.send("Runtime.evaluate", {
|
|
1427
|
+
expression: `(() => {
|
|
1428
|
+
const selector = ${JSON.stringify(selector)};
|
|
1429
|
+
const matches = document.querySelectorAll(selector);
|
|
1430
|
+
if (matches.length === 0) throw new Error('Element not found: ' + selector);
|
|
1431
|
+
if (matches.length > 1) throw new Error(
|
|
1432
|
+
'Selector matched ' + matches.length + ' elements: ' + selector
|
|
1433
|
+
);
|
|
1434
|
+
return matches[0];
|
|
1435
|
+
})()`,
|
|
1436
|
+
returnByValue: false,
|
|
1437
|
+
awaitPromise: true
|
|
1438
|
+
}, sessionId, signal), "selector response");
|
|
1439
|
+
if (selected["exceptionDetails"]) {
|
|
1440
|
+
const details = asRecord(selected["exceptionDetails"], "selector exception");
|
|
1441
|
+
throw new Error(typeof details["text"] === "string" ? details["text"] : `Could not select ${selector}`);
|
|
1442
|
+
}
|
|
1443
|
+
const result = asRecord(selected["result"], "selector result");
|
|
1444
|
+
if (typeof result["objectId"] !== "string") {
|
|
1445
|
+
throw new Error(`Element is no longer available: ${selector}`);
|
|
1446
|
+
}
|
|
1447
|
+
const objectId = result["objectId"];
|
|
1448
|
+
try {
|
|
1449
|
+
const described = asRecord(await cdp.send("DOM.describeNode", { objectId }, sessionId, signal), "DOM.describeNode response");
|
|
1450
|
+
const node = asRecord(described["node"], "described node");
|
|
1451
|
+
if (typeof node["backendNodeId"] !== "number") {
|
|
1452
|
+
throw new Error(`Element is no longer available: ${selector}`);
|
|
1453
|
+
}
|
|
1454
|
+
return node["backendNodeId"];
|
|
1455
|
+
} finally {
|
|
1456
|
+
await cdp.send("Runtime.releaseObject", { objectId }, sessionId, undefined).catch(() => {
|
|
1457
|
+
return;
|
|
1458
|
+
});
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
// src/cdp/actions/click.ts
|
|
1463
|
+
function dispatchMouse(cdp, sessionId, type, point, signal) {
|
|
1464
|
+
return cdp.send("Input.dispatchMouseEvent", {
|
|
1465
|
+
x: point.x,
|
|
1466
|
+
y: point.y,
|
|
1467
|
+
button: "left",
|
|
1468
|
+
clickCount: 1,
|
|
1469
|
+
modifiers: 0,
|
|
1470
|
+
type
|
|
1471
|
+
}, sessionId, signal);
|
|
1472
|
+
}
|
|
1473
|
+
async function pressAndRelease(cdp, sessionId, point, signal) {
|
|
1474
|
+
let pressed = false;
|
|
1475
|
+
try {
|
|
1476
|
+
await dispatchMouse(cdp, sessionId, "mousePressed", point, signal);
|
|
1477
|
+
pressed = true;
|
|
1478
|
+
await sleep(50, signal);
|
|
1479
|
+
await dispatchMouse(cdp, sessionId, "mouseReleased", point, signal);
|
|
1480
|
+
pressed = false;
|
|
1481
|
+
} finally {
|
|
1482
|
+
if (pressed) {
|
|
1483
|
+
await dispatchMouse(cdp, sessionId, "mouseReleased", point, undefined).catch(() => {
|
|
1484
|
+
return;
|
|
1485
|
+
});
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
}
|
|
1489
|
+
async function clickBackendNode(cdp, sessionId, backendNodeId, signal) {
|
|
1490
|
+
const initial = await backendCenter(cdp, sessionId, backendNodeId, true, signal);
|
|
1491
|
+
await dispatchMouse(cdp, sessionId, "mouseMoved", initial, signal);
|
|
1492
|
+
const point = await backendCenter(cdp, sessionId, backendNodeId, false, signal);
|
|
1493
|
+
await pressAndRelease(cdp, sessionId, point, signal);
|
|
1494
|
+
return point;
|
|
1495
|
+
}
|
|
1496
|
+
async function clickSelector(cdp, sessionId, selector, signal) {
|
|
1497
|
+
if (!selector)
|
|
1498
|
+
throw new Error("CSS selector required");
|
|
1499
|
+
const backendNodeId = await selectorBackendNode(cdp, sessionId, selector, signal);
|
|
1500
|
+
const point = await clickBackendNode(cdp, sessionId, backendNodeId, signal);
|
|
1501
|
+
return `Clicked <${point.tag}> "${point.text}"`;
|
|
1502
|
+
}
|
|
1503
|
+
async function clickRef(cdp, sessionId, elementRefs, id, signal) {
|
|
1504
|
+
const ref = requireElementRef(elementRefs, id);
|
|
1505
|
+
await clickBackendNode(cdp, sessionId, ref.backendNodeId, signal);
|
|
1506
|
+
return `Clicked element ${ref.id}`;
|
|
1507
|
+
}
|
|
1508
|
+
async function clickCoordinates(cdp, sessionId, x, y, signal) {
|
|
1509
|
+
if (!Number.isFinite(x) || !Number.isFinite(y)) {
|
|
1510
|
+
throw new Error("x and y must be finite CSS-pixel numbers");
|
|
1511
|
+
}
|
|
1512
|
+
const point = { x, y };
|
|
1513
|
+
await dispatchMouse(cdp, sessionId, "mouseMoved", point, signal);
|
|
1514
|
+
await pressAndRelease(cdp, sessionId, point, signal);
|
|
1515
|
+
return `Clicked at CSS (${x}, ${y})`;
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
// src/cdp/evaluate.ts
|
|
1519
|
+
async function evaluate(cdp, sessionId, expression, signal) {
|
|
1520
|
+
await cdp.send("Runtime.enable", {}, sessionId, signal);
|
|
1521
|
+
const response = asRecord(await cdp.send("Runtime.evaluate", {
|
|
1522
|
+
expression,
|
|
1523
|
+
returnByValue: true,
|
|
1524
|
+
awaitPromise: true
|
|
1525
|
+
}, sessionId, signal), "Runtime.evaluate response");
|
|
1526
|
+
const exception = response["exceptionDetails"];
|
|
1527
|
+
if (exception) {
|
|
1528
|
+
const details = asRecord(exception, "Runtime exception");
|
|
1529
|
+
const nested = details["exception"] && typeof details["exception"] === "object" && !Array.isArray(details["exception"]) ? details["exception"] : undefined;
|
|
1530
|
+
throw new Error(typeof details["text"] === "string" ? details["text"] : typeof nested?.["description"] === "string" ? nested["description"] : "Runtime evaluation failed");
|
|
1531
|
+
}
|
|
1532
|
+
const result = asRecord(response["result"], "Runtime result");
|
|
1533
|
+
return result["value"];
|
|
1534
|
+
}
|
|
1535
|
+
async function evaluateText(cdp, sessionId, expression, signal) {
|
|
1536
|
+
const value = await evaluate(cdp, sessionId, expression, signal);
|
|
1537
|
+
return typeof value === "object" && value !== null ? JSON.stringify(value, null, 2) : String(value ?? "");
|
|
1538
|
+
}
|
|
1539
|
+
|
|
1540
|
+
// src/cdp/actions/page.ts
|
|
1541
|
+
async function html(cdp, sessionId, selector, signal) {
|
|
1542
|
+
if (!selector) {
|
|
1543
|
+
return evaluateText(cdp, sessionId, "document.documentElement.outerHTML", signal);
|
|
1544
|
+
}
|
|
1545
|
+
const value = asRecord(await evaluate(cdp, sessionId, `(() => {
|
|
1546
|
+
const element = document.querySelector(${JSON.stringify(selector)});
|
|
1547
|
+
return element
|
|
1548
|
+
? { ok: true, html: element.outerHTML }
|
|
1549
|
+
: { ok: false };
|
|
1550
|
+
})()`, signal), "HTML result");
|
|
1551
|
+
if (value["ok"] !== true || typeof value["html"] !== "string") {
|
|
1552
|
+
throw new Error(`Element not found: ${selector}`);
|
|
1553
|
+
}
|
|
1554
|
+
return value["html"];
|
|
1555
|
+
}
|
|
1556
|
+
async function htmlRef(cdp, sessionId, elementRefs, id, signal) {
|
|
1557
|
+
const ref = requireElementRef(elementRefs, id);
|
|
1558
|
+
const response = await withBackendObject(cdp, sessionId, ref.backendNodeId, (objectId) => cdp.send("Runtime.callFunctionOn", {
|
|
1559
|
+
objectId,
|
|
1560
|
+
functionDeclaration: "function() { return this.outerHTML; }",
|
|
1561
|
+
returnByValue: true
|
|
1562
|
+
}, sessionId, signal), signal);
|
|
1563
|
+
const record = asRecord(response, "HTML element response");
|
|
1564
|
+
const result = asRecord(record["result"], "HTML element result");
|
|
1565
|
+
return typeof result["value"] === "string" ? result["value"] : "";
|
|
1566
|
+
}
|
|
1567
|
+
async function waitForDocumentReady(cdp, sessionId, timeout = NAVIGATION_TIMEOUT_MS, signal) {
|
|
1568
|
+
const deadline = Date.now() + timeout;
|
|
1569
|
+
let lastState = "";
|
|
1570
|
+
let lastError;
|
|
1571
|
+
while (Date.now() < deadline) {
|
|
1572
|
+
try {
|
|
1573
|
+
lastState = await evaluateText(cdp, sessionId, "document.readyState", signal);
|
|
1574
|
+
if (lastState === "complete")
|
|
1575
|
+
return;
|
|
1576
|
+
} catch (error) {
|
|
1577
|
+
lastError = error;
|
|
1578
|
+
}
|
|
1579
|
+
await sleep(200, signal);
|
|
1580
|
+
}
|
|
1581
|
+
if (lastState) {
|
|
1582
|
+
throw new Error(`Timed out waiting for navigation to finish (last readyState: ${lastState})`);
|
|
1583
|
+
}
|
|
1584
|
+
if (lastError instanceof Error) {
|
|
1585
|
+
throw new Error(`Timed out waiting for navigation to finish (${lastError.message})`);
|
|
1586
|
+
}
|
|
1587
|
+
throw new Error("Timed out waiting for navigation to finish");
|
|
1588
|
+
}
|
|
1589
|
+
async function navigate(cdp, sessionId, url, signal) {
|
|
1590
|
+
assertHttpUrl(url);
|
|
1591
|
+
await cdp.send("Page.enable", {}, sessionId, signal);
|
|
1592
|
+
const loadEvent = cdp.waitForEvent("Page.loadEventFired", NAVIGATION_TIMEOUT_MS, signal);
|
|
1593
|
+
let responseValue;
|
|
1594
|
+
try {
|
|
1595
|
+
responseValue = await cdp.send("Page.navigate", { url }, sessionId, signal);
|
|
1596
|
+
} catch (error) {
|
|
1597
|
+
cancelEventWait(loadEvent);
|
|
1598
|
+
throw error;
|
|
1599
|
+
}
|
|
1600
|
+
const response = asRecord(responseValue, "Page.navigate response");
|
|
1601
|
+
if (typeof response["errorText"] === "string") {
|
|
1602
|
+
cancelEventWait(loadEvent);
|
|
1603
|
+
throw new Error(response["errorText"]);
|
|
1604
|
+
}
|
|
1605
|
+
if (response["loaderId"])
|
|
1606
|
+
await loadEvent.promise;
|
|
1607
|
+
else
|
|
1608
|
+
cancelEventWait(loadEvent);
|
|
1609
|
+
await waitForDocumentReady(cdp, sessionId, 5000, signal);
|
|
1610
|
+
return `Navigated to ${url}`;
|
|
1611
|
+
}
|
|
1612
|
+
function cancelEventWait(wait) {
|
|
1613
|
+
wait.cancel();
|
|
1614
|
+
wait.promise.catch(() => {
|
|
1615
|
+
return;
|
|
1616
|
+
});
|
|
1617
|
+
}
|
|
1618
|
+
async function networkEntries(cdp, sessionId, signal) {
|
|
1619
|
+
const value = await evaluate(cdp, sessionId, `performance.getEntriesByType('resource').map(e => ({
|
|
1620
|
+
name: e.name.substring(0, 120),
|
|
1621
|
+
type: e.initiatorType,
|
|
1622
|
+
duration: Math.round(e.duration),
|
|
1623
|
+
size: e.transferSize
|
|
1624
|
+
}))`, signal);
|
|
1625
|
+
if (!Array.isArray(value)) {
|
|
1626
|
+
throw new Error("Browser resource timing is not an array");
|
|
1627
|
+
}
|
|
1628
|
+
return value.map((entry) => {
|
|
1629
|
+
const record = asRecord(entry, "resource timing entry");
|
|
1630
|
+
const duration = typeof record["duration"] === "number" ? record["duration"] : 0;
|
|
1631
|
+
const size = typeof record["size"] === "number" ? String(record["size"]) : "?";
|
|
1632
|
+
const type = typeof record["type"] === "string" ? record["type"] : "";
|
|
1633
|
+
const name = typeof record["name"] === "string" ? record["name"] : "";
|
|
1634
|
+
return `${String(duration).padStart(5)}ms ${size.padStart(8)}B ${type.padEnd(8)} ${name}`;
|
|
1635
|
+
}).join(`
|
|
1636
|
+
`);
|
|
1637
|
+
}
|
|
1638
|
+
async function loadAll(cdp, sessionId, selector, intervalMs = 1500, signal) {
|
|
1639
|
+
if (!selector)
|
|
1640
|
+
throw new Error("CSS selector required");
|
|
1641
|
+
let clicks = 0;
|
|
1642
|
+
const deadline = Date.now() + 5 * 60 * 1000;
|
|
1643
|
+
while (Date.now() < deadline) {
|
|
1644
|
+
const exists = await evaluate(cdp, sessionId, `!!document.querySelector(${JSON.stringify(selector)})`, signal);
|
|
1645
|
+
if (exists !== true) {
|
|
1646
|
+
return `Clicked "${selector}" ${clicks} time(s) until it disappeared`;
|
|
1647
|
+
}
|
|
1648
|
+
await clickSelector(cdp, sessionId, selector, signal);
|
|
1649
|
+
clicks++;
|
|
1650
|
+
await sleep(intervalMs, signal);
|
|
1651
|
+
}
|
|
1652
|
+
return `Clicked "${selector}" ${clicks} time(s); stopped at the five-minute deadline while it was still present`;
|
|
1653
|
+
}
|
|
1654
|
+
async function rawCommand(cdp, sessionId, method, params, signal) {
|
|
1655
|
+
if (!method) {
|
|
1656
|
+
throw new Error('CDP method required, for example "DOM.getDocument"');
|
|
1657
|
+
}
|
|
1658
|
+
const result = await cdp.send(method, params, sessionId, signal);
|
|
1659
|
+
return JSON.stringify(result, null, 2);
|
|
1660
|
+
}
|
|
1661
|
+
|
|
1662
|
+
// src/cdp/actions/screenshot.ts
|
|
1663
|
+
import { writeFileSync as writeFileSync2 } from "node:fs";
|
|
1664
|
+
async function devicePixelRatio(cdp, sessionId, signal) {
|
|
1665
|
+
try {
|
|
1666
|
+
const value = await evaluate(cdp, sessionId, "window.devicePixelRatio", signal);
|
|
1667
|
+
if (typeof value === "number" && value > 0)
|
|
1668
|
+
return value;
|
|
1669
|
+
} catch {}
|
|
1670
|
+
return 1;
|
|
1671
|
+
}
|
|
1672
|
+
async function capture(cdp, sessionId, file, clip, signal) {
|
|
1673
|
+
const response = asRecord(await cdp.send("Page.captureScreenshot", {
|
|
1674
|
+
format: "png",
|
|
1675
|
+
...clip ? { clip, captureBeyondViewport: false } : {}
|
|
1676
|
+
}, sessionId, signal), "screenshot response");
|
|
1677
|
+
const data = asString(response["data"], "screenshot data");
|
|
1678
|
+
writeFileSync2(file, Buffer.from(data, "base64"));
|
|
1679
|
+
return {
|
|
1680
|
+
file,
|
|
1681
|
+
dpr: await devicePixelRatio(cdp, sessionId, signal),
|
|
1682
|
+
...clip ? { width: clip.width, height: clip.height } : {}
|
|
1683
|
+
};
|
|
1684
|
+
}
|
|
1685
|
+
function captureViewport(cdp, sessionId, file, signal) {
|
|
1686
|
+
return capture(cdp, sessionId, file, undefined, signal);
|
|
1687
|
+
}
|
|
1688
|
+
async function captureSelector(cdp, sessionId, selector, file, signal) {
|
|
1689
|
+
if (!selector)
|
|
1690
|
+
throw new Error("CSS selector required");
|
|
1691
|
+
const value = asRecord(await evaluate(cdp, sessionId, `(() => {
|
|
1692
|
+
const el = document.querySelector(${JSON.stringify(selector)});
|
|
1693
|
+
if (!el) return {
|
|
1694
|
+
ok: false,
|
|
1695
|
+
error: 'Element not found: ' + ${JSON.stringify(selector)}
|
|
1696
|
+
};
|
|
1697
|
+
el.scrollIntoView({ block: 'center', inline: 'center' });
|
|
1698
|
+
const r = el.getBoundingClientRect();
|
|
1699
|
+
const padding = 10;
|
|
1700
|
+
const x = Math.max(0, r.left - padding);
|
|
1701
|
+
const y = Math.max(0, r.top - padding);
|
|
1702
|
+
const right = Math.min(window.innerWidth, r.right + padding);
|
|
1703
|
+
const bottom = Math.min(window.innerHeight, r.bottom + padding);
|
|
1704
|
+
return {
|
|
1705
|
+
ok: true,
|
|
1706
|
+
clip: {
|
|
1707
|
+
x,
|
|
1708
|
+
y,
|
|
1709
|
+
width: Math.max(1, right - x),
|
|
1710
|
+
height: Math.max(1, bottom - y),
|
|
1711
|
+
scale: 1
|
|
1712
|
+
}
|
|
1713
|
+
};
|
|
1714
|
+
})()`, signal), "element screenshot geometry");
|
|
1715
|
+
if (value["ok"] !== true) {
|
|
1716
|
+
throw new Error(typeof value["error"] === "string" ? value["error"] : `Could not capture ${selector}`);
|
|
1717
|
+
}
|
|
1718
|
+
const clipRecord = asRecord(value["clip"], "element screenshot clip");
|
|
1719
|
+
const [x, y, width, height] = ["x", "y", "width", "height"].map((field) => Number(clipRecord[field]));
|
|
1720
|
+
if (x === undefined || y === undefined || width === undefined || height === undefined || ![x, y, width, height].every(Number.isFinite) || width <= 0 || height <= 0) {
|
|
1721
|
+
throw new Error("Element has an invalid screenshot box");
|
|
1722
|
+
}
|
|
1723
|
+
const clip = {
|
|
1724
|
+
x,
|
|
1725
|
+
y,
|
|
1726
|
+
width,
|
|
1727
|
+
height,
|
|
1728
|
+
scale: 1
|
|
1729
|
+
};
|
|
1730
|
+
return capture(cdp, sessionId, file, clip, signal);
|
|
1731
|
+
}
|
|
1732
|
+
async function captureRef(cdp, sessionId, elementRefs, id, file, signal) {
|
|
1733
|
+
const ref = requireElementRef(elementRefs, id);
|
|
1734
|
+
await scrollBackendIntoView(cdp, sessionId, ref.backendNodeId, signal);
|
|
1735
|
+
const response = asRecord(await cdp.send("DOM.getBoxModel", { backendNodeId: ref.backendNodeId }, sessionId, signal), "DOM box model");
|
|
1736
|
+
const model = asRecord(response["model"], "DOM box model");
|
|
1737
|
+
const border = model["border"];
|
|
1738
|
+
if (!Array.isArray(border) || !border.every((value) => typeof value === "number")) {
|
|
1739
|
+
throw new Error("Element has no screenshot box");
|
|
1740
|
+
}
|
|
1741
|
+
const clip = await visibleElementClip(cdp, sessionId, border, 10, signal);
|
|
1742
|
+
return capture(cdp, sessionId, file, clip, signal);
|
|
1743
|
+
}
|
|
1744
|
+
|
|
1745
|
+
// src/cdp/actions/type.ts
|
|
1746
|
+
async function typeAtFocus(cdp, sessionId, text, signal) {
|
|
1747
|
+
if (!text)
|
|
1748
|
+
throw new Error("text required");
|
|
1749
|
+
const focusState = asRecord(await evaluate(cdp, sessionId, `(() => {
|
|
1750
|
+
const el = document.activeElement;
|
|
1751
|
+
if (!el || el === document.body || el === document.documentElement)
|
|
1752
|
+
return { ok: false, error: 'No editable element is focused' };
|
|
1753
|
+
const tag = el.tagName;
|
|
1754
|
+
const inputTypes = new Set([
|
|
1755
|
+
'text', 'search', 'email', 'url', 'tel', 'password', 'number'
|
|
1756
|
+
]);
|
|
1757
|
+
const input = tag === 'INPUT' &&
|
|
1758
|
+
inputTypes.has((el.type || 'text').toLowerCase());
|
|
1759
|
+
const textarea = tag === 'TEXTAREA';
|
|
1760
|
+
const contentEditable = el.isContentEditable;
|
|
1761
|
+
const iframe = tag === 'IFRAME';
|
|
1762
|
+
if (!input && !textarea && !contentEditable && !iframe)
|
|
1763
|
+
return { ok: false, error: 'Focused <' + tag + '> is not editable' };
|
|
1764
|
+
if ((input || textarea) && (el.disabled || el.readOnly))
|
|
1765
|
+
return { ok: false, error: 'Focused <' + tag + '> is disabled or read-only' };
|
|
1766
|
+
return {
|
|
1767
|
+
ok: true,
|
|
1768
|
+
tag,
|
|
1769
|
+
iframe,
|
|
1770
|
+
inspectable: !iframe,
|
|
1771
|
+
before: input || textarea
|
|
1772
|
+
? el.value
|
|
1773
|
+
: contentEditable ? el.textContent : null
|
|
1774
|
+
};
|
|
1775
|
+
})()`, signal), "focused element state");
|
|
1776
|
+
if (focusState["ok"] !== true) {
|
|
1777
|
+
throw new Error(typeof focusState["error"] === "string" ? focusState["error"] : "Focused element is not editable");
|
|
1778
|
+
}
|
|
1779
|
+
await cdp.send("Input.insertText", { text }, sessionId, signal);
|
|
1780
|
+
const tag = typeof focusState["tag"] === "string" ? focusState["tag"] : "ELEMENT";
|
|
1781
|
+
if (focusState["inspectable"] !== true) {
|
|
1782
|
+
return `Sent ${text.length} characters to focused <${tag}>; cross-origin result is not inspectable`;
|
|
1783
|
+
}
|
|
1784
|
+
const after = asRecord(await evaluate(cdp, sessionId, `(() => {
|
|
1785
|
+
const el = document.activeElement;
|
|
1786
|
+
if (!el) return { focused: false, value: null };
|
|
1787
|
+
const tag = el.tagName;
|
|
1788
|
+
const value = tag === 'INPUT' || tag === 'TEXTAREA'
|
|
1789
|
+
? el.value
|
|
1790
|
+
: el.isContentEditable ? el.textContent : null;
|
|
1791
|
+
return { focused: true, tag, value };
|
|
1792
|
+
})()`, signal), "focused element result");
|
|
1793
|
+
if (after["focused"] !== true || after["tag"] !== tag) {
|
|
1794
|
+
throw new Error("Focus changed while typing; input result could not be verified");
|
|
1795
|
+
}
|
|
1796
|
+
if (after["value"] === focusState["before"]) {
|
|
1797
|
+
throw new Error(`Input.insertText completed but focused <${tag}> did not change`);
|
|
1798
|
+
}
|
|
1799
|
+
return `Typed ${text.length} characters into focused <${tag}>`;
|
|
1800
|
+
}
|
|
1801
|
+
async function typeRef(cdp, sessionId, elementRefs, id, text, signal) {
|
|
1802
|
+
if (!text)
|
|
1803
|
+
throw new Error("text required");
|
|
1804
|
+
const ref = requireElementRef(elementRefs, id);
|
|
1805
|
+
await backendCenter(cdp, sessionId, ref.backendNodeId, true, signal);
|
|
1806
|
+
return withBackendObject(cdp, sessionId, ref.backendNodeId, async (objectId) => {
|
|
1807
|
+
const focused = asRecord(await cdp.send("Runtime.callFunctionOn", {
|
|
1808
|
+
objectId,
|
|
1809
|
+
functionDeclaration: `function() {
|
|
1810
|
+
const tag = this.tagName;
|
|
1811
|
+
const inputTypes = new Set([
|
|
1812
|
+
'text', 'search', 'email', 'url', 'tel',
|
|
1813
|
+
'password', 'number'
|
|
1814
|
+
]);
|
|
1815
|
+
const input = tag === 'INPUT' &&
|
|
1816
|
+
inputTypes.has((this.type || 'text').toLowerCase());
|
|
1817
|
+
const textarea = tag === 'TEXTAREA';
|
|
1818
|
+
const contentEditable = this.isContentEditable;
|
|
1819
|
+
if (!input && !textarea && !contentEditable)
|
|
1820
|
+
return { ok: false, error: '<' + tag + '> is not editable' };
|
|
1821
|
+
if ((input || textarea) && (this.disabled || this.readOnly))
|
|
1822
|
+
return { ok: false, error: '<' + tag + '> is disabled or read-only' };
|
|
1823
|
+
this.focus({ preventScroll: true });
|
|
1824
|
+
const root = this.getRootNode();
|
|
1825
|
+
if (root.activeElement !== this &&
|
|
1826
|
+
this.ownerDocument.activeElement !== this)
|
|
1827
|
+
return { ok: false, error: 'Could not focus editable <' + tag + '>' };
|
|
1828
|
+
const before = input || textarea ? this.value : this.textContent;
|
|
1829
|
+
return { ok: true, tag, before };
|
|
1830
|
+
}`,
|
|
1831
|
+
returnByValue: true
|
|
1832
|
+
}, sessionId, signal), "focus response");
|
|
1833
|
+
const focusState = asRecord(asRecord(focused["result"], "focus result")["value"], "focus state");
|
|
1834
|
+
if (focusState["ok"] !== true) {
|
|
1835
|
+
throw new Error(typeof focusState["error"] === "string" ? focusState["error"] : "Element is not editable");
|
|
1836
|
+
}
|
|
1837
|
+
const activeResponse = asRecord(await cdp.send("Runtime.callFunctionOn", {
|
|
1838
|
+
objectId,
|
|
1839
|
+
functionDeclaration: `function() {
|
|
1840
|
+
const root = this.getRootNode();
|
|
1841
|
+
return root.activeElement === this ||
|
|
1842
|
+
this.ownerDocument.activeElement === this;
|
|
1843
|
+
}`,
|
|
1844
|
+
returnByValue: true
|
|
1845
|
+
}, sessionId, signal), "active element response");
|
|
1846
|
+
const activeResult = asRecord(activeResponse["result"], "active element result");
|
|
1847
|
+
if (activeResult["value"] !== true) {
|
|
1848
|
+
throw new Error("Focus changed before typing; input was not sent");
|
|
1849
|
+
}
|
|
1850
|
+
await cdp.send("Input.insertText", { text }, sessionId, signal);
|
|
1851
|
+
const afterResponse = asRecord(await cdp.send("Runtime.callFunctionOn", {
|
|
1852
|
+
objectId,
|
|
1853
|
+
functionDeclaration: `function(before) {
|
|
1854
|
+
const root = this.getRootNode();
|
|
1855
|
+
const active = root.activeElement === this ||
|
|
1856
|
+
this.ownerDocument.activeElement === this;
|
|
1857
|
+
const value = this.tagName === 'INPUT' ||
|
|
1858
|
+
this.tagName === 'TEXTAREA'
|
|
1859
|
+
? this.value
|
|
1860
|
+
: this.textContent;
|
|
1861
|
+
return { active, changed: value !== before };
|
|
1862
|
+
}`,
|
|
1863
|
+
arguments: [{ value: focusState["before"] }],
|
|
1864
|
+
returnByValue: true
|
|
1865
|
+
}, sessionId, signal), "typed element response");
|
|
1866
|
+
const after = asRecord(asRecord(afterResponse["result"], "typed result")["value"], "typed state");
|
|
1867
|
+
if (after["active"] !== true) {
|
|
1868
|
+
throw new Error("Focus changed while typing; input result could not be verified");
|
|
1869
|
+
}
|
|
1870
|
+
const tag = typeof focusState["tag"] === "string" ? focusState["tag"] : "ELEMENT";
|
|
1871
|
+
if (after["changed"] !== true) {
|
|
1872
|
+
throw new Error(`Input.insertText completed but referenced <${tag}> did not change`);
|
|
1873
|
+
}
|
|
1874
|
+
return `Typed ${text.length} characters into referenced <${tag}>`;
|
|
1875
|
+
}, signal);
|
|
1876
|
+
}
|
|
1877
|
+
|
|
1878
|
+
// src/cdp/snapshot.ts
|
|
1879
|
+
var INTERACTIVE_ROLES = new Set([
|
|
1880
|
+
"button",
|
|
1881
|
+
"checkbox",
|
|
1882
|
+
"combobox",
|
|
1883
|
+
"link",
|
|
1884
|
+
"listbox",
|
|
1885
|
+
"menuitem",
|
|
1886
|
+
"option",
|
|
1887
|
+
"menuitemcheckbox",
|
|
1888
|
+
"menuitemradio",
|
|
1889
|
+
"radio",
|
|
1890
|
+
"searchbox",
|
|
1891
|
+
"slider",
|
|
1892
|
+
"spinbutton",
|
|
1893
|
+
"switch",
|
|
1894
|
+
"tab",
|
|
1895
|
+
"textbox",
|
|
1896
|
+
"treeitem"
|
|
1897
|
+
]);
|
|
1898
|
+
var NEXT_ELEMENT_IDS = new WeakMap;
|
|
1899
|
+
function axNode(value) {
|
|
1900
|
+
const record = asRecord(value, "accessibility node");
|
|
1901
|
+
if (typeof record["nodeId"] !== "string") {
|
|
1902
|
+
throw new Error("Accessibility node has no nodeId");
|
|
1903
|
+
}
|
|
1904
|
+
return {
|
|
1905
|
+
nodeId: record["nodeId"],
|
|
1906
|
+
...typeof record["parentId"] === "string" ? { parentId: record["parentId"] } : {},
|
|
1907
|
+
...Array.isArray(record["childIds"]) ? {
|
|
1908
|
+
childIds: record["childIds"].filter((id) => typeof id === "string")
|
|
1909
|
+
} : {},
|
|
1910
|
+
...typeof record["backendDOMNodeId"] === "number" ? { backendDOMNodeId: record["backendDOMNodeId"] } : {},
|
|
1911
|
+
...typeof record["ignored"] === "boolean" ? { ignored: record["ignored"] } : {},
|
|
1912
|
+
...record["role"] ? { role: asRecord(record["role"]) } : {},
|
|
1913
|
+
...record["name"] ? { name: asRecord(record["name"]) } : {},
|
|
1914
|
+
...record["value"] ? { value: asRecord(record["value"]) } : {}
|
|
1915
|
+
};
|
|
1916
|
+
}
|
|
1917
|
+
function shouldShow(node) {
|
|
1918
|
+
const role = String(node.role?.value ?? "");
|
|
1919
|
+
const name = node.name?.value ?? "";
|
|
1920
|
+
const value = node.value?.value;
|
|
1921
|
+
if (role === "InlineTextBox")
|
|
1922
|
+
return false;
|
|
1923
|
+
return role !== "none" && role !== "generic" && !(name === "" && (value === "" || value == null));
|
|
1924
|
+
}
|
|
1925
|
+
function orderedChildren(node, nodesById, childrenByParent) {
|
|
1926
|
+
const children = [];
|
|
1927
|
+
const seen = new Set;
|
|
1928
|
+
for (const childId of node.childIds ?? []) {
|
|
1929
|
+
const child = nodesById.get(childId);
|
|
1930
|
+
if (child && !seen.has(child.nodeId)) {
|
|
1931
|
+
seen.add(child.nodeId);
|
|
1932
|
+
children.push(child);
|
|
1933
|
+
}
|
|
1934
|
+
}
|
|
1935
|
+
for (const child of childrenByParent.get(node.nodeId) ?? []) {
|
|
1936
|
+
if (!seen.has(child.nodeId)) {
|
|
1937
|
+
seen.add(child.nodeId);
|
|
1938
|
+
children.push(child);
|
|
1939
|
+
}
|
|
1940
|
+
}
|
|
1941
|
+
return children;
|
|
1942
|
+
}
|
|
1943
|
+
function normalizeText(value) {
|
|
1944
|
+
return String(value ?? "").replace(/\s+/g, " ").trim();
|
|
1945
|
+
}
|
|
1946
|
+
function splitText(value, max = 700) {
|
|
1947
|
+
const text = normalizeText(value);
|
|
1948
|
+
if (!text)
|
|
1949
|
+
return [];
|
|
1950
|
+
const parts = [];
|
|
1951
|
+
for (let start = 0;start < text.length; start += max) {
|
|
1952
|
+
parts.push(text.slice(start, start + max));
|
|
1953
|
+
}
|
|
1954
|
+
return parts;
|
|
1955
|
+
}
|
|
1956
|
+
async function snapshotData(cdp, sessionId, elementRefs, options = {}) {
|
|
1957
|
+
const lineno = positiveInteger(options.lineno ?? 1, "line cursor");
|
|
1958
|
+
const responseLength2 = snapshotResponseLength(options.responseLength);
|
|
1959
|
+
const response = asRecord(await cdp.send("Accessibility.getFullAXTree", {}, sessionId, options.signal), "Accessibility response");
|
|
1960
|
+
if (!Array.isArray(response["nodes"])) {
|
|
1961
|
+
throw new Error("Accessibility response has no nodes");
|
|
1962
|
+
}
|
|
1963
|
+
const nodes = response["nodes"].map(axNode);
|
|
1964
|
+
const nodesById = new Map(nodes.map((node) => [node.nodeId, node]));
|
|
1965
|
+
const childrenByParent = new Map;
|
|
1966
|
+
for (const node of nodes) {
|
|
1967
|
+
if (!node.parentId)
|
|
1968
|
+
continue;
|
|
1969
|
+
const children = childrenByParent.get(node.parentId) ?? [];
|
|
1970
|
+
children.push(node);
|
|
1971
|
+
childrenByParent.set(node.parentId, children);
|
|
1972
|
+
}
|
|
1973
|
+
elementRefs.clear();
|
|
1974
|
+
const lines = [];
|
|
1975
|
+
const elements = [];
|
|
1976
|
+
const visited = new Set;
|
|
1977
|
+
const nextElementId = () => {
|
|
1978
|
+
const id = NEXT_ELEMENT_IDS.get(elementRefs) ?? 1;
|
|
1979
|
+
if (!Number.isSafeInteger(id)) {
|
|
1980
|
+
throw new Error("Element id limit reached; restart the tab bridge");
|
|
1981
|
+
}
|
|
1982
|
+
NEXT_ELEMENT_IDS.set(elementRefs, id + 1);
|
|
1983
|
+
return id;
|
|
1984
|
+
};
|
|
1985
|
+
const addLine = (text, element, kind = "text") => {
|
|
1986
|
+
for (const part of splitText(text)) {
|
|
1987
|
+
lines.push({
|
|
1988
|
+
line: lines.length + 1,
|
|
1989
|
+
text: part,
|
|
1990
|
+
kind,
|
|
1991
|
+
...element ? { element_id: element.id } : {}
|
|
1992
|
+
});
|
|
1993
|
+
}
|
|
1994
|
+
};
|
|
1995
|
+
const addStaticText = (text) => {
|
|
1996
|
+
const normalized = normalizeText(text);
|
|
1997
|
+
if (!normalized)
|
|
1998
|
+
return;
|
|
1999
|
+
const previous = lines.at(-1);
|
|
2000
|
+
if (previous?.kind === "text" && previous.text.length + normalized.length + 1 <= 700) {
|
|
2001
|
+
previous.text += ` ${normalized}`;
|
|
2002
|
+
return;
|
|
2003
|
+
}
|
|
2004
|
+
addLine(normalized);
|
|
2005
|
+
};
|
|
2006
|
+
const visit = (node, parentName = "") => {
|
|
2007
|
+
if (!node || visited.has(node.nodeId))
|
|
2008
|
+
return;
|
|
2009
|
+
visited.add(node.nodeId);
|
|
2010
|
+
const role = String(node.role?.value ?? "");
|
|
2011
|
+
const name = normalizeText(node.name?.value ?? "");
|
|
2012
|
+
const value = node.value?.value;
|
|
2013
|
+
let renderedName = parentName;
|
|
2014
|
+
if (!node.ignored && shouldShow(node)) {
|
|
2015
|
+
if (INTERACTIVE_ROLES.has(role) && node.backendDOMNodeId) {
|
|
2016
|
+
const element = {
|
|
2017
|
+
id: nextElementId(),
|
|
2018
|
+
role,
|
|
2019
|
+
...name ? { name } : {},
|
|
2020
|
+
...value === "" || value == null ? {} : { value }
|
|
2021
|
+
};
|
|
2022
|
+
elementRefs.set(element.id, node.backendDOMNodeId);
|
|
2023
|
+
elements.push(element);
|
|
2024
|
+
addLine(`[${element.id}] ${role}${name ? ` ${name}` : ""}${value === "" || value == null ? "" : ` = ${JSON.stringify(value)}`}`, element, "interactive");
|
|
2025
|
+
renderedName = name;
|
|
2026
|
+
} else if (role === "StaticText") {
|
|
2027
|
+
if (name && name !== parentName)
|
|
2028
|
+
addStaticText(name);
|
|
2029
|
+
} else if (role === "heading" || role === "image") {
|
|
2030
|
+
if (name)
|
|
2031
|
+
addLine(`${role}: ${name}`, undefined, role);
|
|
2032
|
+
renderedName = name || parentName;
|
|
2033
|
+
}
|
|
2034
|
+
}
|
|
2035
|
+
for (const child of orderedChildren(node, nodesById, childrenByParent)) {
|
|
2036
|
+
visit(child, renderedName);
|
|
2037
|
+
}
|
|
2038
|
+
};
|
|
2039
|
+
for (const root of nodes.filter((node) => !node.parentId || !nodesById.has(node.parentId))) {
|
|
2040
|
+
visit(root);
|
|
2041
|
+
}
|
|
2042
|
+
for (const node of nodes)
|
|
2043
|
+
visit(node);
|
|
2044
|
+
const metadata = asRecord(await evaluate(cdp, sessionId, "({title: document.title, url: location.href})", options.signal), "page metadata");
|
|
2045
|
+
const pattern = options.pattern?.toLowerCase();
|
|
2046
|
+
const matching = pattern ? lines.filter((line2) => line2.text.toLowerCase().includes(pattern)) : lines;
|
|
2047
|
+
const start = lineno - 1;
|
|
2048
|
+
const content = matching.slice(start, start + SNAPSHOT_LIMITS[responseLength2]).map(({ kind: _kind, ...line2 }) => line2);
|
|
2049
|
+
const visibleIds = new Set(content.flatMap((line2) => line2.element_id === undefined ? [] : [line2.element_id]));
|
|
2050
|
+
const hasMore = start + content.length < matching.length;
|
|
2051
|
+
return {
|
|
2052
|
+
...options.refId ? { ref_id: options.refId } : {},
|
|
2053
|
+
title: typeof metadata["title"] === "string" ? metadata["title"] : "",
|
|
2054
|
+
url: typeof metadata["url"] === "string" ? metadata["url"] : "",
|
|
2055
|
+
lineno: start + 1,
|
|
2056
|
+
content,
|
|
2057
|
+
elements: elements.filter((element) => visibleIds.has(element.id)),
|
|
2058
|
+
...options.pattern ? { pattern: options.pattern } : {},
|
|
2059
|
+
...hasMore ? { next_lineno: start + content.length + 1 } : {}
|
|
2060
|
+
};
|
|
2061
|
+
}
|
|
2062
|
+
|
|
2063
|
+
// src/browser/bounds.ts
|
|
2064
|
+
import { StringDecoder } from "node:string_decoder";
|
|
2065
|
+
var OUTPUT_BUDGET_BYTES = 38000;
|
|
2066
|
+
var SNAPSHOT_TITLE_BYTES = 1000;
|
|
2067
|
+
var SNAPSHOT_URL_BYTES = 8000;
|
|
2068
|
+
var SNAPSHOT_PATTERN_BYTES = 2000;
|
|
2069
|
+
var SNAPSHOT_ELEMENT_NAME_BYTES = 2000;
|
|
2070
|
+
var SNAPSHOT_ELEMENT_VALUE_BYTES = 4000;
|
|
2071
|
+
function byteLength(value) {
|
|
2072
|
+
return Buffer.byteLength(JSON.stringify(value));
|
|
2073
|
+
}
|
|
2074
|
+
function truncateUtf8(value, maxBytes) {
|
|
2075
|
+
const bytes = Buffer.from(value);
|
|
2076
|
+
if (bytes.length <= maxBytes)
|
|
2077
|
+
return value;
|
|
2078
|
+
return new StringDecoder("utf8").write(bytes.subarray(0, maxBytes));
|
|
2079
|
+
}
|
|
2080
|
+
function boundedElement(element) {
|
|
2081
|
+
let value = element.value;
|
|
2082
|
+
if (typeof value === "string") {
|
|
2083
|
+
value = truncateUtf8(value, SNAPSHOT_ELEMENT_VALUE_BYTES);
|
|
2084
|
+
} else if (value !== undefined) {
|
|
2085
|
+
const serialized = JSON.stringify(value);
|
|
2086
|
+
if (serialized && Buffer.byteLength(serialized) > SNAPSHOT_ELEMENT_VALUE_BYTES) {
|
|
2087
|
+
value = truncateUtf8(serialized, SNAPSHOT_ELEMENT_VALUE_BYTES);
|
|
2088
|
+
}
|
|
2089
|
+
}
|
|
2090
|
+
return {
|
|
2091
|
+
...element,
|
|
2092
|
+
role: truncateUtf8(element.role, 128),
|
|
2093
|
+
...element.name === undefined ? {} : { name: truncateUtf8(element.name, SNAPSHOT_ELEMENT_NAME_BYTES) },
|
|
2094
|
+
...value === undefined ? {} : { value }
|
|
2095
|
+
};
|
|
2096
|
+
}
|
|
2097
|
+
function boundTabs(pages, query, offset2) {
|
|
2098
|
+
const prefixLength = getDisplayPrefixLength(pages.map((page) => page.targetId));
|
|
2099
|
+
let filtered = pages;
|
|
2100
|
+
if (query) {
|
|
2101
|
+
const normalized = query.toLowerCase();
|
|
2102
|
+
filtered = pages.filter((page) => `${page.title}
|
|
2103
|
+
${page.url}`.toLowerCase().includes(normalized));
|
|
2104
|
+
}
|
|
2105
|
+
if (offset2 > filtered.length) {
|
|
2106
|
+
throw new Error(`offset ${offset2} exceeds tab count ${filtered.length}`);
|
|
2107
|
+
}
|
|
2108
|
+
const tabs = [];
|
|
2109
|
+
for (const page of filtered.slice(offset2)) {
|
|
2110
|
+
const compact = {
|
|
2111
|
+
ref_id: page.targetId.slice(0, prefixLength),
|
|
2112
|
+
title: page.title.slice(0, 500),
|
|
2113
|
+
url: page.url.slice(0, 8000)
|
|
2114
|
+
};
|
|
2115
|
+
if (byteLength({ tabs: [...tabs, compact] }) > OUTPUT_BUDGET_BYTES) {
|
|
2116
|
+
break;
|
|
2117
|
+
}
|
|
2118
|
+
tabs.push(compact);
|
|
2119
|
+
}
|
|
2120
|
+
const remaining = filtered.length - offset2 - tabs.length;
|
|
2121
|
+
return {
|
|
2122
|
+
offset: offset2,
|
|
2123
|
+
tabs,
|
|
2124
|
+
...remaining > 0 ? {
|
|
2125
|
+
truncated: true,
|
|
2126
|
+
omitted_tabs: remaining,
|
|
2127
|
+
next_offset: offset2 + tabs.length
|
|
2128
|
+
} : {}
|
|
2129
|
+
};
|
|
2130
|
+
}
|
|
2131
|
+
function boundSnapshot(page) {
|
|
2132
|
+
const base = {
|
|
2133
|
+
ref_id: page.ref_id === undefined ? undefined : truncateUtf8(page.ref_id, 512),
|
|
2134
|
+
title: truncateUtf8(page.title, SNAPSHOT_TITLE_BYTES),
|
|
2135
|
+
url: truncateUtf8(page.url, SNAPSHOT_URL_BYTES),
|
|
2136
|
+
lineno: page.lineno,
|
|
2137
|
+
...page.pattern ? { pattern: truncateUtf8(page.pattern, SNAPSHOT_PATTERN_BYTES) } : {}
|
|
2138
|
+
};
|
|
2139
|
+
const elements = new Map(page.elements.map((element) => [element.id, boundedElement(element)]));
|
|
2140
|
+
const content = [];
|
|
2141
|
+
const includedElements = [];
|
|
2142
|
+
const includedIds = new Set;
|
|
2143
|
+
for (const line2 of page.content) {
|
|
2144
|
+
const nextContent = [...content, line2];
|
|
2145
|
+
const nextElements = [...includedElements];
|
|
2146
|
+
if (line2.element_id !== undefined && !includedIds.has(line2.element_id) && elements.has(line2.element_id)) {
|
|
2147
|
+
const element = elements.get(line2.element_id);
|
|
2148
|
+
if (element)
|
|
2149
|
+
nextElements.push(element);
|
|
2150
|
+
}
|
|
2151
|
+
if (byteLength({
|
|
2152
|
+
...base,
|
|
2153
|
+
content: nextContent,
|
|
2154
|
+
elements: nextElements
|
|
2155
|
+
}) > OUTPUT_BUDGET_BYTES) {
|
|
2156
|
+
break;
|
|
2157
|
+
}
|
|
2158
|
+
content.push(line2);
|
|
2159
|
+
if (line2.element_id !== undefined && !includedIds.has(line2.element_id) && elements.has(line2.element_id)) {
|
|
2160
|
+
includedIds.add(line2.element_id);
|
|
2161
|
+
const element = elements.get(line2.element_id);
|
|
2162
|
+
if (element)
|
|
2163
|
+
includedElements.push(element);
|
|
2164
|
+
}
|
|
2165
|
+
}
|
|
2166
|
+
const omitted = content.length < page.content.length;
|
|
2167
|
+
return {
|
|
2168
|
+
...base,
|
|
2169
|
+
content,
|
|
2170
|
+
elements: includedElements,
|
|
2171
|
+
...omitted || page.next_lineno ? {
|
|
2172
|
+
truncated: true,
|
|
2173
|
+
next_lineno: omitted ? page.lineno + content.length : page.next_lineno
|
|
2174
|
+
} : {}
|
|
2175
|
+
};
|
|
2176
|
+
}
|
|
2177
|
+
|
|
2178
|
+
// src/browser/launcher.ts
|
|
2179
|
+
import { spawn } from "node:child_process";
|
|
2180
|
+
var BROWSER_START_TIMEOUT_MS = 1e4;
|
|
2181
|
+
var BROWSER_UNIT = "chrome-cdp-browser.service";
|
|
2182
|
+
var PROCESS_OUTPUT_LIMIT = 1 * 1024 * 1024;
|
|
2183
|
+
function abortReason(signal) {
|
|
2184
|
+
return signal.reason instanceof Error ? signal.reason : new Error("Browser launch aborted");
|
|
2185
|
+
}
|
|
2186
|
+
function runProcess(command, args, signal) {
|
|
2187
|
+
if (signal?.aborted)
|
|
2188
|
+
return Promise.reject(abortReason(signal));
|
|
2189
|
+
return new Promise((resolveValue, reject) => {
|
|
2190
|
+
const child = spawn(command, args, {
|
|
2191
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
2192
|
+
});
|
|
2193
|
+
let stdout = "";
|
|
2194
|
+
let stderr = "";
|
|
2195
|
+
let bytes = 0;
|
|
2196
|
+
let settled = false;
|
|
2197
|
+
let killTimer;
|
|
2198
|
+
const cleanup = () => {
|
|
2199
|
+
if (killTimer)
|
|
2200
|
+
clearTimeout(killTimer);
|
|
2201
|
+
signal?.removeEventListener("abort", abort);
|
|
2202
|
+
};
|
|
2203
|
+
const finish = (action) => {
|
|
2204
|
+
if (settled)
|
|
2205
|
+
return;
|
|
2206
|
+
settled = true;
|
|
2207
|
+
cleanup();
|
|
2208
|
+
action();
|
|
2209
|
+
};
|
|
2210
|
+
const running = () => child.exitCode === null && child.signalCode === null;
|
|
2211
|
+
const abort = () => {
|
|
2212
|
+
if (running())
|
|
2213
|
+
child.kill("SIGTERM");
|
|
2214
|
+
killTimer = setTimeout(() => {
|
|
2215
|
+
if (running())
|
|
2216
|
+
child.kill("SIGKILL");
|
|
2217
|
+
}, 1000);
|
|
2218
|
+
killTimer.unref?.();
|
|
2219
|
+
};
|
|
2220
|
+
const append = (target, chunk) => {
|
|
2221
|
+
bytes += chunk.length;
|
|
2222
|
+
if (bytes > PROCESS_OUTPUT_LIMIT) {
|
|
2223
|
+
if (running())
|
|
2224
|
+
child.kill("SIGKILL");
|
|
2225
|
+
finish(() => reject(new Error("Browser launch output exceeded 1 MiB")));
|
|
2226
|
+
return;
|
|
2227
|
+
}
|
|
2228
|
+
if (target === "stdout")
|
|
2229
|
+
stdout += chunk.toString("utf8");
|
|
2230
|
+
else
|
|
2231
|
+
stderr += chunk.toString("utf8");
|
|
2232
|
+
};
|
|
2233
|
+
child.stdout.on("data", (chunk) => append("stdout", chunk));
|
|
2234
|
+
child.stderr.on("data", (chunk) => append("stderr", chunk));
|
|
2235
|
+
child.on("error", (error) => finish(() => reject(error)));
|
|
2236
|
+
child.on("close", (code) => finish(() => {
|
|
2237
|
+
if (signal?.aborted) {
|
|
2238
|
+
reject(abortReason(signal));
|
|
2239
|
+
return;
|
|
2240
|
+
}
|
|
2241
|
+
resolveValue({
|
|
2242
|
+
code: code ?? 1,
|
|
2243
|
+
stdout: stdout.trim(),
|
|
2244
|
+
stderr: stderr.trim()
|
|
2245
|
+
});
|
|
2246
|
+
}));
|
|
2247
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
2248
|
+
});
|
|
2249
|
+
}
|
|
2250
|
+
function endpoint() {
|
|
2251
|
+
return {
|
|
2252
|
+
port: process.env["CDP_PORT"] ?? "9222",
|
|
2253
|
+
host: process.env["CDP_HOST"] ?? "127.0.0.1"
|
|
2254
|
+
};
|
|
2255
|
+
}
|
|
2256
|
+
async function waitForDebugEndpoint(signal, timeout = BROWSER_START_TIMEOUT_MS) {
|
|
2257
|
+
const { port, host } = endpoint();
|
|
2258
|
+
const deadline = Date.now() + timeout;
|
|
2259
|
+
let lastError;
|
|
2260
|
+
while (Date.now() < deadline) {
|
|
2261
|
+
try {
|
|
2262
|
+
await probeDebugPort(port, host);
|
|
2263
|
+
return;
|
|
2264
|
+
} catch (error) {
|
|
2265
|
+
lastError = error;
|
|
2266
|
+
}
|
|
2267
|
+
await sleep(100, signal);
|
|
2268
|
+
}
|
|
2269
|
+
throw new Error(`Browser did not expose CDP at ${host}:${port} within ${timeout}ms${lastError instanceof Error ? ` (${lastError.message})` : ""}`);
|
|
2270
|
+
}
|
|
2271
|
+
async function unitExists(systemctl, signal) {
|
|
2272
|
+
const result = await runProcess(systemctl, ["--user", "show", BROWSER_UNIT, "--property=LoadState", "--value"], signal);
|
|
2273
|
+
return result.code === 0 && result.stdout !== "not-found";
|
|
2274
|
+
}
|
|
2275
|
+
async function waitForBrowserOrUnitRemoval(systemctl, signal) {
|
|
2276
|
+
const { port, host } = endpoint();
|
|
2277
|
+
const deadline = Date.now() + BROWSER_START_TIMEOUT_MS;
|
|
2278
|
+
while (Date.now() < deadline) {
|
|
2279
|
+
try {
|
|
2280
|
+
await probeDebugPort(port, host);
|
|
2281
|
+
return "browser";
|
|
2282
|
+
} catch {}
|
|
2283
|
+
if (!await unitExists(systemctl, signal))
|
|
2284
|
+
return "removed";
|
|
2285
|
+
await sleep(100, signal);
|
|
2286
|
+
}
|
|
2287
|
+
return "timeout";
|
|
2288
|
+
}
|
|
2289
|
+
async function startBrowser(signal) {
|
|
2290
|
+
const { port, host } = endpoint();
|
|
2291
|
+
try {
|
|
2292
|
+
await probeDebugPort(port, host);
|
|
2293
|
+
return `Browser already running with CDP at ${host}:${port}`;
|
|
2294
|
+
} catch {}
|
|
2295
|
+
if (process.platform !== "linux") {
|
|
2296
|
+
throw new Error("Automatic browser launch requires a Linux systemd user session. Start the authenticated browser normally with remote debugging enabled.");
|
|
2297
|
+
}
|
|
2298
|
+
const systemctl = process.env["CDP_SYSTEMCTL"] ?? "/usr/bin/systemctl";
|
|
2299
|
+
const systemdRun = process.env["CDP_SYSTEMD_RUN"] ?? "/usr/bin/systemd-run";
|
|
2300
|
+
const browser = process.env["CDP_BROWSER"] ?? "/usr/bin/chromium";
|
|
2301
|
+
let lastLaunchError = "";
|
|
2302
|
+
for (let attempt = 0;attempt < 3; attempt++) {
|
|
2303
|
+
const state = await waitForBrowserOrUnitRemoval(systemctl, signal);
|
|
2304
|
+
if (state === "browser") {
|
|
2305
|
+
return `Browser already running with CDP at ${host}:${port}`;
|
|
2306
|
+
}
|
|
2307
|
+
if (state === "timeout") {
|
|
2308
|
+
throw new Error(`Browser unit ${BROWSER_UNIT} remained loaded without exposing CDP at ${host}:${port}`);
|
|
2309
|
+
}
|
|
2310
|
+
await runProcess(systemctl, ["--user", "reset-failed", BROWSER_UNIT], signal);
|
|
2311
|
+
const browserArgs = [
|
|
2312
|
+
`--remote-debugging-address=${host}`,
|
|
2313
|
+
`--remote-debugging-port=${port}`
|
|
2314
|
+
];
|
|
2315
|
+
const profile = process.env["CDP_PROFILE_DIRECTORY"];
|
|
2316
|
+
if (profile) {
|
|
2317
|
+
browserArgs.push(`--profile-directory=${profile}`);
|
|
2318
|
+
}
|
|
2319
|
+
browserArgs.push("about:blank");
|
|
2320
|
+
const launched = await runProcess(systemdRun, [
|
|
2321
|
+
"--user",
|
|
2322
|
+
"--unit=chrome-cdp-browser",
|
|
2323
|
+
"--collect",
|
|
2324
|
+
"--property=Type=exec",
|
|
2325
|
+
"--property=Restart=no",
|
|
2326
|
+
browser,
|
|
2327
|
+
...browserArgs
|
|
2328
|
+
], signal);
|
|
2329
|
+
if (launched.code === 0) {
|
|
2330
|
+
await waitForDebugEndpoint(signal);
|
|
2331
|
+
return `Started authenticated browser with CDP at ${host}:${port}`;
|
|
2332
|
+
}
|
|
2333
|
+
lastLaunchError = launched.stderr || launched.stdout || `exit ${launched.code}`;
|
|
2334
|
+
}
|
|
2335
|
+
throw new Error(`Could not launch the browser through the graphical user session: ${lastLaunchError}`);
|
|
2336
|
+
}
|
|
2337
|
+
|
|
2338
|
+
// src/browser/operation-executor.ts
|
|
2339
|
+
class BrowserOperationExecutor {
|
|
2340
|
+
cdp;
|
|
2341
|
+
constructor(cdp) {
|
|
2342
|
+
this.cdp = cdp;
|
|
2343
|
+
}
|
|
2344
|
+
async execute(operation, signal) {
|
|
2345
|
+
switch (operation.action) {
|
|
2346
|
+
case "start":
|
|
2347
|
+
return { result: await startBrowser(signal) };
|
|
2348
|
+
case "tabs":
|
|
2349
|
+
return boundTabs(await this.cdp.pages(signal), operation.query, operation.offset);
|
|
2350
|
+
case "open":
|
|
2351
|
+
if ("url" in operation) {
|
|
2352
|
+
const opened = await this.cdp.open(operation.url, signal);
|
|
2353
|
+
return {
|
|
2354
|
+
ref_id: opened.refId,
|
|
2355
|
+
url: operation.url
|
|
2356
|
+
};
|
|
2357
|
+
}
|
|
2358
|
+
return this.cdp.withTab(operation.ref_id, signal, async (tab) => boundSnapshot(await snapshotData(tab.cdp, tab.sessionId, tab.elementRefs, {
|
|
2359
|
+
refId: tab.refId,
|
|
2360
|
+
lineno: operation.lineno,
|
|
2361
|
+
responseLength: operation.response_length,
|
|
2362
|
+
signal
|
|
2363
|
+
})));
|
|
2364
|
+
case "find":
|
|
2365
|
+
return this.cdp.withTab(operation.ref_id, signal, async (tab) => boundSnapshot(await snapshotData(tab.cdp, tab.sessionId, tab.elementRefs, {
|
|
2366
|
+
refId: tab.refId,
|
|
2367
|
+
pattern: operation.pattern,
|
|
2368
|
+
lineno: operation.lineno,
|
|
2369
|
+
responseLength: operation.response_length,
|
|
2370
|
+
signal
|
|
2371
|
+
})));
|
|
2372
|
+
case "read_result":
|
|
2373
|
+
return readCachedResult(operation);
|
|
2374
|
+
case "discard_result":
|
|
2375
|
+
return discardCachedResult(operation.handle);
|
|
2376
|
+
case "stop":
|
|
2377
|
+
await this.cdp.stop(operation.ref_id);
|
|
2378
|
+
return {
|
|
2379
|
+
stopped: operation.ref_id ?? "all tab daemons"
|
|
2380
|
+
};
|
|
2381
|
+
case "screenshot":
|
|
2382
|
+
return this.screenshot(operation, signal);
|
|
2383
|
+
case "evaluate":
|
|
2384
|
+
return this.cdp.withTab(operation.ref_id, signal, async (tab) => limitedText({ ref_id: tab.refId }, "value", await evaluateText(tab.cdp, tab.sessionId, operation.expression, signal)));
|
|
2385
|
+
case "html":
|
|
2386
|
+
return this.cdp.withTab(operation.ref_id, signal, async (tab) => 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)));
|
|
2387
|
+
case "network":
|
|
2388
|
+
return this.cdp.withTab(operation.ref_id, signal, async (tab) => limitedText({ ref_id: tab.refId }, "entries", await networkEntries(tab.cdp, tab.sessionId, signal)));
|
|
2389
|
+
case "raw":
|
|
2390
|
+
return this.cdp.withTab(operation.ref_id, signal, async (tab) => limitedText({ ref_id: tab.refId }, "result", await rawCommand(tab.cdp, tab.sessionId, operation.method, operation.params, signal)));
|
|
2391
|
+
case "navigate":
|
|
2392
|
+
return this.tabResult(operation.ref_id, signal, (tab) => navigate(tab.cdp, tab.sessionId, operation.url, signal));
|
|
2393
|
+
case "click":
|
|
2394
|
+
return this.tabResult(operation.ref_id, signal, (tab) => {
|
|
2395
|
+
if (operation.id !== undefined) {
|
|
2396
|
+
return clickRef(tab.cdp, tab.sessionId, tab.elementRefs, operation.id, signal);
|
|
2397
|
+
}
|
|
2398
|
+
if (operation.selector) {
|
|
2399
|
+
return clickSelector(tab.cdp, tab.sessionId, operation.selector, signal);
|
|
2400
|
+
}
|
|
2401
|
+
if (operation.x === undefined || operation.y === undefined) {
|
|
2402
|
+
throw new Error("click requires id, selector, or x+y");
|
|
2403
|
+
}
|
|
2404
|
+
return clickCoordinates(tab.cdp, tab.sessionId, operation.x, operation.y, signal);
|
|
2405
|
+
});
|
|
2406
|
+
case "type":
|
|
2407
|
+
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));
|
|
2408
|
+
case "load_all":
|
|
2409
|
+
return this.tabResult(operation.ref_id, signal, (tab) => loadAll(tab.cdp, tab.sessionId, operation.selector, operation.interval_ms, signal));
|
|
2410
|
+
}
|
|
2411
|
+
}
|
|
2412
|
+
async screenshot(operation, signal) {
|
|
2413
|
+
const file = await screenshotPath(operation);
|
|
2414
|
+
return this.cdp.withTab(operation.ref_id, signal, async (tab) => {
|
|
2415
|
+
const capture2 = 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);
|
|
2416
|
+
return {
|
|
2417
|
+
ref_id: tab.refId,
|
|
2418
|
+
...operation.id === undefined ? {} : { id: operation.id },
|
|
2419
|
+
...operation.selector ? { selector: operation.selector } : {},
|
|
2420
|
+
file: capture2.file,
|
|
2421
|
+
dpr: capture2.dpr,
|
|
2422
|
+
coordinates: "CSS pixels; screenshot pixels / DPR"
|
|
2423
|
+
};
|
|
2424
|
+
});
|
|
2425
|
+
}
|
|
2426
|
+
async tabResult(refId, signal, action) {
|
|
2427
|
+
return this.cdp.withTab(refId, signal, async (tab) => ({
|
|
2428
|
+
ref_id: tab.refId,
|
|
2429
|
+
result: await action(tab) || "ok"
|
|
2430
|
+
}));
|
|
2431
|
+
}
|
|
2432
|
+
}
|
|
2433
|
+
|
|
2434
|
+
// src/browser/remote.ts
|
|
2435
|
+
import { mkdir as mkdir2, rm as rm2 } from "node:fs/promises";
|
|
2436
|
+
import { basename as basename2, join as join3 } from "node:path";
|
|
2437
|
+
|
|
2438
|
+
// src/browser/remote-helper.ts
|
|
2439
|
+
import { readFile as readFile2 } from "node:fs/promises";
|
|
2440
|
+
import { fileURLToPath } from "node:url";
|
|
2441
|
+
|
|
2442
|
+
// src/browser/remote-process.ts
|
|
2443
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
2444
|
+
import { StringDecoder as StringDecoder2 } from "node:string_decoder";
|
|
2445
|
+
var OUTPUT_LIMIT_BYTES = 8 * 1024 * 1024;
|
|
2446
|
+
function abortReason2(signal) {
|
|
2447
|
+
return signal.reason instanceof Error ? signal.reason : new Error("Remote browser operation aborted");
|
|
2448
|
+
}
|
|
2449
|
+
function runProgram(command, args, input, signal) {
|
|
2450
|
+
if (signal?.aborted)
|
|
2451
|
+
return Promise.reject(abortReason2(signal));
|
|
2452
|
+
return new Promise((resolveValue, reject) => {
|
|
2453
|
+
const child = spawn2(command, args, {
|
|
2454
|
+
stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"]
|
|
2455
|
+
});
|
|
2456
|
+
let stdout = "";
|
|
2457
|
+
let stderr = "";
|
|
2458
|
+
const stdoutDecoder = new StringDecoder2("utf8");
|
|
2459
|
+
const stderrDecoder = new StringDecoder2("utf8");
|
|
2460
|
+
let bytes = 0;
|
|
2461
|
+
let settled = false;
|
|
2462
|
+
let killTimer;
|
|
2463
|
+
const running = () => child.exitCode === null && child.signalCode === null;
|
|
2464
|
+
const cleanup = () => {
|
|
2465
|
+
if (killTimer)
|
|
2466
|
+
clearTimeout(killTimer);
|
|
2467
|
+
signal?.removeEventListener("abort", abort);
|
|
2468
|
+
};
|
|
2469
|
+
const finish = (action) => {
|
|
2470
|
+
if (settled)
|
|
2471
|
+
return;
|
|
2472
|
+
settled = true;
|
|
2473
|
+
cleanup();
|
|
2474
|
+
action();
|
|
2475
|
+
};
|
|
2476
|
+
const abort = () => {
|
|
2477
|
+
if (running())
|
|
2478
|
+
child.kill("SIGTERM");
|
|
2479
|
+
killTimer = setTimeout(() => {
|
|
2480
|
+
if (running())
|
|
2481
|
+
child.kill("SIGKILL");
|
|
2482
|
+
}, 1000);
|
|
2483
|
+
killTimer.unref?.();
|
|
2484
|
+
};
|
|
2485
|
+
const append = (target, chunk) => {
|
|
2486
|
+
bytes += chunk.length;
|
|
2487
|
+
if (bytes > OUTPUT_LIMIT_BYTES) {
|
|
2488
|
+
if (running())
|
|
2489
|
+
child.kill("SIGKILL");
|
|
2490
|
+
finish(() => reject(new Error("Remote browser output exceeded 8 MiB")));
|
|
2491
|
+
return;
|
|
2492
|
+
}
|
|
2493
|
+
if (target === "stdout")
|
|
2494
|
+
stdout += stdoutDecoder.write(chunk);
|
|
2495
|
+
else
|
|
2496
|
+
stderr += stderrDecoder.write(chunk);
|
|
2497
|
+
};
|
|
2498
|
+
child.stdout?.on("data", (chunk) => append("stdout", chunk));
|
|
2499
|
+
child.stderr?.on("data", (chunk) => append("stderr", chunk));
|
|
2500
|
+
child.on("error", (error) => finish(() => reject(error)));
|
|
2501
|
+
child.on("close", (code) => finish(() => {
|
|
2502
|
+
stdout += stdoutDecoder.end();
|
|
2503
|
+
stderr += stderrDecoder.end();
|
|
2504
|
+
if (signal?.aborted) {
|
|
2505
|
+
reject(abortReason2(signal));
|
|
2506
|
+
return;
|
|
2507
|
+
}
|
|
2508
|
+
resolveValue({
|
|
2509
|
+
code: code ?? 1,
|
|
2510
|
+
stderr: stderr.trim(),
|
|
2511
|
+
stdout: stdout.trim()
|
|
2512
|
+
});
|
|
2513
|
+
}));
|
|
2514
|
+
if (input !== undefined)
|
|
2515
|
+
child.stdin?.end(input);
|
|
2516
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
2517
|
+
});
|
|
2518
|
+
}
|
|
2519
|
+
|
|
2520
|
+
// src/browser/remote-helper.ts
|
|
2521
|
+
var DEPLOY_TIMEOUT_MS = 20000;
|
|
2522
|
+
var REMOTE_HELPER = "~/.pi/agent/pi-browser-worker.mjs";
|
|
2523
|
+
var deployments = new Map;
|
|
2524
|
+
var helperSourcePromise;
|
|
2525
|
+
var DEPLOY_SOURCE = String.raw`
|
|
2526
|
+
const { randomUUID } = require("node:crypto");
|
|
2527
|
+
const { mkdir, readFile, rename, unlink, writeFile } = require("node:fs/promises");
|
|
2528
|
+
const { homedir } = require("node:os");
|
|
2529
|
+
const { dirname, join } = require("node:path");
|
|
2530
|
+
const targetValue = process.argv[1];
|
|
2531
|
+
const marker = "// @howaboua/pi-browser managed worker";
|
|
2532
|
+
const target = targetValue === "~" ? homedir() : targetValue.startsWith("~/") ? join(homedir(), targetValue.slice(2)) : targetValue;
|
|
2533
|
+
const chunks = [];
|
|
2534
|
+
let size = 0;
|
|
2535
|
+
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); });
|
|
2536
|
+
process.stdin.on("end", () => { void (async () => {
|
|
2537
|
+
const source = Buffer.concat(chunks);
|
|
2538
|
+
let existing;
|
|
2539
|
+
try { existing = await readFile(target); } catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
2540
|
+
if (existing) {
|
|
2541
|
+
if (existing.equals(source)) { process.stdout.write(JSON.stringify({ updated: false, path: target }) + "\n"); return; }
|
|
2542
|
+
if (!existing.toString("utf8", 0, 512).includes(marker)) throw new Error(target + " is not owned by pi-browser");
|
|
2543
|
+
}
|
|
2544
|
+
await mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
|
2545
|
+
const temporary = target + "." + process.pid + "." + randomUUID() + ".tmp";
|
|
2546
|
+
try {
|
|
2547
|
+
await writeFile(temporary, source, { mode: 0o600, flag: "wx" });
|
|
2548
|
+
await rename(temporary, target);
|
|
2549
|
+
} catch (error) {
|
|
2550
|
+
await unlink(temporary).catch(() => undefined);
|
|
2551
|
+
throw error;
|
|
2552
|
+
}
|
|
2553
|
+
process.stdout.write(JSON.stringify({ updated: true, path: target }) + "\n");
|
|
2554
|
+
})().catch(error => { process.stderr.write(error.message + "\n"); process.exit(1); }); });
|
|
2555
|
+
`;
|
|
2556
|
+
function remoteNodeCommand(command) {
|
|
2557
|
+
return `${command.nodePath} --preserve-symlinks-main "$HOME"/.pi/agent/pi-browser-worker.mjs`;
|
|
2558
|
+
}
|
|
2559
|
+
function shellQuote(value) {
|
|
2560
|
+
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
2561
|
+
}
|
|
2562
|
+
function waitFor(promise, signal) {
|
|
2563
|
+
if (!signal)
|
|
2564
|
+
return promise;
|
|
2565
|
+
if (signal.aborted)
|
|
2566
|
+
return Promise.reject(abortReason2(signal));
|
|
2567
|
+
return new Promise((resolveValue, reject) => {
|
|
2568
|
+
const abort = () => {
|
|
2569
|
+
cleanup();
|
|
2570
|
+
reject(abortReason2(signal));
|
|
2571
|
+
};
|
|
2572
|
+
const cleanup = () => signal.removeEventListener("abort", abort);
|
|
2573
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
2574
|
+
promise.then((value) => {
|
|
2575
|
+
cleanup();
|
|
2576
|
+
resolveValue(value);
|
|
2577
|
+
}, (error) => {
|
|
2578
|
+
cleanup();
|
|
2579
|
+
reject(error);
|
|
2580
|
+
});
|
|
2581
|
+
});
|
|
2582
|
+
}
|
|
2583
|
+
async function readHelperSource() {
|
|
2584
|
+
const candidates = [
|
|
2585
|
+
fileURLToPath(new URL("../../remote-worker.js", import.meta.url)),
|
|
2586
|
+
fileURLToPath(new URL("../../dist/remote-worker.js", import.meta.url))
|
|
2587
|
+
];
|
|
2588
|
+
let lastError;
|
|
2589
|
+
for (const path of candidates) {
|
|
2590
|
+
try {
|
|
2591
|
+
return await readFile2(path, "utf8");
|
|
2592
|
+
} catch (error) {
|
|
2593
|
+
lastError = error;
|
|
2594
|
+
}
|
|
2595
|
+
}
|
|
2596
|
+
throw new Error(`Could not read bundled browser worker: ${lastError instanceof Error ? lastError.message : String(lastError)}`);
|
|
2597
|
+
}
|
|
2598
|
+
async function deployRemoteHelper(host, command) {
|
|
2599
|
+
helperSourcePromise ??= readHelperSource();
|
|
2600
|
+
let source;
|
|
2601
|
+
try {
|
|
2602
|
+
source = await helperSourcePromise;
|
|
2603
|
+
} catch (error) {
|
|
2604
|
+
helperSourcePromise = undefined;
|
|
2605
|
+
throw error;
|
|
2606
|
+
}
|
|
2607
|
+
const deployment = await runProgram("ssh", [
|
|
2608
|
+
host,
|
|
2609
|
+
`${command.nodePath} -e ${shellQuote(DEPLOY_SOURCE)} ${shellQuote(REMOTE_HELPER)}`
|
|
2610
|
+
], source, AbortSignal.timeout(DEPLOY_TIMEOUT_MS));
|
|
2611
|
+
if (deployment.code !== 0) {
|
|
2612
|
+
throw new Error(deployment.stderr || deployment.stdout || "could not deploy remote browser worker");
|
|
2613
|
+
}
|
|
2614
|
+
}
|
|
2615
|
+
async function ensureRemoteHelper(host, command, signal) {
|
|
2616
|
+
const key = `${host}\x00${command.nodePath}`;
|
|
2617
|
+
let deployment = deployments.get(key);
|
|
2618
|
+
if (!deployment) {
|
|
2619
|
+
deployment = deployRemoteHelper(host, command);
|
|
2620
|
+
deployments.set(key, deployment);
|
|
2621
|
+
deployment.catch(() => {
|
|
2622
|
+
if (deployments.get(key) === deployment)
|
|
2623
|
+
deployments.delete(key);
|
|
2624
|
+
});
|
|
2625
|
+
}
|
|
2626
|
+
await waitFor(deployment, signal);
|
|
2627
|
+
}
|
|
2628
|
+
|
|
2629
|
+
// src/browser/remote.ts
|
|
2630
|
+
var SAFE_REMOTE_FILE = /^\/[A-Za-z0-9_./-]+$/;
|
|
2631
|
+
function isRecord2(value) {
|
|
2632
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2633
|
+
}
|
|
2634
|
+
async function copyRemoteArtifact(host, remoteFile, signal) {
|
|
2635
|
+
if (!SAFE_REMOTE_FILE.test(remoteFile)) {
|
|
2636
|
+
throw new Error(`remote browser returned an unsafe artifact path: ${remoteFile}`);
|
|
2637
|
+
}
|
|
2638
|
+
await mkdir2(artifactDirectory(), { recursive: true, mode: 448 });
|
|
2639
|
+
const localFile = join3(artifactDirectory(), `${host}-${basename2(remoteFile)}`);
|
|
2640
|
+
const copied = await runProgram("scp", ["-q", `${host}:${remoteFile}`, localFile], undefined, signal);
|
|
2641
|
+
if (copied.code !== 0) {
|
|
2642
|
+
throw new Error(copied.stderr || copied.stdout || "could not copy remote screenshot");
|
|
2643
|
+
}
|
|
2644
|
+
try {
|
|
2645
|
+
const removed = await runProgram("ssh", [host, `/usr/bin/rm -- ${remoteFile}`], undefined, signal);
|
|
2646
|
+
if (removed.code !== 0) {
|
|
2647
|
+
throw new Error(removed.stderr || removed.stdout || "copied screenshot but could not remove remote artifact");
|
|
2648
|
+
}
|
|
2649
|
+
return localFile;
|
|
2650
|
+
} catch (error) {
|
|
2651
|
+
await rm2(localFile, { force: true });
|
|
2652
|
+
throw error;
|
|
2653
|
+
}
|
|
2654
|
+
}
|
|
2655
|
+
async function localizeScreenshots(host, operations, result, signal) {
|
|
2656
|
+
for (const [index, operation] of operations.entries()) {
|
|
2657
|
+
if (operation.action !== "screenshot")
|
|
2658
|
+
continue;
|
|
2659
|
+
const item = operations.length === 1 ? result : Array.isArray(result["results"]) ? result["results"][index] : undefined;
|
|
2660
|
+
if (!isRecord2(item) || typeof item["file"] !== "string") {
|
|
2661
|
+
throw new Error(`remote screenshot result ${index} has no file path`);
|
|
2662
|
+
}
|
|
2663
|
+
item["file"] = await copyRemoteArtifact(host, item["file"], signal);
|
|
2664
|
+
}
|
|
2665
|
+
}
|
|
2666
|
+
async function executeRemoteBrowser(route, operations, signal) {
|
|
2667
|
+
if (!route.remote) {
|
|
2668
|
+
throw new Error(`Browser host ${route.name} has no remote command`);
|
|
2669
|
+
}
|
|
2670
|
+
await ensureRemoteHelper(route.name, route.remote, signal);
|
|
2671
|
+
const executed = await runProgram("ssh", [route.name, remoteNodeCommand(route.remote)], JSON.stringify({ operations }), signal);
|
|
2672
|
+
if (executed.code !== 0) {
|
|
2673
|
+
throw new Error(executed.stderr || executed.stdout || `remote browser exited with code ${executed.code}`);
|
|
2674
|
+
}
|
|
2675
|
+
let value;
|
|
2676
|
+
try {
|
|
2677
|
+
value = JSON.parse(executed.stdout);
|
|
2678
|
+
} catch (error) {
|
|
2679
|
+
throw new Error(`remote browser returned invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
2680
|
+
}
|
|
2681
|
+
if (!isRecord2(value)) {
|
|
2682
|
+
throw new Error("remote browser result is not an object");
|
|
2683
|
+
}
|
|
2684
|
+
await localizeScreenshots(route.name, operations, value, signal);
|
|
2685
|
+
return value;
|
|
2686
|
+
}
|
|
2687
|
+
|
|
2688
|
+
// src/browser/runtime.ts
|
|
2689
|
+
class BrowserRuntime {
|
|
2690
|
+
hosts;
|
|
2691
|
+
cdp = new BrowserCdpSession;
|
|
2692
|
+
operations = new BrowserOperationExecutor(this.cdp);
|
|
2693
|
+
routes;
|
|
2694
|
+
constructor(routes = loadBrowserRoutes()) {
|
|
2695
|
+
this.routes = routes;
|
|
2696
|
+
this.hosts = routes.names;
|
|
2697
|
+
}
|
|
2698
|
+
async execute(request, options = {}) {
|
|
2699
|
+
options.signal?.throwIfAborted();
|
|
2700
|
+
await pruneArtifacts();
|
|
2701
|
+
if ("help" in request)
|
|
2702
|
+
return browserHelp(this.hosts);
|
|
2703
|
+
if (request.host) {
|
|
2704
|
+
const route = this.routes.resolve(request.host);
|
|
2705
|
+
if (!route.local) {
|
|
2706
|
+
const first = request.operations[0];
|
|
2707
|
+
if (first) {
|
|
2708
|
+
options.onOperation?.(first, 0, request.operations.length);
|
|
2709
|
+
}
|
|
2710
|
+
const result2 = await executeRemoteBrowser(route, request.operations, options.signal);
|
|
2711
|
+
return { host: request.host, ...result2 };
|
|
2712
|
+
}
|
|
2713
|
+
}
|
|
2714
|
+
const result = await this.executeLocal(request.operations, options);
|
|
2715
|
+
return request.host ? { host: request.host, ...result } : result;
|
|
2716
|
+
}
|
|
2717
|
+
close() {
|
|
2718
|
+
this.cdp.close();
|
|
2719
|
+
}
|
|
2720
|
+
async executeLocal(operations, options) {
|
|
2721
|
+
const results = [];
|
|
2722
|
+
for (const [index, operation] of operations.entries()) {
|
|
2723
|
+
try {
|
|
2724
|
+
options.signal?.throwIfAborted();
|
|
2725
|
+
options.onOperation?.(operation, index, operations.length);
|
|
2726
|
+
results.push(await this.operations.execute(operation, options.signal));
|
|
2727
|
+
} catch (error) {
|
|
2728
|
+
throw new Error(`batch failed at ${operation.action}[${index}] after ${results.length} completed operation(s): ${error instanceof Error ? error.message : String(error)}`);
|
|
2729
|
+
}
|
|
2730
|
+
}
|
|
2731
|
+
const first = results[0];
|
|
2732
|
+
if (results.length === 1 && first)
|
|
2733
|
+
return first;
|
|
2734
|
+
return {
|
|
2735
|
+
results: results.map((result, index) => ({
|
|
2736
|
+
operation: operations[index]?.action ?? "unknown",
|
|
2737
|
+
index,
|
|
2738
|
+
...result
|
|
2739
|
+
}))
|
|
2740
|
+
};
|
|
2741
|
+
}
|
|
2742
|
+
}
|
|
2743
|
+
|
|
2744
|
+
// src/browser/worker-server.ts
|
|
2745
|
+
var INPUT_LIMIT_BYTES = 8 * 1024 * 1024;
|
|
2746
|
+
var START_TIMEOUT_MS = 5000;
|
|
2747
|
+
var IDLE_TIMEOUT_MS = 20 * 60 * 1000;
|
|
2748
|
+
var IS_WINDOWS2 = process.platform === "win32";
|
|
2749
|
+
function workerSocketPath(workerId) {
|
|
2750
|
+
if (IS_WINDOWS2)
|
|
2751
|
+
return `\\\\.\\pipe\\pi-browser-worker-${workerId}`;
|
|
2752
|
+
const directory = process.env["XDG_RUNTIME_DIR"] ? join4(process.env["XDG_RUNTIME_DIR"], "browser-tool") : join4(tmpdir2(), `browser-tool-${process.getuid?.() ?? "user"}`);
|
|
2753
|
+
return join4(directory, `worker-${workerId}.sock`);
|
|
2754
|
+
}
|
|
2755
|
+
async function ensureWorkerSocketDirectory(workerId) {
|
|
2756
|
+
if (IS_WINDOWS2)
|
|
2757
|
+
return;
|
|
2758
|
+
const directory = dirname2(workerSocketPath(workerId));
|
|
2759
|
+
await mkdir3(directory, { recursive: true, mode: 448 });
|
|
2760
|
+
const info = await lstat(directory);
|
|
2761
|
+
const uid = process.getuid?.();
|
|
2762
|
+
if (info.isSymbolicLink() || !info.isDirectory()) {
|
|
2763
|
+
throw new Error(`Browser worker socket directory is not a directory: ${directory}`);
|
|
2764
|
+
}
|
|
2765
|
+
if (uid === undefined || info.uid !== uid) {
|
|
2766
|
+
throw new Error(`Browser worker socket directory is not owned by this user: ${directory}`);
|
|
2767
|
+
}
|
|
2768
|
+
if ((info.mode & 63) !== 0)
|
|
2769
|
+
await chmod(directory, 448);
|
|
2770
|
+
}
|
|
2771
|
+
function parseWorkerOperations(input) {
|
|
2772
|
+
let value;
|
|
2773
|
+
try {
|
|
2774
|
+
value = JSON.parse(input);
|
|
2775
|
+
} catch (error) {
|
|
2776
|
+
throw new Error(`worker input must be valid JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
2777
|
+
}
|
|
2778
|
+
if (!isRecordValue(value))
|
|
2779
|
+
throw new Error("worker input must be an object");
|
|
2780
|
+
const unknown = Object.keys(value).filter((key) => key !== "operations");
|
|
2781
|
+
if (unknown.length > 0) {
|
|
2782
|
+
throw new Error(`unknown worker field(s): ${unknown.join(", ")}`);
|
|
2783
|
+
}
|
|
2784
|
+
if (!Array.isArray(value["operations"]) || value["operations"].length === 0) {
|
|
2785
|
+
throw new Error("worker operations must be a non-empty array");
|
|
2786
|
+
}
|
|
2787
|
+
return value["operations"].map((operation, index) => {
|
|
2788
|
+
if (!isRecordValue(operation)) {
|
|
2789
|
+
throw new Error(`worker operations[${index}] must be an object`);
|
|
2790
|
+
}
|
|
2791
|
+
const parsed = parseActionRequest(operation);
|
|
2792
|
+
if (parsed.action === "help") {
|
|
2793
|
+
throw new Error("help is not a worker operation");
|
|
2794
|
+
}
|
|
2795
|
+
return parsed;
|
|
2796
|
+
});
|
|
2797
|
+
}
|
|
2798
|
+
function readLine(socket) {
|
|
2799
|
+
return new Promise((resolveValue, reject) => {
|
|
2800
|
+
let input = "";
|
|
2801
|
+
let bytes = 0;
|
|
2802
|
+
const decoder = new StringDecoder3("utf8");
|
|
2803
|
+
const cleanup = () => {
|
|
2804
|
+
socket.off("data", onData);
|
|
2805
|
+
socket.off("end", onEnd);
|
|
2806
|
+
socket.off("error", onError);
|
|
2807
|
+
};
|
|
2808
|
+
const onError = (error) => {
|
|
2809
|
+
cleanup();
|
|
2810
|
+
reject(error);
|
|
2811
|
+
};
|
|
2812
|
+
const onEnd = () => onError(new Error("Browser worker closed early"));
|
|
2813
|
+
const onData = (chunk) => {
|
|
2814
|
+
bytes += chunk.length;
|
|
2815
|
+
if (bytes > INPUT_LIMIT_BYTES) {
|
|
2816
|
+
cleanup();
|
|
2817
|
+
reject(new Error("Browser worker input exceeded 8 MiB"));
|
|
2818
|
+
return;
|
|
2819
|
+
}
|
|
2820
|
+
input += decoder.write(chunk);
|
|
2821
|
+
const newline = input.indexOf(`
|
|
2822
|
+
`);
|
|
2823
|
+
if (newline < 0)
|
|
2824
|
+
return;
|
|
2825
|
+
cleanup();
|
|
2826
|
+
resolveValue(input.slice(0, newline));
|
|
2827
|
+
};
|
|
2828
|
+
socket.on("data", onData);
|
|
2829
|
+
socket.once("end", onEnd);
|
|
2830
|
+
socket.once("error", onError);
|
|
2831
|
+
});
|
|
2832
|
+
}
|
|
2833
|
+
async function handleConnection(socket, runtime) {
|
|
2834
|
+
const controller = new AbortController;
|
|
2835
|
+
const abort = () => controller.abort(new Error("Browser worker requester disconnected"));
|
|
2836
|
+
socket.once("close", abort);
|
|
2837
|
+
socket.once("error", abort);
|
|
2838
|
+
let response;
|
|
2839
|
+
try {
|
|
2840
|
+
const operations = parseWorkerOperations(await readLine(socket));
|
|
2841
|
+
response = {
|
|
2842
|
+
ok: true,
|
|
2843
|
+
result: await runtime.execute({ operations }, { signal: controller.signal })
|
|
2844
|
+
};
|
|
2845
|
+
} catch (error) {
|
|
2846
|
+
response = {
|
|
2847
|
+
ok: false,
|
|
2848
|
+
error: error instanceof Error ? error.message : String(error)
|
|
2849
|
+
};
|
|
2850
|
+
}
|
|
2851
|
+
socket.off("close", abort);
|
|
2852
|
+
socket.off("error", abort);
|
|
2853
|
+
if (!socket.destroyed)
|
|
2854
|
+
socket.end(`${JSON.stringify(response)}
|
|
2855
|
+
`);
|
|
2856
|
+
}
|
|
2857
|
+
async function serveBrowserWorker(workerId) {
|
|
2858
|
+
const path = workerSocketPath(workerId);
|
|
2859
|
+
await ensureWorkerSocketDirectory(workerId);
|
|
2860
|
+
const runtime = new BrowserRuntime(new BrowserRoutes);
|
|
2861
|
+
let ownsSocket = false;
|
|
2862
|
+
const server = createServer((socket) => {
|
|
2863
|
+
resetIdle();
|
|
2864
|
+
handleConnection(socket, runtime).finally(resetIdle);
|
|
2865
|
+
});
|
|
2866
|
+
let idleTimer;
|
|
2867
|
+
const close = () => server.close();
|
|
2868
|
+
const resetIdle = () => {
|
|
2869
|
+
if (idleTimer)
|
|
2870
|
+
clearTimeout(idleTimer);
|
|
2871
|
+
idleTimer = setTimeout(close, IDLE_TIMEOUT_MS);
|
|
2872
|
+
idleTimer.unref?.();
|
|
2873
|
+
};
|
|
2874
|
+
process.once("SIGINT", close);
|
|
2875
|
+
process.once("SIGTERM", close);
|
|
2876
|
+
try {
|
|
2877
|
+
await new Promise((resolveValue, reject) => {
|
|
2878
|
+
server.once("error", reject);
|
|
2879
|
+
server.listen(path, () => {
|
|
2880
|
+
ownsSocket = true;
|
|
2881
|
+
server.off("error", reject);
|
|
2882
|
+
resetIdle();
|
|
2883
|
+
});
|
|
2884
|
+
server.once("close", resolveValue);
|
|
2885
|
+
});
|
|
2886
|
+
} finally {
|
|
2887
|
+
if (idleTimer)
|
|
2888
|
+
clearTimeout(idleTimer);
|
|
2889
|
+
process.removeListener("SIGINT", close);
|
|
2890
|
+
process.removeListener("SIGTERM", close);
|
|
2891
|
+
runtime.close();
|
|
2892
|
+
if (!IS_WINDOWS2 && ownsSocket)
|
|
2893
|
+
await rm3(path, { force: true });
|
|
2894
|
+
}
|
|
2895
|
+
}
|
|
2896
|
+
async function requestOnce(input, workerId, signal) {
|
|
2897
|
+
if (signal?.aborted) {
|
|
2898
|
+
return Promise.reject(signal.reason ?? new Error("Browser worker request aborted"));
|
|
2899
|
+
}
|
|
2900
|
+
await ensureWorkerSocketDirectory(workerId);
|
|
2901
|
+
if (signal?.aborted) {
|
|
2902
|
+
throw signal.reason ?? new Error("Browser worker request aborted");
|
|
2903
|
+
}
|
|
2904
|
+
return new Promise((resolveValue, reject) => {
|
|
2905
|
+
const socket = createConnection(workerSocketPath(workerId));
|
|
2906
|
+
const abort = () => {
|
|
2907
|
+
socket.destroy();
|
|
2908
|
+
reject(signal?.reason ?? new Error("Browser worker request aborted"));
|
|
2909
|
+
};
|
|
2910
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
2911
|
+
socket.once("connect", () => socket.write(`${input}
|
|
2912
|
+
`));
|
|
2913
|
+
readLine(socket).then((line2) => {
|
|
2914
|
+
signal?.removeEventListener("abort", abort);
|
|
2915
|
+
socket.destroy();
|
|
2916
|
+
try {
|
|
2917
|
+
const response = JSON.parse(line2);
|
|
2918
|
+
if (!isRecordValue(response) || typeof response["ok"] !== "boolean") {
|
|
2919
|
+
throw new Error("Browser worker returned an invalid response");
|
|
2920
|
+
}
|
|
2921
|
+
resolveValue(response);
|
|
2922
|
+
} catch (error) {
|
|
2923
|
+
reject(error);
|
|
2924
|
+
}
|
|
2925
|
+
}, (error) => {
|
|
2926
|
+
signal?.removeEventListener("abort", abort);
|
|
2927
|
+
socket.destroy();
|
|
2928
|
+
reject(error);
|
|
2929
|
+
});
|
|
2930
|
+
});
|
|
2931
|
+
}
|
|
2932
|
+
function canStartWorker(error) {
|
|
2933
|
+
return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ECONNREFUSED");
|
|
2934
|
+
}
|
|
2935
|
+
async function requestBrowserWorker(input, entryPath, workerId, signal) {
|
|
2936
|
+
try {
|
|
2937
|
+
const response = await requestOnce(input, workerId, signal);
|
|
2938
|
+
if (!response.ok)
|
|
2939
|
+
throw new Error(response.error ?? "Browser worker failed");
|
|
2940
|
+
if (!response.result)
|
|
2941
|
+
throw new Error("Browser worker returned no result");
|
|
2942
|
+
return response.result;
|
|
2943
|
+
} catch (error) {
|
|
2944
|
+
if (!canStartWorker(error))
|
|
2945
|
+
throw error;
|
|
2946
|
+
}
|
|
2947
|
+
if (!IS_WINDOWS2)
|
|
2948
|
+
await rm3(workerSocketPath(workerId), { force: true });
|
|
2949
|
+
const child = spawn3(process.execPath, ["--preserve-symlinks-main", entryPath, "--daemon"], { detached: true, stdio: "ignore" });
|
|
2950
|
+
child.unref();
|
|
2951
|
+
const deadline = Date.now() + START_TIMEOUT_MS;
|
|
2952
|
+
let lastError;
|
|
2953
|
+
while (Date.now() < deadline) {
|
|
2954
|
+
try {
|
|
2955
|
+
const response = await requestOnce(input, workerId, signal);
|
|
2956
|
+
if (!response.ok)
|
|
2957
|
+
throw new Error(response.error ?? "Browser worker failed");
|
|
2958
|
+
if (!response.result)
|
|
2959
|
+
throw new Error("Browser worker returned no result");
|
|
2960
|
+
return response.result;
|
|
2961
|
+
} catch (error) {
|
|
2962
|
+
if (!canStartWorker(error))
|
|
2963
|
+
throw error;
|
|
2964
|
+
lastError = error;
|
|
2965
|
+
await new Promise((resolveValue) => setTimeout(resolveValue, 50));
|
|
2966
|
+
}
|
|
2967
|
+
}
|
|
2968
|
+
throw new Error(`Browser worker did not start within ${START_TIMEOUT_MS}ms${lastError instanceof Error ? `: ${lastError.message}` : ""}`);
|
|
2969
|
+
}
|
|
2970
|
+
|
|
2971
|
+
// remote-worker.ts
|
|
2972
|
+
async function readStdin() {
|
|
2973
|
+
let input = "";
|
|
2974
|
+
process.stdin.setEncoding("utf8");
|
|
2975
|
+
for await (const chunk of process.stdin)
|
|
2976
|
+
input += chunk;
|
|
2977
|
+
return input;
|
|
2978
|
+
}
|
|
2979
|
+
async function main() {
|
|
2980
|
+
const entryPath = fileURLToPath2(import.meta.url);
|
|
2981
|
+
const workerId = createHash("sha256").update(readFileSync3(entryPath)).digest("hex").slice(0, 12);
|
|
2982
|
+
if (process.argv.includes("--daemon")) {
|
|
2983
|
+
await serveBrowserWorker(workerId);
|
|
2984
|
+
return;
|
|
2985
|
+
}
|
|
2986
|
+
const controller = new AbortController;
|
|
2987
|
+
const abort = () => controller.abort(new Error("Remote browser interrupted"));
|
|
2988
|
+
process.once("SIGINT", abort);
|
|
2989
|
+
process.once("SIGTERM", abort);
|
|
2990
|
+
try {
|
|
2991
|
+
const result = await requestBrowserWorker(await readStdin(), entryPath, workerId, controller.signal);
|
|
2992
|
+
process.stdout.write(`${JSON.stringify(result)}
|
|
2993
|
+
`);
|
|
2994
|
+
} finally {
|
|
2995
|
+
process.removeListener("SIGINT", abort);
|
|
2996
|
+
process.removeListener("SIGTERM", abort);
|
|
2997
|
+
}
|
|
2998
|
+
}
|
|
2999
|
+
if (process.argv[1] && realpathSync(fileURLToPath2(import.meta.url)) === realpathSync(resolve2(process.argv[1]))) {
|
|
3000
|
+
main().catch((error) => {
|
|
3001
|
+
process.stderr.write(`pi-browser-worker: ${error instanceof Error ? error.message : String(error)}
|
|
3002
|
+
`);
|
|
3003
|
+
process.exitCode = 1;
|
|
3004
|
+
});
|
|
3005
|
+
}
|