@querying/sneaky 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +171 -2
- package/bin/sneaky-mcp.mjs +5 -0
- package/bin/sneaky.mjs +51 -0
- package/dist/agent/index.d.ts +277 -0
- package/dist/agent/index.js +319 -0
- package/dist/agent/index.js.map +1 -0
- package/dist/browser/index.d.ts +69 -0
- package/dist/browser/index.js +326 -0
- package/dist/browser/index.js.map +1 -0
- package/dist/cli/index.d.ts +51 -0
- package/dist/cli/index.js +189 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/driver/cdp.d.ts +36 -0
- package/dist/driver/cdp.js +240 -0
- package/dist/driver/cdp.js.map +1 -0
- package/dist/driver/frame.d.ts +229 -0
- package/dist/driver/frame.js +794 -0
- package/dist/driver/frame.js.map +1 -0
- package/dist/driver/index.d.ts +13 -0
- package/dist/driver/index.js +6 -0
- package/dist/driver/index.js.map +1 -0
- package/dist/driver/keys.d.ts +9 -0
- package/dist/driver/keys.js +65 -0
- package/dist/driver/keys.js.map +1 -0
- package/dist/driver/launcher.d.ts +49 -0
- package/dist/driver/launcher.js +251 -0
- package/dist/driver/launcher.js.map +1 -0
- package/dist/driver/page.d.ts +391 -0
- package/dist/driver/page.js +1594 -0
- package/dist/driver/page.js.map +1 -0
- package/dist/index.d.ts +501 -0
- package/dist/index.js +688 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp/server.d.ts +35 -0
- package/dist/mcp/server.js +548 -0
- package/dist/mcp/server.js.map +1 -0
- package/dist/repl/cli.d.ts +1 -0
- package/dist/repl/cli.js +246 -0
- package/dist/repl/cli.js.map +1 -0
- package/dist/repl/host.d.ts +46 -0
- package/dist/repl/host.js +167 -0
- package/dist/repl/host.js.map +1 -0
- package/dist/repl/index.d.ts +246 -0
- package/dist/repl/index.js +923 -0
- package/dist/repl/index.js.map +1 -0
- package/dist/repl/transform.d.ts +19 -0
- package/dist/repl/transform.js +590 -0
- package/dist/repl/transform.js.map +1 -0
- package/dist/request/index.d.ts +265 -0
- package/dist/request/index.js +898 -0
- package/dist/request/index.js.map +1 -0
- package/package.json +83 -4
|
@@ -0,0 +1,1594 @@
|
|
|
1
|
+
import { EventEmitter } from "node:events";
|
|
2
|
+
import { writeFileSync } from "node:fs";
|
|
3
|
+
import { CDPConnection, SneakyCDPSession } from "./cdp.js";
|
|
4
|
+
import { SneakyFrame, } from "./frame.js";
|
|
5
|
+
import { parseKeyCombo, resolveKey } from "./keys.js";
|
|
6
|
+
import { launchChromiumProcess } from "./launcher.js";
|
|
7
|
+
export class SneakyRequest {
|
|
8
|
+
data;
|
|
9
|
+
constructor(data) {
|
|
10
|
+
this.data = data;
|
|
11
|
+
}
|
|
12
|
+
url() {
|
|
13
|
+
return this.data.url;
|
|
14
|
+
}
|
|
15
|
+
method() {
|
|
16
|
+
return this.data.method;
|
|
17
|
+
}
|
|
18
|
+
resourceType() {
|
|
19
|
+
return this.data.resourceType.toLowerCase();
|
|
20
|
+
}
|
|
21
|
+
headers() {
|
|
22
|
+
const out = {};
|
|
23
|
+
for (const [k, v] of Object.entries(this.data.headers))
|
|
24
|
+
out[k.toLowerCase()] = v;
|
|
25
|
+
return out;
|
|
26
|
+
}
|
|
27
|
+
async allHeaders() {
|
|
28
|
+
return this.headers();
|
|
29
|
+
}
|
|
30
|
+
postData() {
|
|
31
|
+
return this.data.postData ?? null;
|
|
32
|
+
}
|
|
33
|
+
frame() {
|
|
34
|
+
if (!this.data.frame)
|
|
35
|
+
throw new Error("Request is not associated with a frame");
|
|
36
|
+
return this.data.frame;
|
|
37
|
+
}
|
|
38
|
+
isNavigationRequest() {
|
|
39
|
+
return this.data.isNavigation;
|
|
40
|
+
}
|
|
41
|
+
redirectedFrom() {
|
|
42
|
+
return this.data.redirectedFrom ?? null;
|
|
43
|
+
}
|
|
44
|
+
failure() {
|
|
45
|
+
return this.data.failureText ? { errorText: this.data.failureText } : null;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
export class SneakyResponse {
|
|
49
|
+
cdp;
|
|
50
|
+
sessionId;
|
|
51
|
+
data;
|
|
52
|
+
constructor(cdp, sessionId, data) {
|
|
53
|
+
this.cdp = cdp;
|
|
54
|
+
this.sessionId = sessionId;
|
|
55
|
+
this.data = data;
|
|
56
|
+
}
|
|
57
|
+
url() {
|
|
58
|
+
return this.data.url;
|
|
59
|
+
}
|
|
60
|
+
status() {
|
|
61
|
+
return this.data.status;
|
|
62
|
+
}
|
|
63
|
+
statusText() {
|
|
64
|
+
return this.data.statusText;
|
|
65
|
+
}
|
|
66
|
+
ok() {
|
|
67
|
+
return this.data.status >= 200 && this.data.status < 300;
|
|
68
|
+
}
|
|
69
|
+
headers() {
|
|
70
|
+
const out = {};
|
|
71
|
+
for (const [k, v] of Object.entries(this.data.headers))
|
|
72
|
+
out[k.toLowerCase()] = v;
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
async allHeaders() {
|
|
76
|
+
return this.headers();
|
|
77
|
+
}
|
|
78
|
+
request() {
|
|
79
|
+
return this.data.request;
|
|
80
|
+
}
|
|
81
|
+
frame() {
|
|
82
|
+
return this.data.request.frame();
|
|
83
|
+
}
|
|
84
|
+
async body() {
|
|
85
|
+
const res = await this.cdp.send("Network.getResponseBody", { requestId: this.data.requestId }, this.sessionId);
|
|
86
|
+
return Buffer.from(res.body, res.base64Encoded ? "base64" : "utf8");
|
|
87
|
+
}
|
|
88
|
+
async text() {
|
|
89
|
+
return (await this.body()).toString("utf8");
|
|
90
|
+
}
|
|
91
|
+
async json() {
|
|
92
|
+
return JSON.parse(await this.text());
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const ABORT_MAP = {
|
|
96
|
+
aborted: "Aborted",
|
|
97
|
+
accessdenied: "AccessDenied",
|
|
98
|
+
addressunreachable: "AddressUnreachable",
|
|
99
|
+
blockedbyclient: "BlockedByClient",
|
|
100
|
+
blockedbyresponse: "BlockedByResponse",
|
|
101
|
+
connectionaborted: "ConnectionAborted",
|
|
102
|
+
connectionclosed: "ConnectionClosed",
|
|
103
|
+
connectionfailed: "ConnectionFailed",
|
|
104
|
+
connectionrefused: "ConnectionRefused",
|
|
105
|
+
connectionreset: "ConnectionReset",
|
|
106
|
+
failed: "Failed",
|
|
107
|
+
internetdisconnected: "InternetDisconnected",
|
|
108
|
+
namenotresolved: "NameNotResolved",
|
|
109
|
+
timedout: "TimedOut",
|
|
110
|
+
};
|
|
111
|
+
export class SneakyRoute {
|
|
112
|
+
cdp;
|
|
113
|
+
sessionId;
|
|
114
|
+
fetchRequestId;
|
|
115
|
+
req;
|
|
116
|
+
handled = false;
|
|
117
|
+
constructor(cdp, sessionId, fetchRequestId, req) {
|
|
118
|
+
this.cdp = cdp;
|
|
119
|
+
this.sessionId = sessionId;
|
|
120
|
+
this.fetchRequestId = fetchRequestId;
|
|
121
|
+
this.req = req;
|
|
122
|
+
}
|
|
123
|
+
request() {
|
|
124
|
+
return this.req;
|
|
125
|
+
}
|
|
126
|
+
isHandled() {
|
|
127
|
+
return this.handled;
|
|
128
|
+
}
|
|
129
|
+
async fulfill(options = {}) {
|
|
130
|
+
if (this.handled)
|
|
131
|
+
return;
|
|
132
|
+
this.handled = true;
|
|
133
|
+
const headers = [];
|
|
134
|
+
const rawHeaders = options.headers ?? {};
|
|
135
|
+
let hasContentType = false;
|
|
136
|
+
for (const [k, v] of Object.entries(rawHeaders)) {
|
|
137
|
+
if (k.toLowerCase() === "content-type")
|
|
138
|
+
hasContentType = true;
|
|
139
|
+
headers.push({ name: k, value: String(v) });
|
|
140
|
+
}
|
|
141
|
+
if (options.contentType && !hasContentType) {
|
|
142
|
+
headers.push({ name: "content-type", value: options.contentType });
|
|
143
|
+
}
|
|
144
|
+
const bodyBuf = options.body === undefined
|
|
145
|
+
? Buffer.alloc(0)
|
|
146
|
+
: Buffer.isBuffer(options.body)
|
|
147
|
+
? options.body
|
|
148
|
+
: Buffer.from(options.body, "utf8");
|
|
149
|
+
await this.cdp
|
|
150
|
+
.send("Fetch.fulfillRequest", {
|
|
151
|
+
requestId: this.fetchRequestId,
|
|
152
|
+
responseCode: options.status ?? 200,
|
|
153
|
+
responseHeaders: headers,
|
|
154
|
+
body: bodyBuf.toString("base64"),
|
|
155
|
+
}, this.sessionId)
|
|
156
|
+
.catch(() => { });
|
|
157
|
+
}
|
|
158
|
+
async continue(options = {}) {
|
|
159
|
+
if (this.handled)
|
|
160
|
+
return;
|
|
161
|
+
this.handled = true;
|
|
162
|
+
const params = { requestId: this.fetchRequestId };
|
|
163
|
+
if (options.url)
|
|
164
|
+
params.url = options.url;
|
|
165
|
+
if (options.method)
|
|
166
|
+
params.method = options.method;
|
|
167
|
+
if (options.headers) {
|
|
168
|
+
params.headers = Object.entries(options.headers).map(([name, value]) => ({ name, value }));
|
|
169
|
+
}
|
|
170
|
+
if (options.postData !== undefined) {
|
|
171
|
+
const buf = Buffer.isBuffer(options.postData) ? options.postData : Buffer.from(options.postData, "utf8");
|
|
172
|
+
params.postData = buf.toString("base64");
|
|
173
|
+
}
|
|
174
|
+
await this.cdp.send("Fetch.continueRequest", params, this.sessionId).catch(() => { });
|
|
175
|
+
}
|
|
176
|
+
async abort(errorCode = "failed") {
|
|
177
|
+
if (this.handled)
|
|
178
|
+
return;
|
|
179
|
+
this.handled = true;
|
|
180
|
+
const reason = ABORT_MAP[errorCode.toLowerCase()] ?? "Failed";
|
|
181
|
+
await this.cdp
|
|
182
|
+
.send("Fetch.failRequest", { requestId: this.fetchRequestId, errorReason: reason }, this.sessionId)
|
|
183
|
+
.catch(() => { });
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
export class SneakyDialog {
|
|
187
|
+
cdp;
|
|
188
|
+
sessionId;
|
|
189
|
+
info;
|
|
190
|
+
handled = false;
|
|
191
|
+
constructor(cdp, sessionId, info) {
|
|
192
|
+
this.cdp = cdp;
|
|
193
|
+
this.sessionId = sessionId;
|
|
194
|
+
this.info = info;
|
|
195
|
+
}
|
|
196
|
+
type() {
|
|
197
|
+
return this.info.type;
|
|
198
|
+
}
|
|
199
|
+
message() {
|
|
200
|
+
return this.info.message;
|
|
201
|
+
}
|
|
202
|
+
defaultValue() {
|
|
203
|
+
return this.info.defaultPrompt ?? "";
|
|
204
|
+
}
|
|
205
|
+
async accept(promptText) {
|
|
206
|
+
if (this.handled)
|
|
207
|
+
return;
|
|
208
|
+
this.handled = true;
|
|
209
|
+
const params = { accept: true };
|
|
210
|
+
if (promptText !== undefined)
|
|
211
|
+
params.promptText = promptText;
|
|
212
|
+
await this.cdp.send("Page.handleJavaScriptDialog", params, this.sessionId).catch(() => { });
|
|
213
|
+
}
|
|
214
|
+
async dismiss() {
|
|
215
|
+
if (this.handled)
|
|
216
|
+
return;
|
|
217
|
+
this.handled = true;
|
|
218
|
+
await this.cdp.send("Page.handleJavaScriptDialog", { accept: false }, this.sessionId).catch(() => { });
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
function globToRegExp(glob) {
|
|
222
|
+
if (glob === "**/*" || glob === "*")
|
|
223
|
+
return /^.*$/;
|
|
224
|
+
let re = "^";
|
|
225
|
+
for (let i = 0; i < glob.length; i++) {
|
|
226
|
+
const ch = glob[i];
|
|
227
|
+
if (ch === "*" && glob[i + 1] === "*") {
|
|
228
|
+
re += ".*";
|
|
229
|
+
i++;
|
|
230
|
+
if (glob[i + 1] === "/")
|
|
231
|
+
i++;
|
|
232
|
+
}
|
|
233
|
+
else if (ch === "*") {
|
|
234
|
+
re += "[^/]*";
|
|
235
|
+
}
|
|
236
|
+
else if (ch === "?") {
|
|
237
|
+
re += ".";
|
|
238
|
+
}
|
|
239
|
+
else if ("\\^$+?.()|[]{}".includes(ch)) {
|
|
240
|
+
re += "\\" + ch;
|
|
241
|
+
}
|
|
242
|
+
else {
|
|
243
|
+
re += ch;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return new RegExp(re + "$");
|
|
247
|
+
}
|
|
248
|
+
function matchesRoute(matcher, rawUrl) {
|
|
249
|
+
if (typeof matcher === "function") {
|
|
250
|
+
try {
|
|
251
|
+
return Boolean(matcher(new URL(rawUrl)));
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
return false;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
if (matcher instanceof RegExp)
|
|
258
|
+
return matcher.test(rawUrl);
|
|
259
|
+
return globToRegExp(matcher).test(rawUrl);
|
|
260
|
+
}
|
|
261
|
+
const PAPER_FORMATS = {
|
|
262
|
+
letter: { w: 8.5, h: 11 },
|
|
263
|
+
legal: { w: 8.5, h: 14 },
|
|
264
|
+
tabloid: { w: 11, h: 17 },
|
|
265
|
+
ledger: { w: 17, h: 11 },
|
|
266
|
+
a0: { w: 33.1, h: 46.8 },
|
|
267
|
+
a1: { w: 23.4, h: 33.1 },
|
|
268
|
+
a2: { w: 16.54, h: 23.4 },
|
|
269
|
+
a3: { w: 11.7, h: 16.54 },
|
|
270
|
+
a4: { w: 8.27, h: 11.7 },
|
|
271
|
+
a5: { w: 5.83, h: 8.27 },
|
|
272
|
+
a6: { w: 4.13, h: 5.83 },
|
|
273
|
+
};
|
|
274
|
+
function cssUnitToInches(v) {
|
|
275
|
+
if (v === undefined)
|
|
276
|
+
return undefined;
|
|
277
|
+
if (typeof v === "number")
|
|
278
|
+
return v / 96;
|
|
279
|
+
const s = v.trim().toLowerCase();
|
|
280
|
+
if (!s || s === "0")
|
|
281
|
+
return 0;
|
|
282
|
+
const m = /^(-?\d+(?:\.\d+)?)\s*(px|in|cm|mm|pt)?$/.exec(s);
|
|
283
|
+
if (!m)
|
|
284
|
+
return undefined;
|
|
285
|
+
const n = parseFloat(m[1]);
|
|
286
|
+
switch (m[2] || "px") {
|
|
287
|
+
case "in":
|
|
288
|
+
return n;
|
|
289
|
+
case "cm":
|
|
290
|
+
return n / 2.54;
|
|
291
|
+
case "mm":
|
|
292
|
+
return n / 25.4;
|
|
293
|
+
case "pt":
|
|
294
|
+
return n / 72;
|
|
295
|
+
default:
|
|
296
|
+
return n / 96;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
export class SneakyMouse {
|
|
300
|
+
cdp;
|
|
301
|
+
sessionId;
|
|
302
|
+
beforeDown;
|
|
303
|
+
x = 0;
|
|
304
|
+
y = 0;
|
|
305
|
+
buttons = 0;
|
|
306
|
+
constructor(cdp, sessionId, beforeDown) {
|
|
307
|
+
this.cdp = cdp;
|
|
308
|
+
this.sessionId = sessionId;
|
|
309
|
+
this.beforeDown = beforeDown;
|
|
310
|
+
}
|
|
311
|
+
buttonMask(button) {
|
|
312
|
+
if (button === "right")
|
|
313
|
+
return 2;
|
|
314
|
+
if (button === "middle")
|
|
315
|
+
return 4;
|
|
316
|
+
return 1;
|
|
317
|
+
}
|
|
318
|
+
async move(x, y, options = {}) {
|
|
319
|
+
const steps = Math.max(1, options.steps ?? 1);
|
|
320
|
+
const sx = this.x;
|
|
321
|
+
const sy = this.y;
|
|
322
|
+
for (let i = 1; i <= steps; i++) {
|
|
323
|
+
const nx = sx + ((x - sx) * i) / steps;
|
|
324
|
+
const ny = sy + ((y - sy) * i) / steps;
|
|
325
|
+
this.x = nx;
|
|
326
|
+
this.y = ny;
|
|
327
|
+
await this.cdp.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: nx, y: ny, button: "none", buttons: this.buttons }, this.sessionId);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
async down(options = {}) {
|
|
331
|
+
if (this.beforeDown)
|
|
332
|
+
await this.beforeDown();
|
|
333
|
+
const button = options.button ?? "left";
|
|
334
|
+
this.buttons |= this.buttonMask(button);
|
|
335
|
+
await this.cdp.send("Input.dispatchMouseEvent", {
|
|
336
|
+
type: "mousePressed",
|
|
337
|
+
x: this.x,
|
|
338
|
+
y: this.y,
|
|
339
|
+
button,
|
|
340
|
+
buttons: this.buttons,
|
|
341
|
+
clickCount: options.clickCount ?? 1,
|
|
342
|
+
}, this.sessionId);
|
|
343
|
+
}
|
|
344
|
+
async up(options = {}) {
|
|
345
|
+
const button = options.button ?? "left";
|
|
346
|
+
this.buttons &= ~this.buttonMask(button);
|
|
347
|
+
await this.cdp.send("Input.dispatchMouseEvent", {
|
|
348
|
+
type: "mouseReleased",
|
|
349
|
+
x: this.x,
|
|
350
|
+
y: this.y,
|
|
351
|
+
button,
|
|
352
|
+
buttons: this.buttons,
|
|
353
|
+
clickCount: options.clickCount ?? 1,
|
|
354
|
+
}, this.sessionId);
|
|
355
|
+
}
|
|
356
|
+
async click(x, y, options = {}) {
|
|
357
|
+
await this.move(x, y);
|
|
358
|
+
const count = Math.max(1, options.clickCount ?? 1);
|
|
359
|
+
for (let c = 1; c <= count; c++) {
|
|
360
|
+
await this.down({ button: options.button, clickCount: c });
|
|
361
|
+
if (options.delay && options.delay > 0)
|
|
362
|
+
await new Promise((r) => setTimeout(r, options.delay));
|
|
363
|
+
await this.up({ button: options.button, clickCount: c });
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
async dblclick(x, y, options = {}) {
|
|
367
|
+
return this.click(x, y, { ...options, clickCount: 2 });
|
|
368
|
+
}
|
|
369
|
+
async wheel(deltaX, deltaY) {
|
|
370
|
+
await this.cdp.send("Input.dispatchMouseEvent", { type: "mouseWheel", x: this.x, y: this.y, deltaX, deltaY }, this.sessionId);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
export class SneakyKeyboard {
|
|
374
|
+
cdp;
|
|
375
|
+
sessionId;
|
|
376
|
+
beforeDown;
|
|
377
|
+
modifiers = 0;
|
|
378
|
+
constructor(cdp, sessionId, beforeDown) {
|
|
379
|
+
this.cdp = cdp;
|
|
380
|
+
this.sessionId = sessionId;
|
|
381
|
+
this.beforeDown = beforeDown;
|
|
382
|
+
}
|
|
383
|
+
async down(key) {
|
|
384
|
+
const spec = resolveKey(key);
|
|
385
|
+
if (!spec) {
|
|
386
|
+
await this.insertText(key);
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
if (spec.modBit)
|
|
390
|
+
this.modifiers |= spec.modBit;
|
|
391
|
+
await this.cdp.send("Input.dispatchKeyEvent", {
|
|
392
|
+
type: spec.text ? "keyDown" : "rawKeyDown",
|
|
393
|
+
key: spec.key,
|
|
394
|
+
code: spec.code,
|
|
395
|
+
windowsVirtualKeyCode: spec.keyCode,
|
|
396
|
+
nativeVirtualKeyCode: spec.keyCode,
|
|
397
|
+
text: spec.text,
|
|
398
|
+
unmodifiedText: spec.text,
|
|
399
|
+
modifiers: this.modifiers,
|
|
400
|
+
}, this.sessionId);
|
|
401
|
+
}
|
|
402
|
+
async up(key) {
|
|
403
|
+
const spec = resolveKey(key);
|
|
404
|
+
if (!spec)
|
|
405
|
+
return;
|
|
406
|
+
if (spec.modBit)
|
|
407
|
+
this.modifiers &= ~spec.modBit;
|
|
408
|
+
await this.cdp.send("Input.dispatchKeyEvent", {
|
|
409
|
+
type: "keyUp",
|
|
410
|
+
key: spec.key,
|
|
411
|
+
code: spec.code,
|
|
412
|
+
windowsVirtualKeyCode: spec.keyCode,
|
|
413
|
+
nativeVirtualKeyCode: spec.keyCode,
|
|
414
|
+
modifiers: this.modifiers,
|
|
415
|
+
}, this.sessionId);
|
|
416
|
+
}
|
|
417
|
+
async press(combo, options = {}) {
|
|
418
|
+
const keys = parseKeyCombo(combo);
|
|
419
|
+
for (const k of keys) {
|
|
420
|
+
if (k.modBit)
|
|
421
|
+
this.modifiers |= k.modBit;
|
|
422
|
+
await this.cdp.send("Input.dispatchKeyEvent", {
|
|
423
|
+
type: k.text ? "keyDown" : "rawKeyDown",
|
|
424
|
+
key: k.key,
|
|
425
|
+
code: k.code,
|
|
426
|
+
windowsVirtualKeyCode: k.keyCode,
|
|
427
|
+
nativeVirtualKeyCode: k.keyCode,
|
|
428
|
+
text: k.text,
|
|
429
|
+
unmodifiedText: k.text,
|
|
430
|
+
modifiers: this.modifiers,
|
|
431
|
+
}, this.sessionId);
|
|
432
|
+
}
|
|
433
|
+
if (options.delay && options.delay > 0)
|
|
434
|
+
await new Promise((r) => setTimeout(r, options.delay));
|
|
435
|
+
for (let i = keys.length - 1; i >= 0; i--) {
|
|
436
|
+
const k = keys[i];
|
|
437
|
+
if (k.modBit)
|
|
438
|
+
this.modifiers &= ~k.modBit;
|
|
439
|
+
await this.cdp.send("Input.dispatchKeyEvent", {
|
|
440
|
+
type: "keyUp",
|
|
441
|
+
key: k.key,
|
|
442
|
+
code: k.code,
|
|
443
|
+
windowsVirtualKeyCode: k.keyCode,
|
|
444
|
+
nativeVirtualKeyCode: k.keyCode,
|
|
445
|
+
modifiers: this.modifiers,
|
|
446
|
+
}, this.sessionId);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
async type(text, options = {}) {
|
|
450
|
+
for (const ch of text) {
|
|
451
|
+
const spec = resolveKey(ch);
|
|
452
|
+
if (spec) {
|
|
453
|
+
await this.down(ch);
|
|
454
|
+
await this.up(ch);
|
|
455
|
+
}
|
|
456
|
+
else {
|
|
457
|
+
await this.insertText(ch);
|
|
458
|
+
}
|
|
459
|
+
if (options.delay && options.delay > 0)
|
|
460
|
+
await new Promise((r) => setTimeout(r, options.delay));
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
async insertText(text) {
|
|
464
|
+
await this.cdp.send("Input.insertText", { text }, this.sessionId);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
export class SneakyWebSocketRoute {
|
|
468
|
+
rawUrl;
|
|
469
|
+
closed = false;
|
|
470
|
+
constructor(rawUrl) {
|
|
471
|
+
this.rawUrl = rawUrl;
|
|
472
|
+
}
|
|
473
|
+
url() {
|
|
474
|
+
return this.rawUrl;
|
|
475
|
+
}
|
|
476
|
+
async close(_options) {
|
|
477
|
+
this.closed = true;
|
|
478
|
+
}
|
|
479
|
+
isClosed() {
|
|
480
|
+
return this.closed;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
function buildWebSocketBlockScript(matcher) {
|
|
484
|
+
const re = matcher instanceof RegExp ? matcher : typeof matcher === "string" ? globToRegExp(matcher) : /^.*$/;
|
|
485
|
+
return `(() => {
|
|
486
|
+
const re = new RegExp(${JSON.stringify(re.source)}, ${JSON.stringify(re.flags)});
|
|
487
|
+
const OrigWS = window.WebSocket;
|
|
488
|
+
if (!OrigWS) return;
|
|
489
|
+
function BlockedWebSocket(url, protocols) {
|
|
490
|
+
const href = String(url);
|
|
491
|
+
if (!re.test(href)) return protocols === undefined ? new OrigWS(url) : new OrigWS(url, protocols);
|
|
492
|
+
const et = new EventTarget();
|
|
493
|
+
const sock = Object.assign(et, {
|
|
494
|
+
url: href,
|
|
495
|
+
readyState: 3,
|
|
496
|
+
bufferedAmount: 0,
|
|
497
|
+
extensions: "",
|
|
498
|
+
protocol: "",
|
|
499
|
+
binaryType: "blob",
|
|
500
|
+
CONNECTING: 0, OPEN: 1, CLOSING: 2, CLOSED: 3,
|
|
501
|
+
onopen: null, onerror: null, onclose: null, onmessage: null,
|
|
502
|
+
send() {},
|
|
503
|
+
close() {},
|
|
504
|
+
});
|
|
505
|
+
queueMicrotask(() => {
|
|
506
|
+
const errEv = new Event("error");
|
|
507
|
+
sock.dispatchEvent(errEv);
|
|
508
|
+
if (typeof sock.onerror === "function") sock.onerror(errEv);
|
|
509
|
+
const closeEv = new CloseEvent("close", { code: 1006, reason: "blocked", wasClean: false });
|
|
510
|
+
sock.dispatchEvent(closeEv);
|
|
511
|
+
if (typeof sock.onclose === "function") sock.onclose(closeEv);
|
|
512
|
+
});
|
|
513
|
+
return sock;
|
|
514
|
+
}
|
|
515
|
+
BlockedWebSocket.CONNECTING = 0;
|
|
516
|
+
BlockedWebSocket.OPEN = 1;
|
|
517
|
+
BlockedWebSocket.CLOSING = 2;
|
|
518
|
+
BlockedWebSocket.CLOSED = 3;
|
|
519
|
+
BlockedWebSocket.prototype = OrigWS.prototype;
|
|
520
|
+
window.WebSocket = BlockedWebSocket;
|
|
521
|
+
})();`;
|
|
522
|
+
}
|
|
523
|
+
export class SneakyPage extends EventEmitter {
|
|
524
|
+
ctx;
|
|
525
|
+
cdp;
|
|
526
|
+
targetId;
|
|
527
|
+
sessionId;
|
|
528
|
+
mouse;
|
|
529
|
+
keyboard;
|
|
530
|
+
defaultTimeoutMs = 30_000;
|
|
531
|
+
defaultNavigationTimeoutMs = 30_000;
|
|
532
|
+
closed = false;
|
|
533
|
+
viewport;
|
|
534
|
+
deviceScaleFactor = 1;
|
|
535
|
+
isMobile = false;
|
|
536
|
+
framesMap = new Map();
|
|
537
|
+
oopifSessions = new Set();
|
|
538
|
+
oopifSettles = new Set();
|
|
539
|
+
routes = [];
|
|
540
|
+
fetchEnabled = false;
|
|
541
|
+
inflight = new Set();
|
|
542
|
+
lastNetworkDone = Date.now();
|
|
543
|
+
requestsById = new Map();
|
|
544
|
+
unsubs = [];
|
|
545
|
+
rootFrameId = "";
|
|
546
|
+
constructor(ctx, cdp, targetId, sessionId, initialViewport) {
|
|
547
|
+
super();
|
|
548
|
+
this.ctx = ctx;
|
|
549
|
+
this.cdp = cdp;
|
|
550
|
+
this.targetId = targetId;
|
|
551
|
+
this.sessionId = sessionId;
|
|
552
|
+
this.viewport = initialViewport;
|
|
553
|
+
this.defaultTimeoutMs = ctx.defaultTimeoutMs;
|
|
554
|
+
this.mouse = new SneakyMouse(cdp, sessionId, () => this.awaitOOPIFHitTest());
|
|
555
|
+
this.keyboard = new SneakyKeyboard(cdp, sessionId);
|
|
556
|
+
}
|
|
557
|
+
async awaitOOPIFHitTest() {
|
|
558
|
+
if (this.oopifSettles.size === 0)
|
|
559
|
+
return;
|
|
560
|
+
await Promise.all([...this.oopifSettles]);
|
|
561
|
+
}
|
|
562
|
+
/** Internal bootstrap: enables Page/Network/OOPIF auto-attach (NEVER Runtime.enable). */
|
|
563
|
+
async init(contextOpts, initScripts, proxyAuth) {
|
|
564
|
+
const cdp = this.cdp;
|
|
565
|
+
const sid = this.sessionId;
|
|
566
|
+
await Promise.all([
|
|
567
|
+
cdp.send("Page.enable", undefined, sid),
|
|
568
|
+
cdp.send("Page.bringToFront", undefined, sid).catch(() => { }),
|
|
569
|
+
cdp.send("Network.enable", undefined, sid),
|
|
570
|
+
cdp.send("Page.setLifecycleEventsEnabled", { enabled: true }, sid).catch(() => { }),
|
|
571
|
+
cdp.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: false, flatten: true }, sid).catch(() => { }),
|
|
572
|
+
]);
|
|
573
|
+
// Apply context emulation settings without Runtime.enable.
|
|
574
|
+
this.deviceScaleFactor = contextOpts.deviceScaleFactor ?? 1;
|
|
575
|
+
this.isMobile = Boolean(contextOpts.isMobile);
|
|
576
|
+
if (contextOpts.viewport) {
|
|
577
|
+
await this.setViewportSize(contextOpts.viewport);
|
|
578
|
+
}
|
|
579
|
+
else if (this.deviceScaleFactor !== 1 || this.isMobile) {
|
|
580
|
+
await this.setViewportSize({ width: 1280, height: 800 });
|
|
581
|
+
}
|
|
582
|
+
if (contextOpts.userAgent) {
|
|
583
|
+
await cdp
|
|
584
|
+
.send("Emulation.setUserAgentOverride", { userAgent: contextOpts.userAgent, acceptLanguage: contextOpts.locale }, sid)
|
|
585
|
+
.catch(() => { });
|
|
586
|
+
}
|
|
587
|
+
if (contextOpts.timezoneId) {
|
|
588
|
+
await cdp.send("Emulation.setTimezoneOverride", { timezoneId: contextOpts.timezoneId }, sid).catch(() => { });
|
|
589
|
+
}
|
|
590
|
+
if (contextOpts.locale) {
|
|
591
|
+
await cdp.send("Emulation.setLocaleOverride", { locale: contextOpts.locale }, sid).catch(() => { });
|
|
592
|
+
}
|
|
593
|
+
if (contextOpts.extraHTTPHeaders && Object.keys(contextOpts.extraHTTPHeaders).length > 0) {
|
|
594
|
+
await cdp
|
|
595
|
+
.send("Network.setExtraHTTPHeaders", { headers: contextOpts.extraHTTPHeaders }, sid)
|
|
596
|
+
.catch(() => { });
|
|
597
|
+
}
|
|
598
|
+
if (contextOpts.ignoreHTTPSErrors) {
|
|
599
|
+
await cdp.send("Security.setIgnoreCertificateErrors", { ignore: true }, sid).catch(() => { });
|
|
600
|
+
}
|
|
601
|
+
if (contextOpts.bypassCSP) {
|
|
602
|
+
await cdp.send("Page.setBypassCSP", { enabled: true }, sid).catch(() => { });
|
|
603
|
+
}
|
|
604
|
+
if (contextOpts.serviceWorkers === "block") {
|
|
605
|
+
await cdp.send("Network.setBypassServiceWorker", { bypass: true }, sid).catch(() => { });
|
|
606
|
+
}
|
|
607
|
+
if (contextOpts.colorScheme || contextOpts.reducedMotion) {
|
|
608
|
+
await this.emulateMedia({
|
|
609
|
+
colorScheme: contextOpts.colorScheme === "null" ? null : contextOpts.colorScheme,
|
|
610
|
+
reducedMotion: contextOpts.reducedMotion === "null" ? null : contextOpts.reducedMotion,
|
|
611
|
+
}).catch(() => { });
|
|
612
|
+
}
|
|
613
|
+
for (const src of initScripts) {
|
|
614
|
+
await cdp.send("Page.addScriptToEvaluateOnNewDocument", { source: src }, sid).catch(() => { });
|
|
615
|
+
}
|
|
616
|
+
// Sync initial frame tree.
|
|
617
|
+
const ft = await cdp.send("Page.getFrameTree", undefined, sid);
|
|
618
|
+
this.rootFrameId = ft.frameTree.frame.id;
|
|
619
|
+
this.ingestFrameTree(ft.frameTree, this.targetId, sid, true);
|
|
620
|
+
// Subscribe frame lifecycle events for main session and any attached OOPIF sessions.
|
|
621
|
+
this.bindSessionEvents(sid, this.targetId);
|
|
622
|
+
// Auto-handle cross-origin OOPIF attachments and popup pages.
|
|
623
|
+
this.unsubs.push(cdp.on("Target.attachedToTarget", (params, parentSid) => {
|
|
624
|
+
if (parentSid !== sid && !this.oopifSessions.has(parentSid))
|
|
625
|
+
return;
|
|
626
|
+
const info = params.targetInfo;
|
|
627
|
+
const childSid = params.sessionId;
|
|
628
|
+
if (!childSid || !info?.targetId)
|
|
629
|
+
return;
|
|
630
|
+
if (info.type === "page") {
|
|
631
|
+
void this.ctx.attachExistingPageTarget(info.targetId, childSid).catch(() => { });
|
|
632
|
+
return;
|
|
633
|
+
}
|
|
634
|
+
if (info.type !== "iframe")
|
|
635
|
+
return;
|
|
636
|
+
this.oopifSessions.add(childSid);
|
|
637
|
+
const settle = this.attachOOPIF(childSid, info.targetId, info.url ?? "");
|
|
638
|
+
this.oopifSettles.add(settle);
|
|
639
|
+
void settle.finally(() => this.oopifSettles.delete(settle));
|
|
640
|
+
}));
|
|
641
|
+
this.unsubs.push(cdp.on("Target.detachedFromTarget", (params) => {
|
|
642
|
+
const detachedSid = params.sessionId;
|
|
643
|
+
if (!detachedSid)
|
|
644
|
+
return;
|
|
645
|
+
if (detachedSid === sid) {
|
|
646
|
+
this.markClosed();
|
|
647
|
+
return;
|
|
648
|
+
}
|
|
649
|
+
if (this.oopifSessions.delete(detachedSid)) {
|
|
650
|
+
for (const frame of this.framesMap.values()) {
|
|
651
|
+
if (frame.sessionId === detachedSid) {
|
|
652
|
+
frame.detached = true;
|
|
653
|
+
this.framesMap.delete(frame.id);
|
|
654
|
+
this.emit("framedetached", frame);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
}));
|
|
659
|
+
if (proxyAuth || this.ctx.contextRoutes.length > 0) {
|
|
660
|
+
await this.syncFetchInterception(proxyAuth);
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
async attachOOPIF(childSid, childTargetId, initialUrl) {
|
|
664
|
+
this.bindSessionEvents(childSid, childTargetId);
|
|
665
|
+
await Promise.all([
|
|
666
|
+
this.cdp.send("Page.enable", undefined, childSid).catch(() => { }),
|
|
667
|
+
this.cdp
|
|
668
|
+
.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: false, flatten: true }, childSid)
|
|
669
|
+
.catch(() => { }),
|
|
670
|
+
]);
|
|
671
|
+
const ft = await this.cdp
|
|
672
|
+
.send("Page.getFrameTree", undefined, childSid)
|
|
673
|
+
.catch(() => null);
|
|
674
|
+
if (ft?.frameTree?.frame?.id) {
|
|
675
|
+
this.ingestFrameTree(ft.frameTree, childTargetId, childSid, true);
|
|
676
|
+
}
|
|
677
|
+
else if (childTargetId) {
|
|
678
|
+
const existing = this.framesMap.get(childTargetId);
|
|
679
|
+
if (existing) {
|
|
680
|
+
existing.targetId = childTargetId;
|
|
681
|
+
existing.sessionId = childSid;
|
|
682
|
+
existing.isTargetRoot = true;
|
|
683
|
+
if (initialUrl)
|
|
684
|
+
existing.urlValue = initialUrl;
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
// Wait for the OOPIF renderer to submit its first frame and the parent Viz compositor to commit HitTestRegionList.
|
|
688
|
+
await this.cdp
|
|
689
|
+
.send("Runtime.evaluate", { expression: "new Promise((r) => requestAnimationFrame(r))", awaitPromise: true }, childSid)
|
|
690
|
+
.catch(() => { });
|
|
691
|
+
await this.mainFrame()
|
|
692
|
+
.evalRaw("new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))")
|
|
693
|
+
.catch(() => { });
|
|
694
|
+
}
|
|
695
|
+
ingestFrameTree(node, targetId, sessionId, isRootOfTarget) {
|
|
696
|
+
const f = node.frame;
|
|
697
|
+
const existing = this.framesMap.get(f.id);
|
|
698
|
+
if (existing) {
|
|
699
|
+
existing.targetId = targetId;
|
|
700
|
+
existing.sessionId = sessionId;
|
|
701
|
+
existing.isTargetRoot = isRootOfTarget;
|
|
702
|
+
existing.urlValue = f.url || existing.urlValue;
|
|
703
|
+
if (f.name !== undefined)
|
|
704
|
+
existing.nameValue = f.name;
|
|
705
|
+
if (f.parentId)
|
|
706
|
+
existing.parentFrameId = f.parentId;
|
|
707
|
+
existing.detached = false;
|
|
708
|
+
existing.isolatedContextId = null;
|
|
709
|
+
}
|
|
710
|
+
else {
|
|
711
|
+
const frame = new SneakyFrame(this, f.id, targetId, sessionId, isRootOfTarget);
|
|
712
|
+
frame.urlValue = f.url || "";
|
|
713
|
+
frame.nameValue = f.name || "";
|
|
714
|
+
frame.parentFrameId = f.parentId || null;
|
|
715
|
+
this.framesMap.set(f.id, frame);
|
|
716
|
+
if (f.id !== this.rootFrameId)
|
|
717
|
+
this.emit("frameattached", frame);
|
|
718
|
+
}
|
|
719
|
+
for (const child of node.childFrames ?? []) {
|
|
720
|
+
this.ingestFrameTree(child, targetId, sessionId, false);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
bindSessionEvents(sid, targetId) {
|
|
724
|
+
const cdp = this.cdp;
|
|
725
|
+
this.unsubs.push(cdp.on("Page.frameAttached", (p) => {
|
|
726
|
+
const frameId = p.frameId;
|
|
727
|
+
const parentFrameId = p.parentFrameId;
|
|
728
|
+
if (!frameId)
|
|
729
|
+
return;
|
|
730
|
+
let frame = this.framesMap.get(frameId);
|
|
731
|
+
if (!frame) {
|
|
732
|
+
frame = new SneakyFrame(this, frameId, targetId, sid, false);
|
|
733
|
+
frame.parentFrameId = parentFrameId || null;
|
|
734
|
+
this.framesMap.set(frameId, frame);
|
|
735
|
+
this.emit("frameattached", frame);
|
|
736
|
+
}
|
|
737
|
+
else if (parentFrameId && !frame.parentFrameId) {
|
|
738
|
+
frame.parentFrameId = parentFrameId;
|
|
739
|
+
}
|
|
740
|
+
}, sid));
|
|
741
|
+
this.unsubs.push(cdp.on("Page.frameNavigated", (p) => {
|
|
742
|
+
const f = p.frame;
|
|
743
|
+
if (!f?.id)
|
|
744
|
+
return;
|
|
745
|
+
const fullUrl = (f.url ?? "") + (f.urlFragment ?? "");
|
|
746
|
+
let frame = this.framesMap.get(f.id);
|
|
747
|
+
if (!frame) {
|
|
748
|
+
frame = new SneakyFrame(this, f.id, targetId, sid, f.id === this.rootFrameId || !f.parentId);
|
|
749
|
+
this.framesMap.set(f.id, frame);
|
|
750
|
+
}
|
|
751
|
+
frame.urlValue = fullUrl;
|
|
752
|
+
if (f.name !== undefined)
|
|
753
|
+
frame.nameValue = f.name;
|
|
754
|
+
if (f.parentId)
|
|
755
|
+
frame.parentFrameId = f.parentId;
|
|
756
|
+
frame.isolatedContextId = null;
|
|
757
|
+
this.emit("framenavigated", frame);
|
|
758
|
+
}, sid));
|
|
759
|
+
this.unsubs.push(cdp.on("Page.navigatedWithinDocument", (p) => {
|
|
760
|
+
const frameId = p.frameId;
|
|
761
|
+
const url = p.url;
|
|
762
|
+
if (!frameId || !url)
|
|
763
|
+
return;
|
|
764
|
+
const frame = this.framesMap.get(frameId);
|
|
765
|
+
if (frame) {
|
|
766
|
+
frame.urlValue = url;
|
|
767
|
+
this.emit("framenavigated", frame);
|
|
768
|
+
}
|
|
769
|
+
}, sid));
|
|
770
|
+
this.unsubs.push(cdp.on("Page.frameDetached", (p) => {
|
|
771
|
+
const frameId = p.frameId;
|
|
772
|
+
const reason = p.reason;
|
|
773
|
+
if (!frameId || reason === "swap")
|
|
774
|
+
return;
|
|
775
|
+
const frame = this.framesMap.get(frameId);
|
|
776
|
+
if (frame) {
|
|
777
|
+
frame.detached = true;
|
|
778
|
+
this.framesMap.delete(frameId);
|
|
779
|
+
this.emit("framedetached", frame);
|
|
780
|
+
}
|
|
781
|
+
}, sid));
|
|
782
|
+
this.unsubs.push(cdp.on("Page.javascriptDialogOpening", (p) => {
|
|
783
|
+
const dlg = new SneakyDialog(cdp, sid, {
|
|
784
|
+
type: String(p.type ?? "alert"),
|
|
785
|
+
message: String(p.message ?? ""),
|
|
786
|
+
defaultPrompt: typeof p.defaultPrompt === "string" ? p.defaultPrompt : undefined,
|
|
787
|
+
});
|
|
788
|
+
if (this.listenerCount("dialog") > 0) {
|
|
789
|
+
this.emit("dialog", dlg);
|
|
790
|
+
}
|
|
791
|
+
else if (this.ctx.listenerCount("dialog") > 0) {
|
|
792
|
+
this.ctx.emit("dialog", dlg);
|
|
793
|
+
}
|
|
794
|
+
else {
|
|
795
|
+
void dlg.dismiss();
|
|
796
|
+
}
|
|
797
|
+
}, sid));
|
|
798
|
+
if (sid === this.sessionId) {
|
|
799
|
+
this.unsubs.push(cdp.on("Page.domContentEventFired", () => {
|
|
800
|
+
this.emit("domcontentloaded", this);
|
|
801
|
+
}, sid));
|
|
802
|
+
this.unsubs.push(cdp.on("Page.loadEventFired", () => {
|
|
803
|
+
this.emit("load", this);
|
|
804
|
+
}, sid));
|
|
805
|
+
this.unsubs.push(cdp.on("Network.requestWillBeSent", (p) => {
|
|
806
|
+
const requestId = p.requestId;
|
|
807
|
+
const rawReq = p.request;
|
|
808
|
+
if (!requestId || !rawReq?.url)
|
|
809
|
+
return;
|
|
810
|
+
this.inflight.add(requestId);
|
|
811
|
+
const frameId = p.frameId;
|
|
812
|
+
const resourceType = String(p.type ?? "Other");
|
|
813
|
+
const prevReq = p.redirectResponse ? (this.requestsById.get(requestId) ?? null) : null;
|
|
814
|
+
const req = new SneakyRequest({
|
|
815
|
+
url: rawReq.url,
|
|
816
|
+
method: rawReq.method ?? "GET",
|
|
817
|
+
resourceType,
|
|
818
|
+
headers: rawReq.headers ?? {},
|
|
819
|
+
postData: rawReq.postData,
|
|
820
|
+
frame: (frameId ? this.framesMap.get(frameId) : undefined) ?? this.framesMap.get(this.rootFrameId) ?? null,
|
|
821
|
+
isNavigation: resourceType === "Document",
|
|
822
|
+
redirectedFrom: prevReq,
|
|
823
|
+
});
|
|
824
|
+
this.requestsById.set(requestId, req);
|
|
825
|
+
this.emit("request", req);
|
|
826
|
+
this.ctx.emit("request", req);
|
|
827
|
+
}, sid));
|
|
828
|
+
this.unsubs.push(cdp.on("Network.responseReceived", (p) => {
|
|
829
|
+
const requestId = p.requestId;
|
|
830
|
+
const rawRes = p.response;
|
|
831
|
+
if (!requestId || !rawRes)
|
|
832
|
+
return;
|
|
833
|
+
const frameId = p.frameId;
|
|
834
|
+
const req = this.requestsById.get(requestId) ??
|
|
835
|
+
new SneakyRequest({
|
|
836
|
+
url: rawRes.url ?? "",
|
|
837
|
+
method: "GET",
|
|
838
|
+
resourceType: String(p.type ?? "Other"),
|
|
839
|
+
headers: {},
|
|
840
|
+
frame: (frameId ? this.framesMap.get(frameId) : undefined) ?? this.framesMap.get(this.rootFrameId) ?? null,
|
|
841
|
+
isNavigation: String(p.type ?? "") === "Document",
|
|
842
|
+
});
|
|
843
|
+
const res = new SneakyResponse(cdp, sid, {
|
|
844
|
+
requestId,
|
|
845
|
+
url: rawRes.url ?? req.url(),
|
|
846
|
+
status: rawRes.status ?? 0,
|
|
847
|
+
statusText: rawRes.statusText ?? "",
|
|
848
|
+
headers: rawRes.headers ?? {},
|
|
849
|
+
request: req,
|
|
850
|
+
});
|
|
851
|
+
this.emit("response", res);
|
|
852
|
+
this.ctx.emit("response", res);
|
|
853
|
+
}, sid));
|
|
854
|
+
this.unsubs.push(cdp.on("Network.loadingFinished", (p) => {
|
|
855
|
+
const requestId = p.requestId;
|
|
856
|
+
if (requestId) {
|
|
857
|
+
this.inflight.delete(requestId);
|
|
858
|
+
this.lastNetworkDone = Date.now();
|
|
859
|
+
}
|
|
860
|
+
}, sid));
|
|
861
|
+
this.unsubs.push(cdp.on("Network.loadingFailed", (p) => {
|
|
862
|
+
const requestId = p.requestId;
|
|
863
|
+
if (!requestId)
|
|
864
|
+
return;
|
|
865
|
+
this.inflight.delete(requestId);
|
|
866
|
+
this.lastNetworkDone = Date.now();
|
|
867
|
+
const prev = this.requestsById.get(requestId);
|
|
868
|
+
const failedReq = new SneakyRequest({
|
|
869
|
+
url: prev?.url() ?? "",
|
|
870
|
+
method: prev?.method() ?? "GET",
|
|
871
|
+
resourceType: prev?.resourceType() ?? "other",
|
|
872
|
+
headers: prev?.headers() ?? {},
|
|
873
|
+
frame: prev?.frame() ?? null,
|
|
874
|
+
isNavigation: prev?.isNavigationRequest() ?? false,
|
|
875
|
+
failureText: String(p.errorText ?? "net::ERR_FAILED"),
|
|
876
|
+
});
|
|
877
|
+
this.emit("requestfailed", failedReq);
|
|
878
|
+
}, sid));
|
|
879
|
+
this.unsubs.push(cdp.on("Fetch.requestPaused", (p) => {
|
|
880
|
+
void this.handleFetchPaused(p);
|
|
881
|
+
}, sid));
|
|
882
|
+
this.unsubs.push(cdp.on("Fetch.authRequired", (p) => {
|
|
883
|
+
const requestId = p.requestId;
|
|
884
|
+
if (!requestId)
|
|
885
|
+
return;
|
|
886
|
+
const auth = this.ctx.proxyAuth;
|
|
887
|
+
if (auth) {
|
|
888
|
+
void cdp
|
|
889
|
+
.send("Fetch.continueWithAuth", {
|
|
890
|
+
requestId,
|
|
891
|
+
authChallengeResponse: {
|
|
892
|
+
response: "ProvideCredentials",
|
|
893
|
+
username: auth.username,
|
|
894
|
+
password: auth.password,
|
|
895
|
+
},
|
|
896
|
+
}, sid)
|
|
897
|
+
.catch(() => { });
|
|
898
|
+
}
|
|
899
|
+
else {
|
|
900
|
+
void cdp
|
|
901
|
+
.send("Fetch.continueWithAuth", { requestId, authChallengeResponse: { response: "Default" } }, sid)
|
|
902
|
+
.catch(() => { });
|
|
903
|
+
}
|
|
904
|
+
}, sid));
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
async handleFetchPaused(p) {
|
|
908
|
+
const requestId = p.requestId;
|
|
909
|
+
const rawReq = p.request;
|
|
910
|
+
if (!requestId || !rawReq?.url)
|
|
911
|
+
return;
|
|
912
|
+
const frameId = p.frameId;
|
|
913
|
+
const resourceType = String(p.resourceType ?? "Other");
|
|
914
|
+
const req = new SneakyRequest({
|
|
915
|
+
url: rawReq.url,
|
|
916
|
+
method: rawReq.method ?? "GET",
|
|
917
|
+
resourceType,
|
|
918
|
+
headers: rawReq.headers ?? {},
|
|
919
|
+
postData: rawReq.postData,
|
|
920
|
+
frame: (frameId ? this.framesMap.get(frameId) : undefined) ?? this.framesMap.get(this.rootFrameId) ?? null,
|
|
921
|
+
isNavigation: resourceType === "Document",
|
|
922
|
+
});
|
|
923
|
+
const route = new SneakyRoute(this.cdp, this.sessionId, requestId, req);
|
|
924
|
+
const allRoutes = [...this.routes, ...this.ctx.contextRoutes];
|
|
925
|
+
for (let i = allRoutes.length - 1; i >= 0; i--) {
|
|
926
|
+
const entry = allRoutes[i];
|
|
927
|
+
if (!matchesRoute(entry.matcher, req.url()))
|
|
928
|
+
continue;
|
|
929
|
+
try {
|
|
930
|
+
await entry.handler(route, req);
|
|
931
|
+
}
|
|
932
|
+
catch {
|
|
933
|
+
// If a handler throws without fulfilling, continue the request so the browser doesn't stall.
|
|
934
|
+
}
|
|
935
|
+
if (route.isHandled())
|
|
936
|
+
return;
|
|
937
|
+
}
|
|
938
|
+
await route.continue();
|
|
939
|
+
}
|
|
940
|
+
/** Internal: enable or disable CDP Fetch domain based on registered routes or proxy auth. */
|
|
941
|
+
async syncFetchInterception(proxyAuth) {
|
|
942
|
+
const needAuth = Boolean(proxyAuth ?? this.ctx.proxyAuth);
|
|
943
|
+
const needRoutes = this.routes.length > 0 || this.ctx.contextRoutes.length > 0;
|
|
944
|
+
const want = needAuth || needRoutes;
|
|
945
|
+
if (want && !this.fetchEnabled) {
|
|
946
|
+
this.fetchEnabled = true;
|
|
947
|
+
await this.cdp
|
|
948
|
+
.send("Fetch.enable", { patterns: [{ urlPattern: "*" }], handleAuthRequests: needAuth }, this.sessionId)
|
|
949
|
+
.catch(() => { });
|
|
950
|
+
}
|
|
951
|
+
else if (!want && this.fetchEnabled) {
|
|
952
|
+
this.fetchEnabled = false;
|
|
953
|
+
await this.cdp.send("Fetch.disable", undefined, this.sessionId).catch(() => { });
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
context() {
|
|
957
|
+
return this.ctx;
|
|
958
|
+
}
|
|
959
|
+
isClosed() {
|
|
960
|
+
return this.closed;
|
|
961
|
+
}
|
|
962
|
+
setDefaultTimeout(timeout) {
|
|
963
|
+
this.defaultTimeoutMs = timeout;
|
|
964
|
+
}
|
|
965
|
+
setDefaultNavigationTimeout(timeout) {
|
|
966
|
+
this.defaultNavigationTimeoutMs = timeout;
|
|
967
|
+
}
|
|
968
|
+
viewportSize() {
|
|
969
|
+
return this.viewport ? { ...this.viewport } : null;
|
|
970
|
+
}
|
|
971
|
+
async setViewportSize(size) {
|
|
972
|
+
this.viewport = { width: size.width, height: size.height };
|
|
973
|
+
await this.cdp.send("Emulation.setDeviceMetricsOverride", { width: size.width, height: size.height, deviceScaleFactor: this.deviceScaleFactor, mobile: this.isMobile }, this.sessionId);
|
|
974
|
+
}
|
|
975
|
+
mainFrame() {
|
|
976
|
+
const f = this.framesMap.get(this.rootFrameId);
|
|
977
|
+
if (!f)
|
|
978
|
+
throw new Error("Main frame is not initialized");
|
|
979
|
+
return f;
|
|
980
|
+
}
|
|
981
|
+
frames() {
|
|
982
|
+
return [...this.framesMap.values()].filter((f) => !f.detached);
|
|
983
|
+
}
|
|
984
|
+
frameById(frameId) {
|
|
985
|
+
return this.framesMap.get(frameId);
|
|
986
|
+
}
|
|
987
|
+
childFramesOf(frameId) {
|
|
988
|
+
return this.frames().filter((f) => f.parentFrameId === frameId);
|
|
989
|
+
}
|
|
990
|
+
url() {
|
|
991
|
+
return this.framesMap.get(this.rootFrameId)?.url() ?? "about:blank";
|
|
992
|
+
}
|
|
993
|
+
title() {
|
|
994
|
+
return this.mainFrame().title();
|
|
995
|
+
}
|
|
996
|
+
content() {
|
|
997
|
+
return this.mainFrame().content();
|
|
998
|
+
}
|
|
999
|
+
async setContent(html, options = {}) {
|
|
1000
|
+
const waitUntil = options.waitUntil ?? "load";
|
|
1001
|
+
const timeout = options.timeout ?? this.defaultTimeoutMs;
|
|
1002
|
+
const loadWait = this.prepareLoadWait(waitUntil, timeout);
|
|
1003
|
+
await this.cdp.send("Page.setDocumentContent", { frameId: this.rootFrameId, html }, this.sessionId);
|
|
1004
|
+
await loadWait();
|
|
1005
|
+
}
|
|
1006
|
+
prepareLoadWait(waitUntil, timeoutMs) {
|
|
1007
|
+
if (waitUntil === "commit")
|
|
1008
|
+
return async () => { };
|
|
1009
|
+
let domDone = false;
|
|
1010
|
+
let loadDone = false;
|
|
1011
|
+
let resolveDom = null;
|
|
1012
|
+
let resolveLoad = null;
|
|
1013
|
+
const domPromise = new Promise((r) => (resolveDom = r));
|
|
1014
|
+
const loadPromise = new Promise((r) => (resolveLoad = r));
|
|
1015
|
+
const u1 = this.cdp.on("Page.domContentEventFired", () => {
|
|
1016
|
+
domDone = true;
|
|
1017
|
+
resolveDom?.();
|
|
1018
|
+
}, this.sessionId);
|
|
1019
|
+
const u2 = this.cdp.on("Page.loadEventFired", () => {
|
|
1020
|
+
loadDone = true;
|
|
1021
|
+
resolveDom?.();
|
|
1022
|
+
resolveLoad?.();
|
|
1023
|
+
}, this.sessionId);
|
|
1024
|
+
return async () => {
|
|
1025
|
+
let timerId;
|
|
1026
|
+
try {
|
|
1027
|
+
const timer = new Promise((_, rej) => {
|
|
1028
|
+
timerId = setTimeout(() => {
|
|
1029
|
+
const err = new Error(`Navigation wait (${waitUntil}) timed out after ${timeoutMs}ms`);
|
|
1030
|
+
err.name = "TimeoutError";
|
|
1031
|
+
rej(err);
|
|
1032
|
+
}, timeoutMs);
|
|
1033
|
+
timerId.unref?.();
|
|
1034
|
+
});
|
|
1035
|
+
if (waitUntil === "domcontentloaded") {
|
|
1036
|
+
if (!domDone)
|
|
1037
|
+
await Promise.race([domPromise, timer]);
|
|
1038
|
+
}
|
|
1039
|
+
else {
|
|
1040
|
+
if (!loadDone)
|
|
1041
|
+
await Promise.race([loadPromise, timer]);
|
|
1042
|
+
if (waitUntil === "networkidle") {
|
|
1043
|
+
await this.waitForLoadState("networkidle", { timeout: Math.min(timeoutMs, 10_000) });
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
finally {
|
|
1048
|
+
if (timerId)
|
|
1049
|
+
clearTimeout(timerId);
|
|
1050
|
+
u1();
|
|
1051
|
+
u2();
|
|
1052
|
+
}
|
|
1053
|
+
};
|
|
1054
|
+
}
|
|
1055
|
+
async goto(url, options = {}) {
|
|
1056
|
+
const waitUntil = options.waitUntil ?? "load";
|
|
1057
|
+
const timeout = options.timeout ?? this.defaultNavigationTimeoutMs;
|
|
1058
|
+
let docResponse = null;
|
|
1059
|
+
const onRes = (res) => {
|
|
1060
|
+
if (!docResponse && res.request().isNavigationRequest())
|
|
1061
|
+
docResponse = res;
|
|
1062
|
+
};
|
|
1063
|
+
this.on("response", onRes);
|
|
1064
|
+
const waitDone = this.prepareLoadWait(waitUntil, timeout);
|
|
1065
|
+
try {
|
|
1066
|
+
const nav = await this.cdp.send("Page.navigate", { url }, this.sessionId, timeout);
|
|
1067
|
+
if (nav.errorText) {
|
|
1068
|
+
throw new Error(`Navigation failed: ${nav.errorText}`);
|
|
1069
|
+
}
|
|
1070
|
+
const mf = this.framesMap.get(this.rootFrameId);
|
|
1071
|
+
if (mf) {
|
|
1072
|
+
mf.urlValue = url;
|
|
1073
|
+
mf.isolatedContextId = null;
|
|
1074
|
+
}
|
|
1075
|
+
await waitDone();
|
|
1076
|
+
if (this.oopifSessions.size > 0) {
|
|
1077
|
+
await this.mainFrame()
|
|
1078
|
+
.evalRaw("new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))")
|
|
1079
|
+
.catch(() => { });
|
|
1080
|
+
}
|
|
1081
|
+
// Refresh actual URL after redirects.
|
|
1082
|
+
const actualUrl = await this.evaluate(() => location.href).catch(() => url);
|
|
1083
|
+
if (mf && actualUrl)
|
|
1084
|
+
mf.urlValue = actualUrl;
|
|
1085
|
+
return docResponse;
|
|
1086
|
+
}
|
|
1087
|
+
finally {
|
|
1088
|
+
this.off("response", onRes);
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
async reload(options = {}) {
|
|
1092
|
+
const waitUntil = options.waitUntil ?? "load";
|
|
1093
|
+
const timeout = options.timeout ?? this.defaultTimeoutMs;
|
|
1094
|
+
const waitDone = this.prepareLoadWait(waitUntil, timeout);
|
|
1095
|
+
await this.cdp.send("Page.reload", { ignoreCache: false }, this.sessionId, timeout);
|
|
1096
|
+
await waitDone();
|
|
1097
|
+
}
|
|
1098
|
+
async waitForLoadState(state = "load", options = {}) {
|
|
1099
|
+
const timeout = options.timeout ?? this.defaultTimeoutMs;
|
|
1100
|
+
const deadline = Date.now() + timeout;
|
|
1101
|
+
if (state === "domcontentloaded" || state === "load") {
|
|
1102
|
+
while (Date.now() < deadline) {
|
|
1103
|
+
const rs = await this.evaluate(() => document.readyState).catch(() => "");
|
|
1104
|
+
if (state === "domcontentloaded" && (rs === "interactive" || rs === "complete"))
|
|
1105
|
+
return;
|
|
1106
|
+
if (state === "load" && rs === "complete")
|
|
1107
|
+
return;
|
|
1108
|
+
await new Promise((r) => setTimeout(r, 35));
|
|
1109
|
+
}
|
|
1110
|
+
const err = new Error(`waitForLoadState(${state}) timed out after ${timeout}ms`);
|
|
1111
|
+
err.name = "TimeoutError";
|
|
1112
|
+
throw err;
|
|
1113
|
+
}
|
|
1114
|
+
if (state === "networkidle") {
|
|
1115
|
+
while (Date.now() < deadline) {
|
|
1116
|
+
if (this.inflight.size === 0 && Date.now() - this.lastNetworkDone >= 500)
|
|
1117
|
+
return;
|
|
1118
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
1119
|
+
}
|
|
1120
|
+
const err = new Error(`waitForLoadState(networkidle) timed out after ${timeout}ms`);
|
|
1121
|
+
err.name = "TimeoutError";
|
|
1122
|
+
throw err;
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
async waitForTimeout(ms) {
|
|
1126
|
+
await new Promise((r) => setTimeout(r, ms));
|
|
1127
|
+
}
|
|
1128
|
+
async addInitScript(fn, arg) {
|
|
1129
|
+
const source = typeof fn === "string" ? fn : `(${fn.toString()})(${arg === undefined ? "" : JSON.stringify(arg)});`;
|
|
1130
|
+
await this.cdp.send("Page.addScriptToEvaluateOnNewDocument", { source }, this.sessionId);
|
|
1131
|
+
}
|
|
1132
|
+
async addStyleTag(options) {
|
|
1133
|
+
await this.evaluate((opts) => {
|
|
1134
|
+
if (opts.url) {
|
|
1135
|
+
const link = document.createElement("link");
|
|
1136
|
+
link.rel = "stylesheet";
|
|
1137
|
+
link.href = opts.url;
|
|
1138
|
+
document.head.appendChild(link);
|
|
1139
|
+
}
|
|
1140
|
+
else if (opts.content) {
|
|
1141
|
+
const style = document.createElement("style");
|
|
1142
|
+
style.textContent = opts.content;
|
|
1143
|
+
document.head.appendChild(style);
|
|
1144
|
+
}
|
|
1145
|
+
}, options);
|
|
1146
|
+
}
|
|
1147
|
+
async emulateMedia(options) {
|
|
1148
|
+
const features = [];
|
|
1149
|
+
if (options.colorScheme)
|
|
1150
|
+
features.push({ name: "prefers-color-scheme", value: options.colorScheme });
|
|
1151
|
+
if (options.reducedMotion)
|
|
1152
|
+
features.push({ name: "prefers-reduced-motion", value: options.reducedMotion });
|
|
1153
|
+
await this.cdp.send("Emulation.setEmulatedMedia", { media: options.media ?? "", features }, this.sessionId);
|
|
1154
|
+
}
|
|
1155
|
+
async route(matcher, handler) {
|
|
1156
|
+
this.routes.push({ matcher, handler });
|
|
1157
|
+
await this.syncFetchInterception();
|
|
1158
|
+
}
|
|
1159
|
+
async unroute(matcher, handler) {
|
|
1160
|
+
for (let i = this.routes.length - 1; i >= 0; i--) {
|
|
1161
|
+
if (this.routes[i].matcher === matcher && (!handler || this.routes[i].handler === handler)) {
|
|
1162
|
+
this.routes.splice(i, 1);
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
await this.syncFetchInterception();
|
|
1166
|
+
}
|
|
1167
|
+
async unrouteAll(_options) {
|
|
1168
|
+
this.routes.length = 0;
|
|
1169
|
+
await this.syncFetchInterception();
|
|
1170
|
+
}
|
|
1171
|
+
async routeWebSocket(matcher, _handler) {
|
|
1172
|
+
await this.addInitScript(buildWebSocketBlockScript(matcher));
|
|
1173
|
+
}
|
|
1174
|
+
evaluate(fn, arg) {
|
|
1175
|
+
return arguments.length >= 2 ? this.mainFrame().evaluate(fn, arg) : this.mainFrame().evaluate(fn);
|
|
1176
|
+
}
|
|
1177
|
+
locator(selector) {
|
|
1178
|
+
return this.mainFrame().locator(selector);
|
|
1179
|
+
}
|
|
1180
|
+
getByRole(role, options) {
|
|
1181
|
+
return this.mainFrame().getByRole(role, options);
|
|
1182
|
+
}
|
|
1183
|
+
getByText(text, options) {
|
|
1184
|
+
return this.mainFrame().getByText(text, options);
|
|
1185
|
+
}
|
|
1186
|
+
getByLabel(text) {
|
|
1187
|
+
return this.mainFrame().getByLabel(text);
|
|
1188
|
+
}
|
|
1189
|
+
$(selector) {
|
|
1190
|
+
return this.mainFrame().$(selector);
|
|
1191
|
+
}
|
|
1192
|
+
$$(selector) {
|
|
1193
|
+
return this.mainFrame().$$(selector);
|
|
1194
|
+
}
|
|
1195
|
+
waitForSelector(selector, options) {
|
|
1196
|
+
return this.mainFrame().waitForSelector(selector, options);
|
|
1197
|
+
}
|
|
1198
|
+
waitForFunction(fn, arg, options) {
|
|
1199
|
+
return this.mainFrame().waitForFunction(fn, arg, options);
|
|
1200
|
+
}
|
|
1201
|
+
async screenshot(options = {}) {
|
|
1202
|
+
const format = options.type ?? "png";
|
|
1203
|
+
const params = { format, fromSurface: true };
|
|
1204
|
+
if (format !== "png" && options.quality !== undefined)
|
|
1205
|
+
params.quality = options.quality;
|
|
1206
|
+
if (options.clip) {
|
|
1207
|
+
params.clip = {
|
|
1208
|
+
x: options.clip.x,
|
|
1209
|
+
y: options.clip.y,
|
|
1210
|
+
width: options.clip.width,
|
|
1211
|
+
height: options.clip.height,
|
|
1212
|
+
scale: 1,
|
|
1213
|
+
};
|
|
1214
|
+
}
|
|
1215
|
+
else if (options.fullPage) {
|
|
1216
|
+
params.captureBeyondViewport = true;
|
|
1217
|
+
const metrics = await this.cdp.send("Page.getLayoutMetrics", undefined, this.sessionId);
|
|
1218
|
+
const sz = metrics.cssContentSize ?? metrics.contentSize;
|
|
1219
|
+
if (sz && sz.width > 0 && sz.height > 0) {
|
|
1220
|
+
params.clip = { x: 0, y: 0, width: sz.width, height: sz.height, scale: 1 };
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
const res = await this.cdp.send("Page.captureScreenshot", params, this.sessionId);
|
|
1224
|
+
if (options.clip || options.fullPage) {
|
|
1225
|
+
// Clipped/fullPage screenshots temporarily shift the main frame's compositor viewport; wait for
|
|
1226
|
+
// Viz to restore the parent HitTestRegionList so subsequent OOPIF mouse clicks route accurately.
|
|
1227
|
+
await this.mainFrame()
|
|
1228
|
+
.evalRaw("new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))")
|
|
1229
|
+
.catch(() => { });
|
|
1230
|
+
}
|
|
1231
|
+
const buf = Buffer.from(res.data, "base64");
|
|
1232
|
+
if (options.path)
|
|
1233
|
+
writeFileSync(options.path, buf);
|
|
1234
|
+
return buf;
|
|
1235
|
+
}
|
|
1236
|
+
async pdf(options = {}) {
|
|
1237
|
+
const fmt = options.format ? PAPER_FORMATS[options.format.toLowerCase()] : undefined;
|
|
1238
|
+
const params = {
|
|
1239
|
+
landscape: Boolean(options.landscape),
|
|
1240
|
+
displayHeaderFooter: Boolean(options.displayHeaderFooter),
|
|
1241
|
+
printBackground: Boolean(options.printBackground),
|
|
1242
|
+
preferCSSPageSize: Boolean(options.preferCSSPageSize),
|
|
1243
|
+
scale: options.scale ?? 1,
|
|
1244
|
+
};
|
|
1245
|
+
const w = cssUnitToInches(options.width) ?? fmt?.w;
|
|
1246
|
+
const h = cssUnitToInches(options.height) ?? fmt?.h;
|
|
1247
|
+
if (w !== undefined)
|
|
1248
|
+
params.paperWidth = w;
|
|
1249
|
+
if (h !== undefined)
|
|
1250
|
+
params.paperHeight = h;
|
|
1251
|
+
if (options.margin) {
|
|
1252
|
+
const mt = cssUnitToInches(options.margin.top);
|
|
1253
|
+
const mb = cssUnitToInches(options.margin.bottom);
|
|
1254
|
+
const ml = cssUnitToInches(options.margin.left);
|
|
1255
|
+
const mr = cssUnitToInches(options.margin.right);
|
|
1256
|
+
if (mt !== undefined)
|
|
1257
|
+
params.marginTop = mt;
|
|
1258
|
+
if (mb !== undefined)
|
|
1259
|
+
params.marginBottom = mb;
|
|
1260
|
+
if (ml !== undefined)
|
|
1261
|
+
params.marginLeft = ml;
|
|
1262
|
+
if (mr !== undefined)
|
|
1263
|
+
params.marginRight = mr;
|
|
1264
|
+
}
|
|
1265
|
+
if (options.headerTemplate)
|
|
1266
|
+
params.headerTemplate = options.headerTemplate;
|
|
1267
|
+
if (options.footerTemplate)
|
|
1268
|
+
params.footerTemplate = options.footerTemplate;
|
|
1269
|
+
if (options.pageRanges)
|
|
1270
|
+
params.pageRanges = options.pageRanges;
|
|
1271
|
+
const res = await this.cdp.send("Page.printToPDF", params, this.sessionId, 60_000);
|
|
1272
|
+
const buf = Buffer.from(res.data, "base64");
|
|
1273
|
+
if (options.path)
|
|
1274
|
+
writeFileSync(options.path, buf);
|
|
1275
|
+
return buf;
|
|
1276
|
+
}
|
|
1277
|
+
markClosed() {
|
|
1278
|
+
if (this.closed)
|
|
1279
|
+
return;
|
|
1280
|
+
this.closed = true;
|
|
1281
|
+
for (const u of this.unsubs)
|
|
1282
|
+
u();
|
|
1283
|
+
this.unsubs.length = 0;
|
|
1284
|
+
this.ctx.removePage(this);
|
|
1285
|
+
this.emit("close");
|
|
1286
|
+
}
|
|
1287
|
+
async close() {
|
|
1288
|
+
if (this.closed)
|
|
1289
|
+
return;
|
|
1290
|
+
this.markClosed();
|
|
1291
|
+
await this.cdp.send("Target.closeTarget", { targetId: this.targetId }).catch(() => { });
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
export class SneakyContext extends EventEmitter {
|
|
1295
|
+
browser;
|
|
1296
|
+
cdp;
|
|
1297
|
+
browserContextId;
|
|
1298
|
+
options;
|
|
1299
|
+
defaultTimeoutMs = 30_000;
|
|
1300
|
+
contextRoutes = [];
|
|
1301
|
+
proxyAuth;
|
|
1302
|
+
initScripts = [];
|
|
1303
|
+
pageList = [];
|
|
1304
|
+
closed = false;
|
|
1305
|
+
constructor(browser, cdp, browserContextId, options, proxyAuth) {
|
|
1306
|
+
super();
|
|
1307
|
+
this.browser = browser;
|
|
1308
|
+
this.cdp = cdp;
|
|
1309
|
+
this.browserContextId = browserContextId;
|
|
1310
|
+
this.options = options;
|
|
1311
|
+
this.proxyAuth = proxyAuth;
|
|
1312
|
+
}
|
|
1313
|
+
pages() {
|
|
1314
|
+
return [...this.pageList];
|
|
1315
|
+
}
|
|
1316
|
+
removePage(p) {
|
|
1317
|
+
const idx = this.pageList.indexOf(p);
|
|
1318
|
+
if (idx >= 0)
|
|
1319
|
+
this.pageList.splice(idx, 1);
|
|
1320
|
+
}
|
|
1321
|
+
setDefaultTimeout(timeout) {
|
|
1322
|
+
this.defaultTimeoutMs = timeout;
|
|
1323
|
+
for (const p of this.pageList)
|
|
1324
|
+
p.setDefaultTimeout(timeout);
|
|
1325
|
+
}
|
|
1326
|
+
setDefaultNavigationTimeout(timeout) {
|
|
1327
|
+
for (const p of this.pageList)
|
|
1328
|
+
p.setDefaultNavigationTimeout(timeout);
|
|
1329
|
+
}
|
|
1330
|
+
async addInitScript(fn, arg) {
|
|
1331
|
+
const source = typeof fn === "string" ? fn : `(${fn.toString()})(${arg === undefined ? "" : JSON.stringify(arg)});`;
|
|
1332
|
+
this.initScripts.push(source);
|
|
1333
|
+
for (const p of this.pageList) {
|
|
1334
|
+
await this.cdp.send("Page.addScriptToEvaluateOnNewDocument", { source }, p.sessionId).catch(() => { });
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
async route(matcher, handler) {
|
|
1338
|
+
this.contextRoutes.push({ matcher, handler });
|
|
1339
|
+
for (const p of this.pageList)
|
|
1340
|
+
await p.syncFetchInterception();
|
|
1341
|
+
}
|
|
1342
|
+
async routeWebSocket(matcher, _handler) {
|
|
1343
|
+
await this.addInitScript(buildWebSocketBlockScript(matcher));
|
|
1344
|
+
}
|
|
1345
|
+
async unroute(matcher, handler) {
|
|
1346
|
+
for (let i = this.contextRoutes.length - 1; i >= 0; i--) {
|
|
1347
|
+
if (this.contextRoutes[i].matcher === matcher && (!handler || this.contextRoutes[i].handler === handler)) {
|
|
1348
|
+
this.contextRoutes.splice(i, 1);
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
for (const p of this.pageList)
|
|
1352
|
+
await p.syncFetchInterception();
|
|
1353
|
+
}
|
|
1354
|
+
async newPage() {
|
|
1355
|
+
const createParams = { url: "about:blank" };
|
|
1356
|
+
if (this.browserContextId)
|
|
1357
|
+
createParams.browserContextId = this.browserContextId;
|
|
1358
|
+
const { targetId } = await this.cdp.send("Target.createTarget", createParams);
|
|
1359
|
+
return this.attachPageTarget(targetId);
|
|
1360
|
+
}
|
|
1361
|
+
async attachPageTarget(targetId) {
|
|
1362
|
+
const { sessionId } = await this.cdp.send("Target.attachToTarget", {
|
|
1363
|
+
targetId,
|
|
1364
|
+
flatten: true,
|
|
1365
|
+
});
|
|
1366
|
+
return this.attachExistingPageTarget(targetId, sessionId);
|
|
1367
|
+
}
|
|
1368
|
+
async attachExistingPageTarget(targetId, sessionId) {
|
|
1369
|
+
const existing = this.pageList.find((p) => p.targetId === targetId);
|
|
1370
|
+
if (existing)
|
|
1371
|
+
return existing;
|
|
1372
|
+
const vp = this.options.viewport === undefined ? { width: 1280, height: 800 } : this.options.viewport;
|
|
1373
|
+
const page = new SneakyPage(this, this.cdp, targetId, sessionId, vp);
|
|
1374
|
+
await page.init(this.options, this.initScripts, this.proxyAuth);
|
|
1375
|
+
this.pageList.push(page);
|
|
1376
|
+
this.emit("page", page);
|
|
1377
|
+
return page;
|
|
1378
|
+
}
|
|
1379
|
+
/** Creates a direct CDP session attached to a Page or cross-origin OOPIF Frame target. */
|
|
1380
|
+
async newCDPSession(pageOrFrame) {
|
|
1381
|
+
const targetId = pageOrFrame.targetId;
|
|
1382
|
+
const { sessionId } = await this.cdp.send("Target.attachToTarget", {
|
|
1383
|
+
targetId,
|
|
1384
|
+
flatten: true,
|
|
1385
|
+
});
|
|
1386
|
+
return new SneakyCDPSession(this.cdp, sessionId, true);
|
|
1387
|
+
}
|
|
1388
|
+
async cookies(urls) {
|
|
1389
|
+
const sid = this.pageList[0]?.sessionId ?? "";
|
|
1390
|
+
const params = {};
|
|
1391
|
+
if (urls)
|
|
1392
|
+
params.urls = Array.isArray(urls) ? urls : [urls];
|
|
1393
|
+
const res = await this.cdp.send(sid ? "Network.getCookies" : "Storage.getCookies", sid ? params : this.browserContextId ? { browserContextId: this.browserContextId } : undefined, sid);
|
|
1394
|
+
return res.cookies ?? [];
|
|
1395
|
+
}
|
|
1396
|
+
async addCookies(cookies) {
|
|
1397
|
+
const sid = this.pageList[0]?.sessionId ?? "";
|
|
1398
|
+
if (sid) {
|
|
1399
|
+
await this.cdp.send("Network.setCookies", { cookies }, sid);
|
|
1400
|
+
}
|
|
1401
|
+
else {
|
|
1402
|
+
await this.cdp.send("Storage.setCookies", {
|
|
1403
|
+
cookies,
|
|
1404
|
+
...(this.browserContextId ? { browserContextId: this.browserContextId } : {}),
|
|
1405
|
+
});
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
async clearCookies() {
|
|
1409
|
+
const sid = this.pageList[0]?.sessionId ?? "";
|
|
1410
|
+
if (sid) {
|
|
1411
|
+
await this.cdp.send("Network.clearBrowserCookies", undefined, sid);
|
|
1412
|
+
}
|
|
1413
|
+
else {
|
|
1414
|
+
await this.cdp.send("Storage.clearCookies", this.browserContextId ? { browserContextId: this.browserContextId } : undefined);
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
async close() {
|
|
1418
|
+
if (this.closed)
|
|
1419
|
+
return;
|
|
1420
|
+
this.closed = true;
|
|
1421
|
+
for (const p of [...this.pageList]) {
|
|
1422
|
+
await p.close().catch(() => { });
|
|
1423
|
+
}
|
|
1424
|
+
if (this.browserContextId) {
|
|
1425
|
+
await this.cdp.send("Target.disposeBrowserContext", { browserContextId: this.browserContextId }).catch(() => { });
|
|
1426
|
+
}
|
|
1427
|
+
this.browser.removeContext(this);
|
|
1428
|
+
this.emit("close");
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
export class SneakyBrowser extends EventEmitter {
|
|
1432
|
+
cdp;
|
|
1433
|
+
proc;
|
|
1434
|
+
contextList = [];
|
|
1435
|
+
closed = false;
|
|
1436
|
+
versionStr = "";
|
|
1437
|
+
constructor(cdp, proc) {
|
|
1438
|
+
super();
|
|
1439
|
+
this.cdp = cdp;
|
|
1440
|
+
this.proc = proc;
|
|
1441
|
+
cdp.onClose(() => {
|
|
1442
|
+
if (!this.closed) {
|
|
1443
|
+
this.closed = true;
|
|
1444
|
+
this.emit("disconnected");
|
|
1445
|
+
}
|
|
1446
|
+
});
|
|
1447
|
+
}
|
|
1448
|
+
async init() {
|
|
1449
|
+
const v = await this.cdp.send("Browser.getVersion").catch(() => ({ product: "Chrome/135.0.0.0" }));
|
|
1450
|
+
this.versionStr = (v.product ?? "").replace(/^.*\//, "") || "135.0.0.0";
|
|
1451
|
+
}
|
|
1452
|
+
version() {
|
|
1453
|
+
return this.versionStr;
|
|
1454
|
+
}
|
|
1455
|
+
isConnected() {
|
|
1456
|
+
return !this.closed && !this.cdp.isClosed();
|
|
1457
|
+
}
|
|
1458
|
+
contexts() {
|
|
1459
|
+
return [...this.contextList];
|
|
1460
|
+
}
|
|
1461
|
+
removeContext(ctx) {
|
|
1462
|
+
const idx = this.contextList.indexOf(ctx);
|
|
1463
|
+
if (idx >= 0)
|
|
1464
|
+
this.contextList.splice(idx, 1);
|
|
1465
|
+
}
|
|
1466
|
+
async newContext(options = {}) {
|
|
1467
|
+
const params = { disposeOnDetach: true };
|
|
1468
|
+
let proxyAuth = this.proc?.proxyAuth;
|
|
1469
|
+
if (options.proxy?.server) {
|
|
1470
|
+
let server = options.proxy.server;
|
|
1471
|
+
if (options.proxy.username !== undefined) {
|
|
1472
|
+
proxyAuth = { username: options.proxy.username, password: options.proxy.password ?? "" };
|
|
1473
|
+
}
|
|
1474
|
+
else {
|
|
1475
|
+
try {
|
|
1476
|
+
const u = new URL(server);
|
|
1477
|
+
if (u.username || u.password) {
|
|
1478
|
+
proxyAuth = { username: decodeURIComponent(u.username), password: decodeURIComponent(u.password) };
|
|
1479
|
+
u.username = "";
|
|
1480
|
+
u.password = "";
|
|
1481
|
+
server = u.toString().replace(/\/$/, "");
|
|
1482
|
+
}
|
|
1483
|
+
}
|
|
1484
|
+
catch { }
|
|
1485
|
+
}
|
|
1486
|
+
params.proxyServer = server;
|
|
1487
|
+
if (options.proxy.bypass)
|
|
1488
|
+
params.proxyBypassList = options.proxy.bypass;
|
|
1489
|
+
}
|
|
1490
|
+
const { browserContextId } = await this.cdp.send("Target.createBrowserContext", params);
|
|
1491
|
+
const ctx = new SneakyContext(this, this.cdp, browserContextId, options, proxyAuth);
|
|
1492
|
+
this.contextList.push(ctx);
|
|
1493
|
+
return ctx;
|
|
1494
|
+
}
|
|
1495
|
+
/** Attaches to the default browser context (for launchPersistentContext or connectOverCDP). */
|
|
1496
|
+
async defaultContext(options = {}) {
|
|
1497
|
+
const ctx = new SneakyContext(this, this.cdp, undefined, options, this.proc?.proxyAuth);
|
|
1498
|
+
this.contextList.push(ctx);
|
|
1499
|
+
const { targetInfos } = await this.cdp.send("Target.getTargets");
|
|
1500
|
+
const pages = (targetInfos ?? []).filter((t) => t.type === "page");
|
|
1501
|
+
for (const t of pages) {
|
|
1502
|
+
await ctx.attachPageTarget(t.targetId);
|
|
1503
|
+
}
|
|
1504
|
+
if (ctx.pages().length === 0) {
|
|
1505
|
+
await ctx.newPage();
|
|
1506
|
+
}
|
|
1507
|
+
return ctx;
|
|
1508
|
+
}
|
|
1509
|
+
async newPage(options = {}) {
|
|
1510
|
+
const ctx = await this.newContext(options);
|
|
1511
|
+
const page = await ctx.newPage();
|
|
1512
|
+
page.once("close", () => {
|
|
1513
|
+
void ctx.close().catch(() => { });
|
|
1514
|
+
});
|
|
1515
|
+
return page;
|
|
1516
|
+
}
|
|
1517
|
+
async close() {
|
|
1518
|
+
if (this.closed)
|
|
1519
|
+
return;
|
|
1520
|
+
this.closed = true;
|
|
1521
|
+
for (const ctx of [...this.contextList]) {
|
|
1522
|
+
await ctx.close().catch(() => { });
|
|
1523
|
+
}
|
|
1524
|
+
if (this.proc) {
|
|
1525
|
+
await this.cdp.send("Browser.close").catch(() => { });
|
|
1526
|
+
this.cdp.close();
|
|
1527
|
+
await this.proc.kill();
|
|
1528
|
+
}
|
|
1529
|
+
else {
|
|
1530
|
+
this.cdp.close();
|
|
1531
|
+
}
|
|
1532
|
+
this.emit("disconnected");
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
export async function launch(options = {}) {
|
|
1536
|
+
const proc = await launchChromiumProcess(options);
|
|
1537
|
+
try {
|
|
1538
|
+
const cdp = await CDPConnection.dial(proc.wsUrl);
|
|
1539
|
+
const browser = new SneakyBrowser(cdp, proc);
|
|
1540
|
+
await browser.init();
|
|
1541
|
+
return browser;
|
|
1542
|
+
}
|
|
1543
|
+
catch (err) {
|
|
1544
|
+
await proc.kill().catch(() => { });
|
|
1545
|
+
throw err;
|
|
1546
|
+
}
|
|
1547
|
+
}
|
|
1548
|
+
export async function launchPersistentContext(userDataDir, options = {}) {
|
|
1549
|
+
const browser = await launch({ ...options, userDataDir });
|
|
1550
|
+
const ctx = await browser.defaultContext({
|
|
1551
|
+
viewport: options.viewport,
|
|
1552
|
+
userAgent: options.userAgent,
|
|
1553
|
+
locale: options.locale,
|
|
1554
|
+
timezoneId: options.timezoneId ?? options.timezone,
|
|
1555
|
+
extraHTTPHeaders: options.extraHTTPHeaders,
|
|
1556
|
+
ignoreHTTPSErrors: options.ignoreHTTPSErrors,
|
|
1557
|
+
proxy: options.proxy,
|
|
1558
|
+
});
|
|
1559
|
+
// Closing a persistent context closes the underlying browser process.
|
|
1560
|
+
const origClose = ctx.close.bind(ctx);
|
|
1561
|
+
ctx.close = async () => {
|
|
1562
|
+
await origClose();
|
|
1563
|
+
await browser.close();
|
|
1564
|
+
};
|
|
1565
|
+
return ctx;
|
|
1566
|
+
}
|
|
1567
|
+
export async function connectOverCDP(endpointUrl) {
|
|
1568
|
+
let wsUrl = endpointUrl;
|
|
1569
|
+
if (endpointUrl.startsWith("http://") || endpointUrl.startsWith("https://")) {
|
|
1570
|
+
const res = await fetch(`${endpointUrl.replace(/\/$/, "")}/json/version`);
|
|
1571
|
+
if (!res.ok)
|
|
1572
|
+
throw new Error(`Failed to resolve CDP endpoint ${endpointUrl}: HTTP ${res.status}`);
|
|
1573
|
+
const meta = (await res.json());
|
|
1574
|
+
if (!meta.webSocketDebuggerUrl)
|
|
1575
|
+
throw new Error(`No webSocketDebuggerUrl at ${endpointUrl}/json/version`);
|
|
1576
|
+
wsUrl = meta.webSocketDebuggerUrl;
|
|
1577
|
+
}
|
|
1578
|
+
const cdp = await CDPConnection.dial(wsUrl);
|
|
1579
|
+
const browser = new SneakyBrowser(cdp);
|
|
1580
|
+
await browser.init();
|
|
1581
|
+
await browser.defaultContext();
|
|
1582
|
+
return browser;
|
|
1583
|
+
}
|
|
1584
|
+
/** Drop-in Playwright `chromium` object powered by sneaky-agent's zero-Runtime.enable stealth CDP driver. */
|
|
1585
|
+
export const chromium = {
|
|
1586
|
+
launch,
|
|
1587
|
+
launchPersistentContext,
|
|
1588
|
+
connectOverCDP,
|
|
1589
|
+
use(_plugin) {
|
|
1590
|
+
// No-op compatibility shim for playwright-extra callers; stealth is built into sneaky-agent.
|
|
1591
|
+
return chromium;
|
|
1592
|
+
},
|
|
1593
|
+
};
|
|
1594
|
+
//# sourceMappingURL=page.js.map
|