@xbrowser/cli 1.28.0 → 1.30.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/README.md +2 -2
- package/dist/{browser-4IYIHZ6R.js → browser-6PFTHZI3.js} +8 -6
- package/dist/{browser-NYYCR4O7.js → browser-I2NLJN2A.js} +5 -3
- package/dist/{browser-ZD53IMUJ.js → browser-KOUA4ZDA.js} +6 -4
- package/dist/{cdp-driver-EFEW4ZEN.js → cdp-driver-3ETNFQA4.js} +4 -4
- package/dist/{cdp-driver-HB744QB4.js → cdp-driver-U7HDQMQ5.js} +1578 -896
- package/dist/{cdp-driver-4X6Q62WI.js → cdp-driver-WBFJNOLD.js} +3 -3
- package/dist/{chunk-SEEWE5SJ.js → chunk-2KPI5GKP.js} +3 -0
- package/dist/{chunk-OEC7ZSFW.js → chunk-3K57RYVC.js} +1942 -1580
- package/dist/{chunk-75DNUI6M.js → chunk-6UJU2FJK.js} +146 -0
- package/dist/{chunk-FNXA6FDM.js → chunk-BND5O5KC.js} +2 -1
- package/dist/{chunk-KECYFWJO.js → chunk-BOZTIIBT.js} +441 -427
- package/dist/{chunk-WK3INZLA.js → chunk-KPTD3SNJ.js} +1121 -759
- package/dist/{chunk-OSZNJT4U.js → chunk-LM32MNBB.js} +79 -8
- package/dist/{chunk-T2AI24A5.js → chunk-NAIHOVDZ.js} +3 -0
- package/dist/{chunk-WYETQ5C7.js → chunk-NEE6EMYA.js} +14 -1
- package/dist/{chunk-3PUOISKE.js → chunk-NINETOM4.js} +524 -495
- package/dist/{chunk-SOPN4XDK.js → chunk-O5PASNI7.js} +2 -1
- package/dist/{chunk-ME5FO5YV.js → chunk-OCECE22C.js} +1578 -896
- package/dist/{chunk-HSYRAV3H.js → chunk-OSIDUT4H.js} +2151 -1440
- package/dist/{chunk-HBMEFSTB.js → chunk-QCV2PI7U.js} +2 -1
- package/dist/{chunk-IR6C24P7.js → chunk-RMYKVZIZ.js} +1103 -1043
- package/dist/{chunk-R3F4K2SB.js → chunk-SMYSNO4M.js} +10 -0
- package/dist/{chunk-J3HXZVSN.js → chunk-SPNWUUHA.js} +1452 -916
- package/dist/{chunk-PGKV24QN.js → chunk-TBJUSUKF.js} +1 -1
- package/dist/{chunk-V6KGBU5J.js → chunk-VYTQLZAX.js} +1091 -1040
- package/dist/cli.js +3447 -3377
- package/dist/daemon-main.js +1240 -786
- package/dist/{human-interaction-CTZ4IWXJ.js → human-interaction-ISMMOJOK.js} +2 -2
- package/dist/{human-interaction-HJCK45SL.js → human-interaction-STTZZZ5N.js} +1 -1
- package/dist/{human-interaction-V3VDGHHI.js → human-interaction-UXFYV7DU.js} +1 -1
- package/dist/index.d.ts +458 -476
- package/dist/index.js +3766 -3576
- package/dist/{launcher-SJ44X25U.js → launcher-TOLF23ET.js} +1 -1
- package/dist/{launcher-XHKIC4GP.js → launcher-ZYB32LSZ.js} +1 -1
- package/dist/{plugin-singleton-GGSBI3EG.js → plugin-singleton-A6RNITJW.js} +1 -1
- package/dist/{proxy-NKCYE76M.js → proxy-H3RIUOCN.js} +2 -2
- package/dist/{recovery-EBKORYEU.js → recovery-JFGV3DBX.js} +1 -1
- package/dist/{recovery-5C4FBA5O.js → recovery-ORHJSBDN.js} +2 -2
- package/dist/{recovery-IMZUGWSS.js → recovery-XDKN63O5.js} +1 -1
- package/dist/{server-26SE6YZR.js → server-TG47W7MV.js} +7 -7
- package/dist/{server-JXF3JOAM.js → server-U3YAX5MJ.js} +4 -4
- package/dist/{session-recorder-GEZVQBKW.js → session-recorder-N7VEKJVW.js} +1 -1
- package/dist/{session-recorder-563ISSJK.js → session-recorder-RUNQOJ7T.js} +1 -1
- package/dist/{session-replayer-TXTNTG33.js → session-replayer-XLWQ47BB.js} +1 -1
- package/dist/{stealth-QNSMIHQK.js → stealth-FMPZO2OB.js} +1 -1
- package/dist/{stealth-MHJNBJY7.js → stealth-MCKFKPZ6.js} +1 -1
- package/package.json +9 -3
|
@@ -5,11 +5,11 @@ import {
|
|
|
5
5
|
landingOffset,
|
|
6
6
|
rand,
|
|
7
7
|
typingDelay
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-SMYSNO4M.js";
|
|
9
9
|
import {
|
|
10
10
|
connectToCDP,
|
|
11
11
|
launchChrome
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-2KPI5GKP.js";
|
|
13
13
|
import {
|
|
14
14
|
errMsg
|
|
15
15
|
} from "./chunk-GDKLH7ZY.js";
|
|
@@ -18,10 +18,78 @@ import {
|
|
|
18
18
|
} from "./chunk-KFQGP6VL.js";
|
|
19
19
|
|
|
20
20
|
// src/browser.ts
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
|
|
24
|
-
|
|
21
|
+
import { readdirSync as readdirSync2, unlinkSync as unlinkSync2 } from "fs";
|
|
22
|
+
import { join as join3 } from "path";
|
|
23
|
+
|
|
24
|
+
// src/utils/cdp.ts
|
|
25
|
+
async function fetchNoProxy(url) {
|
|
26
|
+
const savedProxy = {
|
|
27
|
+
http_proxy: process.env.http_proxy,
|
|
28
|
+
https_proxy: process.env.https_proxy,
|
|
29
|
+
HTTP_PROXY: process.env.HTTP_PROXY,
|
|
30
|
+
HTTPS_PROXY: process.env.HTTPS_PROXY,
|
|
31
|
+
all_proxy: process.env.all_proxy,
|
|
32
|
+
ALL_PROXY: process.env.ALL_PROXY
|
|
33
|
+
};
|
|
34
|
+
for (const key of Object.keys(savedProxy)) delete process.env[key];
|
|
35
|
+
try {
|
|
36
|
+
return await fetch(url);
|
|
37
|
+
} finally {
|
|
38
|
+
for (const [key, val] of Object.entries(savedProxy)) {
|
|
39
|
+
if (val !== void 0) process.env[key] = val;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
async function resolveCDPEndpoint(raw) {
|
|
44
|
+
if (raw === "auto") {
|
|
45
|
+
const ports = [9222, 9221, 9223, 9224];
|
|
46
|
+
for (const port of ports) {
|
|
47
|
+
try {
|
|
48
|
+
const httpResp = await fetchNoProxy(`http://localhost:${port}/json/version`);
|
|
49
|
+
if (httpResp.ok) {
|
|
50
|
+
const data = await httpResp.json();
|
|
51
|
+
if (data.webSocketDebuggerUrl) {
|
|
52
|
+
return data.webSocketDebuggerUrl;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
} catch {
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
throw new Error(
|
|
59
|
+
`Could not auto-discover CDP endpoint. Tried ports: ${ports.join(", ")}.
|
|
60
|
+
\u53EF\u80FD\u539F\u56E0\uFF1A\u6CA1\u6709 Chrome \u4EE5 --remote-debugging-port \u542F\u52A8\u3002
|
|
61
|
+
\u89E3\u51B3\u65B9\u6CD5\uFF1A
|
|
62
|
+
1. \u542F\u52A8 Chrome: google-chrome --remote-debugging-port=9222
|
|
63
|
+
2. \u6216\u7528 cdp-tunnel: npx cdp-tunnel setup
|
|
64
|
+
3. \u6216\u6307\u5B9A\u7AEF\u53E3: --cdp <port>`
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
if (/^\d+$/.test(raw)) {
|
|
68
|
+
const port = raw;
|
|
69
|
+
const httpResp = await fetchNoProxy(`http://localhost:${port}/json/version`);
|
|
70
|
+
const data = await httpResp.json();
|
|
71
|
+
if (!data.webSocketDebuggerUrl) {
|
|
72
|
+
throw new Error(`Could not discover CDP endpoint from localhost:${port}`);
|
|
73
|
+
}
|
|
74
|
+
return data.webSocketDebuggerUrl;
|
|
75
|
+
}
|
|
76
|
+
if (raw.startsWith("http://") || raw.startsWith("https://")) {
|
|
77
|
+
try {
|
|
78
|
+
const u = new URL(raw);
|
|
79
|
+
u.pathname = (u.pathname.replace(/\/+$/, "") || "") + "/json/version";
|
|
80
|
+
const httpResp = await fetchNoProxy(u.toString());
|
|
81
|
+
const data = await httpResp.json();
|
|
82
|
+
if (!data.webSocketDebuggerUrl) {
|
|
83
|
+
throw new Error(`Could not discover CDP endpoint from ${raw}`);
|
|
84
|
+
}
|
|
85
|
+
return data.webSocketDebuggerUrl;
|
|
86
|
+
} catch (error) {
|
|
87
|
+
console.warn(`Failed to fetch WebSocket URL from ${raw}, using endpoint directly: ${error instanceof Error ? error.message : String(error)}`);
|
|
88
|
+
return raw;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return raw;
|
|
92
|
+
}
|
|
25
93
|
|
|
26
94
|
// src/cdp-driver/browser.ts
|
|
27
95
|
import { EventEmitter as EventEmitter3 } from "events";
|
|
@@ -36,12 +104,16 @@ import { EventEmitter as EventEmitter2 } from "events";
|
|
|
36
104
|
import { EventEmitter } from "events";
|
|
37
105
|
|
|
38
106
|
// src/cdp-driver/mouse.ts
|
|
107
|
+
function buttonBit(button) {
|
|
108
|
+
return button === "left" ? 1 : button === "right" ? 2 : 4;
|
|
109
|
+
}
|
|
39
110
|
var XBMouseImpl = class {
|
|
40
111
|
conn;
|
|
41
112
|
sessionId;
|
|
42
113
|
_x = 0;
|
|
43
114
|
_y = 0;
|
|
44
115
|
_button = "none";
|
|
116
|
+
_buttons = 0;
|
|
45
117
|
constructor(conn, sessionId) {
|
|
46
118
|
this.conn = conn;
|
|
47
119
|
this.sessionId = sessionId;
|
|
@@ -72,7 +144,7 @@ var XBMouseImpl = class {
|
|
|
72
144
|
_truncated = true;
|
|
73
145
|
break;
|
|
74
146
|
}
|
|
75
|
-
await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x, y: p.y, button: this._button });
|
|
147
|
+
await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x, y: p.y, button: this._button, buttons: this._buttons });
|
|
76
148
|
this._x = p.x;
|
|
77
149
|
this._y = p.y;
|
|
78
150
|
await sleep(p.delay);
|
|
@@ -80,7 +152,7 @@ var XBMouseImpl = class {
|
|
|
80
152
|
this._x = tx;
|
|
81
153
|
this._y = ty;
|
|
82
154
|
if (_truncated) {
|
|
83
|
-
await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: tx, y: ty, button: this._button });
|
|
155
|
+
await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: tx, y: ty, button: this._button, buttons: this._buttons });
|
|
84
156
|
}
|
|
85
157
|
await sleep(rand(...DEFAULT_STEALTH_CONFIG.aimPause));
|
|
86
158
|
} else {
|
|
@@ -92,7 +164,7 @@ var XBMouseImpl = class {
|
|
|
92
164
|
const ry = stealth ? this._y + rand(...DEFAULT_STEALTH_CONFIG.releaseDrift) * (Math.random() < 0.5 ? -1 : 1) : this._y;
|
|
93
165
|
this._x = rx;
|
|
94
166
|
this._y = ry;
|
|
95
|
-
await this.send("Input.dispatchMouseEvent", { type: "mouseReleased", x: rx, y: ry, button, clickCount: opts.clickCount ?? 1 });
|
|
167
|
+
await this.send("Input.dispatchMouseEvent", { type: "mouseReleased", x: rx, y: ry, button, buttons: this._buttons, clickCount: opts.clickCount ?? 1 });
|
|
96
168
|
for (let i = 1; i < (opts.clickCount ?? 1); i++) {
|
|
97
169
|
if (opts.delay) await sleep(opts.delay);
|
|
98
170
|
await this.down({ button });
|
|
@@ -105,11 +177,13 @@ var XBMouseImpl = class {
|
|
|
105
177
|
async down(opts = {}) {
|
|
106
178
|
const button = opts.button ?? "left";
|
|
107
179
|
this._button = button;
|
|
180
|
+
this._buttons |= buttonBit(button);
|
|
108
181
|
await this.send("Input.dispatchMouseEvent", {
|
|
109
182
|
type: "mousePressed",
|
|
110
183
|
x: this._x,
|
|
111
184
|
y: this._y,
|
|
112
185
|
button,
|
|
186
|
+
buttons: this._buttons,
|
|
113
187
|
// r23: press 必须与 release 声明同一 clickCount——Chrome 按序列计数
|
|
114
188
|
// 合成 click/dblclick,press 缺声明会把计数器重置(dblclick 永不合成)
|
|
115
189
|
clickCount: opts.clickCount ?? 1
|
|
@@ -123,8 +197,11 @@ var XBMouseImpl = class {
|
|
|
123
197
|
x: this._x,
|
|
124
198
|
y: this._y,
|
|
125
199
|
button,
|
|
200
|
+
// release 先带位发送再清位(Puppeteer 同序——DOM mouseup 的 buttons 反映释放后状态)
|
|
201
|
+
buttons: this._buttons,
|
|
126
202
|
clickCount: opts.clickCount ?? 1
|
|
127
203
|
});
|
|
204
|
+
this._buttons &= ~buttonBit(button);
|
|
128
205
|
}
|
|
129
206
|
async move(x, y, opts = {}) {
|
|
130
207
|
const stealth = opts.stealth ?? process.env.XBROWSER_STEALTH !== "off";
|
|
@@ -142,7 +219,8 @@ var XBMouseImpl = class {
|
|
|
142
219
|
type: "mouseMoved",
|
|
143
220
|
x: this._x,
|
|
144
221
|
y: this._y,
|
|
145
|
-
button: this._button
|
|
222
|
+
button: this._button,
|
|
223
|
+
buttons: this._buttons
|
|
146
224
|
});
|
|
147
225
|
}
|
|
148
226
|
this._x = x;
|
|
@@ -162,9 +240,11 @@ var XBMouseImpl = class {
|
|
|
162
240
|
x: this._x,
|
|
163
241
|
y: this._y,
|
|
164
242
|
button: "left",
|
|
243
|
+
buttons: 1,
|
|
165
244
|
clickCount: 1
|
|
166
245
|
});
|
|
167
246
|
this._button = "left";
|
|
247
|
+
this._buttons |= 1;
|
|
168
248
|
const steps = opts.steps ?? Math.max(10, Math.min(24, Math.round(Math.hypot(x - this._x, y - this._y) / 20)));
|
|
169
249
|
const fx = this._x, fy = this._y;
|
|
170
250
|
for (let i = 1; i <= steps; i++) {
|
|
@@ -176,7 +256,8 @@ var XBMouseImpl = class {
|
|
|
176
256
|
type: "mouseMoved",
|
|
177
257
|
x: this._x,
|
|
178
258
|
y: this._y,
|
|
179
|
-
button: this._button
|
|
259
|
+
button: this._button,
|
|
260
|
+
buttons: this._buttons
|
|
180
261
|
});
|
|
181
262
|
}
|
|
182
263
|
this._x = x;
|
|
@@ -187,15 +268,22 @@ var XBMouseImpl = class {
|
|
|
187
268
|
x,
|
|
188
269
|
y,
|
|
189
270
|
button: "left",
|
|
271
|
+
buttons: this._buttons,
|
|
190
272
|
clickCount: 1
|
|
191
273
|
});
|
|
192
274
|
this._button = "none";
|
|
275
|
+
this._buttons &= ~1;
|
|
276
|
+
}
|
|
277
|
+
async wheelAt(x, y, deltaX, deltaY) {
|
|
278
|
+
await this.move(x, y);
|
|
279
|
+
await this.wheel(deltaX, deltaY);
|
|
193
280
|
}
|
|
194
281
|
async wheel(deltaX, deltaY) {
|
|
195
282
|
await this.send("Input.dispatchMouseEvent", {
|
|
196
283
|
type: "mouseWheel",
|
|
197
284
|
x: this._x,
|
|
198
285
|
y: this._y,
|
|
286
|
+
buttons: this._buttons,
|
|
199
287
|
deltaX,
|
|
200
288
|
deltaY
|
|
201
289
|
});
|
|
@@ -1435,6 +1523,216 @@ var XBElementHandleImpl = class {
|
|
|
1435
1523
|
}
|
|
1436
1524
|
};
|
|
1437
1525
|
|
|
1526
|
+
// src/cdp-driver/page-media.ts
|
|
1527
|
+
var MediaService = class {
|
|
1528
|
+
constructor(options) {
|
|
1529
|
+
this.options = options;
|
|
1530
|
+
}
|
|
1531
|
+
options;
|
|
1532
|
+
async screenshot(opts = {}) {
|
|
1533
|
+
const params = {
|
|
1534
|
+
format: opts.type ?? "png"
|
|
1535
|
+
};
|
|
1536
|
+
if (opts.quality !== void 0 && (opts.type === "jpeg" || !opts.type && opts.quality)) {
|
|
1537
|
+
params.quality = opts.quality;
|
|
1538
|
+
}
|
|
1539
|
+
if (opts.fullPage) {
|
|
1540
|
+
params.captureBeyondViewport = true;
|
|
1541
|
+
}
|
|
1542
|
+
if (opts.clip) {
|
|
1543
|
+
const clip = {
|
|
1544
|
+
x: Math.round(opts.clip.x),
|
|
1545
|
+
y: Math.round(opts.clip.y),
|
|
1546
|
+
width: Math.round(Math.max(1, opts.clip.width)),
|
|
1547
|
+
height: Math.round(Math.max(1, opts.clip.height)),
|
|
1548
|
+
scale: opts.clip.scale ?? 1
|
|
1549
|
+
};
|
|
1550
|
+
params.clip = clip;
|
|
1551
|
+
}
|
|
1552
|
+
if (opts.omitBackground) {
|
|
1553
|
+
params.omitBackground = true;
|
|
1554
|
+
}
|
|
1555
|
+
const result = await this.options.conn.send(
|
|
1556
|
+
"Page.captureScreenshot",
|
|
1557
|
+
params,
|
|
1558
|
+
this.options.sessionId
|
|
1559
|
+
);
|
|
1560
|
+
return Buffer.from(result.data, "base64");
|
|
1561
|
+
}
|
|
1562
|
+
async pdf(opts = {}) {
|
|
1563
|
+
const params = {};
|
|
1564
|
+
if (opts.landscape !== void 0) params.landscape = opts.landscape;
|
|
1565
|
+
if (opts.printBackground !== void 0) params.printBackground = opts.printBackground;
|
|
1566
|
+
if (opts.scale !== void 0) params.scale = opts.scale;
|
|
1567
|
+
if (opts.format) params.paperFormat = opts.format;
|
|
1568
|
+
if (opts.preferCSSPageSize !== void 0) params.preferCSSPageSize = opts.preferCSSPageSize;
|
|
1569
|
+
if (opts.margin) {
|
|
1570
|
+
if (opts.margin.top) params.marginTop = parseFloat(opts.margin.top);
|
|
1571
|
+
if (opts.margin.bottom) params.marginBottom = parseFloat(opts.margin.bottom);
|
|
1572
|
+
if (opts.margin.left) params.marginLeft = parseFloat(opts.margin.left);
|
|
1573
|
+
if (opts.margin.right) params.marginRight = parseFloat(opts.margin.right);
|
|
1574
|
+
}
|
|
1575
|
+
const result = await this.options.conn.send("Page.printToPDF", params, this.options.sessionId);
|
|
1576
|
+
return Buffer.from(result.data, "base64");
|
|
1577
|
+
}
|
|
1578
|
+
viewportSize() {
|
|
1579
|
+
return this.options.viewportSize ?? null;
|
|
1580
|
+
}
|
|
1581
|
+
async setViewportSize(size) {
|
|
1582
|
+
await this.options.conn.send(
|
|
1583
|
+
"Emulation.setDeviceMetricsOverride",
|
|
1584
|
+
{
|
|
1585
|
+
width: size.width,
|
|
1586
|
+
height: size.height,
|
|
1587
|
+
deviceScaleFactor: 1,
|
|
1588
|
+
mobile: false
|
|
1589
|
+
},
|
|
1590
|
+
this.options.sessionId
|
|
1591
|
+
);
|
|
1592
|
+
this.options.onViewportSize(size);
|
|
1593
|
+
}
|
|
1594
|
+
/**
|
|
1595
|
+
* env-E2: 缩放变异——deviceScaleFactor 切换(CSS 像素坐标空间不变,
|
|
1596
|
+
* 物理像素翻倍)。保留当前 CSS 视口尺寸,只换 DSF。
|
|
1597
|
+
*/
|
|
1598
|
+
async setDeviceScaleFactor(dsf) {
|
|
1599
|
+
const size = this.options.viewportSize ?? await this.options.evaluate(
|
|
1600
|
+
"({ width: window.innerWidth, height: window.innerHeight })"
|
|
1601
|
+
);
|
|
1602
|
+
await this.options.conn.send(
|
|
1603
|
+
"Emulation.setDeviceMetricsOverride",
|
|
1604
|
+
{
|
|
1605
|
+
width: size.width,
|
|
1606
|
+
height: size.height,
|
|
1607
|
+
deviceScaleFactor: dsf,
|
|
1608
|
+
mobile: false
|
|
1609
|
+
},
|
|
1610
|
+
this.options.sessionId
|
|
1611
|
+
);
|
|
1612
|
+
this.options.onViewportSize(size);
|
|
1613
|
+
}
|
|
1614
|
+
// ── Scripts ─────────────────────────────────────────────────
|
|
1615
|
+
};
|
|
1616
|
+
|
|
1617
|
+
// src/cdp-driver/page-file-input.ts
|
|
1618
|
+
var FileInputService = class {
|
|
1619
|
+
constructor(options) {
|
|
1620
|
+
this.options = options;
|
|
1621
|
+
}
|
|
1622
|
+
options;
|
|
1623
|
+
async dropFiles(selector, payload) {
|
|
1624
|
+
await this.options.evaluate(`
|
|
1625
|
+
(function() {
|
|
1626
|
+
var el = ${queryJS(selector)};
|
|
1627
|
+
if (!el) throw new Error('drop target not found: ' + ${JSON.stringify(selector)});
|
|
1628
|
+
var b64 = ${JSON.stringify(payload.buffer.toString("base64"))};
|
|
1629
|
+
var bin = atob(b64);
|
|
1630
|
+
var buf = new Uint8Array(bin.length);
|
|
1631
|
+
for (var i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
|
|
1632
|
+
var file = new File([buf], ${JSON.stringify(payload.name)}, { type: ${JSON.stringify(payload.mimeType)} });
|
|
1633
|
+
var dt = new DataTransfer();
|
|
1634
|
+
dt.items.add(file);
|
|
1635
|
+
var rect = el.getBoundingClientRect();
|
|
1636
|
+
var opts = {
|
|
1637
|
+
bubbles: true, cancelable: true,
|
|
1638
|
+
clientX: rect.x + rect.width / 2, clientY: rect.y + rect.height / 2,
|
|
1639
|
+
};
|
|
1640
|
+
el.dispatchEvent(new DragEvent('dragenter', Object.assign({ dataTransfer: dt }, opts)));
|
|
1641
|
+
el.dispatchEvent(new DragEvent('dragover', Object.assign({ dataTransfer: dt }, opts)));
|
|
1642
|
+
el.dispatchEvent(new DragEvent('drop', Object.assign({ dataTransfer: dt }, opts)));
|
|
1643
|
+
})()
|
|
1644
|
+
`);
|
|
1645
|
+
}
|
|
1646
|
+
async setInputFiles(selector, files) {
|
|
1647
|
+
const fileArr = Array.isArray(files) ? files : [files];
|
|
1648
|
+
const fileList = fileArr.map((f) => ({
|
|
1649
|
+
name: f.name,
|
|
1650
|
+
type: f.mimeType,
|
|
1651
|
+
dataBase64: f.buffer.toString("base64")
|
|
1652
|
+
}));
|
|
1653
|
+
await this.options.evaluate(`
|
|
1654
|
+
(function() {
|
|
1655
|
+
var selector = ${JSON.stringify(selector)};
|
|
1656
|
+
var input = ${queryJS(selector)};
|
|
1657
|
+
if (!input) throw new Error('Element not found: ' + selector);
|
|
1658
|
+
|
|
1659
|
+
var fileList = ${JSON.stringify(fileList)};
|
|
1660
|
+
var dt = new DataTransfer();
|
|
1661
|
+
|
|
1662
|
+
fileList.forEach(function(f) {
|
|
1663
|
+
var binary = atob(f.dataBase64);
|
|
1664
|
+
var bytes = new Uint8Array(binary.length);
|
|
1665
|
+
for (var i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
1666
|
+
var blob = new Blob([bytes], { type: f.type });
|
|
1667
|
+
var file = new File([blob], f.name, { type: f.type });
|
|
1668
|
+
dt.items.add(file);
|
|
1669
|
+
});
|
|
1670
|
+
|
|
1671
|
+
input.files = dt.files;
|
|
1672
|
+
input.dispatchEvent(new Event('input', { bubbles: true }));
|
|
1673
|
+
input.dispatchEvent(new Event('change', { bubbles: true }));
|
|
1674
|
+
})()
|
|
1675
|
+
`);
|
|
1676
|
+
}
|
|
1677
|
+
// ── dragAndDrop ─────────────────────────────────────────────
|
|
1678
|
+
async dragAndDrop(source, target) {
|
|
1679
|
+
const sourceRect = await this.options.evaluate(`
|
|
1680
|
+
(function() {
|
|
1681
|
+
const el = ${queryJS(source)};
|
|
1682
|
+
if (!el) throw new Error('Source not found: ${source}');
|
|
1683
|
+
el.scrollIntoView({ behavior: 'instant', block: 'center' });
|
|
1684
|
+
const r = el.getBoundingClientRect();
|
|
1685
|
+
return { x: r.x, y: r.y, width: r.width, height: r.height };
|
|
1686
|
+
})()
|
|
1687
|
+
`);
|
|
1688
|
+
const targetRect = await this.options.evaluate(`
|
|
1689
|
+
(function() {
|
|
1690
|
+
const el = ${queryJS(target)};
|
|
1691
|
+
if (!el) throw new Error('Target not found: ${target}');
|
|
1692
|
+
el.scrollIntoView({ behavior: 'instant', block: 'center' });
|
|
1693
|
+
const r = el.getBoundingClientRect();
|
|
1694
|
+
return { x: r.x, y: r.y, width: r.width, height: r.height };
|
|
1695
|
+
})()
|
|
1696
|
+
`);
|
|
1697
|
+
const sx = sourceRect.x + sourceRect.width / 2;
|
|
1698
|
+
const sy = sourceRect.y + sourceRect.height / 2;
|
|
1699
|
+
const tx = targetRect.x + targetRect.width / 2;
|
|
1700
|
+
const ty = targetRect.y + targetRect.height / 2;
|
|
1701
|
+
try {
|
|
1702
|
+
await this.options.conn.send("Input.dispatchDragEvent", {
|
|
1703
|
+
type: "dragStart",
|
|
1704
|
+
x: sx,
|
|
1705
|
+
y: sy,
|
|
1706
|
+
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
1707
|
+
}, this.options.sessionId);
|
|
1708
|
+
await this.options.conn.send("Input.dispatchDragEvent", {
|
|
1709
|
+
type: "dragOver",
|
|
1710
|
+
x: tx,
|
|
1711
|
+
y: ty,
|
|
1712
|
+
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
1713
|
+
}, this.options.sessionId);
|
|
1714
|
+
await this.options.conn.send("Input.dispatchDragEvent", {
|
|
1715
|
+
type: "drop",
|
|
1716
|
+
x: tx,
|
|
1717
|
+
y: ty,
|
|
1718
|
+
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
1719
|
+
}, this.options.sessionId);
|
|
1720
|
+
await this.options.conn.send("Input.dispatchDragEvent", {
|
|
1721
|
+
type: "dragCancel",
|
|
1722
|
+
x: sx,
|
|
1723
|
+
y: sy,
|
|
1724
|
+
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
1725
|
+
}, this.options.sessionId);
|
|
1726
|
+
} catch {
|
|
1727
|
+
await this.options.mouse.move(sx, sy);
|
|
1728
|
+
await this.options.mouse.down();
|
|
1729
|
+
await this.options.mouse.move(tx, ty, { steps: 10 });
|
|
1730
|
+
await this.options.mouse.up();
|
|
1731
|
+
}
|
|
1732
|
+
}
|
|
1733
|
+
// ── setOfflineMode ──────────────────────────────────────────
|
|
1734
|
+
};
|
|
1735
|
+
|
|
1438
1736
|
// src/cdp-driver/page-helpers.ts
|
|
1439
1737
|
function globToRegex(glob) {
|
|
1440
1738
|
let pattern = glob.replace(/[\\^${}()|[\]+]/g, "\\$&").replace(/\./g, "\\.").replace(/\*\*/g, "{{DOUBLESTAR}}").replace(/\*/g, "[^/]*").replace(/{{DOUBLESTAR}}/g, ".*").replace(/\?/g, ".");
|
|
@@ -1586,18 +1884,964 @@ function createXBRouteFetch(conn, sessionId, params, emitter) {
|
|
|
1586
1884
|
};
|
|
1587
1885
|
}
|
|
1588
1886
|
|
|
1589
|
-
// src/cdp-driver/page.ts
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1887
|
+
// src/cdp-driver/page-network-events.ts
|
|
1888
|
+
function setupNetworkEvents(options) {
|
|
1889
|
+
options.addSubscription(
|
|
1890
|
+
options.conn.subscribe("Network.requestWillBeSent", options.sessionId, (params) => {
|
|
1891
|
+
const p = params;
|
|
1892
|
+
options.state.inflightRequests.add(p.requestId);
|
|
1893
|
+
options.storeRequest(p.requestId, {
|
|
1894
|
+
url: p.request.url,
|
|
1895
|
+
method: p.request.method,
|
|
1896
|
+
headers: p.request.headers,
|
|
1897
|
+
postData: p.request.postData ?? null,
|
|
1898
|
+
resourceType: p.type
|
|
1899
|
+
});
|
|
1900
|
+
options.emit("request", createXBRequest(
|
|
1901
|
+
null,
|
|
1902
|
+
{
|
|
1903
|
+
requestId: p.requestId,
|
|
1904
|
+
url: p.request.url,
|
|
1905
|
+
method: p.request.method,
|
|
1906
|
+
headers: p.request.headers,
|
|
1907
|
+
postData: p.request.postData ?? null,
|
|
1908
|
+
resourceType: p.type
|
|
1909
|
+
}
|
|
1910
|
+
));
|
|
1911
|
+
options.checkNetworkIdle();
|
|
1912
|
+
})
|
|
1913
|
+
);
|
|
1914
|
+
options.addSubscription(
|
|
1915
|
+
options.conn.subscribe("Network.responseReceived", options.sessionId, (params) => {
|
|
1916
|
+
const p = params;
|
|
1917
|
+
options.storeResponse(p.requestId, {
|
|
1918
|
+
status: p.response.status,
|
|
1919
|
+
url: p.response.url,
|
|
1920
|
+
headers: p.response.headers
|
|
1921
|
+
});
|
|
1922
|
+
options.emit("response", createXBResponse(
|
|
1923
|
+
{ requestId: p.requestId, status: p.response.status, url: p.response.url, headers: p.response.headers },
|
|
1924
|
+
options.conn,
|
|
1925
|
+
options.sessionId
|
|
1926
|
+
));
|
|
1927
|
+
})
|
|
1928
|
+
);
|
|
1929
|
+
options.addSubscription(
|
|
1930
|
+
options.conn.subscribe("Network.loadingFinished", options.sessionId, (params) => {
|
|
1931
|
+
const p = params;
|
|
1932
|
+
options.state.inflightRequests.delete(p.requestId);
|
|
1933
|
+
options.emit("requestfinished", p);
|
|
1934
|
+
options.checkNetworkIdle();
|
|
1935
|
+
})
|
|
1936
|
+
);
|
|
1937
|
+
options.addSubscription(
|
|
1938
|
+
options.conn.subscribe("Network.loadingFailed", options.sessionId, (params) => {
|
|
1939
|
+
const p = params;
|
|
1940
|
+
options.state.inflightRequests.delete(p.requestId);
|
|
1941
|
+
options.checkNetworkIdle();
|
|
1942
|
+
})
|
|
1943
|
+
);
|
|
1944
|
+
}
|
|
1945
|
+
|
|
1946
|
+
// src/cdp-driver/page-lifecycle-events.ts
|
|
1947
|
+
function setupPageEvents(options) {
|
|
1948
|
+
options.addSubscription(
|
|
1949
|
+
options.conn.subscribe("Page.frameNavigated", options.sessionId, (params) => {
|
|
1950
|
+
const p = params;
|
|
1951
|
+
if (p.frame) {
|
|
1952
|
+
options.setUrl(p.frame.url);
|
|
1953
|
+
}
|
|
1954
|
+
options.emit("framenavigated", options.mainFrame());
|
|
1955
|
+
})
|
|
1956
|
+
);
|
|
1957
|
+
options.addSubscription(
|
|
1958
|
+
options.conn.subscribe("Page.loadEventFired", options.sessionId, () => {
|
|
1959
|
+
options.markLoadFired();
|
|
1960
|
+
})
|
|
1961
|
+
);
|
|
1962
|
+
options.addSubscription(
|
|
1963
|
+
options.conn.subscribe("Page.domContentEventFired", options.sessionId, () => {
|
|
1964
|
+
options.markDomContentFired();
|
|
1965
|
+
})
|
|
1966
|
+
);
|
|
1967
|
+
options.addSubscription(
|
|
1968
|
+
options.conn.subscribe("Page.javascriptDialogOpening", options.sessionId, (params) => {
|
|
1969
|
+
const p = params;
|
|
1970
|
+
const dialog = {
|
|
1971
|
+
type: p.type,
|
|
1972
|
+
message: () => p.message,
|
|
1973
|
+
defaultValue: () => p.defaultValue,
|
|
1974
|
+
accept: async (text) => {
|
|
1975
|
+
await options.conn.send("Page.handleJavaScriptDialog", {
|
|
1976
|
+
accept: true,
|
|
1977
|
+
promptText: text
|
|
1978
|
+
}, options.sessionId);
|
|
1979
|
+
},
|
|
1980
|
+
dismiss: async () => {
|
|
1981
|
+
await options.conn.send("Page.handleJavaScriptDialog", {
|
|
1982
|
+
accept: false
|
|
1983
|
+
}, options.sessionId);
|
|
1984
|
+
}
|
|
1985
|
+
};
|
|
1986
|
+
options.emit("dialog", dialog);
|
|
1987
|
+
const autoAccept = p.type === "beforeunload" ? options.getBeforeUnloadAccept() : false;
|
|
1988
|
+
setTimeout(() => {
|
|
1989
|
+
options.conn.send("Page.handleJavaScriptDialog", { accept: autoAccept }, options.sessionId).catch(() => {
|
|
1990
|
+
});
|
|
1991
|
+
}, 0);
|
|
1992
|
+
})
|
|
1993
|
+
);
|
|
1994
|
+
options.addSubscription(
|
|
1995
|
+
options.conn.subscribe("Page.fileChooserOpened", options.sessionId, async (params) => {
|
|
1996
|
+
const p = params;
|
|
1997
|
+
let selector = "";
|
|
1998
|
+
try {
|
|
1999
|
+
const result = await options.conn.send("DOM.describeNode", { backendNodeId: p.backendNodeId }, options.sessionId);
|
|
2000
|
+
const attrs = result.node?.attributes || [];
|
|
2001
|
+
const idIdx = attrs.indexOf("id");
|
|
2002
|
+
if (idIdx >= 0) selector = "#" + attrs[idIdx + 1];
|
|
2003
|
+
} catch {
|
|
2004
|
+
}
|
|
2005
|
+
if (!selector) {
|
|
2006
|
+
try {
|
|
2007
|
+
const result = await options.conn.send("DOM.resolveNode", { backendNodeId: p.backendNodeId }, options.sessionId);
|
|
2008
|
+
const evalResult = await options.conn.send("Runtime.callFunctionOn", {
|
|
2009
|
+
objectId: result.objectId,
|
|
2010
|
+
functionDeclaration: 'function() { return this.id || this.name || "" }',
|
|
2011
|
+
returnByValue: true
|
|
2012
|
+
}, options.sessionId);
|
|
2013
|
+
if (evalResult.result?.value) selector = "#" + evalResult.result.value;
|
|
2014
|
+
} catch {
|
|
2015
|
+
}
|
|
2016
|
+
}
|
|
2017
|
+
const fileChooser = {
|
|
2018
|
+
selector,
|
|
2019
|
+
isMultiple: p.mode === "selectMultiple",
|
|
2020
|
+
setFiles: async (files) => {
|
|
2021
|
+
const fileArray = Array.isArray(files) ? files : [files];
|
|
2022
|
+
await options.setInputFiles(selector || 'input[type="file"]', fileArray);
|
|
2023
|
+
}
|
|
2024
|
+
};
|
|
2025
|
+
options.emit("filechooser", fileChooser);
|
|
2026
|
+
})
|
|
2027
|
+
);
|
|
2028
|
+
}
|
|
2029
|
+
|
|
2030
|
+
// src/cdp-driver/page-network-waits.ts
|
|
2031
|
+
var NetworkWaitService = class {
|
|
2032
|
+
constructor(options) {
|
|
2033
|
+
this.options = options;
|
|
2034
|
+
}
|
|
2035
|
+
options;
|
|
2036
|
+
// ── waitForResponse ─────────────────────────────────────────
|
|
2037
|
+
async waitForResponse(urlOrPredicate, opts = {}) {
|
|
2038
|
+
const timeout = opts.timeout ?? 3e4;
|
|
2039
|
+
const predicate = createResponsePredicate(urlOrPredicate);
|
|
2040
|
+
for (const [, data] of this.options.responses) {
|
|
2041
|
+
const response = createXBResponse(data, this.options.conn, this.options.sessionId);
|
|
2042
|
+
if (predicate(response)) return response;
|
|
2043
|
+
}
|
|
2044
|
+
return new Promise((resolve, reject) => {
|
|
2045
|
+
const timer = setTimeout(() => {
|
|
2046
|
+
this.options.off("response", handler);
|
|
2047
|
+
reject(new Error(`waitForResponse timed out after ${timeout}ms`));
|
|
2048
|
+
}, timeout);
|
|
2049
|
+
const handler = (params) => {
|
|
2050
|
+
let response;
|
|
2051
|
+
const respObj = params;
|
|
2052
|
+
if (respObj.response) {
|
|
2053
|
+
const data = {
|
|
2054
|
+
requestId: respObj.requestId || "",
|
|
2055
|
+
status: respObj.response.status || 0,
|
|
2056
|
+
url: respObj.response.url || "",
|
|
2057
|
+
headers: respObj.response.headers || {}
|
|
2058
|
+
};
|
|
2059
|
+
response = createXBResponse(data, this.options.conn, this.options.sessionId);
|
|
2060
|
+
} else if (typeof params.status === "function") {
|
|
2061
|
+
response = params;
|
|
2062
|
+
} else {
|
|
2063
|
+
return;
|
|
2064
|
+
}
|
|
2065
|
+
if (predicate(response)) {
|
|
2066
|
+
clearTimeout(timer);
|
|
2067
|
+
this.options.off("response", handler);
|
|
2068
|
+
resolve(response);
|
|
2069
|
+
}
|
|
2070
|
+
};
|
|
2071
|
+
this.options.on("response", handler);
|
|
2072
|
+
});
|
|
2073
|
+
}
|
|
2074
|
+
// ── waitForRequest ──────────────────────────────────────────
|
|
2075
|
+
async waitForRequest(urlOrPredicate, opts = {}) {
|
|
2076
|
+
const timeout = opts.timeout ?? 3e4;
|
|
2077
|
+
const predicate = createRequestPredicate(urlOrPredicate);
|
|
2078
|
+
for (const [, data] of this.options.requests) {
|
|
2079
|
+
const request = createXBRequest(this.pageLike(), data);
|
|
2080
|
+
if (predicate(request)) return request;
|
|
2081
|
+
}
|
|
2082
|
+
return new Promise((resolve, reject) => {
|
|
2083
|
+
const timer = setTimeout(() => {
|
|
2084
|
+
this.options.off("request", handler);
|
|
2085
|
+
reject(new Error(`waitForRequest timed out after ${timeout}ms`));
|
|
2086
|
+
}, timeout);
|
|
2087
|
+
const handler = (params) => {
|
|
2088
|
+
let request;
|
|
2089
|
+
const reqObj = params;
|
|
2090
|
+
if (reqObj.request) {
|
|
2091
|
+
request = createXBRequest(this.pageLike(), {
|
|
2092
|
+
requestId: reqObj.requestId || "",
|
|
2093
|
+
url: reqObj.request.url || "",
|
|
2094
|
+
method: reqObj.request.method || "",
|
|
2095
|
+
headers: reqObj.request.headers || {},
|
|
2096
|
+
postData: reqObj.request.postData ?? null,
|
|
2097
|
+
resourceType: reqObj.type || ""
|
|
2098
|
+
});
|
|
2099
|
+
} else if (typeof params.url === "function") {
|
|
2100
|
+
request = params;
|
|
2101
|
+
} else {
|
|
2102
|
+
return;
|
|
2103
|
+
}
|
|
2104
|
+
if (predicate(request)) {
|
|
2105
|
+
clearTimeout(timer);
|
|
2106
|
+
this.options.off("request", handler);
|
|
2107
|
+
resolve(request);
|
|
2108
|
+
}
|
|
2109
|
+
};
|
|
2110
|
+
this.options.on("request", handler);
|
|
2111
|
+
});
|
|
2112
|
+
}
|
|
2113
|
+
// ── waitForURL ──────────────────────────────────────────────
|
|
2114
|
+
async waitForURL(url, opts = {}) {
|
|
2115
|
+
const timeout = opts.timeout ?? 3e4;
|
|
2116
|
+
const checkFn = typeof url === "function" ? url : typeof url === "string" ? (current) => matchGlob(url, current) : (current) => url.test(current);
|
|
2117
|
+
if (checkFn(this.options.currentUrl())) return;
|
|
2118
|
+
return new Promise((resolve, reject) => {
|
|
2119
|
+
const timer = setTimeout(() => {
|
|
2120
|
+
this.options.off("framenavigated", handler);
|
|
2121
|
+
reject(new Error(`waitForURL timed out after ${timeout}ms`));
|
|
2122
|
+
}, timeout);
|
|
2123
|
+
const handler = () => {
|
|
2124
|
+
if (checkFn(this.options.currentUrl())) {
|
|
2125
|
+
clearTimeout(timer);
|
|
2126
|
+
this.options.off("framenavigated", handler);
|
|
2127
|
+
resolve();
|
|
2128
|
+
}
|
|
2129
|
+
};
|
|
2130
|
+
this.options.on("framenavigated", handler);
|
|
2131
|
+
});
|
|
2132
|
+
}
|
|
2133
|
+
pageLike() {
|
|
2134
|
+
return {
|
|
2135
|
+
_networkResponses: this.options.responses,
|
|
2136
|
+
_connection: this.options.conn,
|
|
2137
|
+
sessionId: this.options.sessionId
|
|
2138
|
+
};
|
|
2139
|
+
}
|
|
2140
|
+
};
|
|
2141
|
+
|
|
2142
|
+
// src/cdp-driver/page-routes.ts
|
|
2143
|
+
var NetworkRouteService = class {
|
|
2144
|
+
constructor(options) {
|
|
2145
|
+
this.options = options;
|
|
2146
|
+
}
|
|
2147
|
+
options;
|
|
2148
|
+
routeHandlers = [];
|
|
2149
|
+
interceptionEnabled = false;
|
|
2150
|
+
get isInterceptionEnabled() {
|
|
2151
|
+
return this.interceptionEnabled;
|
|
2152
|
+
}
|
|
2153
|
+
subscriptions = [];
|
|
2154
|
+
async route(url, handler) {
|
|
2155
|
+
const regex = typeof url === "string" ? globToRegex(url) : url;
|
|
2156
|
+
this.routeHandlers.push({ pattern: String(url), regex, handler });
|
|
2157
|
+
if (!this.interceptionEnabled) {
|
|
2158
|
+
this.interceptionEnabled = true;
|
|
2159
|
+
await this.options.conn.send("Fetch.enable", {
|
|
2160
|
+
patterns: [{ urlPattern: "*", requestStage: "Request" }],
|
|
2161
|
+
// sup-s9: 保留认证自动响应(Fetch.enable 为替换语义,不带此参数
|
|
2162
|
+
// 会顶掉 _init 的 auth 配置)
|
|
2163
|
+
handleAuthRequests: true
|
|
2164
|
+
}, this.options.sessionId);
|
|
2165
|
+
this.subscriptions.push(
|
|
2166
|
+
this.options.conn.subscribe("Fetch.requestPaused", this.options.sessionId, (params) => {
|
|
2167
|
+
this._handleRequestPaused(params);
|
|
2168
|
+
})
|
|
2169
|
+
);
|
|
2170
|
+
}
|
|
2171
|
+
}
|
|
2172
|
+
async unroute(url, handler) {
|
|
2173
|
+
const regex = typeof url === "string" ? globToRegex(url) : url;
|
|
2174
|
+
this.routeHandlers = this.routeHandlers.filter(
|
|
2175
|
+
(h) => !(regex.source === h.regex.source && (!handler || h.handler === handler))
|
|
2176
|
+
);
|
|
2177
|
+
if (this.routeHandlers.length === 0 && this.interceptionEnabled) {
|
|
2178
|
+
this.interceptionEnabled = false;
|
|
2179
|
+
await this.options.conn.send("Fetch.disable", void 0, this.options.sessionId).catch(() => {
|
|
2180
|
+
});
|
|
2181
|
+
}
|
|
2182
|
+
}
|
|
2183
|
+
async _handleRequestPaused(params) {
|
|
2184
|
+
const requestUrl = params.request.url;
|
|
2185
|
+
for (const { regex, handler } of this.routeHandlers) {
|
|
2186
|
+
if (regex.test(requestUrl)) {
|
|
2187
|
+
this.options.emit("request", createXBRequest(
|
|
2188
|
+
null,
|
|
2189
|
+
{
|
|
2190
|
+
requestId: params.requestId,
|
|
2191
|
+
url: params.request.url,
|
|
2192
|
+
method: params.request.method,
|
|
2193
|
+
headers: params.request.headers,
|
|
2194
|
+
postData: params.request.postData ?? null,
|
|
2195
|
+
resourceType: params.resourceType
|
|
2196
|
+
}
|
|
2197
|
+
));
|
|
2198
|
+
const route = createXBRouteFetch(this.options.conn, this.options.sessionId, params, void 0);
|
|
2199
|
+
try {
|
|
2200
|
+
await handler(route);
|
|
2201
|
+
} catch {
|
|
2202
|
+
await this.options.conn.send("Fetch.continueRequest", {
|
|
2203
|
+
requestId: params.requestId
|
|
2204
|
+
}, this.options.sessionId).catch(() => {
|
|
2205
|
+
});
|
|
2206
|
+
}
|
|
2207
|
+
return;
|
|
2208
|
+
}
|
|
2209
|
+
}
|
|
2210
|
+
await this.options.conn.send("Fetch.continueRequest", {
|
|
2211
|
+
requestId: params.requestId
|
|
2212
|
+
}, this.options.sessionId).catch(() => {
|
|
2213
|
+
});
|
|
2214
|
+
}
|
|
2215
|
+
};
|
|
2216
|
+
|
|
2217
|
+
// src/cdp-driver/page-navigation.ts
|
|
2218
|
+
var NavigationService = class {
|
|
2219
|
+
constructor(options) {
|
|
2220
|
+
this.options = options;
|
|
2221
|
+
}
|
|
2222
|
+
options;
|
|
2223
|
+
async goto(url, opts = {}) {
|
|
2224
|
+
if (this.options.isClosed()) throw new Error("Page is closed");
|
|
2225
|
+
const waitUntil = opts.waitUntil ?? "load";
|
|
2226
|
+
const timeout = opts.timeout ?? 3e4;
|
|
2227
|
+
this.options.state.loadFired = false;
|
|
2228
|
+
this.options.state.domContentFired = false;
|
|
2229
|
+
this.options.state.networkIdle = false;
|
|
2230
|
+
if (process.env.XBROWSER_STEALTH !== "off") {
|
|
2231
|
+
try {
|
|
2232
|
+
await this.options.conn.send(
|
|
2233
|
+
"Page.addScriptToEvaluateOnNewDocument",
|
|
2234
|
+
{ source: buildStealthInitScript({ ...DEFAULT_STEALTH_CONFIG, ...this.options.stealthConfig ?? {} }) },
|
|
2235
|
+
this.options.sessionId
|
|
2236
|
+
);
|
|
2237
|
+
} catch {
|
|
2238
|
+
}
|
|
2239
|
+
try {
|
|
2240
|
+
const rawUa = await this.options.conn.send(
|
|
2241
|
+
"Runtime.evaluate",
|
|
2242
|
+
{ expression: "navigator.userAgent", returnByValue: true },
|
|
2243
|
+
this.options.sessionId
|
|
2244
|
+
);
|
|
2245
|
+
const ua = rawUa?.value || "";
|
|
2246
|
+
const cleaned = ua.replace(/HeadlessChrome/g, "Chrome");
|
|
2247
|
+
if (cleaned !== ua) {
|
|
2248
|
+
await this.options.conn.send(
|
|
2249
|
+
"Network.setUserAgentOverride",
|
|
2250
|
+
{ userAgent: cleaned },
|
|
2251
|
+
this.options.sessionId
|
|
2252
|
+
);
|
|
2253
|
+
}
|
|
2254
|
+
} catch {
|
|
2255
|
+
}
|
|
2256
|
+
}
|
|
2257
|
+
const result = await this.options.conn.send(
|
|
2258
|
+
"Page.navigate",
|
|
2259
|
+
{ url, referrer: opts.referer },
|
|
2260
|
+
this.options.sessionId
|
|
2261
|
+
);
|
|
2262
|
+
if (result.errorText) {
|
|
2263
|
+
throw new Error(`Navigation failed: ${result.errorText}`);
|
|
2264
|
+
}
|
|
2265
|
+
if (waitUntil === "commit") {
|
|
2266
|
+
this.options.setUrl(url);
|
|
2267
|
+
return {
|
|
2268
|
+
status: () => 0,
|
|
2269
|
+
ok: () => false,
|
|
2270
|
+
url: () => url,
|
|
2271
|
+
headers: () => ({})
|
|
2272
|
+
};
|
|
2273
|
+
}
|
|
2274
|
+
await this.options.waitForLoadState(waitUntil, timeout);
|
|
2275
|
+
this.options.setUrl(url);
|
|
2276
|
+
const statusCode = 200;
|
|
2277
|
+
const finalUrl = url;
|
|
2278
|
+
const headers = {};
|
|
2279
|
+
return {
|
|
2280
|
+
status: () => statusCode,
|
|
2281
|
+
ok: () => statusCode >= 200 && statusCode < 300,
|
|
2282
|
+
url: () => finalUrl,
|
|
2283
|
+
headers: () => headers
|
|
2284
|
+
};
|
|
2285
|
+
}
|
|
2286
|
+
async goBack(opts = {}) {
|
|
2287
|
+
try {
|
|
2288
|
+
const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
|
|
2289
|
+
if (navHistory.currentIndex > 0) {
|
|
2290
|
+
const prevUrl = navHistory.entries[navHistory.currentIndex - 1]?.url;
|
|
2291
|
+
if (prevUrl && prevUrl !== "about:blank") {
|
|
2292
|
+
await this.options.conn.send("Page.navigate", { url: prevUrl }, this.options.sessionId);
|
|
2293
|
+
await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
|
|
2294
|
+
});
|
|
2295
|
+
this.options.setUrl(prevUrl);
|
|
2296
|
+
return;
|
|
2297
|
+
}
|
|
2298
|
+
}
|
|
2299
|
+
} catch {
|
|
2300
|
+
}
|
|
2301
|
+
await this.options.evaluate("() => history.back()");
|
|
2302
|
+
await this.options.waitForTimeout(3e3);
|
|
2303
|
+
this.options.setUrl(await this.options.evaluate("location.href").catch(() => this.options.currentUrl()));
|
|
2304
|
+
}
|
|
2305
|
+
async goForward(opts = {}) {
|
|
2306
|
+
try {
|
|
2307
|
+
const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
|
|
2308
|
+
if (navHistory.currentIndex < navHistory.entries.length - 1) {
|
|
2309
|
+
const nextUrl = navHistory.entries[navHistory.currentIndex + 1]?.url;
|
|
2310
|
+
if (nextUrl && nextUrl !== "about:blank") {
|
|
2311
|
+
await this.options.conn.send("Page.navigate", { url: nextUrl }, this.options.sessionId);
|
|
2312
|
+
await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
|
|
2313
|
+
});
|
|
2314
|
+
this.options.setUrl(nextUrl);
|
|
2315
|
+
return;
|
|
2316
|
+
}
|
|
2317
|
+
}
|
|
2318
|
+
} catch {
|
|
2319
|
+
}
|
|
2320
|
+
await this.options.evaluate("() => history.forward()");
|
|
2321
|
+
await this.options.waitForTimeout(3e3);
|
|
2322
|
+
this.options.setUrl(await this.options.evaluate("location.href").catch(() => this.options.currentUrl()));
|
|
2323
|
+
}
|
|
2324
|
+
async reload(opts = {}) {
|
|
2325
|
+
this.options.state.loadFired = false;
|
|
2326
|
+
this.options.state.domContentFired = false;
|
|
2327
|
+
this.options.state.networkIdle = false;
|
|
2328
|
+
await this.options.conn.send("Page.reload", void 0, this.options.sessionId);
|
|
2329
|
+
await this.options.waitForLoadState(opts.waitUntil ?? "load", opts.timeout);
|
|
2330
|
+
}
|
|
2331
|
+
async waitForLoadState(state = "load", timeout = 3e4) {
|
|
2332
|
+
if (this.options.isClosed()) throw new Error("Page is closed");
|
|
2333
|
+
const checkState = () => {
|
|
2334
|
+
switch (state) {
|
|
2335
|
+
case "domcontentloaded":
|
|
2336
|
+
return this.options.state.domContentFired;
|
|
2337
|
+
case "load":
|
|
2338
|
+
return this.options.state.loadFired;
|
|
2339
|
+
case "networkidle":
|
|
2340
|
+
return this.options.state.networkIdle;
|
|
2341
|
+
case "commit":
|
|
2342
|
+
return this.options.state.domContentFired;
|
|
2343
|
+
default:
|
|
2344
|
+
return true;
|
|
2345
|
+
}
|
|
2346
|
+
};
|
|
2347
|
+
if (checkState()) return;
|
|
2348
|
+
return new Promise((resolve, reject) => {
|
|
2349
|
+
const timer = setTimeout(() => {
|
|
2350
|
+
reject(new Error(`waitForLoadState('${state}') timeout after ${timeout}ms`));
|
|
2351
|
+
}, timeout);
|
|
2352
|
+
const check = () => {
|
|
2353
|
+
if (checkState()) {
|
|
2354
|
+
clearTimeout(timer);
|
|
2355
|
+
resolve();
|
|
2356
|
+
} else {
|
|
2357
|
+
setTimeout(check, 50);
|
|
2358
|
+
}
|
|
2359
|
+
};
|
|
2360
|
+
check();
|
|
2361
|
+
});
|
|
2362
|
+
}
|
|
2363
|
+
async waitForTimeout(ms) {
|
|
2364
|
+
await new Promise((resolve) => {
|
|
2365
|
+
const timer = setTimeout(resolve, ms);
|
|
2366
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
2367
|
+
});
|
|
2368
|
+
}
|
|
2369
|
+
};
|
|
2370
|
+
|
|
2371
|
+
// src/cdp-driver/page-dom.ts
|
|
2372
|
+
var DomQueryService = class {
|
|
2373
|
+
constructor(options) {
|
|
2374
|
+
this.options = options;
|
|
2375
|
+
}
|
|
2376
|
+
options;
|
|
2377
|
+
/** Query a single element, returns CDP nodeId or 0 if not found */
|
|
2378
|
+
async querySelector(selector) {
|
|
2379
|
+
if (selector.startsWith("xpath=")) {
|
|
2380
|
+
const found = await this.options.evaluate(`
|
|
2381
|
+
(() => { const el = ${queryJS(selector)}; return !!el; })()
|
|
2382
|
+
`).catch(() => false);
|
|
2383
|
+
if (!found) return 0;
|
|
2384
|
+
try {
|
|
2385
|
+
const search = await this.options.conn.send(
|
|
2386
|
+
"DOM.performSearch",
|
|
2387
|
+
{ query: selector.slice(6) },
|
|
2388
|
+
this.options.sessionId
|
|
2389
|
+
);
|
|
2390
|
+
if (search.nodeId) return search.nodeId;
|
|
2391
|
+
} catch {
|
|
2392
|
+
}
|
|
2393
|
+
return 1;
|
|
2394
|
+
}
|
|
2395
|
+
const withTimeout = (p, ms) => Promise.race([p, new Promise((r) => setTimeout(() => r(null), ms))]);
|
|
2396
|
+
const doc = await withTimeout(
|
|
2397
|
+
this.options.conn.send("DOM.getDocument", { depth: 0 }, this.options.sessionId),
|
|
2398
|
+
8e3
|
|
2399
|
+
);
|
|
2400
|
+
if (!doc) return 0;
|
|
2401
|
+
const result = await withTimeout(
|
|
2402
|
+
this.options.conn.send(
|
|
2403
|
+
"DOM.querySelector",
|
|
2404
|
+
{ nodeId: doc.root.nodeId, selector },
|
|
2405
|
+
this.options.sessionId
|
|
2406
|
+
),
|
|
2407
|
+
8e3
|
|
2408
|
+
);
|
|
2409
|
+
if (!result) return 0;
|
|
2410
|
+
return result.nodeId;
|
|
2411
|
+
}
|
|
2412
|
+
/** Query all matching elements, returns array of CDP nodeIds */
|
|
2413
|
+
async querySelectorAll(selector) {
|
|
2414
|
+
const doc = await this.options.conn.send(
|
|
2415
|
+
"DOM.getDocument",
|
|
2416
|
+
{ depth: 0 },
|
|
2417
|
+
this.options.sessionId
|
|
2418
|
+
);
|
|
2419
|
+
const result = await this.options.conn.send(
|
|
2420
|
+
"DOM.querySelectorAll",
|
|
2421
|
+
{ nodeId: doc.root.nodeId, selector },
|
|
2422
|
+
this.options.sessionId
|
|
2423
|
+
);
|
|
2424
|
+
return result.nodeIds ?? [];
|
|
2425
|
+
}
|
|
2426
|
+
/** Resolve a CDP nodeId to a RemoteObject for evaluate */
|
|
2427
|
+
async resolveNode(nodeId) {
|
|
2428
|
+
const result = await this.options.conn.send(
|
|
2429
|
+
"DOM.resolveNode",
|
|
2430
|
+
{ nodeId },
|
|
2431
|
+
this.options.sessionId
|
|
2432
|
+
);
|
|
2433
|
+
return result.object.objectId;
|
|
2434
|
+
}
|
|
2435
|
+
/** Get the box model for a nodeId */
|
|
2436
|
+
async getBoxModel(nodeId) {
|
|
2437
|
+
try {
|
|
2438
|
+
const result = await this.options.conn.send("DOM.getBoxModel", { nodeId }, this.options.sessionId);
|
|
2439
|
+
const c = result.model?.content;
|
|
2440
|
+
if (!c || c.length < 8) return null;
|
|
2441
|
+
const x1 = c[0];
|
|
2442
|
+
const y1 = c[1];
|
|
2443
|
+
const x2 = c[4];
|
|
2444
|
+
const y2 = c[5];
|
|
2445
|
+
return {
|
|
2446
|
+
x: Math.min(x1, x2),
|
|
2447
|
+
y: Math.min(y1, y2),
|
|
2448
|
+
width: Math.abs(x2 - x1),
|
|
2449
|
+
height: Math.abs(y2 - y1)
|
|
2450
|
+
};
|
|
2451
|
+
} catch {
|
|
2452
|
+
return null;
|
|
2453
|
+
}
|
|
2454
|
+
}
|
|
2455
|
+
/** Call a function on a RemoteObject */
|
|
2456
|
+
async callFunctionOn(objectId, functionDeclaration, args = []) {
|
|
2457
|
+
const result = await this.options.conn.send("Runtime.callFunctionOn", {
|
|
2458
|
+
objectId,
|
|
2459
|
+
functionDeclaration,
|
|
2460
|
+
arguments: args.map((a) => ({ value: a })),
|
|
2461
|
+
returnByValue: true
|
|
2462
|
+
}, this.options.sessionId);
|
|
2463
|
+
if (result.exceptionDetails) {
|
|
2464
|
+
throw new Error(`CallFunctionOn error: ${result.exceptionDetails.text}`);
|
|
2465
|
+
}
|
|
2466
|
+
return result.result?.value;
|
|
2467
|
+
}
|
|
2468
|
+
/** Send a CDP command scoped to this page's session */
|
|
2469
|
+
async _cdpSend(method, params) {
|
|
2470
|
+
return this.options.conn.send(method, params, this.options.sessionId);
|
|
2471
|
+
}
|
|
2472
|
+
/** sup-s11: beforeunload 自动应答语义——'accept'(默认,离开页面,与录制
|
|
2473
|
+
* 意图一致)或 'dismiss'(取消导航留守原页,尽力而为:此构建上 CDP
|
|
2474
|
+
* accept:false 对浏览器侧导航的取消语义不稳定,不保证)。 */
|
|
2475
|
+
};
|
|
2476
|
+
|
|
2477
|
+
// src/cdp-driver/page-runtime.ts
|
|
2478
|
+
var RuntimeEvaluationService = class {
|
|
2479
|
+
constructor(options) {
|
|
2480
|
+
this.options = options;
|
|
2481
|
+
}
|
|
2482
|
+
options;
|
|
2483
|
+
async title() {
|
|
2484
|
+
let title = "";
|
|
2485
|
+
for (let attempt = 0; attempt < 20; attempt++) {
|
|
2486
|
+
try {
|
|
2487
|
+
title = await this.evaluate("document.title");
|
|
2488
|
+
if (title) return title;
|
|
2489
|
+
} catch {
|
|
2490
|
+
}
|
|
2491
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
2492
|
+
}
|
|
2493
|
+
return title;
|
|
2494
|
+
}
|
|
2495
|
+
async content() {
|
|
2496
|
+
return this.evaluate("document.documentElement.outerHTML");
|
|
2497
|
+
}
|
|
2498
|
+
// ── Evaluation ──────────────────────────────────────────────
|
|
2499
|
+
async evaluate(fn, ...args) {
|
|
2500
|
+
if (this.options.isClosed()) throw new Error("Page is closed");
|
|
2501
|
+
this.options.conn.send("Page.handleJavaScriptDialog", { accept: false }, this.options.sessionId).catch(() => {
|
|
2502
|
+
});
|
|
2503
|
+
let expression;
|
|
2504
|
+
if (typeof fn === "string") {
|
|
2505
|
+
expression = fn;
|
|
2506
|
+
} else {
|
|
2507
|
+
const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
|
|
2508
|
+
expression = `(()=>{const __fn=(${fn.toString()});return __fn(${argStr});})()`;
|
|
2509
|
+
}
|
|
2510
|
+
const result = await this.options.conn.send("Runtime.evaluate", {
|
|
2511
|
+
expression,
|
|
2512
|
+
returnByValue: true,
|
|
2513
|
+
awaitPromise: true
|
|
2514
|
+
}, this.options.sessionId);
|
|
2515
|
+
if (result.exceptionDetails) {
|
|
2516
|
+
const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
|
|
2517
|
+
throw new Error(`${detail}`);
|
|
2518
|
+
}
|
|
2519
|
+
return result.result?.value;
|
|
2520
|
+
}
|
|
2521
|
+
/**
|
|
2522
|
+
* 在指定 iframe 上下文中执行表达式(攻防 D16 能力建设,2026-08-19)。
|
|
2523
|
+
*
|
|
2524
|
+
* 双路径:
|
|
2525
|
+
* 1. 同进程 iframe —— Runtime.enable 收集 executionContextCreated,
|
|
2526
|
+
* 找到目标 frameId 的 contextId,用 contextId 定向执行;
|
|
2527
|
+
* 2. 跨域 OOPIF(独立 target)—— Target.setAutoAttach(flatten) 监听
|
|
2528
|
+
* attachedToTarget 中 type==='iframe' 的会话,用其 sessionId 执行。
|
|
2529
|
+
*
|
|
2530
|
+
* 这绕过了页面同源策略(那是页面 JS 的约束,CDP 是调试通道)——
|
|
2531
|
+
* 支付窗/验证码/第三方嵌入内容的读写都靠它。
|
|
2532
|
+
*/
|
|
2533
|
+
async evaluateInFrame(urlIncludes, expression) {
|
|
2534
|
+
if (this.options.isClosed()) throw new Error("Page is closed");
|
|
2535
|
+
const evalIn = async (sessionId, contextId) => {
|
|
2536
|
+
const params = { expression, returnByValue: true, awaitPromise: true };
|
|
2537
|
+
if (contextId !== void 0) params.contextId = contextId;
|
|
2538
|
+
const result = await this.options.conn.send("Runtime.evaluate", params, sessionId);
|
|
2539
|
+
if (result.exceptionDetails) {
|
|
2540
|
+
const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
|
|
2541
|
+
throw new Error(`[frame ${urlIncludes}] ${detail}`);
|
|
2542
|
+
}
|
|
2543
|
+
return result.result?.value;
|
|
2544
|
+
};
|
|
2545
|
+
const attachedA = await this.tryAttachViaTargets(urlIncludes);
|
|
2546
|
+
if (attachedA) {
|
|
2547
|
+
try {
|
|
2548
|
+
return await evalIn(attachedA);
|
|
2549
|
+
} finally {
|
|
2550
|
+
this.detachQuietly(attachedA);
|
|
2551
|
+
}
|
|
2552
|
+
}
|
|
2553
|
+
const tree = await this.options.conn.send("Page.getFrameTree", void 0, this.options.sessionId);
|
|
2554
|
+
const all = [];
|
|
2555
|
+
const walk = (node) => {
|
|
2556
|
+
all.push({ id: node.frame.id, url: node.frame.url });
|
|
2557
|
+
for (const child of node.childFrames || []) walk(child);
|
|
2558
|
+
};
|
|
2559
|
+
walk(tree.frameTree);
|
|
2560
|
+
const mainId = tree.frameTree?.frame?.id;
|
|
2561
|
+
const target = all.find((f) => f.id !== mainId && f.url.includes(urlIncludes));
|
|
2562
|
+
if (target) {
|
|
2563
|
+
const contexts = [];
|
|
2564
|
+
const onCtx = (raw) => {
|
|
2565
|
+
const c = raw?.context;
|
|
2566
|
+
if (c?.id && c?.auxData?.frameId) contexts.push({ id: c.id, frameId: c.auxData.frameId });
|
|
2567
|
+
};
|
|
2568
|
+
this.options.conn.on("Runtime.executionContextCreated", onCtx);
|
|
2569
|
+
try {
|
|
2570
|
+
await this.options.conn.send("Runtime.enable", void 0, this.options.sessionId).catch(() => {
|
|
2571
|
+
});
|
|
2572
|
+
await new Promise((r) => setTimeout(r, 400));
|
|
2573
|
+
} finally {
|
|
2574
|
+
this.options.conn.off("Runtime.executionContextCreated", onCtx);
|
|
2575
|
+
}
|
|
2576
|
+
const ctx = contexts.find((c) => c.frameId === target.id);
|
|
2577
|
+
if (ctx) return evalIn(this.options.sessionId, ctx.id);
|
|
2578
|
+
}
|
|
2579
|
+
const attachedC = await this.tryAttachViaAutoAttach(urlIncludes);
|
|
2580
|
+
if (attachedC) {
|
|
2581
|
+
try {
|
|
2582
|
+
return await evalIn(attachedC);
|
|
2583
|
+
} finally {
|
|
2584
|
+
this.detachQuietly(attachedC);
|
|
2585
|
+
}
|
|
2586
|
+
}
|
|
2587
|
+
throw new Error(`frame not found for "${urlIncludes}"\uFF08OOPIF target\u3001frame \u6811\u3001auto-attach \u4E09\u8DEF\u5747\u672A\u547D\u4E2D\uFF1B\u53EF\u80FD\u4ECD\u5728\u52A0\u8F7D\uFF09`);
|
|
2588
|
+
}
|
|
2589
|
+
/**
|
|
2590
|
+
* 输入专用 frame session 解析(mouse/click/fill --frame)。
|
|
2591
|
+
*
|
|
2592
|
+
* 与 evaluateInFrame 的区别:必须拿到**真实 target session**(Input 域
|
|
2593
|
+
* 事件派发到该 session 才会进入 iframe 的渲染进程——主页面 session 上
|
|
2594
|
+
* 派发的输入进不去 OOPIF,qqmail 验证码 4 次页面级拖动全败的实证)。
|
|
2595
|
+
* 因此只走 A(getTargets attach)/ C(auto-attach)两路;同进程 frame
|
|
2596
|
+
* 没有 session,但 locator 层的坐标偏移本就支持同源 iframe,直接用普通
|
|
2597
|
+
* click/fill 即可。
|
|
2598
|
+
*
|
|
2599
|
+
* 坐标语义:返回的 session 上派发 Input 事件用 **iframe 局部坐标**
|
|
2600
|
+
* (与该 session 内 getBoundingClientRect 一致)。
|
|
2601
|
+
*/
|
|
2602
|
+
async resolveFrameSession(urlIncludes) {
|
|
2603
|
+
if (this.options.isClosed()) throw new Error("Page is closed");
|
|
2604
|
+
const viaTargets = await this.tryAttachViaTargets(urlIncludes);
|
|
2605
|
+
if (viaTargets) return viaTargets;
|
|
2606
|
+
const viaAuto = await this.tryAttachViaAutoAttach(urlIncludes);
|
|
2607
|
+
if (viaAuto) return viaAuto;
|
|
2608
|
+
try {
|
|
2609
|
+
const tree = await this.options.conn.send("Page.getFrameTree", void 0, this.options.sessionId);
|
|
2610
|
+
const urls = [];
|
|
2611
|
+
const walk = (node) => {
|
|
2612
|
+
urls.push(node.frame.url);
|
|
2613
|
+
for (const child of node.childFrames || []) walk(child);
|
|
2614
|
+
};
|
|
2615
|
+
walk(tree.frameTree);
|
|
2616
|
+
if (urls.some((u) => u.includes(urlIncludes))) {
|
|
2617
|
+
throw new Error(`frame "${urlIncludes}" \u662F\u540C\u8FDB\u7A0B iframe\uFF08\u65E0\u72EC\u7ACB target\uFF09\u2014\u2014\u666E\u901A click/fill/mouse \u5373\u53EF\uFF08locator \u5C42\u5DF2\u652F\u6301\u540C\u6E90 iframe \u5750\u6807\u504F\u79FB\uFF09`);
|
|
2618
|
+
}
|
|
2619
|
+
} catch (err) {
|
|
2620
|
+
if (err instanceof Error && err.message.includes("\u540C\u8FDB\u7A0B")) throw err;
|
|
2621
|
+
}
|
|
2622
|
+
throw new Error(`no OOPIF target for "${urlIncludes}"\uFF08\u7528 'xbrowser frames' \u67E5\u770B\u53EF\u89C1\u7684 iframe target\uFF1BOOPIF \u53EA\u5728 Target.getTargets \u91CC\u51FA\u73B0\uFF09`);
|
|
2623
|
+
}
|
|
2624
|
+
/** 浏览器级 iframe target 列表(OOPIF 可见性——Page.getFrameTree 看不到它们) */
|
|
2625
|
+
async listFrameTargets() {
|
|
2626
|
+
try {
|
|
2627
|
+
const tg = await this.options.conn.send("Target.getTargets", void 0);
|
|
2628
|
+
return (tg.targetInfos || []).filter((t) => t.type === "iframe").map((t) => ({ url: t.url || "", targetId: t.targetId }));
|
|
2629
|
+
} catch {
|
|
2630
|
+
return [];
|
|
2631
|
+
}
|
|
2632
|
+
}
|
|
2633
|
+
/** 路径 A:浏览器级 Target.getTargets 平铺 iframe target,按 URL 子串 attach。
|
|
2634
|
+
* 多次导航后列表里可能残留正在销毁的陈旧 target——attach 后用 location.href
|
|
2635
|
+
* 验证候选确实是活目标,不匹配则换下一个(验证码 iframe 重建场景实测会撞上)。 */
|
|
2636
|
+
async tryAttachViaTargets(urlIncludes) {
|
|
2637
|
+
try {
|
|
2638
|
+
const tg = await this.options.conn.send("Target.getTargets", void 0);
|
|
2639
|
+
const candidates = (tg.targetInfos || []).filter((t) => t.type === "iframe" && (t.url || "").includes(urlIncludes));
|
|
2640
|
+
for (const hit of candidates) {
|
|
2641
|
+
try {
|
|
2642
|
+
const att = await this.options.conn.send("Target.attachToTarget", { targetId: hit.targetId, flatten: true });
|
|
2643
|
+
const probe = await this.options.conn.send("Runtime.evaluate", { expression: "location.href", returnByValue: true }, att.sessionId);
|
|
2644
|
+
const href = typeof probe.result?.value === "string" ? probe.result.value : "";
|
|
2645
|
+
if (probe.exceptionDetails || !href.includes(urlIncludes)) {
|
|
2646
|
+
this.detachQuietly(att.sessionId);
|
|
2647
|
+
continue;
|
|
2648
|
+
}
|
|
2649
|
+
return att.sessionId;
|
|
2650
|
+
} catch {
|
|
2651
|
+
continue;
|
|
2652
|
+
}
|
|
2653
|
+
}
|
|
2654
|
+
} catch {
|
|
2655
|
+
}
|
|
2656
|
+
return null;
|
|
2657
|
+
}
|
|
2658
|
+
/** 路径 C:Target.setAutoAttach 监听后续 attach 的 iframe target(兜底) */
|
|
2659
|
+
async tryAttachViaAutoAttach(urlIncludes) {
|
|
2660
|
+
const attached = [];
|
|
2661
|
+
const onAttach = (raw) => {
|
|
2662
|
+
const ev = raw;
|
|
2663
|
+
if (ev?.sessionId && ev.targetInfo?.type === "iframe") {
|
|
2664
|
+
attached.push({ sessionId: ev.sessionId, url: ev.targetInfo.url || "" });
|
|
2665
|
+
}
|
|
2666
|
+
};
|
|
2667
|
+
this.options.conn.on("Target.attachedToTarget", onAttach);
|
|
2668
|
+
try {
|
|
2669
|
+
await this.options.conn.send("Target.setAutoAttach", {
|
|
2670
|
+
autoAttach: true,
|
|
2671
|
+
waitForDebuggerOnStart: false,
|
|
2672
|
+
flatten: true
|
|
2673
|
+
}, this.options.sessionId);
|
|
2674
|
+
await new Promise((r) => setTimeout(r, 600));
|
|
2675
|
+
} finally {
|
|
2676
|
+
this.options.conn.off("Target.attachedToTarget", onAttach);
|
|
2677
|
+
this.options.conn.send("Target.setAutoAttach", { autoAttach: false, waitForDebuggerOnStart: false, flatten: true }, this.options.sessionId).catch(() => {
|
|
2678
|
+
});
|
|
2679
|
+
}
|
|
2680
|
+
const hit = attached.find((a) => a.url.includes(urlIncludes));
|
|
2681
|
+
return hit ? hit.sessionId : null;
|
|
2682
|
+
}
|
|
2683
|
+
detachQuietly(sessionId) {
|
|
2684
|
+
this.options.conn.send("Target.detachFromTarget", { sessionId }).catch(() => {
|
|
2685
|
+
});
|
|
2686
|
+
}
|
|
2687
|
+
/** evaluateHandle — evaluates fn and returns a handle for element bounding box */
|
|
2688
|
+
async evaluateHandle(fn, ...args) {
|
|
2689
|
+
let expression;
|
|
2690
|
+
if (typeof fn === "string") {
|
|
2691
|
+
expression = fn;
|
|
2692
|
+
} else {
|
|
2693
|
+
const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
|
|
2694
|
+
expression = `(()=>{const __fn=(${fn.toString()});const __el=__fn(${argStr});if(__el&&typeof __el.getBoundingClientRect==='function'){const r=__el.getBoundingClientRect();return JSON.parse(JSON.stringify({x:r.x,y:r.y,w:r.width,h:r.height}));}return null;})()`;
|
|
2695
|
+
}
|
|
2696
|
+
const result = await this.options.conn.send("Runtime.evaluate", { expression, returnByValue: true }).catch(() => ({ result: { value: null } }));
|
|
2697
|
+
let box = null;
|
|
2698
|
+
try {
|
|
2699
|
+
box = JSON.parse(result.result?.value);
|
|
2700
|
+
} catch {
|
|
2701
|
+
}
|
|
2702
|
+
return {
|
|
2703
|
+
asElement: () => box ? { boundingBox: async () => box } : null
|
|
2704
|
+
};
|
|
2705
|
+
}
|
|
2706
|
+
async $eval(selector, fn, ...args) {
|
|
2707
|
+
const fnBody = typeof fn === "function" ? fn.toString() : fn;
|
|
2708
|
+
const selJSON = JSON.stringify(selector);
|
|
2709
|
+
const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
|
|
2710
|
+
return this.evaluate(
|
|
2711
|
+
`(function(sel, xpathExpr, fnStr, ...evalArgs) {
|
|
2712
|
+
const el = xpathExpr
|
|
2713
|
+
? document.evaluate(xpathExpr, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
|
|
2714
|
+
: document.querySelector(sel);
|
|
2715
|
+
if (!el) throw new Error('No element found for selector: ' + sel);
|
|
2716
|
+
const fn = new Function('return ' + fnStr)();
|
|
2717
|
+
return fn(el, ...evalArgs);
|
|
2718
|
+
})(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
|
|
2719
|
+
);
|
|
2720
|
+
}
|
|
2721
|
+
async $$eval(selector, fn, ...args) {
|
|
2722
|
+
const fnBody = typeof fn === "function" ? fn.toString() : fn;
|
|
2723
|
+
const selJSON = JSON.stringify(selector);
|
|
2724
|
+
const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
|
|
2725
|
+
return this.evaluate(
|
|
2726
|
+
`(function(sel, xpathExpr, fnStr, ...evalArgs) {
|
|
2727
|
+
const els = xpathExpr
|
|
2728
|
+
? (() => { const it = document.evaluate(xpathExpr, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); const r=[]; for(let i=0;i<it.snapshotLength;i++) r.push(it.snapshotItem(i)); return r; })()
|
|
2729
|
+
: Array.from(document.querySelectorAll(sel));
|
|
2730
|
+
const fn = new Function('return ' + fnStr)();
|
|
2731
|
+
return fn(els, ...evalArgs);
|
|
2732
|
+
})(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
|
|
2733
|
+
);
|
|
2734
|
+
}
|
|
2735
|
+
};
|
|
2736
|
+
|
|
2737
|
+
// src/cdp-driver/page-frame-input.ts
|
|
2738
|
+
function isSessionDeadError(err) {
|
|
2739
|
+
return /session (with given id )?not found|no session with given id/i.test(errMsg(err));
|
|
2740
|
+
}
|
|
2741
|
+
var FrameInputService = class {
|
|
2742
|
+
constructor(deps) {
|
|
2743
|
+
this.deps = deps;
|
|
2744
|
+
}
|
|
2745
|
+
deps;
|
|
2746
|
+
/** urlIncludes → 已 attach 的 session + 鼠标实例(跨命令保持位置状态) */
|
|
2747
|
+
cache = /* @__PURE__ */ new Map();
|
|
2748
|
+
/**
|
|
2749
|
+
* 拿到指定 OOPIF 的鼠标(Input 域派发进 iframe 渲染进程,isTrusted=true)。
|
|
2750
|
+
* 缓存的 session 失效(iframe 重建/刷新)时自动重 attach;重 attach 会
|
|
2751
|
+
* 重置鼠标位置——调用方需重新读取目标元素坐标。
|
|
2752
|
+
*/
|
|
2753
|
+
async frameMouse(urlIncludes, opts = {}) {
|
|
2754
|
+
if (opts.fresh) this.cache.delete(urlIncludes);
|
|
2755
|
+
const cached = this.cache.get(urlIncludes);
|
|
2756
|
+
if (cached) {
|
|
2757
|
+
try {
|
|
2758
|
+
await this.deps.conn.send("Runtime.evaluate", { expression: "1", returnByValue: true }, cached.sessionId);
|
|
2759
|
+
return cached.mouse;
|
|
2760
|
+
} catch {
|
|
2761
|
+
this.cache.delete(urlIncludes);
|
|
2762
|
+
}
|
|
2763
|
+
}
|
|
2764
|
+
const sessionId = await this.deps.resolveFrameSession(urlIncludes);
|
|
2765
|
+
const mouse = new XBMouseImpl(this.deps.conn, sessionId);
|
|
2766
|
+
this.cache.set(urlIncludes, { sessionId, mouse });
|
|
2767
|
+
return mouse;
|
|
2768
|
+
}
|
|
2769
|
+
/**
|
|
2770
|
+
* 带重试的 frame 鼠标操作:Chrome 异步销毁旧 OOPIF target 的窗口期里
|
|
2771
|
+
* (连续导航/验证码 iframe 重建),probe 通过后 dispatch 仍可能撞上死
|
|
2772
|
+
* session——session 失效时强制重 attach 再做一次。
|
|
2773
|
+
*/
|
|
2774
|
+
async runFrameMouse(urlIncludes, fn) {
|
|
2775
|
+
try {
|
|
2776
|
+
return await fn(await this.frameMouse(urlIncludes));
|
|
2777
|
+
} catch (err) {
|
|
2778
|
+
if (!isSessionDeadError(err)) throw err;
|
|
2779
|
+
this.cache.delete(urlIncludes);
|
|
2780
|
+
return fn(await this.frameMouse(urlIncludes, { fresh: true }));
|
|
2781
|
+
}
|
|
2782
|
+
}
|
|
2783
|
+
/** 在 OOPIF 内点击选择器命中的元素(frame 局部坐标,stealth 落点偏移继承) */
|
|
2784
|
+
async clickInFrame(urlIncludes, selector, opts = {}) {
|
|
2785
|
+
const rect = await this.pollFrameRect(urlIncludes, selector, opts.timeoutMs ?? 5e3);
|
|
2786
|
+
const x = rect.x + rect.width / 2;
|
|
2787
|
+
const y = rect.y + rect.height / 2;
|
|
2788
|
+
await this.runFrameMouse(urlIncludes, (mouse) => mouse.click(x, y, { elementWidth: rect.width, elementHeight: rect.height }));
|
|
2789
|
+
return { x, y };
|
|
2790
|
+
}
|
|
2791
|
+
/** 在 OOPIF 内填输入框:点击聚焦 → el.select() 全选 → insertText 整体替换 → 回读验证 */
|
|
2792
|
+
async fillInFrame(urlIncludes, selector, text, opts = {}) {
|
|
2793
|
+
try {
|
|
2794
|
+
return await this.fillInFrameInner(urlIncludes, selector, text, opts);
|
|
2795
|
+
} catch (err) {
|
|
2796
|
+
if (!isSessionDeadError(err)) throw err;
|
|
2797
|
+
this.cache.delete(urlIncludes);
|
|
2798
|
+
return this.fillInFrameInner(urlIncludes, selector, text, opts);
|
|
2799
|
+
}
|
|
2800
|
+
}
|
|
2801
|
+
async fillInFrameInner(urlIncludes, selector, text, opts = {}) {
|
|
2802
|
+
await this.clickInFrame(urlIncludes, selector, opts);
|
|
2803
|
+
const cached = this.cache.get(urlIncludes);
|
|
2804
|
+
if (!cached) throw new Error(`frame session lost for "${urlIncludes}"`);
|
|
2805
|
+
await this.deps.evaluateInFrame(
|
|
2806
|
+
urlIncludes,
|
|
2807
|
+
`(() => { const el = document.querySelector(${JSON.stringify(selector)}); if (el && typeof el.select === 'function') el.select(); return true; })()`
|
|
2808
|
+
);
|
|
2809
|
+
await this.deps.conn.send("Input.insertText", { text }, cached.sessionId);
|
|
2810
|
+
const readback = await this.deps.evaluateInFrame(
|
|
2811
|
+
urlIncludes,
|
|
2812
|
+
`(() => { const el = document.querySelector(${JSON.stringify(selector)}); return el ? String(el.value ?? '') : ''; })()`
|
|
2813
|
+
);
|
|
2814
|
+
return { value: readback ?? "" };
|
|
2815
|
+
}
|
|
2816
|
+
/** 轮询 OOPIF 内元素 rect(等待元素出现/可测量) */
|
|
2817
|
+
async pollFrameRect(urlIncludes, selector, timeoutMs) {
|
|
2818
|
+
const expr = `(() => { const el = document.querySelector(${JSON.stringify(selector)}); if (!el) return null; const r = el.getBoundingClientRect(); if (r.width === 0 || r.height === 0) return null; return { x: r.x, y: r.y, width: r.width, height: r.height }; })()`;
|
|
2819
|
+
const deadline = Date.now() + timeoutMs;
|
|
2820
|
+
let lastErr;
|
|
2821
|
+
while (Date.now() < deadline) {
|
|
2822
|
+
try {
|
|
2823
|
+
const rect = await this.deps.evaluateInFrame(urlIncludes, expr);
|
|
2824
|
+
if (rect) return rect;
|
|
2825
|
+
} catch (err) {
|
|
2826
|
+
lastErr = err;
|
|
2827
|
+
}
|
|
2828
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
2829
|
+
}
|
|
2830
|
+
throw new Error(`[frame ${urlIncludes}] element "${selector}" not found/visible within ${timeoutMs}ms${lastErr instanceof Error ? `\uFF08last: ${lastErr.message}\uFF09` : ""}`);
|
|
2831
|
+
}
|
|
2832
|
+
};
|
|
2833
|
+
|
|
2834
|
+
// src/cdp-driver/page.ts
|
|
2835
|
+
var XBPageImpl = class _XBPageImpl {
|
|
2836
|
+
conn;
|
|
2837
|
+
_emitter = new EventEmitter();
|
|
2838
|
+
_subscriptions = [];
|
|
2839
|
+
sessionId;
|
|
2840
|
+
_targetId;
|
|
1596
2841
|
_contextImpl;
|
|
1597
2842
|
_browserImpl;
|
|
1598
2843
|
_closed = false;
|
|
1599
2844
|
_url = "about:blank";
|
|
1600
|
-
_title = "";
|
|
1601
2845
|
_viewportSize = null;
|
|
1602
2846
|
_loadState = {
|
|
1603
2847
|
loadFired: true,
|
|
@@ -1606,6 +2850,14 @@ var XBPageImpl = class _XBPageImpl {
|
|
|
1606
2850
|
};
|
|
1607
2851
|
mouse;
|
|
1608
2852
|
keyboard;
|
|
2853
|
+
mediaService;
|
|
2854
|
+
fileInputService;
|
|
2855
|
+
networkWaitService;
|
|
2856
|
+
networkRouteService;
|
|
2857
|
+
navigationService;
|
|
2858
|
+
domQueryService;
|
|
2859
|
+
runtimeEvaluationService;
|
|
2860
|
+
frameInputService;
|
|
1609
2861
|
// Network tracking for waitForLoadState('networkidle')
|
|
1610
2862
|
inflightRequests = /* @__PURE__ */ new Set();
|
|
1611
2863
|
networkIdleResolve = null;
|
|
@@ -1619,6 +2871,65 @@ var XBPageImpl = class _XBPageImpl {
|
|
|
1619
2871
|
this._browserImpl = browser;
|
|
1620
2872
|
this.mouse = new XBMouseImpl(conn, sessionId);
|
|
1621
2873
|
this.keyboard = new XBKeyboardImpl(conn, sessionId);
|
|
2874
|
+
this.mediaService = new MediaService({
|
|
2875
|
+
conn,
|
|
2876
|
+
sessionId,
|
|
2877
|
+
viewportSize: this._viewportSize,
|
|
2878
|
+
evaluate: (script) => this.evaluate(script),
|
|
2879
|
+
onViewportSize: (size) => {
|
|
2880
|
+
this._viewportSize = size;
|
|
2881
|
+
}
|
|
2882
|
+
});
|
|
2883
|
+
this.fileInputService = new FileInputService({
|
|
2884
|
+
conn,
|
|
2885
|
+
sessionId,
|
|
2886
|
+
evaluate: (script) => this.evaluate(script),
|
|
2887
|
+
mouse: this.mouse
|
|
2888
|
+
});
|
|
2889
|
+
this.networkWaitService = new NetworkWaitService({
|
|
2890
|
+
conn,
|
|
2891
|
+
sessionId,
|
|
2892
|
+
responses: this._networkResponses,
|
|
2893
|
+
requests: this._networkRequests,
|
|
2894
|
+
on: (event, handler) => this._emitter.on(event, handler),
|
|
2895
|
+
off: (event, handler) => this._emitter.removeListener(event, handler),
|
|
2896
|
+
currentUrl: () => this.url()
|
|
2897
|
+
});
|
|
2898
|
+
this.networkRouteService = new NetworkRouteService({
|
|
2899
|
+
conn,
|
|
2900
|
+
sessionId,
|
|
2901
|
+
emit: (event, ...args) => this._emit(event, ...args)
|
|
2902
|
+
});
|
|
2903
|
+
this.navigationService = new NavigationService({
|
|
2904
|
+
conn,
|
|
2905
|
+
sessionId,
|
|
2906
|
+
state: this._loadState,
|
|
2907
|
+
stealthConfig: this._contextImpl.stealthConfig,
|
|
2908
|
+
isClosed: () => this._closed,
|
|
2909
|
+
setUrl: (url) => {
|
|
2910
|
+
this._url = url;
|
|
2911
|
+
},
|
|
2912
|
+
currentUrl: () => this.url(),
|
|
2913
|
+
waitForLoadState: (state, timeout) => this.waitForLoadState(state, timeout),
|
|
2914
|
+
waitForTimeout: (ms) => this.waitForTimeout(ms),
|
|
2915
|
+
evaluate: (script) => this.evaluate(script)
|
|
2916
|
+
});
|
|
2917
|
+
this.runtimeEvaluationService = new RuntimeEvaluationService({
|
|
2918
|
+
conn,
|
|
2919
|
+
sessionId,
|
|
2920
|
+
isClosed: () => this._closed,
|
|
2921
|
+
url: () => this.url()
|
|
2922
|
+
});
|
|
2923
|
+
this.frameInputService = new FrameInputService({
|
|
2924
|
+
conn,
|
|
2925
|
+
resolveFrameSession: (urlIncludes) => this.runtimeEvaluationService.resolveFrameSession(urlIncludes),
|
|
2926
|
+
evaluateInFrame: (urlIncludes, expression) => this.evaluateInFrame(urlIncludes, expression)
|
|
2927
|
+
});
|
|
2928
|
+
this.domQueryService = new DomQueryService({
|
|
2929
|
+
conn,
|
|
2930
|
+
sessionId,
|
|
2931
|
+
evaluate: (script) => this.evaluate(script)
|
|
2932
|
+
});
|
|
1622
2933
|
}
|
|
1623
2934
|
_emit(event, ...args) {
|
|
1624
2935
|
this._emitter.emit(event, ...args);
|
|
@@ -1644,7 +2955,7 @@ var XBPageImpl = class _XBPageImpl {
|
|
|
1644
2955
|
});
|
|
1645
2956
|
this._subscriptions.push(
|
|
1646
2957
|
this.conn.subscribe("Fetch.requestPaused", this.sessionId, (params) => {
|
|
1647
|
-
if (this.
|
|
2958
|
+
if (this.networkRouteService.isInterceptionEnabled) return;
|
|
1648
2959
|
const p = params;
|
|
1649
2960
|
this.conn.send("Fetch.continueRequest", { requestId: p.requestId }, this.sessionId).catch(() => {
|
|
1650
2961
|
});
|
|
@@ -1823,9 +3134,9 @@ var XBPageImpl = class _XBPageImpl {
|
|
|
1823
3134
|
"Target.getTargetInfo",
|
|
1824
3135
|
{ targetId: this._targetId }
|
|
1825
3136
|
);
|
|
1826
|
-
|
|
1827
|
-
this.
|
|
1828
|
-
if (
|
|
3137
|
+
const curUrl = info.targetInfo?.url ?? info.url;
|
|
3138
|
+
if (curUrl) this._url = curUrl;
|
|
3139
|
+
if (curUrl && curUrl !== "about:blank" && curUrl !== "") {
|
|
1829
3140
|
this._loadState = { loadFired: true, domContentFired: true, networkIdle: true };
|
|
1830
3141
|
}
|
|
1831
3142
|
} catch {
|
|
@@ -1836,108 +3147,16 @@ var XBPageImpl = class _XBPageImpl {
|
|
|
1836
3147
|
}
|
|
1837
3148
|
// ── Navigation ──────────────────────────────────────────────
|
|
1838
3149
|
async goto(url, opts = {}) {
|
|
1839
|
-
|
|
1840
|
-
const waitUntil = opts.waitUntil ?? "load";
|
|
1841
|
-
const timeout = opts.timeout ?? 3e4;
|
|
1842
|
-
this._loadState = { loadFired: false, domContentFired: false, networkIdle: false };
|
|
1843
|
-
if (process.env.XBROWSER_STEALTH !== "off") {
|
|
1844
|
-
try {
|
|
1845
|
-
await this.conn.send(
|
|
1846
|
-
"Page.addScriptToEvaluateOnNewDocument",
|
|
1847
|
-
{ source: buildStealthInitScript({ ...DEFAULT_STEALTH_CONFIG, ...this._contextImpl.stealthConfig ?? {} }) },
|
|
1848
|
-
this.sessionId
|
|
1849
|
-
);
|
|
1850
|
-
} catch {
|
|
1851
|
-
}
|
|
1852
|
-
try {
|
|
1853
|
-
const rawUa = await this.conn.send(
|
|
1854
|
-
"Runtime.evaluate",
|
|
1855
|
-
{ expression: "navigator.userAgent", returnByValue: true },
|
|
1856
|
-
this.sessionId
|
|
1857
|
-
);
|
|
1858
|
-
const ua = rawUa?.value || "";
|
|
1859
|
-
const cleaned = ua.replace(/HeadlessChrome/g, "Chrome");
|
|
1860
|
-
if (cleaned !== ua) {
|
|
1861
|
-
await this.conn.send(
|
|
1862
|
-
"Network.setUserAgentOverride",
|
|
1863
|
-
{ userAgent: cleaned },
|
|
1864
|
-
this.sessionId
|
|
1865
|
-
);
|
|
1866
|
-
}
|
|
1867
|
-
} catch {
|
|
1868
|
-
}
|
|
1869
|
-
}
|
|
1870
|
-
const result = await this.conn.send(
|
|
1871
|
-
"Page.navigate",
|
|
1872
|
-
{ url, referrer: opts.referer },
|
|
1873
|
-
this.sessionId
|
|
1874
|
-
);
|
|
1875
|
-
if (result.errorText) {
|
|
1876
|
-
throw new Error(`Navigation failed: ${result.errorText}`);
|
|
1877
|
-
}
|
|
1878
|
-
if (waitUntil === "commit") {
|
|
1879
|
-
this._url = url;
|
|
1880
|
-
return {
|
|
1881
|
-
status: () => 0,
|
|
1882
|
-
ok: () => false,
|
|
1883
|
-
url: () => url,
|
|
1884
|
-
headers: () => ({})
|
|
1885
|
-
};
|
|
1886
|
-
}
|
|
1887
|
-
await this.waitForLoadState(waitUntil, timeout);
|
|
1888
|
-
this._url = url;
|
|
1889
|
-
const statusCode = 200;
|
|
1890
|
-
const finalUrl = url;
|
|
1891
|
-
const headers = {};
|
|
1892
|
-
return {
|
|
1893
|
-
status: () => statusCode,
|
|
1894
|
-
ok: () => statusCode >= 200 && statusCode < 300,
|
|
1895
|
-
url: () => finalUrl,
|
|
1896
|
-
headers: () => headers
|
|
1897
|
-
};
|
|
3150
|
+
return this.navigationService.goto(url, opts);
|
|
1898
3151
|
}
|
|
1899
3152
|
async goBack(opts = {}) {
|
|
1900
|
-
|
|
1901
|
-
const navHistory = await this.conn.send("Page.getNavigationHistory", void 0, this.sessionId);
|
|
1902
|
-
if (navHistory.currentIndex > 0) {
|
|
1903
|
-
const prevUrl = navHistory.entries[navHistory.currentIndex - 1]?.url;
|
|
1904
|
-
if (prevUrl && prevUrl !== "about:blank") {
|
|
1905
|
-
await this.conn.send("Page.navigate", { url: prevUrl }, this.sessionId);
|
|
1906
|
-
await this.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
|
|
1907
|
-
});
|
|
1908
|
-
this._url = prevUrl;
|
|
1909
|
-
return;
|
|
1910
|
-
}
|
|
1911
|
-
}
|
|
1912
|
-
} catch {
|
|
1913
|
-
}
|
|
1914
|
-
await this.evaluate("() => history.back()");
|
|
1915
|
-
await this.waitForTimeout(3e3);
|
|
1916
|
-
this._url = await this.evaluate("location.href").catch(() => this._url);
|
|
3153
|
+
return this.navigationService.goBack(opts);
|
|
1917
3154
|
}
|
|
1918
3155
|
async goForward(opts = {}) {
|
|
1919
|
-
|
|
1920
|
-
const navHistory = await this.conn.send("Page.getNavigationHistory", void 0, this.sessionId);
|
|
1921
|
-
if (navHistory.currentIndex < navHistory.entries.length - 1) {
|
|
1922
|
-
const nextUrl = navHistory.entries[navHistory.currentIndex + 1]?.url;
|
|
1923
|
-
if (nextUrl && nextUrl !== "about:blank") {
|
|
1924
|
-
await this.conn.send("Page.navigate", { url: nextUrl }, this.sessionId);
|
|
1925
|
-
await this.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
|
|
1926
|
-
});
|
|
1927
|
-
this._url = nextUrl;
|
|
1928
|
-
return;
|
|
1929
|
-
}
|
|
1930
|
-
}
|
|
1931
|
-
} catch {
|
|
1932
|
-
}
|
|
1933
|
-
await this.evaluate("() => history.forward()");
|
|
1934
|
-
await this.waitForTimeout(3e3);
|
|
1935
|
-
this._url = await this.evaluate("location.href").catch(() => this._url);
|
|
3156
|
+
return this.navigationService.goForward(opts);
|
|
1936
3157
|
}
|
|
1937
3158
|
async reload(opts = {}) {
|
|
1938
|
-
this.
|
|
1939
|
-
await this.conn.send("Page.reload", void 0, this.sessionId);
|
|
1940
|
-
await this.waitForLoadState(opts.waitUntil ?? "load", opts.timeout);
|
|
3159
|
+
return this.navigationService.reload(opts);
|
|
1941
3160
|
}
|
|
1942
3161
|
async waitForLoadState(state = "load", timeout = 3e4) {
|
|
1943
3162
|
if (this._closed) throw new Error("Page is closed");
|
|
@@ -1981,233 +3200,98 @@ var XBPageImpl = class _XBPageImpl {
|
|
|
1981
3200
|
const state = opts.state ?? "visible";
|
|
1982
3201
|
const timeout = opts.timeout ?? 3e4;
|
|
1983
3202
|
const deadline = Date.now() + timeout;
|
|
1984
|
-
while (Date.now() < deadline) {
|
|
1985
|
-
const exists = await this.evaluate(
|
|
1986
|
-
`(function() { const el = ${queryJS(selector)}; return !!el; })()`
|
|
1987
|
-
);
|
|
1988
|
-
if (state === "attached" && exists) return;
|
|
1989
|
-
if (state === "detached" && !exists) return;
|
|
1990
|
-
if (state === "visible" && exists) {
|
|
1991
|
-
const visible = await this.evaluate(
|
|
1992
|
-
`(function() { const el = ${queryJS(selector)}; if (!el) return false; const rect = el.getBoundingClientRect(); const style = window.getComputedStyle(el); return rect.width > 0 && rect.height > 0 && style.visibility !== 'hidden' && style.display !== 'none'; })()`
|
|
1993
|
-
);
|
|
1994
|
-
if (visible) return;
|
|
1995
|
-
}
|
|
1996
|
-
if (state === "hidden") {
|
|
1997
|
-
if (!exists) return;
|
|
1998
|
-
const visible = await this.evaluate(
|
|
1999
|
-
`(function() { const el = ${queryJS(selector)}; if (!el) return false; const rect = el.getBoundingClientRect(); const style = window.getComputedStyle(el); return rect.width > 0 && rect.height > 0 && style.visibility !== 'hidden' && style.display !== 'none'; })()`
|
|
2000
|
-
);
|
|
2001
|
-
if (!visible) return;
|
|
2002
|
-
}
|
|
2003
|
-
await this.waitForTimeout(100);
|
|
2004
|
-
}
|
|
2005
|
-
throw new Error(`waitForSelector('${selector}', state='${state}') timeout after ${timeout}ms`);
|
|
2006
|
-
}
|
|
2007
|
-
async waitForFunction(fn, opts = {}, ...args) {
|
|
2008
|
-
const timeout = opts.timeout ?? 3e4;
|
|
2009
|
-
const polling = opts.polling ?? 100;
|
|
2010
|
-
const deadline = Date.now() + timeout;
|
|
2011
|
-
const fnBody = typeof fn === "function" ? fn.toString() : fn;
|
|
2012
|
-
let lastError = null;
|
|
2013
|
-
while (Date.now() < deadline) {
|
|
2014
|
-
try {
|
|
2015
|
-
const result = await this.evaluate(
|
|
2016
|
-
`(function(fnStr, ...evalArgs) { const fn = new Function('return ' + fnStr); return fn(...evalArgs); })(${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
|
|
2017
|
-
);
|
|
2018
|
-
if (result) return result;
|
|
2019
|
-
} catch (err) {
|
|
2020
|
-
lastError = err instanceof Error ? err : new Error(errMsg(err));
|
|
2021
|
-
}
|
|
2022
|
-
const pollMs = typeof polling === "number" ? polling : 16;
|
|
2023
|
-
await this.waitForTimeout(pollMs);
|
|
2024
|
-
}
|
|
2025
|
-
const detail = lastError ? `
|
|
2026
|
-
Last error: ${lastError.message}` : "";
|
|
2027
|
-
throw new Error(`waitForFunction timeout after ${timeout}ms${detail}`);
|
|
2028
|
-
}
|
|
2029
|
-
url() {
|
|
2030
|
-
return this._url;
|
|
2031
|
-
}
|
|
2032
|
-
async title() {
|
|
2033
|
-
for (let i = 0; i < 20; i++) {
|
|
2034
|
-
try {
|
|
2035
|
-
this._title = await this.evaluate("document.title");
|
|
2036
|
-
if (this._title) return this._title;
|
|
2037
|
-
} catch {
|
|
2038
|
-
}
|
|
2039
|
-
await new Promise((r) => setTimeout(r, 50));
|
|
2040
|
-
}
|
|
2041
|
-
try {
|
|
2042
|
-
const info = await this._cdpSend("Target.getTargetInfo", { targetId: this._targetId });
|
|
2043
|
-
if (info?.title) {
|
|
2044
|
-
this._title = info.title;
|
|
2045
|
-
return this._title;
|
|
2046
|
-
}
|
|
2047
|
-
} catch {
|
|
2048
|
-
}
|
|
2049
|
-
return this._title;
|
|
2050
|
-
}
|
|
2051
|
-
async content() {
|
|
2052
|
-
return this.evaluate("document.documentElement.outerHTML");
|
|
2053
|
-
}
|
|
2054
|
-
// ── Evaluation ──────────────────────────────────────────────
|
|
2055
|
-
async evaluate(fn, ...args) {
|
|
2056
|
-
if (this._closed) throw new Error("Page is closed");
|
|
2057
|
-
this.conn.send("Page.handleJavaScriptDialog", { accept: false }, this.sessionId).catch(() => {
|
|
2058
|
-
});
|
|
2059
|
-
let expression;
|
|
2060
|
-
if (typeof fn === "string") {
|
|
2061
|
-
expression = fn;
|
|
2062
|
-
} else {
|
|
2063
|
-
const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
|
|
2064
|
-
expression = `(()=>{const __fn=(${fn.toString()});return __fn(${argStr});})()`;
|
|
2065
|
-
}
|
|
2066
|
-
const result = await this.conn.send("Runtime.evaluate", {
|
|
2067
|
-
expression,
|
|
2068
|
-
returnByValue: true,
|
|
2069
|
-
awaitPromise: true
|
|
2070
|
-
}, this.sessionId);
|
|
2071
|
-
if (result.exceptionDetails) {
|
|
2072
|
-
const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
|
|
2073
|
-
throw new Error(`${detail}`);
|
|
2074
|
-
}
|
|
2075
|
-
return result.result?.value;
|
|
2076
|
-
}
|
|
2077
|
-
/**
|
|
2078
|
-
* 在指定 iframe 上下文中执行表达式(攻防 D16 能力建设,2026-08-19)。
|
|
2079
|
-
*
|
|
2080
|
-
* 双路径:
|
|
2081
|
-
* 1. 同进程 iframe —— Runtime.enable 收集 executionContextCreated,
|
|
2082
|
-
* 找到目标 frameId 的 contextId,用 contextId 定向执行;
|
|
2083
|
-
* 2. 跨域 OOPIF(独立 target)—— Target.setAutoAttach(flatten) 监听
|
|
2084
|
-
* attachedToTarget 中 type==='iframe' 的会话,用其 sessionId 执行。
|
|
2085
|
-
*
|
|
2086
|
-
* 这绕过了页面同源策略(那是页面 JS 的约束,CDP 是调试通道)——
|
|
2087
|
-
* 支付窗/验证码/第三方嵌入内容的读写都靠它。
|
|
2088
|
-
*/
|
|
2089
|
-
async evaluateInFrame(urlIncludes, expression) {
|
|
2090
|
-
if (this._closed) throw new Error("Page is closed");
|
|
2091
|
-
const evalIn = async (sessionId, contextId) => {
|
|
2092
|
-
const params = { expression, returnByValue: true, awaitPromise: true };
|
|
2093
|
-
if (contextId !== void 0) params.contextId = contextId;
|
|
2094
|
-
const result = await this.conn.send("Runtime.evaluate", params, sessionId);
|
|
2095
|
-
if (result.exceptionDetails) {
|
|
2096
|
-
const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
|
|
2097
|
-
throw new Error(`[frame ${urlIncludes}] ${detail}`);
|
|
2098
|
-
}
|
|
2099
|
-
return result.result?.value;
|
|
2100
|
-
};
|
|
2101
|
-
try {
|
|
2102
|
-
const tg = await this.conn.send("Target.getTargets", void 0);
|
|
2103
|
-
const hit2 = (tg.targetInfos || []).find((t) => t.type === "iframe" && (t.url || "").includes(urlIncludes));
|
|
2104
|
-
if (hit2) {
|
|
2105
|
-
const att = await this.conn.send("Target.attachToTarget", { targetId: hit2.targetId, flatten: true });
|
|
2106
|
-
return evalIn(att.sessionId);
|
|
2107
|
-
}
|
|
2108
|
-
} catch {
|
|
2109
|
-
}
|
|
2110
|
-
const tree = await this.conn.send("Page.getFrameTree", void 0, this.sessionId);
|
|
2111
|
-
const all = [];
|
|
2112
|
-
const walk = (node) => {
|
|
2113
|
-
all.push({ id: node.frame.id, url: node.frame.url });
|
|
2114
|
-
for (const child of node.childFrames || []) walk(child);
|
|
2115
|
-
};
|
|
2116
|
-
walk(tree.frameTree);
|
|
2117
|
-
const mainId = tree.frameTree?.frame?.id;
|
|
2118
|
-
const target = all.find((f) => f.id !== mainId && f.url.includes(urlIncludes));
|
|
2119
|
-
if (target) {
|
|
2120
|
-
const contexts = [];
|
|
2121
|
-
const onCtx = (raw) => {
|
|
2122
|
-
const c = raw?.context;
|
|
2123
|
-
if (c?.id && c?.auxData?.frameId) contexts.push({ id: c.id, frameId: c.auxData.frameId });
|
|
2124
|
-
};
|
|
2125
|
-
this.conn.on("Runtime.executionContextCreated", onCtx);
|
|
2126
|
-
try {
|
|
2127
|
-
await this.conn.send("Runtime.enable", void 0, this.sessionId).catch(() => {
|
|
2128
|
-
});
|
|
2129
|
-
await new Promise((r) => setTimeout(r, 400));
|
|
2130
|
-
} finally {
|
|
2131
|
-
this.conn.off("Runtime.executionContextCreated", onCtx);
|
|
3203
|
+
while (Date.now() < deadline) {
|
|
3204
|
+
const exists = await this.evaluate(
|
|
3205
|
+
`(function() { const el = ${queryJS(selector)}; return !!el; })()`
|
|
3206
|
+
);
|
|
3207
|
+
if (state === "attached" && exists) return;
|
|
3208
|
+
if (state === "detached" && !exists) return;
|
|
3209
|
+
if (state === "visible" && exists) {
|
|
3210
|
+
const visible = await this.evaluate(
|
|
3211
|
+
`(function() { const el = ${queryJS(selector)}; if (!el) return false; const rect = el.getBoundingClientRect(); const style = window.getComputedStyle(el); return rect.width > 0 && rect.height > 0 && style.visibility !== 'hidden' && style.display !== 'none'; })()`
|
|
3212
|
+
);
|
|
3213
|
+
if (visible) return;
|
|
2132
3214
|
}
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
if (ev?.sessionId && ev.targetInfo?.type === "iframe") {
|
|
2140
|
-
attached.push({ sessionId: ev.sessionId, url: ev.targetInfo.url || "" });
|
|
3215
|
+
if (state === "hidden") {
|
|
3216
|
+
if (!exists) return;
|
|
3217
|
+
const visible = await this.evaluate(
|
|
3218
|
+
`(function() { const el = ${queryJS(selector)}; if (!el) return false; const rect = el.getBoundingClientRect(); const style = window.getComputedStyle(el); return rect.width > 0 && rect.height > 0 && style.visibility !== 'hidden' && style.display !== 'none'; })()`
|
|
3219
|
+
);
|
|
3220
|
+
if (!visible) return;
|
|
2141
3221
|
}
|
|
2142
|
-
|
|
2143
|
-
this.conn.on("Target.attachedToTarget", onAttach);
|
|
2144
|
-
try {
|
|
2145
|
-
await this.conn.send("Target.setAutoAttach", {
|
|
2146
|
-
autoAttach: true,
|
|
2147
|
-
waitForDebuggerOnStart: false,
|
|
2148
|
-
flatten: true
|
|
2149
|
-
}, this.sessionId);
|
|
2150
|
-
await new Promise((r) => setTimeout(r, 600));
|
|
2151
|
-
} finally {
|
|
2152
|
-
this.conn.off("Target.attachedToTarget", onAttach);
|
|
2153
|
-
this.conn.send("Target.setAutoAttach", { autoAttach: false, waitForDebuggerOnStart: false, flatten: true }, this.sessionId).catch(() => {
|
|
2154
|
-
});
|
|
2155
|
-
}
|
|
2156
|
-
const hit = attached.find((a) => a.url.includes(urlIncludes));
|
|
2157
|
-
if (!hit) {
|
|
2158
|
-
throw new Error(`frame not found for "${urlIncludes}"\uFF08OOPIF target\u3001frame \u6811\u3001auto-attach \u4E09\u8DEF\u5747\u672A\u547D\u4E2D\uFF1B\u53EF\u80FD\u4ECD\u5728\u52A0\u8F7D\uFF09`);
|
|
3222
|
+
await this.waitForTimeout(100);
|
|
2159
3223
|
}
|
|
2160
|
-
|
|
3224
|
+
throw new Error(`waitForSelector('${selector}', state='${state}') timeout after ${timeout}ms`);
|
|
2161
3225
|
}
|
|
2162
|
-
|
|
2163
|
-
|
|
2164
|
-
|
|
2165
|
-
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
3226
|
+
async waitForFunction(fn, opts = {}, ...args) {
|
|
3227
|
+
const timeout = opts.timeout ?? 3e4;
|
|
3228
|
+
const polling = opts.polling ?? 100;
|
|
3229
|
+
const deadline = Date.now() + timeout;
|
|
3230
|
+
const fnBody = typeof fn === "function" ? fn.toString() : fn;
|
|
3231
|
+
let lastError = null;
|
|
3232
|
+
while (Date.now() < deadline) {
|
|
3233
|
+
try {
|
|
3234
|
+
const result = await this.evaluate(
|
|
3235
|
+
`(function(fnStr, ...evalArgs) { const fn = new Function('return ' + fnStr); return fn(...evalArgs); })(${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
|
|
3236
|
+
);
|
|
3237
|
+
if (result) return result;
|
|
3238
|
+
} catch (err) {
|
|
3239
|
+
lastError = err instanceof Error ? err : new Error(errMsg(err));
|
|
3240
|
+
}
|
|
3241
|
+
const pollMs = typeof polling === "number" ? polling : 16;
|
|
3242
|
+
await this.waitForTimeout(pollMs);
|
|
2176
3243
|
}
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
};
|
|
3244
|
+
const detail = lastError ? `
|
|
3245
|
+
Last error: ${lastError.message}` : "";
|
|
3246
|
+
throw new Error(`waitForFunction timeout after ${timeout}ms${detail}`);
|
|
3247
|
+
}
|
|
3248
|
+
url() {
|
|
3249
|
+
return this._url;
|
|
3250
|
+
}
|
|
3251
|
+
async title() {
|
|
3252
|
+
return this.runtimeEvaluationService.title();
|
|
3253
|
+
}
|
|
3254
|
+
async content() {
|
|
3255
|
+
return this.runtimeEvaluationService.content();
|
|
3256
|
+
}
|
|
3257
|
+
async evaluate(fn, ...args) {
|
|
3258
|
+
return this.runtimeEvaluationService.evaluate(fn, ...args);
|
|
3259
|
+
}
|
|
3260
|
+
async evaluateInFrame(urlIncludes, expression) {
|
|
3261
|
+
return this.runtimeEvaluationService.evaluateInFrame(urlIncludes, expression);
|
|
3262
|
+
}
|
|
3263
|
+
/** 浏览器级 iframe target 列表(OOPIF 可见——frames 命令用) */
|
|
3264
|
+
async listFrameTargets() {
|
|
3265
|
+
return this.runtimeEvaluationService.listFrameTargets();
|
|
3266
|
+
}
|
|
3267
|
+
/**
|
|
3268
|
+
* 拿到指定 OOPIF 的鼠标(Input 域派发进 iframe 渲染进程,isTrusted=true)。
|
|
3269
|
+
* 坐标语义:iframe 局部坐标(与该 session 内 getBoundingClientRect 一致)。
|
|
3270
|
+
* session 失效自动重 attach(鼠标位置会重置,需重读目标坐标)。
|
|
3271
|
+
*/
|
|
3272
|
+
async frameMouse(urlIncludes, opts) {
|
|
3273
|
+
return this.frameInputService.frameMouse(urlIncludes, opts);
|
|
3274
|
+
}
|
|
3275
|
+
async runFrameMouse(urlIncludes, fn) {
|
|
3276
|
+
return this.frameInputService.runFrameMouse(urlIncludes, fn);
|
|
3277
|
+
}
|
|
3278
|
+
/** 在 OOPIF 内点击选择器命中的元素(轮询等待 + stealth 落点) */
|
|
3279
|
+
async clickInFrame(urlIncludes, selector, opts) {
|
|
3280
|
+
return this.frameInputService.clickInFrame(urlIncludes, selector, opts);
|
|
3281
|
+
}
|
|
3282
|
+
/** 在 OOPIF 内填输入框(点击聚焦 + insertText + 回读) */
|
|
3283
|
+
async fillInFrame(urlIncludes, selector, text, opts) {
|
|
3284
|
+
return this.frameInputService.fillInFrame(urlIncludes, selector, text, opts);
|
|
3285
|
+
}
|
|
3286
|
+
async evaluateHandle(script, ...args) {
|
|
3287
|
+
return this.runtimeEvaluationService.evaluateHandle(script, ...args);
|
|
2180
3288
|
}
|
|
2181
3289
|
async $eval(selector, fn, ...args) {
|
|
2182
|
-
|
|
2183
|
-
const selJSON = JSON.stringify(selector);
|
|
2184
|
-
const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
|
|
2185
|
-
return this.evaluate(
|
|
2186
|
-
`(function(sel, xpathExpr, fnStr, ...evalArgs) {
|
|
2187
|
-
const el = xpathExpr
|
|
2188
|
-
? document.evaluate(xpathExpr, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
|
|
2189
|
-
: document.querySelector(sel);
|
|
2190
|
-
if (!el) throw new Error('No element found for selector: ' + sel);
|
|
2191
|
-
const fn = new Function('return ' + fnStr)();
|
|
2192
|
-
return fn(el, ...evalArgs);
|
|
2193
|
-
})(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
|
|
2194
|
-
);
|
|
3290
|
+
return this.runtimeEvaluationService.$eval(selector, fn, ...args);
|
|
2195
3291
|
}
|
|
2196
3292
|
async $$eval(selector, fn, ...args) {
|
|
2197
|
-
|
|
2198
|
-
const selJSON = JSON.stringify(selector);
|
|
2199
|
-
const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
|
|
2200
|
-
return this.evaluate(
|
|
2201
|
-
`(function(sel, xpathExpr, fnStr, ...evalArgs) {
|
|
2202
|
-
const els = xpathExpr
|
|
2203
|
-
? (() => { const it = document.evaluate(xpathExpr, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); const r=[]; for(let i=0;i<it.snapshotLength;i++) r.push(it.snapshotItem(i)); return r; })()
|
|
2204
|
-
: Array.from(document.querySelectorAll(sel));
|
|
2205
|
-
const fn = new Function('return ' + fnStr)();
|
|
2206
|
-
return fn(els, ...evalArgs);
|
|
2207
|
-
})(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
|
|
2208
|
-
);
|
|
3293
|
+
return this.runtimeEvaluationService.$$eval(selector, fn, ...args);
|
|
2209
3294
|
}
|
|
2210
|
-
// ── Locator ─────────────────────────────────────────────────
|
|
2211
3295
|
locator(selector) {
|
|
2212
3296
|
return new XBLocatorImpl(this, selector);
|
|
2213
3297
|
}
|
|
@@ -2328,88 +3412,20 @@ Last error: ${lastError.message}` : "";
|
|
|
2328
3412
|
}
|
|
2329
3413
|
// ── Screen ──────────────────────────────────────────────────
|
|
2330
3414
|
async screenshot(opts = {}) {
|
|
2331
|
-
|
|
2332
|
-
format: opts.type ?? "png"
|
|
2333
|
-
};
|
|
2334
|
-
if (opts.quality !== void 0 && (opts.type === "jpeg" || !opts.type && opts.quality)) {
|
|
2335
|
-
params.quality = opts.quality;
|
|
2336
|
-
}
|
|
2337
|
-
if (opts.fullPage) {
|
|
2338
|
-
params.captureBeyondViewport = true;
|
|
2339
|
-
}
|
|
2340
|
-
if (opts.clip) {
|
|
2341
|
-
const clip = {
|
|
2342
|
-
x: Math.round(opts.clip.x),
|
|
2343
|
-
y: Math.round(opts.clip.y),
|
|
2344
|
-
width: Math.round(Math.max(1, opts.clip.width)),
|
|
2345
|
-
height: Math.round(Math.max(1, opts.clip.height)),
|
|
2346
|
-
scale: 1
|
|
2347
|
-
};
|
|
2348
|
-
params.clip = clip;
|
|
2349
|
-
}
|
|
2350
|
-
if (opts.omitBackground) {
|
|
2351
|
-
params.omitBackground = true;
|
|
2352
|
-
}
|
|
2353
|
-
const result = await this.conn.send(
|
|
2354
|
-
"Page.captureScreenshot",
|
|
2355
|
-
params,
|
|
2356
|
-
this.sessionId
|
|
2357
|
-
);
|
|
2358
|
-
return Buffer.from(result.data, "base64");
|
|
3415
|
+
return this.mediaService.screenshot(opts);
|
|
2359
3416
|
}
|
|
2360
3417
|
async pdf(opts = {}) {
|
|
2361
|
-
|
|
2362
|
-
if (opts.landscape !== void 0) params.landscape = opts.landscape;
|
|
2363
|
-
if (opts.printBackground !== void 0) params.printBackground = opts.printBackground;
|
|
2364
|
-
if (opts.scale !== void 0) params.scale = opts.scale;
|
|
2365
|
-
if (opts.format) params.paperFormat = opts.format;
|
|
2366
|
-
if (opts.preferCSSPageSize !== void 0) params.preferCSSPageSize = opts.preferCSSPageSize;
|
|
2367
|
-
if (opts.margin) {
|
|
2368
|
-
if (opts.margin.top) params.marginTop = parseFloat(opts.margin.top);
|
|
2369
|
-
if (opts.margin.bottom) params.marginBottom = parseFloat(opts.margin.bottom);
|
|
2370
|
-
if (opts.margin.left) params.marginLeft = parseFloat(opts.margin.left);
|
|
2371
|
-
if (opts.margin.right) params.marginRight = parseFloat(opts.margin.right);
|
|
2372
|
-
}
|
|
2373
|
-
const result = await this.conn.send("Page.printToPDF", params, this.sessionId);
|
|
2374
|
-
return Buffer.from(result.data, "base64");
|
|
3418
|
+
return this.mediaService.pdf(opts);
|
|
2375
3419
|
}
|
|
2376
3420
|
viewportSize() {
|
|
2377
|
-
return this._viewportSize
|
|
3421
|
+
return this._viewportSize;
|
|
2378
3422
|
}
|
|
2379
3423
|
async setViewportSize(size) {
|
|
2380
|
-
|
|
2381
|
-
"Emulation.setDeviceMetricsOverride",
|
|
2382
|
-
{
|
|
2383
|
-
width: size.width,
|
|
2384
|
-
height: size.height,
|
|
2385
|
-
deviceScaleFactor: 1,
|
|
2386
|
-
mobile: false
|
|
2387
|
-
},
|
|
2388
|
-
this.sessionId
|
|
2389
|
-
);
|
|
2390
|
-
this._viewportSize = size;
|
|
3424
|
+
return this.mediaService.setViewportSize(size);
|
|
2391
3425
|
}
|
|
2392
|
-
/**
|
|
2393
|
-
* env-E2: 缩放变异——deviceScaleFactor 切换(CSS 像素坐标空间不变,
|
|
2394
|
-
* 物理像素翻倍)。保留当前 CSS 视口尺寸,只换 DSF。
|
|
2395
|
-
*/
|
|
2396
3426
|
async setDeviceScaleFactor(dsf) {
|
|
2397
|
-
|
|
2398
|
-
"({ width: window.innerWidth, height: window.innerHeight })"
|
|
2399
|
-
);
|
|
2400
|
-
await this.conn.send(
|
|
2401
|
-
"Emulation.setDeviceMetricsOverride",
|
|
2402
|
-
{
|
|
2403
|
-
width: size.width,
|
|
2404
|
-
height: size.height,
|
|
2405
|
-
deviceScaleFactor: dsf,
|
|
2406
|
-
mobile: false
|
|
2407
|
-
},
|
|
2408
|
-
this.sessionId
|
|
2409
|
-
);
|
|
2410
|
-
this._viewportSize = size;
|
|
3427
|
+
return this.mediaService.setDeviceScaleFactor(dsf);
|
|
2411
3428
|
}
|
|
2412
|
-
// ── Scripts ─────────────────────────────────────────────────
|
|
2413
3429
|
async addInitScript(script) {
|
|
2414
3430
|
await this.conn.send(
|
|
2415
3431
|
"Page.addScriptToEvaluateOnNewDocument",
|
|
@@ -2537,83 +3553,17 @@ Last error: ${lastError.message}` : "";
|
|
|
2537
3553
|
}
|
|
2538
3554
|
}
|
|
2539
3555
|
// ── CDP helpers exposed for locator/element ─────────────────
|
|
2540
|
-
/** Query a single element, returns CDP nodeId or 0 if not found */
|
|
2541
3556
|
async querySelector(selector) {
|
|
2542
|
-
|
|
2543
|
-
const found = await this.evaluate(`
|
|
2544
|
-
(() => { const el = ${queryJS(selector)}; return !!el; })()
|
|
2545
|
-
`).catch(() => false);
|
|
2546
|
-
if (!found) return 0;
|
|
2547
|
-
try {
|
|
2548
|
-
const search = await this.conn.send(
|
|
2549
|
-
"DOM.performSearch",
|
|
2550
|
-
{ query: selector.slice(6) },
|
|
2551
|
-
this.sessionId
|
|
2552
|
-
);
|
|
2553
|
-
if (search.nodeId) return search.nodeId;
|
|
2554
|
-
} catch {
|
|
2555
|
-
}
|
|
2556
|
-
return 1;
|
|
2557
|
-
}
|
|
2558
|
-
const withTimeout = (p, ms) => Promise.race([p, new Promise((r) => setTimeout(() => r(null), ms))]);
|
|
2559
|
-
const doc = await withTimeout(
|
|
2560
|
-
this.conn.send("DOM.getDocument", { depth: 0 }, this.sessionId),
|
|
2561
|
-
8e3
|
|
2562
|
-
);
|
|
2563
|
-
if (!doc) return 0;
|
|
2564
|
-
const result = await withTimeout(
|
|
2565
|
-
this.conn.send(
|
|
2566
|
-
"DOM.querySelector",
|
|
2567
|
-
{ nodeId: doc.root.nodeId, selector },
|
|
2568
|
-
this.sessionId
|
|
2569
|
-
),
|
|
2570
|
-
8e3
|
|
2571
|
-
);
|
|
2572
|
-
if (!result) return 0;
|
|
2573
|
-
return result.nodeId;
|
|
3557
|
+
return this.domQueryService.querySelector(selector);
|
|
2574
3558
|
}
|
|
2575
|
-
/** Query all matching elements, returns array of CDP nodeIds */
|
|
2576
3559
|
async querySelectorAll(selector) {
|
|
2577
|
-
|
|
2578
|
-
"DOM.getDocument",
|
|
2579
|
-
{ depth: 0 },
|
|
2580
|
-
this.sessionId
|
|
2581
|
-
);
|
|
2582
|
-
const result = await this.conn.send(
|
|
2583
|
-
"DOM.querySelectorAll",
|
|
2584
|
-
{ nodeId: doc.root.nodeId, selector },
|
|
2585
|
-
this.sessionId
|
|
2586
|
-
);
|
|
2587
|
-
return result.nodeIds ?? [];
|
|
3560
|
+
return this.domQueryService.querySelectorAll(selector);
|
|
2588
3561
|
}
|
|
2589
|
-
/** Resolve a CDP nodeId to a RemoteObject for evaluate */
|
|
2590
3562
|
async resolveNode(nodeId) {
|
|
2591
|
-
|
|
2592
|
-
"DOM.resolveNode",
|
|
2593
|
-
{ nodeId },
|
|
2594
|
-
this.sessionId
|
|
2595
|
-
);
|
|
2596
|
-
return result.object.objectId;
|
|
3563
|
+
return this.domQueryService.resolveNode(nodeId);
|
|
2597
3564
|
}
|
|
2598
|
-
/** Get the box model for a nodeId */
|
|
2599
3565
|
async getBoxModel(nodeId) {
|
|
2600
|
-
|
|
2601
|
-
const result = await this.conn.send("DOM.getBoxModel", { nodeId }, this.sessionId);
|
|
2602
|
-
const c = result.model?.content;
|
|
2603
|
-
if (!c || c.length < 8) return null;
|
|
2604
|
-
const x1 = c[0];
|
|
2605
|
-
const y1 = c[1];
|
|
2606
|
-
const x2 = c[4];
|
|
2607
|
-
const y2 = c[5];
|
|
2608
|
-
return {
|
|
2609
|
-
x: Math.min(x1, x2),
|
|
2610
|
-
y: Math.min(y1, y2),
|
|
2611
|
-
width: Math.abs(x2 - x1),
|
|
2612
|
-
height: Math.abs(y2 - y1)
|
|
2613
|
-
};
|
|
2614
|
-
} catch {
|
|
2615
|
-
return null;
|
|
2616
|
-
}
|
|
3566
|
+
return this.domQueryService.getBoxModel(nodeId);
|
|
2617
3567
|
}
|
|
2618
3568
|
/** Call a function on a RemoteObject */
|
|
2619
3569
|
async callFunctionOn(objectId, functionDeclaration, args = []) {
|
|
@@ -2632,9 +3582,6 @@ Last error: ${lastError.message}` : "";
|
|
|
2632
3582
|
async _cdpSend(method, params) {
|
|
2633
3583
|
return this.conn.send(method, params, this.sessionId);
|
|
2634
3584
|
}
|
|
2635
|
-
/** sup-s11: beforeunload 自动应答语义——'accept'(默认,离开页面,与录制
|
|
2636
|
-
* 意图一致)或 'dismiss'(取消导航留守原页,尽力而为:此构建上 CDP
|
|
2637
|
-
* accept:false 对浏览器侧导航的取消语义不稳定,不保证)。 */
|
|
2638
3585
|
setBeforeUnloadBehavior(mode) {
|
|
2639
3586
|
this._beforeUnloadAccept = mode === "accept";
|
|
2640
3587
|
}
|
|
@@ -2656,144 +3603,38 @@ Last error: ${lastError.message}` : "";
|
|
|
2656
3603
|
return this.conn.subscribe(event, this.sessionId, handler);
|
|
2657
3604
|
}
|
|
2658
3605
|
// ── Private: Event Setup ────────────────────────────────────
|
|
2659
|
-
setupPageEvents() {
|
|
2660
|
-
|
|
2661
|
-
|
|
2662
|
-
|
|
2663
|
-
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
this.
|
|
2667
|
-
}
|
|
2668
|
-
|
|
2669
|
-
|
|
2670
|
-
|
|
3606
|
+
setupPageEvents() {
|
|
3607
|
+
setupPageEvents({
|
|
3608
|
+
conn: this.conn,
|
|
3609
|
+
sessionId: this.sessionId,
|
|
3610
|
+
addSubscription: (unsubscribe) => this._subscriptions.push(unsubscribe),
|
|
3611
|
+
emit: (event, ...args) => this._emit(event, ...args),
|
|
3612
|
+
setUrl: (url) => {
|
|
3613
|
+
this._url = url;
|
|
3614
|
+
},
|
|
3615
|
+
currentUrl: () => this.url(),
|
|
3616
|
+
mainFrame: () => this.mainFrame(),
|
|
3617
|
+
markLoadFired: () => {
|
|
2671
3618
|
this._loadState.loadFired = true;
|
|
2672
|
-
}
|
|
2673
|
-
|
|
2674
|
-
this._subscriptions.push(
|
|
2675
|
-
this.conn.subscribe("Page.domContentEventFired", this.sessionId, () => {
|
|
3619
|
+
},
|
|
3620
|
+
markDomContentFired: () => {
|
|
2676
3621
|
this._loadState.domContentFired = true;
|
|
2677
|
-
}
|
|
2678
|
-
|
|
2679
|
-
|
|
2680
|
-
|
|
2681
|
-
const p = params;
|
|
2682
|
-
const dialog = {
|
|
2683
|
-
type: p.type,
|
|
2684
|
-
message: () => p.message,
|
|
2685
|
-
defaultValue: () => p.defaultValue,
|
|
2686
|
-
accept: async (text) => {
|
|
2687
|
-
await this.conn.send("Page.handleJavaScriptDialog", {
|
|
2688
|
-
accept: true,
|
|
2689
|
-
promptText: text
|
|
2690
|
-
}, this.sessionId);
|
|
2691
|
-
},
|
|
2692
|
-
dismiss: async () => {
|
|
2693
|
-
await this.conn.send("Page.handleJavaScriptDialog", {
|
|
2694
|
-
accept: false
|
|
2695
|
-
}, this.sessionId);
|
|
2696
|
-
}
|
|
2697
|
-
};
|
|
2698
|
-
this._emit("dialog", dialog);
|
|
2699
|
-
const autoAccept = p.type === "beforeunload" ? this._beforeUnloadAccept : false;
|
|
2700
|
-
setTimeout(() => {
|
|
2701
|
-
this.conn.send("Page.handleJavaScriptDialog", { accept: autoAccept }, this.sessionId).catch(() => {
|
|
2702
|
-
});
|
|
2703
|
-
}, 0);
|
|
2704
|
-
})
|
|
2705
|
-
);
|
|
2706
|
-
this._subscriptions.push(
|
|
2707
|
-
this.conn.subscribe("Page.fileChooserOpened", this.sessionId, async (params) => {
|
|
2708
|
-
const p = params;
|
|
2709
|
-
let selector = "";
|
|
2710
|
-
try {
|
|
2711
|
-
const result = await this.conn.send("DOM.describeNode", { backendNodeId: p.backendNodeId }, this.sessionId);
|
|
2712
|
-
const attrs = result.node?.attributes || [];
|
|
2713
|
-
const idIdx = attrs.indexOf("id");
|
|
2714
|
-
if (idIdx >= 0) selector = "#" + attrs[idIdx + 1];
|
|
2715
|
-
} catch {
|
|
2716
|
-
}
|
|
2717
|
-
if (!selector) {
|
|
2718
|
-
try {
|
|
2719
|
-
const result = await this.conn.send("DOM.resolveNode", { backendNodeId: p.backendNodeId }, this.sessionId);
|
|
2720
|
-
const evalResult = await this.conn.send("Runtime.callFunctionOn", {
|
|
2721
|
-
objectId: result.objectId,
|
|
2722
|
-
functionDeclaration: 'function() { return this.id || this.name || "" }',
|
|
2723
|
-
returnByValue: true
|
|
2724
|
-
}, this.sessionId);
|
|
2725
|
-
if (evalResult.result?.value) selector = "#" + evalResult.result.value;
|
|
2726
|
-
} catch {
|
|
2727
|
-
}
|
|
2728
|
-
}
|
|
2729
|
-
const fileChooser = {
|
|
2730
|
-
selector,
|
|
2731
|
-
isMultiple: p.mode === "selectMultiple",
|
|
2732
|
-
setFiles: async (files) => {
|
|
2733
|
-
const fileArray = Array.isArray(files) ? files : [files];
|
|
2734
|
-
await this.setInputFiles(selector || 'input[type="file"]', fileArray);
|
|
2735
|
-
}
|
|
2736
|
-
};
|
|
2737
|
-
this._emit("filechooser", fileChooser);
|
|
2738
|
-
})
|
|
2739
|
-
);
|
|
3622
|
+
},
|
|
3623
|
+
getBeforeUnloadAccept: () => this._beforeUnloadAccept,
|
|
3624
|
+
setInputFiles: (selector, files) => this.setInputFiles(selector, files)
|
|
3625
|
+
});
|
|
2740
3626
|
}
|
|
2741
3627
|
setupNetworkEvents() {
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
|
|
2748
|
-
|
|
2749
|
-
|
|
2750
|
-
|
|
2751
|
-
|
|
2752
|
-
});
|
|
2753
|
-
this._emit("request", createXBRequest(
|
|
2754
|
-
null,
|
|
2755
|
-
{
|
|
2756
|
-
requestId: p.requestId,
|
|
2757
|
-
url: p.request.url,
|
|
2758
|
-
method: p.request.method,
|
|
2759
|
-
headers: p.request.headers,
|
|
2760
|
-
postData: p.request.postData ?? null,
|
|
2761
|
-
resourceType: p.type
|
|
2762
|
-
}
|
|
2763
|
-
));
|
|
2764
|
-
this.checkNetworkIdle();
|
|
2765
|
-
})
|
|
2766
|
-
);
|
|
2767
|
-
this._subscriptions.push(
|
|
2768
|
-
this.conn.subscribe("Network.responseReceived", this.sessionId, (params) => {
|
|
2769
|
-
const p = params;
|
|
2770
|
-
this._storeNetworkResponse(p.requestId, {
|
|
2771
|
-
status: p.response.status,
|
|
2772
|
-
url: p.response.url,
|
|
2773
|
-
headers: p.response.headers
|
|
2774
|
-
});
|
|
2775
|
-
this._emit("response", createXBResponse(
|
|
2776
|
-
{ requestId: p.requestId, status: p.response.status, url: p.response.url, headers: p.response.headers },
|
|
2777
|
-
this.conn,
|
|
2778
|
-
this.sessionId
|
|
2779
|
-
));
|
|
2780
|
-
})
|
|
2781
|
-
);
|
|
2782
|
-
this._subscriptions.push(
|
|
2783
|
-
this.conn.subscribe("Network.loadingFinished", this.sessionId, (params) => {
|
|
2784
|
-
const p = params;
|
|
2785
|
-
this.inflightRequests.delete(p.requestId);
|
|
2786
|
-
this._emit("requestfinished", p);
|
|
2787
|
-
this.checkNetworkIdle();
|
|
2788
|
-
})
|
|
2789
|
-
);
|
|
2790
|
-
this._subscriptions.push(
|
|
2791
|
-
this.conn.subscribe("Network.loadingFailed", this.sessionId, (params) => {
|
|
2792
|
-
const p = params;
|
|
2793
|
-
this.inflightRequests.delete(p.requestId);
|
|
2794
|
-
this.checkNetworkIdle();
|
|
2795
|
-
})
|
|
2796
|
-
);
|
|
3628
|
+
setupNetworkEvents({
|
|
3629
|
+
conn: this.conn,
|
|
3630
|
+
sessionId: this.sessionId,
|
|
3631
|
+
state: { inflightRequests: this.inflightRequests },
|
|
3632
|
+
emit: (event, ...args) => this._emit(event, ...args),
|
|
3633
|
+
storeRequest: (id, data) => this._storeNetworkRequest(id, data),
|
|
3634
|
+
storeResponse: (id, data) => this._storeNetworkResponse(id, data),
|
|
3635
|
+
checkNetworkIdle: () => this.checkNetworkIdle(),
|
|
3636
|
+
addSubscription: (unsubscribe) => this._subscriptions.push(unsubscribe)
|
|
3637
|
+
});
|
|
2797
3638
|
}
|
|
2798
3639
|
setupConsoleEvents() {
|
|
2799
3640
|
this._subscriptions.push(
|
|
@@ -2832,301 +3673,45 @@ Last error: ${lastError.message}` : "";
|
|
|
2832
3673
|
} else {
|
|
2833
3674
|
if (this.networkIdleTimer) {
|
|
2834
3675
|
clearTimeout(this.networkIdleTimer);
|
|
2835
|
-
this.networkIdleTimer = null;
|
|
2836
|
-
}
|
|
2837
|
-
}
|
|
2838
|
-
}
|
|
2839
|
-
// ── Network Data Store (for waitForResponse/waitForRequest) ──
|
|
2840
|
-
_networkResponses = /* @__PURE__ */ new Map();
|
|
2841
|
-
_networkRequests = /* @__PURE__ */ new Map();
|
|
2842
|
-
|
|
2843
|
-
|
|
2844
|
-
|
|
2845
|
-
|
|
2846
|
-
|
|
2847
|
-
|
|
2848
|
-
|
|
2849
|
-
|
|
2850
|
-
|
|
2851
|
-
|
|
2852
|
-
|
|
2853
|
-
async
|
|
2854
|
-
|
|
2855
|
-
|
|
2856
|
-
|
|
2857
|
-
|
|
2858
|
-
|
|
2859
|
-
|
|
2860
|
-
return
|
|
2861
|
-
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
|
|
2865
|
-
|
|
2866
|
-
|
|
2867
|
-
|
|
2868
|
-
|
|
2869
|
-
|
|
2870
|
-
requestId: respObj.requestId || "",
|
|
2871
|
-
status: respObj.response.status || 0,
|
|
2872
|
-
url: respObj.response.url || "",
|
|
2873
|
-
headers: respObj.response.headers || {}
|
|
2874
|
-
};
|
|
2875
|
-
response = createXBResponse(data, this.conn, this.sessionId);
|
|
2876
|
-
} else if (typeof params.status === "function") {
|
|
2877
|
-
response = params;
|
|
2878
|
-
} else {
|
|
2879
|
-
return;
|
|
2880
|
-
}
|
|
2881
|
-
if (predicate(response)) {
|
|
2882
|
-
clearTimeout(timer);
|
|
2883
|
-
this._emitter.removeListener("response", handler);
|
|
2884
|
-
resolve(response);
|
|
2885
|
-
}
|
|
2886
|
-
};
|
|
2887
|
-
this._emitter.on("response", handler);
|
|
2888
|
-
});
|
|
2889
|
-
}
|
|
2890
|
-
// ── waitForRequest ──────────────────────────────────────────
|
|
2891
|
-
async waitForRequest(urlOrPredicate, opts = {}) {
|
|
2892
|
-
const timeout = opts.timeout ?? 3e4;
|
|
2893
|
-
const predicate = createRequestPredicate(urlOrPredicate);
|
|
2894
|
-
for (const [, data] of this._networkRequests) {
|
|
2895
|
-
const request = createXBRequest(this, data);
|
|
2896
|
-
if (predicate(request)) return request;
|
|
2897
|
-
}
|
|
2898
|
-
return new Promise((resolve, reject) => {
|
|
2899
|
-
const timer = setTimeout(() => {
|
|
2900
|
-
this._emitter.removeListener("request", handler);
|
|
2901
|
-
reject(new Error(`waitForRequest timed out after ${timeout}ms`));
|
|
2902
|
-
}, timeout);
|
|
2903
|
-
const handler = (params) => {
|
|
2904
|
-
let request;
|
|
2905
|
-
const reqObj = params;
|
|
2906
|
-
if (reqObj.request) {
|
|
2907
|
-
request = createXBRequest(this, {
|
|
2908
|
-
requestId: reqObj.requestId || "",
|
|
2909
|
-
url: reqObj.request.url || "",
|
|
2910
|
-
method: reqObj.request.method || "",
|
|
2911
|
-
headers: reqObj.request.headers || {},
|
|
2912
|
-
postData: reqObj.request.postData ?? null,
|
|
2913
|
-
resourceType: reqObj.type || ""
|
|
2914
|
-
});
|
|
2915
|
-
} else if (typeof params.url === "function") {
|
|
2916
|
-
request = params;
|
|
2917
|
-
} else {
|
|
2918
|
-
return;
|
|
2919
|
-
}
|
|
2920
|
-
if (predicate(request)) {
|
|
2921
|
-
clearTimeout(timer);
|
|
2922
|
-
this._emitter.removeListener("request", handler);
|
|
2923
|
-
resolve(request);
|
|
2924
|
-
}
|
|
2925
|
-
};
|
|
2926
|
-
this._emitter.on("request", handler);
|
|
2927
|
-
});
|
|
2928
|
-
}
|
|
2929
|
-
// ── waitForURL ──────────────────────────────────────────────
|
|
2930
|
-
async waitForURL(url, opts = {}) {
|
|
2931
|
-
const timeout = opts.timeout ?? 3e4;
|
|
2932
|
-
const checkFn = typeof url === "function" ? url : typeof url === "string" ? (current) => matchGlob(url, current) : (current) => url.test(current);
|
|
2933
|
-
if (checkFn(this._url)) return;
|
|
2934
|
-
return new Promise((resolve, reject) => {
|
|
2935
|
-
const timer = setTimeout(() => {
|
|
2936
|
-
this._emitter.removeListener("framenavigated", handler);
|
|
2937
|
-
reject(new Error(`waitForURL timed out after ${timeout}ms`));
|
|
2938
|
-
}, timeout);
|
|
2939
|
-
const handler = () => {
|
|
2940
|
-
if (checkFn(this._url)) {
|
|
2941
|
-
clearTimeout(timer);
|
|
2942
|
-
this._emitter.removeListener("framenavigated", handler);
|
|
2943
|
-
resolve();
|
|
2944
|
-
}
|
|
2945
|
-
};
|
|
2946
|
-
this._emitter.on("framenavigated", handler);
|
|
2947
|
-
});
|
|
2948
|
-
}
|
|
2949
|
-
// ── route / unroute ─────────────────────────────────────────
|
|
2950
|
-
async route(url, handler) {
|
|
2951
|
-
const regex = typeof url === "string" ? globToRegex(url) : url;
|
|
2952
|
-
this._routeHandlers.push({ pattern: String(url), regex, handler });
|
|
2953
|
-
if (!this._interceptionEnabled) {
|
|
2954
|
-
this._interceptionEnabled = true;
|
|
2955
|
-
await this.conn.send("Fetch.enable", {
|
|
2956
|
-
patterns: [{ urlPattern: "*", requestStage: "Request" }],
|
|
2957
|
-
// sup-s9: 保留认证自动响应(Fetch.enable 为替换语义,不带此参数
|
|
2958
|
-
// 会顶掉 _init 的 auth 配置)
|
|
2959
|
-
handleAuthRequests: true
|
|
2960
|
-
}, this.sessionId);
|
|
2961
|
-
this._subscriptions.push(
|
|
2962
|
-
this.conn.subscribe("Fetch.requestPaused", this.sessionId, (params) => {
|
|
2963
|
-
this._handleRequestPaused(params);
|
|
2964
|
-
})
|
|
2965
|
-
);
|
|
2966
|
-
}
|
|
2967
|
-
}
|
|
2968
|
-
async unroute(url, handler) {
|
|
2969
|
-
const regex = typeof url === "string" ? globToRegex(url) : url;
|
|
2970
|
-
this._routeHandlers = this._routeHandlers.filter(
|
|
2971
|
-
(h) => !(regex.source === h.regex.source && (!handler || h.handler === handler))
|
|
2972
|
-
);
|
|
2973
|
-
if (this._routeHandlers.length === 0 && this._interceptionEnabled) {
|
|
2974
|
-
this._interceptionEnabled = false;
|
|
2975
|
-
await this.conn.send("Fetch.disable", void 0, this.sessionId).catch(() => {
|
|
2976
|
-
});
|
|
2977
|
-
}
|
|
2978
|
-
}
|
|
2979
|
-
async _handleRequestPaused(params) {
|
|
2980
|
-
const requestUrl = params.request.url;
|
|
2981
|
-
for (const { regex, handler } of this._routeHandlers) {
|
|
2982
|
-
if (regex.test(requestUrl)) {
|
|
2983
|
-
this._emit("request", createXBRequest(
|
|
2984
|
-
null,
|
|
2985
|
-
{
|
|
2986
|
-
requestId: params.requestId,
|
|
2987
|
-
url: params.request.url,
|
|
2988
|
-
method: params.request.method,
|
|
2989
|
-
headers: params.request.headers,
|
|
2990
|
-
postData: params.request.postData ?? null,
|
|
2991
|
-
resourceType: params.resourceType
|
|
2992
|
-
}
|
|
2993
|
-
));
|
|
2994
|
-
const route = createXBRouteFetch(this.conn, this.sessionId, params, this._emitter);
|
|
2995
|
-
try {
|
|
2996
|
-
await handler(route);
|
|
2997
|
-
} catch {
|
|
2998
|
-
await this.conn.send("Fetch.continueRequest", {
|
|
2999
|
-
requestId: params.requestId
|
|
3000
|
-
}, this.sessionId).catch(() => {
|
|
3001
|
-
});
|
|
3002
|
-
}
|
|
3003
|
-
return;
|
|
3004
|
-
}
|
|
3005
|
-
}
|
|
3006
|
-
await this.conn.send("Fetch.continueRequest", {
|
|
3007
|
-
requestId: params.requestId
|
|
3008
|
-
}, this.sessionId).catch(() => {
|
|
3009
|
-
});
|
|
3010
|
-
}
|
|
3011
|
-
// ── setInputFiles ───────────────────────────────────────────
|
|
3012
|
-
/**
|
|
3013
|
-
* sup-s4: Dropzone 拖拽上传模拟——Dropzone/Uppy/自绘上传区只监听
|
|
3014
|
-
* dragover/drop(无 input[type=file] 可点),真实用户靠 OS 文件拖入
|
|
3015
|
-
* 触发,自动化无法产生 OS 拖拽。页内构造 DataTransfer+File,按拖放
|
|
3016
|
-
* 协议派发 dragenter/dragover/drop(bubbles+cancelable,坐标取目标
|
|
3017
|
-
* 中心)。
|
|
3018
|
-
*/
|
|
3019
|
-
async dropFiles(selector, payload) {
|
|
3020
|
-
await this.evaluate(`
|
|
3021
|
-
(function() {
|
|
3022
|
-
var el = ${queryJS(selector)};
|
|
3023
|
-
if (!el) throw new Error('drop target not found: ' + ${JSON.stringify(selector)});
|
|
3024
|
-
var b64 = ${JSON.stringify(payload.buffer.toString("base64"))};
|
|
3025
|
-
var bin = atob(b64);
|
|
3026
|
-
var buf = new Uint8Array(bin.length);
|
|
3027
|
-
for (var i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
|
|
3028
|
-
var file = new File([buf], ${JSON.stringify(payload.name)}, { type: ${JSON.stringify(payload.mimeType)} });
|
|
3029
|
-
var dt = new DataTransfer();
|
|
3030
|
-
dt.items.add(file);
|
|
3031
|
-
var rect = el.getBoundingClientRect();
|
|
3032
|
-
var opts = {
|
|
3033
|
-
bubbles: true, cancelable: true,
|
|
3034
|
-
clientX: rect.x + rect.width / 2, clientY: rect.y + rect.height / 2,
|
|
3035
|
-
};
|
|
3036
|
-
el.dispatchEvent(new DragEvent('dragenter', Object.assign({ dataTransfer: dt }, opts)));
|
|
3037
|
-
el.dispatchEvent(new DragEvent('dragover', Object.assign({ dataTransfer: dt }, opts)));
|
|
3038
|
-
el.dispatchEvent(new DragEvent('drop', Object.assign({ dataTransfer: dt }, opts)));
|
|
3039
|
-
})()
|
|
3040
|
-
`);
|
|
3041
|
-
}
|
|
3042
|
-
async setInputFiles(selector, files) {
|
|
3043
|
-
const fileArr = Array.isArray(files) ? files : [files];
|
|
3044
|
-
const fileList = fileArr.map((f) => ({
|
|
3045
|
-
name: f.name,
|
|
3046
|
-
type: f.mimeType,
|
|
3047
|
-
dataBase64: f.buffer.toString("base64")
|
|
3048
|
-
}));
|
|
3049
|
-
await this.evaluate(`
|
|
3050
|
-
(function() {
|
|
3051
|
-
var selector = ${JSON.stringify(selector)};
|
|
3052
|
-
var input = ${queryJS(selector)};
|
|
3053
|
-
if (!input) throw new Error('Element not found: ' + selector);
|
|
3054
|
-
|
|
3055
|
-
var fileList = ${JSON.stringify(fileList)};
|
|
3056
|
-
var dt = new DataTransfer();
|
|
3057
|
-
|
|
3058
|
-
fileList.forEach(function(f) {
|
|
3059
|
-
var binary = atob(f.dataBase64);
|
|
3060
|
-
var bytes = new Uint8Array(binary.length);
|
|
3061
|
-
for (var i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
3062
|
-
var blob = new Blob([bytes], { type: f.type });
|
|
3063
|
-
var file = new File([blob], f.name, { type: f.type });
|
|
3064
|
-
dt.items.add(file);
|
|
3065
|
-
});
|
|
3066
|
-
|
|
3067
|
-
input.files = dt.files;
|
|
3068
|
-
input.dispatchEvent(new Event('input', { bubbles: true }));
|
|
3069
|
-
input.dispatchEvent(new Event('change', { bubbles: true }));
|
|
3070
|
-
})()
|
|
3071
|
-
`);
|
|
3676
|
+
this.networkIdleTimer = null;
|
|
3677
|
+
}
|
|
3678
|
+
}
|
|
3679
|
+
}
|
|
3680
|
+
// ── Network Data Store (for waitForResponse/waitForRequest) ──
|
|
3681
|
+
_networkResponses = /* @__PURE__ */ new Map();
|
|
3682
|
+
_networkRequests = /* @__PURE__ */ new Map();
|
|
3683
|
+
_beforeUnloadAccept = true;
|
|
3684
|
+
/** Store network data — called by browser.ts installNetworkCapture or internal event handlers */
|
|
3685
|
+
_storeNetworkRequest(requestId, data) {
|
|
3686
|
+
this._networkRequests.set(requestId, { requestId, ...data });
|
|
3687
|
+
}
|
|
3688
|
+
_storeNetworkResponse(requestId, data) {
|
|
3689
|
+
this._networkResponses.set(requestId, { requestId, ...data });
|
|
3690
|
+
}
|
|
3691
|
+
async waitForResponse(urlOrPredicate, opts = {}) {
|
|
3692
|
+
return this.networkWaitService.waitForResponse(urlOrPredicate, opts);
|
|
3693
|
+
}
|
|
3694
|
+
async waitForRequest(urlOrPredicate, opts = {}) {
|
|
3695
|
+
return this.networkWaitService.waitForRequest(urlOrPredicate, opts);
|
|
3696
|
+
}
|
|
3697
|
+
async waitForURL(url, opts = {}) {
|
|
3698
|
+
return this.networkWaitService.waitForURL(url, opts);
|
|
3699
|
+
}
|
|
3700
|
+
async route(pattern, handler) {
|
|
3701
|
+
return this.networkRouteService.route(pattern, handler);
|
|
3702
|
+
}
|
|
3703
|
+
async unroute(pattern) {
|
|
3704
|
+
return this.networkRouteService.unroute(pattern);
|
|
3705
|
+
}
|
|
3706
|
+
async dropFiles(selector, payload) {
|
|
3707
|
+
return this.fileInputService.dropFiles(selector, payload);
|
|
3708
|
+
}
|
|
3709
|
+
async setInputFiles(selector, files) {
|
|
3710
|
+
return this.fileInputService.setInputFiles(selector, files);
|
|
3072
3711
|
}
|
|
3073
|
-
// ── dragAndDrop ─────────────────────────────────────────────
|
|
3074
3712
|
async dragAndDrop(source, target) {
|
|
3075
|
-
|
|
3076
|
-
(function() {
|
|
3077
|
-
const el = ${queryJS(source)};
|
|
3078
|
-
if (!el) throw new Error('Source not found: ${source}');
|
|
3079
|
-
el.scrollIntoView({ behavior: 'instant', block: 'center' });
|
|
3080
|
-
const r = el.getBoundingClientRect();
|
|
3081
|
-
return { x: r.x, y: r.y, width: r.width, height: r.height };
|
|
3082
|
-
})()
|
|
3083
|
-
`);
|
|
3084
|
-
const targetRect = await this.evaluate(`
|
|
3085
|
-
(function() {
|
|
3086
|
-
const el = ${queryJS(target)};
|
|
3087
|
-
if (!el) throw new Error('Target not found: ${target}');
|
|
3088
|
-
el.scrollIntoView({ behavior: 'instant', block: 'center' });
|
|
3089
|
-
const r = el.getBoundingClientRect();
|
|
3090
|
-
return { x: r.x, y: r.y, width: r.width, height: r.height };
|
|
3091
|
-
})()
|
|
3092
|
-
`);
|
|
3093
|
-
const sx = sourceRect.x + sourceRect.width / 2;
|
|
3094
|
-
const sy = sourceRect.y + sourceRect.height / 2;
|
|
3095
|
-
const tx = targetRect.x + targetRect.width / 2;
|
|
3096
|
-
const ty = targetRect.y + targetRect.height / 2;
|
|
3097
|
-
try {
|
|
3098
|
-
await this.conn.send("Input.dispatchDragEvent", {
|
|
3099
|
-
type: "dragStart",
|
|
3100
|
-
x: sx,
|
|
3101
|
-
y: sy,
|
|
3102
|
-
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
3103
|
-
}, this.sessionId);
|
|
3104
|
-
await this.conn.send("Input.dispatchDragEvent", {
|
|
3105
|
-
type: "dragOver",
|
|
3106
|
-
x: tx,
|
|
3107
|
-
y: ty,
|
|
3108
|
-
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
3109
|
-
}, this.sessionId);
|
|
3110
|
-
await this.conn.send("Input.dispatchDragEvent", {
|
|
3111
|
-
type: "drop",
|
|
3112
|
-
x: tx,
|
|
3113
|
-
y: ty,
|
|
3114
|
-
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
3115
|
-
}, this.sessionId);
|
|
3116
|
-
await this.conn.send("Input.dispatchDragEvent", {
|
|
3117
|
-
type: "dragCancel",
|
|
3118
|
-
x: sx,
|
|
3119
|
-
y: sy,
|
|
3120
|
-
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
3121
|
-
}, this.sessionId);
|
|
3122
|
-
} catch {
|
|
3123
|
-
await this.mouse.move(sx, sy);
|
|
3124
|
-
await this.mouse.down();
|
|
3125
|
-
await this.mouse.move(tx, ty, { steps: 10 });
|
|
3126
|
-
await this.mouse.up();
|
|
3127
|
-
}
|
|
3713
|
+
return this.fileInputService.dragAndDrop(source, target);
|
|
3128
3714
|
}
|
|
3129
|
-
// ── setOfflineMode ──────────────────────────────────────────
|
|
3130
3715
|
async setOfflineMode(offline) {
|
|
3131
3716
|
await this.conn.send("Network.emulateNetworkConditions", {
|
|
3132
3717
|
offline,
|
|
@@ -3422,12 +4007,22 @@ var XBBrowserImpl = class {
|
|
|
3422
4007
|
this._exitHandler = null;
|
|
3423
4008
|
}
|
|
3424
4009
|
if (this.childProcess) {
|
|
3425
|
-
const { killChrome: killChrome2 } = await import("./launcher-
|
|
4010
|
+
const { killChrome: killChrome2 } = await import("./launcher-ZYB32LSZ.js");
|
|
3426
4011
|
await killChrome2(this.childProcess, this.tmpDir);
|
|
3427
4012
|
}
|
|
3428
4013
|
await this.conn.close();
|
|
3429
4014
|
this._emitter.emit("disconnected");
|
|
3430
4015
|
}
|
|
4016
|
+
async disconnect() {
|
|
4017
|
+
if (this._disconnected) return;
|
|
4018
|
+
this._disconnected = true;
|
|
4019
|
+
if (this._exitHandler) {
|
|
4020
|
+
process.removeListener("exit", this._exitHandler);
|
|
4021
|
+
this._exitHandler = null;
|
|
4022
|
+
}
|
|
4023
|
+
await this.conn.close();
|
|
4024
|
+
this._emitter.emit("disconnected");
|
|
4025
|
+
}
|
|
3431
4026
|
async newContext(opts = {}) {
|
|
3432
4027
|
if (this.launchOpts?.stealthConfig && !opts.stealthConfig) {
|
|
3433
4028
|
opts = { ...opts, stealthConfig: this.launchOpts.stealthConfig };
|
|
@@ -3592,7 +4187,7 @@ var XBBrowserImpl = class {
|
|
|
3592
4187
|
if (pageTargets.length === 0 && httpFallbackUrl) {
|
|
3593
4188
|
console.log(`[discoverContexts] Target.getTargets returned ${targetInfos.length} targets (0 page type). Falling back to HTTP /json/list at ${httpFallbackUrl}`);
|
|
3594
4189
|
try {
|
|
3595
|
-
const { getCDPTargets: getCDPTargets3 } = await import("./launcher-
|
|
4190
|
+
const { getCDPTargets: getCDPTargets3 } = await import("./launcher-ZYB32LSZ.js");
|
|
3596
4191
|
const httpPages = await getCDPTargets3(httpFallbackUrl);
|
|
3597
4192
|
console.log(`[discoverContexts] HTTP /json/list returned ${httpPages.length} pages`);
|
|
3598
4193
|
for (const p of httpPages) {
|
|
@@ -4038,6 +4633,149 @@ Or add random variation: page.type(selector, text, {delay: 50 + Math.random() *
|
|
|
4038
4633
|
return null;
|
|
4039
4634
|
}
|
|
4040
4635
|
|
|
4636
|
+
// src/cdp-interceptor/rules/humanize-transform.ts
|
|
4637
|
+
var CURSOR_KEY = "humanize-cursor";
|
|
4638
|
+
var KEYS_KEY = "humanize-keys";
|
|
4639
|
+
var MOUSE_STEP_DELAYS = [16, 19, 23, 28];
|
|
4640
|
+
var TYPE_DELAYS = [42, 58, 74, 96, 118, 155, 210];
|
|
4641
|
+
function rand2(min, max) {
|
|
4642
|
+
return min + Math.random() * (max - min);
|
|
4643
|
+
}
|
|
4644
|
+
function roundCoordinate(value) {
|
|
4645
|
+
return Math.round(value * 100) / 100;
|
|
4646
|
+
}
|
|
4647
|
+
function humanMousePath(fromX, fromY, toX, toY) {
|
|
4648
|
+
const dist = Math.hypot(toX - fromX, toY - fromY);
|
|
4649
|
+
const n = Math.max(8, Math.min(28, Math.round(dist / 15)));
|
|
4650
|
+
const shortMove = dist < 120;
|
|
4651
|
+
const curvature = shortMove ? rand2(2, 6) : Math.max(dist * rand2(0.12, 0.22), rand2(18, 35));
|
|
4652
|
+
const dir = Math.random() < 0.5 ? 1 : -1;
|
|
4653
|
+
const dx = toX - fromX;
|
|
4654
|
+
const dy = toY - fromY;
|
|
4655
|
+
const d = dist || 1;
|
|
4656
|
+
const c1x = fromX + dx * 0.3 - dy / d * curvature * 0.5 * dir;
|
|
4657
|
+
const c1y = fromY + dy * 0.3 + dx / d * curvature * 0.5 * dir;
|
|
4658
|
+
const c2x = fromX + dx * 0.7 - dy / d * curvature * 0.8 * dir;
|
|
4659
|
+
const c2y = fromY + dy * 0.7 + dx / d * curvature * 0.8 * dir;
|
|
4660
|
+
const amp = shortMove ? Math.min(2, 3.2) : 3.2;
|
|
4661
|
+
const points = [];
|
|
4662
|
+
for (let i = 1; i <= n; i++) {
|
|
4663
|
+
const t = i / n;
|
|
4664
|
+
const eased = t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;
|
|
4665
|
+
const mt = 1 - eased;
|
|
4666
|
+
const px = mt ** 3 * fromX + 3 * mt ** 2 * eased * c1x + 3 * mt * eased ** 2 * c2x + eased ** 3 * toX;
|
|
4667
|
+
const py = mt ** 3 * fromY + 3 * mt ** 2 * eased * c1y + 3 * mt * eased ** 2 * c2y + eased ** 3 * toY;
|
|
4668
|
+
points.push({
|
|
4669
|
+
x: roundCoordinate(px + rand2(-amp, amp)),
|
|
4670
|
+
y: roundCoordinate(py + rand2(-amp, amp)),
|
|
4671
|
+
delay: MOUSE_STEP_DELAYS[Math.floor(Math.random() * MOUSE_STEP_DELAYS.length)]
|
|
4672
|
+
});
|
|
4673
|
+
}
|
|
4674
|
+
if (!shortMove) {
|
|
4675
|
+
const over = rand2(6, 14);
|
|
4676
|
+
points.push({
|
|
4677
|
+
x: roundCoordinate(toX + dx / d * over + rand2(-2, 2)),
|
|
4678
|
+
y: roundCoordinate(toY + dy / d * over + rand2(-2, 2)),
|
|
4679
|
+
delay: Math.round(rand2(14, 30))
|
|
4680
|
+
});
|
|
4681
|
+
points.push({
|
|
4682
|
+
x: roundCoordinate(toX + dx / d * over * 0.4),
|
|
4683
|
+
y: roundCoordinate(toY + dy / d * over * 0.4),
|
|
4684
|
+
delay: Math.round(rand2(14, 30))
|
|
4685
|
+
});
|
|
4686
|
+
}
|
|
4687
|
+
points.push({
|
|
4688
|
+
x: roundCoordinate(toX + rand2(-1, 1)),
|
|
4689
|
+
y: roundCoordinate(toY + rand2(-1, 1)),
|
|
4690
|
+
delay: Math.round(rand2(14, 30))
|
|
4691
|
+
});
|
|
4692
|
+
return points;
|
|
4693
|
+
}
|
|
4694
|
+
function characterKeyEvents(text) {
|
|
4695
|
+
const events = [];
|
|
4696
|
+
for (const char of text) {
|
|
4697
|
+
if (char === "\n") {
|
|
4698
|
+
events.push(
|
|
4699
|
+
{ type: "rawKeyDown", key: "Enter", code: "Enter", windowsVirtualKeyCode: 13 },
|
|
4700
|
+
{ type: "char", text: "\r" },
|
|
4701
|
+
{ type: "keyUp", key: "Enter", code: "Enter", windowsVirtualKeyCode: 13 }
|
|
4702
|
+
);
|
|
4703
|
+
continue;
|
|
4704
|
+
}
|
|
4705
|
+
events.push(
|
|
4706
|
+
{ type: "rawKeyDown", key: char, text: char, unmodifiedText: char },
|
|
4707
|
+
{ type: "char", text: char },
|
|
4708
|
+
{ type: "keyUp", key: char }
|
|
4709
|
+
);
|
|
4710
|
+
}
|
|
4711
|
+
return events;
|
|
4712
|
+
}
|
|
4713
|
+
function isMouseEvent(method) {
|
|
4714
|
+
return method === "Input.dispatchMouseEvent";
|
|
4715
|
+
}
|
|
4716
|
+
var humanizeTransformRule = {
|
|
4717
|
+
id: "humanize-transform",
|
|
4718
|
+
name: "Humanize Trusted Input Transform",
|
|
4719
|
+
priority: 45,
|
|
4720
|
+
canHandle(ctx) {
|
|
4721
|
+
return isMouseEvent(ctx.method) || ctx.method === "Input.insertText";
|
|
4722
|
+
},
|
|
4723
|
+
evaluate(ctx) {
|
|
4724
|
+
if (ctx.method === "Input.insertText") return this.transformInsertText(ctx);
|
|
4725
|
+
return this.transformMouseEvent(ctx);
|
|
4726
|
+
},
|
|
4727
|
+
transformMouseEvent(ctx) {
|
|
4728
|
+
const params = ctx.params;
|
|
4729
|
+
if (params.type !== "mouseMoved" || typeof params.x !== "number" || typeof params.y !== "number") {
|
|
4730
|
+
const x = params.x;
|
|
4731
|
+
const y = params.y;
|
|
4732
|
+
if (typeof x === "number" && typeof y === "number") {
|
|
4733
|
+
ctx.sessionState.set(CURSOR_KEY, { x, y });
|
|
4734
|
+
}
|
|
4735
|
+
return null;
|
|
4736
|
+
}
|
|
4737
|
+
const cursor = ctx.sessionState.get(CURSOR_KEY) ?? { x: 0, y: 0 };
|
|
4738
|
+
const jump = Math.hypot(params.x - cursor.x, params.y - cursor.y);
|
|
4739
|
+
ctx.sessionState.set(CURSOR_KEY, { x: params.x, y: params.y });
|
|
4740
|
+
if (jump < 32) return null;
|
|
4741
|
+
const path = humanMousePath(cursor.x, cursor.y, params.x, params.y);
|
|
4742
|
+
return {
|
|
4743
|
+
ruleId: this.id,
|
|
4744
|
+
action: "transform",
|
|
4745
|
+
severity: "info",
|
|
4746
|
+
reason: `Expanded instant mouse jump of ${jump.toFixed(0)}px into ${path.length} trusted bezier moves.`,
|
|
4747
|
+
suggestion: "Use page.mouse.move with steps for explicit control; this transform preserves isTrusted=true.",
|
|
4748
|
+
transformedParams: { __sequence: path.map((point) => ({
|
|
4749
|
+
method: "Input.dispatchMouseEvent",
|
|
4750
|
+
params: { type: "mouseMoved", x: point.x, y: point.y, button: params.button ?? "none" },
|
|
4751
|
+
delayMs: point.delay
|
|
4752
|
+
})) }
|
|
4753
|
+
};
|
|
4754
|
+
},
|
|
4755
|
+
transformInsertText(ctx) {
|
|
4756
|
+
const params = ctx.params;
|
|
4757
|
+
const text = params.text ?? "";
|
|
4758
|
+
if (!text) return null;
|
|
4759
|
+
const timing = ctx.sessionState.get(KEYS_KEY) ?? { lastDelay: TYPE_DELAYS[1] };
|
|
4760
|
+
const bucket = TYPE_DELAYS[Math.floor(Math.random() * TYPE_DELAYS.length)];
|
|
4761
|
+
const events = characterKeyEvents(text).map((event, index) => ({
|
|
4762
|
+
method: "Input.dispatchKeyEvent",
|
|
4763
|
+
params: event,
|
|
4764
|
+
delayMs: index === 0 ? 0 : Math.max(24, Math.round(bucket + rand2(-bucket * 0.45, bucket * 0.55)))
|
|
4765
|
+
}));
|
|
4766
|
+
timing.lastDelay = bucket;
|
|
4767
|
+
ctx.sessionState.set(KEYS_KEY, timing);
|
|
4768
|
+
return {
|
|
4769
|
+
ruleId: this.id,
|
|
4770
|
+
action: "transform",
|
|
4771
|
+
severity: "info",
|
|
4772
|
+
reason: `Expanded Input.insertText (${text.length} chars) into ${events.length} trusted key events with variable rhythm.`,
|
|
4773
|
+
suggestion: "Use page.type for explicit control; this transform preserves the native keyboard command stream.",
|
|
4774
|
+
transformedParams: { __sequence: events }
|
|
4775
|
+
};
|
|
4776
|
+
}
|
|
4777
|
+
};
|
|
4778
|
+
|
|
4041
4779
|
// src/cdp-interceptor/rules/automation-signals.ts
|
|
4042
4780
|
var AUTOMATION_PATTERNS = [
|
|
4043
4781
|
// ── Playwright markers ─────────────────────────
|
|
@@ -4556,6 +5294,7 @@ var BUILTIN_RULES = [
|
|
|
4556
5294
|
eventSimulationRule,
|
|
4557
5295
|
mouseTrajectoryRule,
|
|
4558
5296
|
inputKeystrokeRule,
|
|
5297
|
+
humanizeTransformRule,
|
|
4559
5298
|
emulationOverrideRule,
|
|
4560
5299
|
networkAnomalyRule,
|
|
4561
5300
|
pageLifecycleRule
|
|
@@ -4588,8 +5327,10 @@ function createRuleEngine(customRules) {
|
|
|
4588
5327
|
if (isProbeMarked(code)) return null;
|
|
4589
5328
|
} catch {
|
|
4590
5329
|
}
|
|
5330
|
+
const humanizeEnabled = process.env.XBROWSER_HUMANIZE_CDP === "on";
|
|
4591
5331
|
for (const rule of rules) {
|
|
4592
5332
|
if (rule.canHandle && !rule.canHandle(fullCtx)) continue;
|
|
5333
|
+
if (rule.id === "humanize-transform" && !humanizeEnabled) continue;
|
|
4593
5334
|
const decision = rule.evaluate(fullCtx);
|
|
4594
5335
|
if (!decision) continue;
|
|
4595
5336
|
if (decision.action !== "pass") return decision;
|
|
@@ -4731,6 +5472,15 @@ var CDPConnection = class _CDPConnection extends EventEmitter4 {
|
|
|
4731
5472
|
if (decision && decision.action === "block") {
|
|
4732
5473
|
throw new Error(`[CDP-Guard] ${decision.reason}${decision.suggestion ? " | \u66FF\u4EE3: " + decision.suggestion : ""} [${decision.ruleId}]`);
|
|
4733
5474
|
}
|
|
5475
|
+
if (decision && decision.action === "transform" && Array.isArray(decision.transformedParams?.__sequence)) {
|
|
5476
|
+
const sequence = decision.transformedParams.__sequence;
|
|
5477
|
+
let last;
|
|
5478
|
+
for (const step of sequence) {
|
|
5479
|
+
if (step.delayMs) await new Promise((resolve) => setTimeout(resolve, step.delayMs));
|
|
5480
|
+
last = await this.send(step.method, step.params, sessionId, effectiveTimeout);
|
|
5481
|
+
}
|
|
5482
|
+
return last;
|
|
5483
|
+
}
|
|
4734
5484
|
}
|
|
4735
5485
|
if (this.closed) {
|
|
4736
5486
|
throw new Error(`CDP connection closed: ${this.closeReason ?? "unknown"}`);
|
|
@@ -4913,7 +5663,7 @@ async function launch(options = {}) {
|
|
|
4913
5663
|
const bv = await conn.send("Browser.getVersion");
|
|
4914
5664
|
const m = bv.product.match(/(\d+)\.(\d+)\.(\d+)\.(\d+)/);
|
|
4915
5665
|
if (m && !options.stealthConfig?.uaChProfile) {
|
|
4916
|
-
const { deriveUaChProfileForBinary } = await import("./stealth-
|
|
5666
|
+
const { deriveUaChProfileForBinary } = await import("./stealth-MCKFKPZ6.js");
|
|
4917
5667
|
stealthOpts = { stealthConfig: { uaChProfile: deriveUaChProfileForBinary(m[0], m[1]) } };
|
|
4918
5668
|
}
|
|
4919
5669
|
} catch {
|
|
@@ -4928,6 +5678,9 @@ async function launch(options = {}) {
|
|
|
4928
5678
|
return { browser, wsEndpoint };
|
|
4929
5679
|
}
|
|
4930
5680
|
|
|
5681
|
+
// src/browser/connection.ts
|
|
5682
|
+
import { existsSync } from "fs";
|
|
5683
|
+
|
|
4931
5684
|
// src/cdp-interceptor/proxy.ts
|
|
4932
5685
|
import { WebSocketServer, WebSocket as WebSocket2 } from "ws";
|
|
4933
5686
|
|
|
@@ -5307,236 +6060,101 @@ ${blockMsg}
|
|
|
5307
6060
|
return;
|
|
5308
6061
|
}
|
|
5309
6062
|
if (decision?.action === "transform" && decision.transformedParams) {
|
|
5310
|
-
const
|
|
5311
|
-
|
|
5312
|
-
|
|
5313
|
-
|
|
5314
|
-
|
|
5315
|
-
|
|
5316
|
-
|
|
5317
|
-
|
|
5318
|
-
handleBrowserMessage(clientWs, _browserWs, raw) {
|
|
5319
|
-
const msg = this.parseMessage(raw);
|
|
5320
|
-
if (!msg) {
|
|
5321
|
-
clientWs.send(raw.toString());
|
|
5322
|
-
return;
|
|
5323
|
-
}
|
|
5324
|
-
if ("method" in msg) {
|
|
5325
|
-
const event = msg;
|
|
5326
|
-
const ctx = {
|
|
5327
|
-
method: event.method,
|
|
5328
|
-
params: event.params ?? {},
|
|
5329
|
-
sessionId: event.sessionId ?? "browser",
|
|
5330
|
-
direction: "browser\u2192client"
|
|
5331
|
-
};
|
|
5332
|
-
const decision = this.engine.evaluate(ctx);
|
|
5333
|
-
if (decision?.action === "block") {
|
|
5334
|
-
return;
|
|
5335
|
-
}
|
|
5336
|
-
}
|
|
5337
|
-
clientWs.send(raw.toString());
|
|
5338
|
-
}
|
|
5339
|
-
// ── Utilities ────────────────────────────────────────────────
|
|
5340
|
-
parseMessage(raw) {
|
|
5341
|
-
try {
|
|
5342
|
-
return JSON.parse(raw.toString());
|
|
5343
|
-
} catch {
|
|
5344
|
-
return null;
|
|
5345
|
-
}
|
|
5346
|
-
}
|
|
5347
|
-
recordDecision(decision) {
|
|
5348
|
-
if (!this.stats.byRule[decision.ruleId]) {
|
|
5349
|
-
this.stats.byRule[decision.ruleId] = { matched: 0, blocked: 0, transformed: 0 };
|
|
5350
|
-
}
|
|
5351
|
-
this.stats.byRule[decision.ruleId].matched++;
|
|
5352
|
-
if (decision.action === "block") {
|
|
5353
|
-
this.stats.byRule[decision.ruleId].blocked++;
|
|
5354
|
-
} else if (decision.action === "transform") {
|
|
5355
|
-
this.stats.byRule[decision.ruleId].transformed++;
|
|
5356
|
-
}
|
|
5357
|
-
}
|
|
5358
|
-
};
|
|
5359
|
-
|
|
5360
|
-
// src/utils/cdp.ts
|
|
5361
|
-
async function fetchNoProxy(url) {
|
|
5362
|
-
const savedProxy = {
|
|
5363
|
-
http_proxy: process.env.http_proxy,
|
|
5364
|
-
https_proxy: process.env.https_proxy,
|
|
5365
|
-
HTTP_PROXY: process.env.HTTP_PROXY,
|
|
5366
|
-
HTTPS_PROXY: process.env.HTTPS_PROXY,
|
|
5367
|
-
all_proxy: process.env.all_proxy,
|
|
5368
|
-
ALL_PROXY: process.env.ALL_PROXY
|
|
5369
|
-
};
|
|
5370
|
-
for (const key of Object.keys(savedProxy)) delete process.env[key];
|
|
5371
|
-
try {
|
|
5372
|
-
return await fetch(url);
|
|
5373
|
-
} finally {
|
|
5374
|
-
for (const [key, val] of Object.entries(savedProxy)) {
|
|
5375
|
-
if (val !== void 0) process.env[key] = val;
|
|
5376
|
-
}
|
|
5377
|
-
}
|
|
5378
|
-
}
|
|
5379
|
-
async function resolveCDPEndpoint(raw) {
|
|
5380
|
-
if (raw === "auto") {
|
|
5381
|
-
const ports = [9222, 9221, 9223, 9224];
|
|
5382
|
-
for (const port of ports) {
|
|
5383
|
-
try {
|
|
5384
|
-
const httpResp = await fetchNoProxy(`http://localhost:${port}/json/version`);
|
|
5385
|
-
if (httpResp.ok) {
|
|
5386
|
-
const data = await httpResp.json();
|
|
5387
|
-
if (data.webSocketDebuggerUrl) {
|
|
5388
|
-
return data.webSocketDebuggerUrl;
|
|
6063
|
+
const sequence = decision.transformedParams.__sequence;
|
|
6064
|
+
if (Array.isArray(sequence)) {
|
|
6065
|
+
this.stats.transformedMessages++;
|
|
6066
|
+
const dispatch = async () => {
|
|
6067
|
+
for (const step of sequence) {
|
|
6068
|
+
if (step.delayMs) await new Promise((resolve) => setTimeout(resolve, step.delayMs));
|
|
6069
|
+
const transformed2 = { id: request.id, method: step.method, params: step.params, sessionId: request.sessionId };
|
|
6070
|
+
browserWs.send(JSON.stringify(transformed2));
|
|
5389
6071
|
}
|
|
5390
|
-
}
|
|
5391
|
-
|
|
5392
|
-
|
|
5393
|
-
|
|
5394
|
-
|
|
5395
|
-
|
|
5396
|
-
|
|
5397
|
-
|
|
5398
|
-
1. \u542F\u52A8 Chrome: google-chrome --remote-debugging-port=9222
|
|
5399
|
-
2. \u6216\u7528 cdp-tunnel: npx cdp-tunnel setup
|
|
5400
|
-
3. \u6216\u6307\u5B9A\u7AEF\u53E3: --cdp <port>`
|
|
5401
|
-
);
|
|
5402
|
-
}
|
|
5403
|
-
if (/^\d+$/.test(raw)) {
|
|
5404
|
-
const port = raw;
|
|
5405
|
-
const httpResp = await fetchNoProxy(`http://localhost:${port}/json/version`);
|
|
5406
|
-
const data = await httpResp.json();
|
|
5407
|
-
if (!data.webSocketDebuggerUrl) {
|
|
5408
|
-
throw new Error(`Could not discover CDP endpoint from localhost:${port}`);
|
|
5409
|
-
}
|
|
5410
|
-
return data.webSocketDebuggerUrl;
|
|
5411
|
-
}
|
|
5412
|
-
if (raw.startsWith("http://") || raw.startsWith("https://")) {
|
|
5413
|
-
try {
|
|
5414
|
-
const u = new URL(raw);
|
|
5415
|
-
u.pathname = (u.pathname.replace(/\/+$/, "") || "") + "/json/version";
|
|
5416
|
-
const httpResp = await fetchNoProxy(u.toString());
|
|
5417
|
-
const data = await httpResp.json();
|
|
5418
|
-
if (!data.webSocketDebuggerUrl) {
|
|
5419
|
-
throw new Error(`Could not discover CDP endpoint from ${raw}`);
|
|
5420
|
-
}
|
|
5421
|
-
return data.webSocketDebuggerUrl;
|
|
5422
|
-
} catch (error) {
|
|
5423
|
-
console.warn(`Failed to fetch WebSocket URL from ${raw}, using endpoint directly: ${error instanceof Error ? error.message : String(error)}`);
|
|
5424
|
-
return raw;
|
|
5425
|
-
}
|
|
5426
|
-
}
|
|
5427
|
-
return raw;
|
|
5428
|
-
}
|
|
5429
|
-
|
|
5430
|
-
// src/browser.ts
|
|
5431
|
-
import { SessionStore } from "@dyyz1993/xcli-core";
|
|
5432
|
-
function logSessionEvent(event, details) {
|
|
5433
|
-
const ts = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
|
|
5434
|
-
const pid = process.pid;
|
|
5435
|
-
console.error(`[SESSION] ${ts} [PID:${pid}] ${event} | ${details}`);
|
|
5436
|
-
}
|
|
5437
|
-
var SESSION_DIR = join2(homedir(), ".xbrowser", "sessions");
|
|
5438
|
-
function sessionFile(name) {
|
|
5439
|
-
return join2(SESSION_DIR, `${name}.json`);
|
|
5440
|
-
}
|
|
5441
|
-
function ensureSessionDir() {
|
|
5442
|
-
mkdirSync2(SESSION_DIR, { recursive: true });
|
|
5443
|
-
}
|
|
5444
|
-
var sessions = new SessionStore();
|
|
5445
|
-
var _sharedBrowser = null;
|
|
5446
|
-
var _sharedCdpProxy = null;
|
|
5447
|
-
var IDLE_TIMEOUT_MS = (process.env.XBROWSER_IDLE_TIMEOUT ? parseInt(process.env.XBROWSER_IDLE_TIMEOUT, 10) : 30) * 60 * 1e3;
|
|
5448
|
-
var idleTimer = null;
|
|
5449
|
-
function resetIdleTimer() {
|
|
5450
|
-
if (idleTimer) clearTimeout(idleTimer);
|
|
5451
|
-
idleTimer = setTimeout(async () => {
|
|
5452
|
-
const now = Date.now();
|
|
5453
|
-
let allIdle = true;
|
|
5454
|
-
const idleSessions = [];
|
|
5455
|
-
for (const s of sessions) {
|
|
5456
|
-
if (now - s.lastActivityAt < IDLE_TIMEOUT_MS) {
|
|
5457
|
-
allIdle = false;
|
|
5458
|
-
} else {
|
|
5459
|
-
idleSessions.push(`${s.name}(${(now - s.lastActivityAt) / 1e3}s idle)`);
|
|
5460
|
-
}
|
|
5461
|
-
}
|
|
5462
|
-
if (allIdle && (sessions.size > 0 || _sharedBrowser)) {
|
|
5463
|
-
logSessionEvent("idle_timeout", `Sessions idle for >${IDLE_TIMEOUT_MS / 6e4}min. Sessions: ${idleSessions.join(", ") || "all"}. Calling destroyBrowser()`);
|
|
5464
|
-
await destroyBrowser().catch(() => {
|
|
5465
|
-
});
|
|
6072
|
+
};
|
|
6073
|
+
void dispatch();
|
|
6074
|
+
return;
|
|
6075
|
+
}
|
|
6076
|
+
const transformed = { ...request, params: decision.transformedParams };
|
|
6077
|
+
this.stats.transformedMessages++;
|
|
6078
|
+
browserWs.send(JSON.stringify(transformed));
|
|
6079
|
+
return;
|
|
5466
6080
|
}
|
|
5467
|
-
|
|
5468
|
-
|
|
5469
|
-
idleTimer.unref();
|
|
6081
|
+
this.stats.passedMessages++;
|
|
6082
|
+
browserWs.send(raw.toString());
|
|
5470
6083
|
}
|
|
5471
|
-
|
|
5472
|
-
|
|
5473
|
-
|
|
5474
|
-
|
|
5475
|
-
|
|
5476
|
-
}
|
|
5477
|
-
|
|
5478
|
-
|
|
5479
|
-
|
|
5480
|
-
|
|
5481
|
-
|
|
5482
|
-
|
|
5483
|
-
|
|
5484
|
-
|
|
5485
|
-
|
|
6084
|
+
handleBrowserMessage(clientWs, _browserWs, raw) {
|
|
6085
|
+
const msg = this.parseMessage(raw);
|
|
6086
|
+
if (!msg) {
|
|
6087
|
+
clientWs.send(raw.toString());
|
|
6088
|
+
return;
|
|
6089
|
+
}
|
|
6090
|
+
if ("method" in msg) {
|
|
6091
|
+
const event = msg;
|
|
6092
|
+
const ctx = {
|
|
6093
|
+
method: event.method,
|
|
6094
|
+
params: event.params ?? {},
|
|
6095
|
+
sessionId: event.sessionId ?? "browser",
|
|
6096
|
+
direction: "browser\u2192client"
|
|
6097
|
+
};
|
|
6098
|
+
const decision = this.engine.evaluate(ctx);
|
|
6099
|
+
if (decision?.action === "block") {
|
|
6100
|
+
return;
|
|
5486
6101
|
}
|
|
5487
6102
|
}
|
|
6103
|
+
clientWs.send(raw.toString());
|
|
5488
6104
|
}
|
|
5489
|
-
|
|
5490
|
-
|
|
6105
|
+
// ── Utilities ────────────────────────────────────────────────
|
|
6106
|
+
parseMessage(raw) {
|
|
5491
6107
|
try {
|
|
5492
|
-
|
|
6108
|
+
return JSON.parse(raw.toString());
|
|
5493
6109
|
} catch {
|
|
6110
|
+
return null;
|
|
5494
6111
|
}
|
|
5495
|
-
_sharedBrowser = null;
|
|
5496
6112
|
}
|
|
5497
|
-
|
|
5498
|
-
|
|
5499
|
-
|
|
5500
|
-
}
|
|
6113
|
+
recordDecision(decision) {
|
|
6114
|
+
if (!this.stats.byRule[decision.ruleId]) {
|
|
6115
|
+
this.stats.byRule[decision.ruleId] = { matched: 0, blocked: 0, transformed: 0 };
|
|
6116
|
+
}
|
|
6117
|
+
this.stats.byRule[decision.ruleId].matched++;
|
|
6118
|
+
if (decision.action === "block") {
|
|
6119
|
+
this.stats.byRule[decision.ruleId].blocked++;
|
|
6120
|
+
} else if (decision.action === "transform") {
|
|
6121
|
+
this.stats.byRule[decision.ruleId].transformed++;
|
|
5501
6122
|
}
|
|
5502
|
-
_sharedCdpProxy = null;
|
|
5503
6123
|
}
|
|
5504
|
-
|
|
5505
|
-
|
|
6124
|
+
};
|
|
6125
|
+
|
|
6126
|
+
// src/browser/connection.ts
|
|
5506
6127
|
async function getCDPTargets2(cdpEndpoint) {
|
|
5507
6128
|
try {
|
|
5508
|
-
const
|
|
6129
|
+
const endpoint = String(cdpEndpoint);
|
|
5509
6130
|
let url = "http://localhost:9222/json/list";
|
|
5510
|
-
if (
|
|
5511
|
-
const
|
|
5512
|
-
|
|
5513
|
-
url =
|
|
5514
|
-
} else if (/^\d+$/.test(
|
|
5515
|
-
url = `http://localhost:${
|
|
5516
|
-
}
|
|
5517
|
-
const
|
|
5518
|
-
return await
|
|
6131
|
+
if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) {
|
|
6132
|
+
const parsed = new URL(endpoint);
|
|
6133
|
+
parsed.pathname = (parsed.pathname.replace(/\/+$/, "") || "") + "/json/list";
|
|
6134
|
+
url = parsed.toString();
|
|
6135
|
+
} else if (/^\d+$/.test(endpoint)) {
|
|
6136
|
+
url = `http://localhost:${endpoint}/json/list`;
|
|
6137
|
+
}
|
|
6138
|
+
const response = await fetch(url);
|
|
6139
|
+
return await response.json();
|
|
5519
6140
|
} catch {
|
|
5520
6141
|
return [];
|
|
5521
6142
|
}
|
|
5522
6143
|
}
|
|
5523
6144
|
async function findTargetPage(cdpEndpoint, target) {
|
|
5524
6145
|
const targets = await getCDPTargets2(cdpEndpoint);
|
|
5525
|
-
const pages = targets.filter((
|
|
5526
|
-
const byId = pages.find((
|
|
6146
|
+
const pages = targets.filter((item) => item.url && !item.url.startsWith("about:blank") && !item.url.startsWith("chrome://") && !item.url.startsWith("chrome-untrusted://") && !item.url.startsWith("chrome-error://"));
|
|
6147
|
+
const byId = pages.find((item) => item.id === target);
|
|
5527
6148
|
if (byId) return { pageId: byId.id, wsUrl: byId.webSocketDebuggerUrl, title: byId.title, url: byId.url };
|
|
5528
6149
|
const lowerTarget = target.toLowerCase();
|
|
5529
|
-
const byTitle = pages.find((
|
|
6150
|
+
const byTitle = pages.find((item) => item.title?.toLowerCase().includes(lowerTarget));
|
|
5530
6151
|
if (byTitle) return { pageId: byTitle.id, wsUrl: byTitle.webSocketDebuggerUrl, title: byTitle.title, url: byTitle.url };
|
|
5531
|
-
const byUrl = pages.find((
|
|
6152
|
+
const byUrl = pages.find((item) => item.url.toLowerCase().includes(lowerTarget));
|
|
5532
6153
|
if (byUrl) return { pageId: byUrl.id, wsUrl: byUrl.webSocketDebuggerUrl, title: byUrl.title, url: byUrl.url };
|
|
5533
6154
|
return null;
|
|
5534
6155
|
}
|
|
5535
6156
|
function resolveLaunchOpts(ctx) {
|
|
5536
|
-
|
|
5537
|
-
return { cdpEndpoint: ctx.cdpEndpoint };
|
|
5538
|
-
}
|
|
5539
|
-
return { headless: true };
|
|
6157
|
+
return ctx.cdpEndpoint ? { cdpEndpoint: ctx.cdpEndpoint } : { headless: true };
|
|
5540
6158
|
}
|
|
5541
6159
|
var CHROMIUM_CANDIDATES = [
|
|
5542
6160
|
"/Applications/Chromium.app/Contents/MacOS/Chromium",
|
|
@@ -5546,57 +6164,58 @@ var CHROMIUM_CANDIDATES = [
|
|
|
5546
6164
|
"/usr/bin/google-chrome"
|
|
5547
6165
|
];
|
|
5548
6166
|
function discoverChromiumPath() {
|
|
5549
|
-
|
|
5550
|
-
|
|
5551
|
-
|
|
5552
|
-
|
|
6167
|
+
return CHROMIUM_CANDIDATES.find((path) => existsSync(path));
|
|
6168
|
+
}
|
|
6169
|
+
var browserPool = /* @__PURE__ */ new Map();
|
|
6170
|
+
var sharedCdpProxy = null;
|
|
6171
|
+
function getSharedCdpProxy() {
|
|
6172
|
+
return sharedCdpProxy;
|
|
6173
|
+
}
|
|
6174
|
+
function setSharedCdpProxy(proxy) {
|
|
6175
|
+
sharedCdpProxy = proxy;
|
|
5553
6176
|
}
|
|
5554
|
-
var _browserPool = /* @__PURE__ */ new Map();
|
|
5555
6177
|
async function createBrowser(options) {
|
|
5556
6178
|
if (options?.cdpEndpoint) {
|
|
5557
6179
|
const realEndpoint = await resolveCDPEndpoint(options.cdpEndpoint);
|
|
5558
6180
|
if (!options.intercept) {
|
|
5559
|
-
const pooled =
|
|
5560
|
-
if (pooled && !pooled.disconnected)
|
|
5561
|
-
|
|
5562
|
-
}
|
|
5563
|
-
if (pooled) _browserPool.delete(realEndpoint);
|
|
6181
|
+
const pooled = browserPool.get(realEndpoint);
|
|
6182
|
+
if (pooled && !pooled.disconnected) return pooled;
|
|
6183
|
+
if (pooled) browserPool.delete(realEndpoint);
|
|
5564
6184
|
}
|
|
5565
6185
|
if (options.intercept) {
|
|
5566
6186
|
const config = typeof options.intercept === "object" ? { ...options.intercept, cdpEndpoint: realEndpoint } : { cdpEndpoint: realEndpoint };
|
|
5567
|
-
|
|
5568
|
-
const proxyPort = await
|
|
6187
|
+
sharedCdpProxy = new CDPInterceptorProxy(config);
|
|
6188
|
+
const proxyPort = await sharedCdpProxy.start();
|
|
5569
6189
|
console.error(`[CDP Interceptor] Proxy running on ws://localhost:${proxyPort}, forwarding to ${realEndpoint}`);
|
|
5570
6190
|
const { browser: browser3 } = await launch({ cdpEndpoint: `ws://localhost:${proxyPort}` });
|
|
5571
6191
|
return browser3;
|
|
5572
6192
|
}
|
|
5573
6193
|
const { browser: browser2 } = await launch({ cdpEndpoint: realEndpoint });
|
|
5574
|
-
await browser2.discoverContexts().catch((
|
|
5575
|
-
console.error(`[browser] discoverContexts failed: ${errMsg(
|
|
6194
|
+
await browser2.discoverContexts().catch((error) => {
|
|
6195
|
+
console.error(`[browser] discoverContexts failed: ${errMsg(error)}`);
|
|
5576
6196
|
});
|
|
5577
|
-
|
|
6197
|
+
browserPool.set(realEndpoint, browser2);
|
|
5578
6198
|
return browser2;
|
|
5579
6199
|
}
|
|
5580
6200
|
const executablePath = options?.executablePath || process.env.XBROWSER_CHROMIUM_PATH || discoverChromiumPath();
|
|
5581
6201
|
const { browser } = await launch({ executablePath, headless: options?.headless ?? true });
|
|
5582
6202
|
return browser;
|
|
5583
6203
|
}
|
|
5584
|
-
|
|
5585
|
-
|
|
5586
|
-
|
|
5587
|
-
|
|
5588
|
-
|
|
5589
|
-
|
|
5590
|
-
}
|
|
5591
|
-
|
|
5592
|
-
|
|
5593
|
-
}
|
|
5594
|
-
function
|
|
5595
|
-
return
|
|
6204
|
+
|
|
6205
|
+
// src/browser/state.ts
|
|
6206
|
+
import { randomUUID } from "crypto";
|
|
6207
|
+
import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync, readdirSync, unlinkSync, writeFileSync } from "fs";
|
|
6208
|
+
import { join as join2 } from "path";
|
|
6209
|
+
import { homedir } from "os";
|
|
6210
|
+
import { SessionStore } from "@dyyz1993/xcli-core";
|
|
6211
|
+
var SESSION_DIR = join2(homedir(), ".xbrowser", "sessions");
|
|
6212
|
+
var sessions = new SessionStore();
|
|
6213
|
+
var sharedState = { browser: null, idleTimer: null };
|
|
6214
|
+
function sessionFile(name) {
|
|
6215
|
+
return join2(SESSION_DIR, `${name}.json`);
|
|
5596
6216
|
}
|
|
5597
|
-
function
|
|
5598
|
-
|
|
5599
|
-
session.lastActivityAt = Date.now();
|
|
6217
|
+
function ensureSessionDir() {
|
|
6218
|
+
mkdirSync2(SESSION_DIR, { recursive: true });
|
|
5600
6219
|
}
|
|
5601
6220
|
function saveSessionDiskMeta(name, data) {
|
|
5602
6221
|
ensureSessionDir();
|
|
@@ -5610,20 +6229,40 @@ function saveSessionDiskMeta(name, data) {
|
|
|
5610
6229
|
writeFileSync(file, JSON.stringify(existing, null, 2));
|
|
5611
6230
|
}
|
|
5612
6231
|
function readSessionDiskMeta(name) {
|
|
5613
|
-
const file = sessionFile(name);
|
|
5614
6232
|
try {
|
|
5615
|
-
return JSON.parse(readFileSync(
|
|
6233
|
+
return JSON.parse(readFileSync(sessionFile(name), "utf8"));
|
|
5616
6234
|
} catch {
|
|
5617
6235
|
return null;
|
|
5618
6236
|
}
|
|
5619
6237
|
}
|
|
5620
6238
|
function deleteSessionDiskMeta(name) {
|
|
5621
|
-
const file = sessionFile(name);
|
|
5622
6239
|
try {
|
|
5623
|
-
unlinkSync(
|
|
6240
|
+
unlinkSync(sessionFile(name));
|
|
5624
6241
|
} catch {
|
|
5625
6242
|
}
|
|
5626
6243
|
}
|
|
6244
|
+
function newSessionId() {
|
|
6245
|
+
return randomUUID();
|
|
6246
|
+
}
|
|
6247
|
+
|
|
6248
|
+
// src/browser/lifecycle.ts
|
|
6249
|
+
function registerSession(session) {
|
|
6250
|
+
const complete = {
|
|
6251
|
+
id: session.id ?? newSessionId(),
|
|
6252
|
+
createdAt: session.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
6253
|
+
lastActivityAt: session.lastActivityAt ?? Date.now(),
|
|
6254
|
+
...session
|
|
6255
|
+
};
|
|
6256
|
+
sessions.set(complete);
|
|
6257
|
+
resetIdleTimer();
|
|
6258
|
+
return complete;
|
|
6259
|
+
}
|
|
6260
|
+
|
|
6261
|
+
// src/browser/restore.ts
|
|
6262
|
+
function logSessionEvent(event, details) {
|
|
6263
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
|
|
6264
|
+
console.error(`[SESSION] ${timestamp} [PID:${process.pid}] ${event} | ${details}`);
|
|
6265
|
+
}
|
|
5627
6266
|
async function isSessionPageAlive(session) {
|
|
5628
6267
|
const page = session.page;
|
|
5629
6268
|
if (!page || typeof page.evaluate !== "function") return false;
|
|
@@ -5635,69 +6274,65 @@ async function isSessionPageAlive(session) {
|
|
|
5635
6274
|
]);
|
|
5636
6275
|
return true;
|
|
5637
6276
|
} catch {
|
|
5638
|
-
await new Promise((
|
|
6277
|
+
await new Promise((resolve) => setTimeout(resolve, 400));
|
|
5639
6278
|
}
|
|
5640
6279
|
}
|
|
5641
6280
|
return false;
|
|
5642
6281
|
}
|
|
5643
|
-
async function findOrRestoreSession(name, cdpEndpoint) {
|
|
5644
|
-
|
|
5645
|
-
|
|
5646
|
-
|
|
5647
|
-
|
|
6282
|
+
async function findOrRestoreSession(name, cdpEndpoint, cleanup = async () => false, installNetworkCapture2 = async () => {
|
|
6283
|
+
}) {
|
|
6284
|
+
const inMemory = findSession(name);
|
|
6285
|
+
if (inMemory) {
|
|
6286
|
+
if (await isSessionPageAlive(inMemory)) return inMemory;
|
|
6287
|
+
logSessionEvent("stale_session", `name="${name}" \u2014 page probe failed; rebuilding`);
|
|
5648
6288
|
try {
|
|
5649
|
-
await
|
|
6289
|
+
await cleanup(name);
|
|
5650
6290
|
} catch {
|
|
5651
6291
|
}
|
|
5652
6292
|
}
|
|
5653
6293
|
const meta = readSessionDiskMeta(name);
|
|
5654
6294
|
if (!meta) return void 0;
|
|
5655
|
-
const
|
|
5656
|
-
if (!
|
|
6295
|
+
const endpoint = cdpEndpoint || meta.cdpEndpoint;
|
|
6296
|
+
if (!endpoint) return void 0;
|
|
5657
6297
|
try {
|
|
5658
|
-
const
|
|
5659
|
-
await new Promise((
|
|
5660
|
-
let contexts =
|
|
6298
|
+
const browser = await createBrowser({ cdpEndpoint: endpoint });
|
|
6299
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
6300
|
+
let contexts = browser.contexts();
|
|
5661
6301
|
if (contexts.length === 0) {
|
|
5662
|
-
await new Promise((
|
|
5663
|
-
contexts =
|
|
6302
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
6303
|
+
contexts = browser.contexts();
|
|
5664
6304
|
}
|
|
5665
|
-
const context = contexts[0] || await
|
|
6305
|
+
const context = contexts[0] || await browser.newContext();
|
|
5666
6306
|
const savedUrl = meta.conversationUrl || meta.url;
|
|
5667
|
-
|
|
6307
|
+
let targetHostname = "";
|
|
6308
|
+
if (savedUrl) {
|
|
5668
6309
|
try {
|
|
5669
|
-
|
|
6310
|
+
targetHostname = new URL(savedUrl).hostname;
|
|
5670
6311
|
} catch {
|
|
5671
|
-
|
|
6312
|
+
targetHostname = "";
|
|
5672
6313
|
}
|
|
5673
|
-
}
|
|
6314
|
+
}
|
|
5674
6315
|
let page = null;
|
|
5675
6316
|
let fallbackPage = null;
|
|
5676
|
-
for (const
|
|
5677
|
-
const
|
|
5678
|
-
|
|
5679
|
-
|
|
5680
|
-
if (
|
|
5681
|
-
|
|
5682
|
-
|
|
5683
|
-
break;
|
|
5684
|
-
}
|
|
5685
|
-
if (!fallbackPage) {
|
|
5686
|
-
fallbackPage = p;
|
|
5687
|
-
}
|
|
6317
|
+
for (const browserContext of contexts) {
|
|
6318
|
+
for (const candidate of browserContext.pages()) {
|
|
6319
|
+
const url = candidate.url();
|
|
6320
|
+
if (!url || url === "about:blank" || url.startsWith("chrome://") || url.startsWith("chrome-untrusted://") || url.startsWith("chrome-error://")) continue;
|
|
6321
|
+
if (targetHostname && url.includes(targetHostname)) {
|
|
6322
|
+
page = candidate;
|
|
6323
|
+
break;
|
|
5688
6324
|
}
|
|
6325
|
+
fallbackPage ??= candidate;
|
|
5689
6326
|
}
|
|
5690
6327
|
if (page) break;
|
|
5691
6328
|
}
|
|
5692
|
-
page
|
|
6329
|
+
page ??= fallbackPage;
|
|
5693
6330
|
if (!page) {
|
|
5694
|
-
const targets = await getCDPTargets2(
|
|
5695
|
-
const
|
|
5696
|
-
|
|
5697
|
-
);
|
|
5698
|
-
if (matchTarget && matchTarget.url) {
|
|
6331
|
+
const targets = await getCDPTargets2(endpoint);
|
|
6332
|
+
const match = targets.find((target) => target.url && target.url !== "about:blank" && !target.url.startsWith("chrome://") && !target.url.startsWith("chrome-untrusted://") && !target.url.startsWith("chrome-error://") && (!targetHostname || target.url.includes(targetHostname)));
|
|
6333
|
+
if (match?.url) {
|
|
5699
6334
|
page = await context.newPage();
|
|
5700
|
-
await page.goto(
|
|
6335
|
+
await page.goto(match.url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
|
|
5701
6336
|
});
|
|
5702
6337
|
}
|
|
5703
6338
|
}
|
|
@@ -5711,7 +6346,6 @@ async function findOrRestoreSession(name, cdpEndpoint) {
|
|
|
5711
6346
|
new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 3e3))
|
|
5712
6347
|
]);
|
|
5713
6348
|
} catch {
|
|
5714
|
-
console.log(`[Session] "${name}" restored page unresponsive, creating fresh session`);
|
|
5715
6349
|
deleteSessionDiskMeta(name);
|
|
5716
6350
|
return void 0;
|
|
5717
6351
|
}
|
|
@@ -5726,191 +6360,41 @@ async function findOrRestoreSession(name, cdpEndpoint) {
|
|
|
5726
6360
|
}
|
|
5727
6361
|
}
|
|
5728
6362
|
const session = {
|
|
5729
|
-
id: meta.id
|
|
6363
|
+
id: meta.id,
|
|
5730
6364
|
name,
|
|
5731
6365
|
context,
|
|
5732
6366
|
page,
|
|
5733
|
-
browser
|
|
5734
|
-
createdAt: meta.createdAt
|
|
6367
|
+
browser,
|
|
6368
|
+
createdAt: meta.createdAt,
|
|
5735
6369
|
lastActivityAt: Date.now(),
|
|
5736
6370
|
isCDP: true,
|
|
5737
|
-
cdpEndpoint:
|
|
6371
|
+
cdpEndpoint: endpoint
|
|
5738
6372
|
};
|
|
5739
|
-
for (const
|
|
5740
|
-
if (
|
|
5741
|
-
logSessionEvent("remove_stale", `Removing stale session name="${name}" id="${existingSession.id}" during restore`);
|
|
5742
|
-
sessions.removeById(existingSession.id);
|
|
5743
|
-
}
|
|
6373
|
+
for (const existing of sessions.list()) {
|
|
6374
|
+
if (existing.name === name) sessions.removeById(existing.id);
|
|
5744
6375
|
}
|
|
5745
6376
|
sessions.set(session);
|
|
5746
|
-
|
|
5747
|
-
await installNetworkCapture(page, name);
|
|
6377
|
+
await installNetworkCapture2(session.page, name);
|
|
5748
6378
|
return session;
|
|
5749
|
-
} catch (
|
|
5750
|
-
console.error(`[Session Restore] Failed for "${name}":`, errMsg(
|
|
6379
|
+
} catch (error) {
|
|
6380
|
+
console.error(`[Session Restore] Failed for "${name}":`, errMsg(error));
|
|
5751
6381
|
deleteSessionDiskMeta(name);
|
|
5752
6382
|
return void 0;
|
|
5753
6383
|
}
|
|
5754
6384
|
}
|
|
5755
|
-
|
|
5756
|
-
|
|
5757
|
-
|
|
5758
|
-
const { browser: b2 } = await launch({ cdpEndpoint: endpoint });
|
|
5759
|
-
const contexts = b2.contexts();
|
|
5760
|
-
const ctx = contexts[0] || await b2.newContext();
|
|
5761
|
-
const allPages = ctx.pages();
|
|
5762
|
-
const existingPages = allPages.filter((p) => {
|
|
5763
|
-
const url = p.url();
|
|
5764
|
-
return url !== "about:blank" && !url.startsWith("chrome://") && !url.startsWith("chrome-untrusted://") && !url.startsWith("chrome-error://");
|
|
5765
|
-
});
|
|
5766
|
-
const page2 = existingPages.length > 0 ? existingPages[0] : allPages.length > 0 ? allPages[0] : await ctx.newPage();
|
|
5767
|
-
resetIdleTimer();
|
|
5768
|
-
ephemeralConnections.set(page2, b2);
|
|
5769
|
-
return { context: ctx, page: page2 };
|
|
5770
|
-
}
|
|
5771
|
-
const b = await getBrowser(options);
|
|
5772
|
-
const context = await b.newContext();
|
|
5773
|
-
const page = await context.newPage();
|
|
5774
|
-
resetIdleTimer();
|
|
5775
|
-
return { context, page };
|
|
5776
|
-
}
|
|
5777
|
-
var ephemeralConnections = /* @__PURE__ */ new WeakMap();
|
|
5778
|
-
async function closeEphemeralContext(context) {
|
|
5779
|
-
try {
|
|
5780
|
-
const pages = context.pages();
|
|
5781
|
-
for (const p of pages) {
|
|
5782
|
-
const conn = ephemeralConnections.get(p);
|
|
5783
|
-
if (conn) {
|
|
5784
|
-
ephemeralConnections.delete(p);
|
|
5785
|
-
await conn.close();
|
|
5786
|
-
break;
|
|
5787
|
-
}
|
|
5788
|
-
}
|
|
5789
|
-
await context.close();
|
|
5790
|
-
} catch {
|
|
5791
|
-
}
|
|
5792
|
-
if (sessions.size === 0 && idleTimer) {
|
|
5793
|
-
clearTimeout(idleTimer);
|
|
5794
|
-
idleTimer = null;
|
|
5795
|
-
}
|
|
5796
|
-
}
|
|
5797
|
-
function getAllSessions() {
|
|
5798
|
-
return sessions.list();
|
|
5799
|
-
}
|
|
5800
|
-
async function installNetworkCapture(page, sessionName) {
|
|
5801
|
-
if (process.env.XBROWSER_DAEMON_WORKER !== "1") return;
|
|
5802
|
-
const { networkStore } = await import("./network-store-YVDNUREI.js");
|
|
5803
|
-
const requestData = /* @__PURE__ */ new Map();
|
|
5804
|
-
const responseMeta = /* @__PURE__ */ new Map();
|
|
5805
|
-
const xbPage = page;
|
|
5806
|
-
xbPage.on("request", (params) => {
|
|
5807
|
-
try {
|
|
5808
|
-
const p = params;
|
|
5809
|
-
requestData.set(p.requestId, {
|
|
5810
|
-
method: p.request.method,
|
|
5811
|
-
headers: p.request.headers,
|
|
5812
|
-
postData: p.request.postData ?? null,
|
|
5813
|
-
resourceType: p.type
|
|
5814
|
-
});
|
|
5815
|
-
} catch {
|
|
5816
|
-
}
|
|
5817
|
-
});
|
|
5818
|
-
xbPage.on("response", (params) => {
|
|
5819
|
-
try {
|
|
5820
|
-
const p = params;
|
|
5821
|
-
responseMeta.set(p.requestId, {
|
|
5822
|
-
status: p.response.status,
|
|
5823
|
-
url: p.response.url,
|
|
5824
|
-
headers: p.response.headers,
|
|
5825
|
-
mimeType: p.response.mimeType,
|
|
5826
|
-
type: p.type
|
|
5827
|
-
});
|
|
5828
|
-
} catch {
|
|
5829
|
-
}
|
|
5830
|
-
});
|
|
5831
|
-
xbPage.on("requestfinished", async (params) => {
|
|
5832
|
-
try {
|
|
5833
|
-
const p = params;
|
|
5834
|
-
const meta = responseMeta.get(p.requestId);
|
|
5835
|
-
if (!meta) return;
|
|
5836
|
-
const req = requestData.get(p.requestId);
|
|
5837
|
-
const method = req?.method ?? "GET";
|
|
5838
|
-
const contentType = meta.headers["content-type"] || meta.headers["Content-Type"] || "";
|
|
5839
|
-
const resourceType = req?.resourceType ?? meta.type;
|
|
5840
|
-
const requestHeaders = req?.headers ?? {};
|
|
5841
|
-
let requestBody = void 0;
|
|
5842
|
-
const isPostLike = ["POST", "PATCH", "PUT"].includes(method);
|
|
5843
|
-
if (isPostLike && requestHeaders["content-type"]?.includes("application/json")) {
|
|
5844
|
-
const postData = req?.postData;
|
|
5845
|
-
if (postData) {
|
|
5846
|
-
try {
|
|
5847
|
-
requestBody = JSON.parse(postData);
|
|
5848
|
-
} catch {
|
|
5849
|
-
requestBody = postData;
|
|
5850
|
-
}
|
|
5851
|
-
}
|
|
5852
|
-
}
|
|
5853
|
-
let responseBody = void 0;
|
|
5854
|
-
let size = 0;
|
|
5855
|
-
const isJsonish = contentType.includes("json") || contentType.includes("javascript") || contentType.includes("text/");
|
|
5856
|
-
if (isJsonish) {
|
|
5857
|
-
try {
|
|
5858
|
-
const bodyResult = await xbPage._cdpSend(
|
|
5859
|
-
"Network.getResponseBody",
|
|
5860
|
-
{ requestId: p.requestId }
|
|
5861
|
-
);
|
|
5862
|
-
const text = bodyResult.body ?? "";
|
|
5863
|
-
size = text.length;
|
|
5864
|
-
if (size <= 10240) {
|
|
5865
|
-
try {
|
|
5866
|
-
responseBody = JSON.parse(text);
|
|
5867
|
-
} catch {
|
|
5868
|
-
responseBody = text.slice(0, 200);
|
|
5869
|
-
}
|
|
5870
|
-
}
|
|
5871
|
-
} catch {
|
|
5872
|
-
}
|
|
5873
|
-
} else {
|
|
5874
|
-
try {
|
|
5875
|
-
const bodyResult = await xbPage._cdpSend(
|
|
5876
|
-
"Network.getResponseBody",
|
|
5877
|
-
{ requestId: p.requestId }
|
|
5878
|
-
);
|
|
5879
|
-
size = bodyResult.body?.length ?? 0;
|
|
5880
|
-
} catch {
|
|
5881
|
-
size = 0;
|
|
5882
|
-
}
|
|
5883
|
-
}
|
|
5884
|
-
networkStore.add(sessionName, {
|
|
5885
|
-
timestamp: Date.now(),
|
|
5886
|
-
method,
|
|
5887
|
-
url: meta.url,
|
|
5888
|
-
path: new URL(meta.url).pathname,
|
|
5889
|
-
status: meta.status,
|
|
5890
|
-
contentType,
|
|
5891
|
-
size,
|
|
5892
|
-
headers: meta.headers,
|
|
5893
|
-
body: responseBody,
|
|
5894
|
-
requestHeaders,
|
|
5895
|
-
requestBody,
|
|
5896
|
-
resourceType
|
|
5897
|
-
});
|
|
5898
|
-
requestData.delete(p.requestId);
|
|
5899
|
-
responseMeta.delete(p.requestId);
|
|
5900
|
-
} catch {
|
|
5901
|
-
}
|
|
5902
|
-
});
|
|
5903
|
-
}
|
|
5904
|
-
async function createSession(name, url, options) {
|
|
6385
|
+
|
|
6386
|
+
// src/browser/create-session.ts
|
|
6387
|
+
async function createSessionImpl(name, url, options, deps) {
|
|
5905
6388
|
const existing = findSession(name);
|
|
5906
6389
|
if (existing) {
|
|
5907
|
-
logSessionEvent("replace_session", `name="${name}" id="${existing.id}" \u2014 closing existing session before creating new one`);
|
|
5908
|
-
await closeSessionByName(name);
|
|
6390
|
+
deps.logSessionEvent("replace_session", `name="${name}" id="${existing.id}" \u2014 closing existing session before creating new one`);
|
|
6391
|
+
await deps.closeSessionByName(name);
|
|
5909
6392
|
}
|
|
5910
6393
|
const b = await createBrowser(options);
|
|
5911
6394
|
const isCDP = !!options?.cdpEndpoint;
|
|
5912
6395
|
let context;
|
|
5913
6396
|
let page;
|
|
6397
|
+
let reusedExistingPage = false;
|
|
5914
6398
|
if (isCDP) {
|
|
5915
6399
|
const targetHostname = url ? (() => {
|
|
5916
6400
|
try {
|
|
@@ -5992,22 +6476,12 @@ async function createSession(name, url, options) {
|
|
|
5992
6476
|
const pUrl0 = await resolvePageUrl(p);
|
|
5993
6477
|
if (ownedUrls.has(pUrl0)) continue;
|
|
5994
6478
|
const pUrl = pUrl0;
|
|
5995
|
-
|
|
5996
|
-
|
|
5997
|
-
|
|
6479
|
+
let hostnameMatches = false;
|
|
6480
|
+
try {
|
|
6481
|
+
hostnameMatches = new URL(pUrl).hostname === targetHostname;
|
|
6482
|
+
} catch {
|
|
5998
6483
|
}
|
|
5999
|
-
|
|
6000
|
-
if (targetPage) break;
|
|
6001
|
-
}
|
|
6002
|
-
}
|
|
6003
|
-
if (!targetPage) {
|
|
6004
|
-
for (const ctx of contexts) {
|
|
6005
|
-
const pages = ctx.pages();
|
|
6006
|
-
for (const p of pages) {
|
|
6007
|
-
const pUrl0 = await resolvePageUrl(p);
|
|
6008
|
-
if (ownedUrls.has(pUrl0)) continue;
|
|
6009
|
-
const pUrl = pUrl0;
|
|
6010
|
-
if (isRealPageUrl(pUrl)) {
|
|
6484
|
+
if (isRealPageUrl(pUrl) && hostnameMatches) {
|
|
6011
6485
|
targetPage = p;
|
|
6012
6486
|
break;
|
|
6013
6487
|
}
|
|
@@ -6016,7 +6490,7 @@ async function createSession(name, url, options) {
|
|
|
6016
6490
|
}
|
|
6017
6491
|
}
|
|
6018
6492
|
if (!targetPage && options?.cdpEndpoint) {
|
|
6019
|
-
const targets = await
|
|
6493
|
+
const targets = await deps.getCDPTargets(options.cdpEndpoint);
|
|
6020
6494
|
const ownedUrlsT = /* @__PURE__ */ new Set();
|
|
6021
6495
|
for (const ssn of sessions.list()) {
|
|
6022
6496
|
try {
|
|
@@ -6025,9 +6499,15 @@ async function createSession(name, url, options) {
|
|
|
6025
6499
|
} catch {
|
|
6026
6500
|
}
|
|
6027
6501
|
}
|
|
6028
|
-
const matchTarget = targets.find(
|
|
6029
|
-
(
|
|
6030
|
-
|
|
6502
|
+
const matchTarget = targets.find((t) => {
|
|
6503
|
+
if (!t.url || !isRealPageUrl(t.url) || ownedUrlsT.has(t.url)) return false;
|
|
6504
|
+
if (!url) return false;
|
|
6505
|
+
try {
|
|
6506
|
+
return new URL(t.url).hostname === targetHostname;
|
|
6507
|
+
} catch {
|
|
6508
|
+
return false;
|
|
6509
|
+
}
|
|
6510
|
+
});
|
|
6031
6511
|
if (matchTarget && matchTarget.url) {
|
|
6032
6512
|
const ownedUrls2 = /* @__PURE__ */ new Set();
|
|
6033
6513
|
for (const ssn of sessions.list()) {
|
|
@@ -6060,31 +6540,12 @@ async function createSession(name, url, options) {
|
|
|
6060
6540
|
}
|
|
6061
6541
|
}
|
|
6062
6542
|
}
|
|
6543
|
+
const targetPageExisted = !!targetPage;
|
|
6063
6544
|
if (!targetPage) {
|
|
6064
|
-
|
|
6065
|
-
if (pages.length > 1) {
|
|
6066
|
-
try {
|
|
6067
|
-
const owned = /* @__PURE__ */ new Set();
|
|
6068
|
-
for (const ssn of sessions.list()) owned.add(ssn.page);
|
|
6069
|
-
for (const p of pages) {
|
|
6070
|
-
if (owned.has(p)) continue;
|
|
6071
|
-
const vis = await p.evaluate("document.visibilityState").catch(() => "hidden");
|
|
6072
|
-
if (vis === "visible") {
|
|
6073
|
-
targetPage = p;
|
|
6074
|
-
break;
|
|
6075
|
-
}
|
|
6076
|
-
}
|
|
6077
|
-
} catch {
|
|
6078
|
-
}
|
|
6079
|
-
}
|
|
6080
|
-
if (!targetPage && pages.length > 0) {
|
|
6081
|
-
targetPage = pages[0];
|
|
6082
|
-
}
|
|
6083
|
-
if (!targetPage) {
|
|
6084
|
-
targetPage = await context.newPage();
|
|
6085
|
-
}
|
|
6545
|
+
targetPage = await context.newPage();
|
|
6086
6546
|
}
|
|
6087
6547
|
page = targetPage;
|
|
6548
|
+
reusedExistingPage = targetPageExisted;
|
|
6088
6549
|
if (isCDP) {
|
|
6089
6550
|
await Promise.resolve(targetPage.bringToFront?.()).catch(() => {
|
|
6090
6551
|
});
|
|
@@ -6097,30 +6558,280 @@ async function createSession(name, url, options) {
|
|
|
6097
6558
|
await page.goto(url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
|
|
6098
6559
|
});
|
|
6099
6560
|
}
|
|
6100
|
-
const session = {
|
|
6101
|
-
id: randomUUID(),
|
|
6561
|
+
const session = deps.registerSession({
|
|
6102
6562
|
name,
|
|
6103
6563
|
context,
|
|
6104
6564
|
page,
|
|
6105
6565
|
browser: b,
|
|
6106
|
-
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
6107
|
-
lastActivityAt: Date.now(),
|
|
6108
6566
|
isCDP,
|
|
6109
|
-
cdpEndpoint: options?.cdpEndpoint
|
|
6110
|
-
|
|
6111
|
-
|
|
6112
|
-
logSessionEvent("create_session", `name="${name}" id="${session.id}" url="${url || "(no url)"}" isCDP=${isCDP} cdpEndpoint=${options?.cdpEndpoint || "(none)"}`);
|
|
6113
|
-
|
|
6114
|
-
await installNetworkCapture(page, name);
|
|
6567
|
+
cdpEndpoint: options?.cdpEndpoint,
|
|
6568
|
+
...isCDP ? { reusedExistingPage } : {}
|
|
6569
|
+
});
|
|
6570
|
+
deps.logSessionEvent("create_session", `name="${name}" id="${session.id}" url="${url || "(no url)"}" isCDP=${isCDP} cdpEndpoint=${options?.cdpEndpoint || "(none)"}`);
|
|
6571
|
+
await deps.installNetworkCapture(page, name);
|
|
6115
6572
|
return session;
|
|
6116
6573
|
}
|
|
6574
|
+
|
|
6575
|
+
// src/browser.ts
|
|
6576
|
+
function logSessionEvent2(event, details) {
|
|
6577
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
|
|
6578
|
+
console.error(`[SESSION] ${timestamp} [PID:${process.pid}] ${event} | ${details}`);
|
|
6579
|
+
}
|
|
6580
|
+
var IDLE_TIMEOUT_MS = (process.env.XBROWSER_IDLE_TIMEOUT ? parseInt(process.env.XBROWSER_IDLE_TIMEOUT, 10) : 30) * 60 * 1e3;
|
|
6581
|
+
function resetIdleTimer() {
|
|
6582
|
+
if (sharedState.idleTimer) clearTimeout(sharedState.idleTimer);
|
|
6583
|
+
sharedState.idleTimer = setTimeout(async () => {
|
|
6584
|
+
const now = Date.now();
|
|
6585
|
+
let allIdle = true;
|
|
6586
|
+
const idleSessions = [];
|
|
6587
|
+
for (const s of sessions) {
|
|
6588
|
+
if (now - s.lastActivityAt < IDLE_TIMEOUT_MS) {
|
|
6589
|
+
allIdle = false;
|
|
6590
|
+
} else {
|
|
6591
|
+
idleSessions.push(`${s.name}(${(now - s.lastActivityAt) / 1e3}s idle)`);
|
|
6592
|
+
}
|
|
6593
|
+
}
|
|
6594
|
+
if (allIdle && (sessions.size > 0 || sharedState.browser)) {
|
|
6595
|
+
logSessionEvent2("idle_timeout", `Sessions idle for >${IDLE_TIMEOUT_MS / 6e4}min. Sessions: ${idleSessions.join(", ") || "all"}. Calling destroyBrowser()`);
|
|
6596
|
+
await destroyBrowser().catch(() => {
|
|
6597
|
+
});
|
|
6598
|
+
}
|
|
6599
|
+
}, IDLE_TIMEOUT_MS);
|
|
6600
|
+
if (sharedState.idleTimer && typeof sharedState.idleTimer.unref === "function") {
|
|
6601
|
+
sharedState.idleTimer.unref();
|
|
6602
|
+
}
|
|
6603
|
+
}
|
|
6604
|
+
async function findOrRestoreSession2(name, cdpEndpoint) {
|
|
6605
|
+
return findOrRestoreSession(
|
|
6606
|
+
name,
|
|
6607
|
+
cdpEndpoint,
|
|
6608
|
+
closeSessionByName,
|
|
6609
|
+
installNetworkCapture
|
|
6610
|
+
);
|
|
6611
|
+
}
|
|
6612
|
+
function touchSession(id) {
|
|
6613
|
+
const s = sessions.get(id);
|
|
6614
|
+
if (s) s.lastActivityAt = Date.now();
|
|
6615
|
+
resetIdleTimer();
|
|
6616
|
+
}
|
|
6617
|
+
process.on("exit", () => {
|
|
6618
|
+
for (const session of sessions.list()) {
|
|
6619
|
+
if (session.isCDP) {
|
|
6620
|
+
logSessionEvent2("process_exit", `Session "${session.name}": CDP connection (not closing external browser).`);
|
|
6621
|
+
} else {
|
|
6622
|
+
logSessionEvent2("process_exit", `Session "${session.name}": Closing self-launched browser.`);
|
|
6623
|
+
try {
|
|
6624
|
+
session.browser?.close();
|
|
6625
|
+
} catch {
|
|
6626
|
+
}
|
|
6627
|
+
}
|
|
6628
|
+
}
|
|
6629
|
+
if (sharedState.browser) {
|
|
6630
|
+
logSessionEvent2("process_exit", "Closing shared browser (self-launched only, external CDP is safe).");
|
|
6631
|
+
try {
|
|
6632
|
+
sharedState.browser.close();
|
|
6633
|
+
} catch {
|
|
6634
|
+
}
|
|
6635
|
+
sharedState.browser = null;
|
|
6636
|
+
}
|
|
6637
|
+
const cdpProxy = getSharedCdpProxy();
|
|
6638
|
+
if (cdpProxy) {
|
|
6639
|
+
try {
|
|
6640
|
+
cdpProxy.stop();
|
|
6641
|
+
} catch {
|
|
6642
|
+
}
|
|
6643
|
+
setSharedCdpProxy(null);
|
|
6644
|
+
}
|
|
6645
|
+
sessions.clear();
|
|
6646
|
+
});
|
|
6647
|
+
async function getBrowser(options) {
|
|
6648
|
+
if (sharedState.browser) return sharedState.browser;
|
|
6649
|
+
sharedState.browser = await createBrowser(options);
|
|
6650
|
+
if (options?.cdpEndpoint && options.intercept) {
|
|
6651
|
+
}
|
|
6652
|
+
return sharedState.browser;
|
|
6653
|
+
}
|
|
6654
|
+
function findSession(name) {
|
|
6655
|
+
return sessions.find(name);
|
|
6656
|
+
}
|
|
6657
|
+
function getSessionById2(id) {
|
|
6658
|
+
return sessions.get(id);
|
|
6659
|
+
}
|
|
6660
|
+
function setActivePage2(session, page) {
|
|
6661
|
+
session.page = page;
|
|
6662
|
+
session.lastActivityAt = Date.now();
|
|
6663
|
+
}
|
|
6664
|
+
async function createEphemeralContext(options) {
|
|
6665
|
+
if (options?.cdpEndpoint) {
|
|
6666
|
+
const endpoint = await resolveCDPEndpoint(options.cdpEndpoint);
|
|
6667
|
+
const { browser: b2 } = await launch({ cdpEndpoint: endpoint });
|
|
6668
|
+
const contexts = b2.contexts();
|
|
6669
|
+
const ctx = contexts[0] || await b2.newContext();
|
|
6670
|
+
const allPages = ctx.pages();
|
|
6671
|
+
const existingPages = allPages.filter((p) => {
|
|
6672
|
+
const url = p.url();
|
|
6673
|
+
return url !== "about:blank" && !url.startsWith("chrome://") && !url.startsWith("chrome-untrusted://") && !url.startsWith("chrome-error://");
|
|
6674
|
+
});
|
|
6675
|
+
const page2 = existingPages.length > 0 ? existingPages[0] : allPages.length > 0 ? allPages[0] : await ctx.newPage();
|
|
6676
|
+
resetIdleTimer();
|
|
6677
|
+
ephemeralConnections.set(page2, b2);
|
|
6678
|
+
return { context: ctx, page: page2 };
|
|
6679
|
+
}
|
|
6680
|
+
const b = await getBrowser(options);
|
|
6681
|
+
const context = await b.newContext();
|
|
6682
|
+
const page = await context.newPage();
|
|
6683
|
+
resetIdleTimer();
|
|
6684
|
+
return { context, page };
|
|
6685
|
+
}
|
|
6686
|
+
var ephemeralConnections = /* @__PURE__ */ new WeakMap();
|
|
6687
|
+
async function closeEphemeralContext(context) {
|
|
6688
|
+
try {
|
|
6689
|
+
const pages = context.pages();
|
|
6690
|
+
for (const p of pages) {
|
|
6691
|
+
const conn = ephemeralConnections.get(p);
|
|
6692
|
+
if (conn) {
|
|
6693
|
+
ephemeralConnections.delete(p);
|
|
6694
|
+
await conn.close();
|
|
6695
|
+
break;
|
|
6696
|
+
}
|
|
6697
|
+
}
|
|
6698
|
+
await context.close();
|
|
6699
|
+
} catch {
|
|
6700
|
+
}
|
|
6701
|
+
if (sessions.size === 0 && sharedState.idleTimer) {
|
|
6702
|
+
clearTimeout(sharedState.idleTimer);
|
|
6703
|
+
sharedState.idleTimer = null;
|
|
6704
|
+
}
|
|
6705
|
+
}
|
|
6706
|
+
function getAllSessions2() {
|
|
6707
|
+
return sessions.list();
|
|
6708
|
+
}
|
|
6709
|
+
async function installNetworkCapture(page, sessionName) {
|
|
6710
|
+
if (process.env.XBROWSER_DAEMON_WORKER !== "1") return;
|
|
6711
|
+
const { networkStore } = await import("./network-store-YVDNUREI.js");
|
|
6712
|
+
const requestData = /* @__PURE__ */ new Map();
|
|
6713
|
+
const responseMeta = /* @__PURE__ */ new Map();
|
|
6714
|
+
const xbPage = page;
|
|
6715
|
+
xbPage.on("request", (params) => {
|
|
6716
|
+
try {
|
|
6717
|
+
const p = params;
|
|
6718
|
+
requestData.set(p.requestId, {
|
|
6719
|
+
method: p.request.method,
|
|
6720
|
+
headers: p.request.headers,
|
|
6721
|
+
postData: p.request.postData ?? null,
|
|
6722
|
+
resourceType: p.type
|
|
6723
|
+
});
|
|
6724
|
+
} catch {
|
|
6725
|
+
}
|
|
6726
|
+
});
|
|
6727
|
+
xbPage.on("response", (params) => {
|
|
6728
|
+
try {
|
|
6729
|
+
const p = params;
|
|
6730
|
+
responseMeta.set(p.requestId, {
|
|
6731
|
+
status: p.response.status,
|
|
6732
|
+
url: p.response.url,
|
|
6733
|
+
headers: p.response.headers,
|
|
6734
|
+
mimeType: p.response.mimeType,
|
|
6735
|
+
type: p.type
|
|
6736
|
+
});
|
|
6737
|
+
} catch {
|
|
6738
|
+
}
|
|
6739
|
+
});
|
|
6740
|
+
xbPage.on("requestfinished", async (params) => {
|
|
6741
|
+
try {
|
|
6742
|
+
const p = params;
|
|
6743
|
+
const meta = responseMeta.get(p.requestId);
|
|
6744
|
+
if (!meta) return;
|
|
6745
|
+
const req = requestData.get(p.requestId);
|
|
6746
|
+
const method = req?.method ?? "GET";
|
|
6747
|
+
const contentType = meta.headers["content-type"] || meta.headers["Content-Type"] || "";
|
|
6748
|
+
const resourceType = req?.resourceType ?? meta.type;
|
|
6749
|
+
const requestHeaders = req?.headers ?? {};
|
|
6750
|
+
let requestBody = void 0;
|
|
6751
|
+
const isPostLike = ["POST", "PATCH", "PUT"].includes(method);
|
|
6752
|
+
if (isPostLike && requestHeaders["content-type"]?.includes("application/json")) {
|
|
6753
|
+
const postData = req?.postData;
|
|
6754
|
+
if (postData) {
|
|
6755
|
+
try {
|
|
6756
|
+
requestBody = JSON.parse(postData);
|
|
6757
|
+
} catch {
|
|
6758
|
+
requestBody = postData;
|
|
6759
|
+
}
|
|
6760
|
+
}
|
|
6761
|
+
}
|
|
6762
|
+
let responseBody = void 0;
|
|
6763
|
+
let size = 0;
|
|
6764
|
+
const isJsonish = contentType.includes("json") || contentType.includes("javascript") || contentType.includes("text/");
|
|
6765
|
+
if (isJsonish) {
|
|
6766
|
+
try {
|
|
6767
|
+
const bodyResult = await xbPage._cdpSend(
|
|
6768
|
+
"Network.getResponseBody",
|
|
6769
|
+
{ requestId: p.requestId }
|
|
6770
|
+
);
|
|
6771
|
+
const text = bodyResult.body ?? "";
|
|
6772
|
+
size = text.length;
|
|
6773
|
+
if (size <= 10240) {
|
|
6774
|
+
try {
|
|
6775
|
+
responseBody = JSON.parse(text);
|
|
6776
|
+
} catch {
|
|
6777
|
+
responseBody = text.slice(0, 200);
|
|
6778
|
+
}
|
|
6779
|
+
}
|
|
6780
|
+
} catch {
|
|
6781
|
+
}
|
|
6782
|
+
} else {
|
|
6783
|
+
try {
|
|
6784
|
+
const bodyResult = await xbPage._cdpSend(
|
|
6785
|
+
"Network.getResponseBody",
|
|
6786
|
+
{ requestId: p.requestId }
|
|
6787
|
+
);
|
|
6788
|
+
size = bodyResult.body?.length ?? 0;
|
|
6789
|
+
} catch {
|
|
6790
|
+
size = 0;
|
|
6791
|
+
}
|
|
6792
|
+
}
|
|
6793
|
+
networkStore.add(sessionName, {
|
|
6794
|
+
timestamp: Date.now(),
|
|
6795
|
+
method,
|
|
6796
|
+
url: meta.url,
|
|
6797
|
+
path: new URL(meta.url).pathname,
|
|
6798
|
+
status: meta.status,
|
|
6799
|
+
contentType,
|
|
6800
|
+
size,
|
|
6801
|
+
headers: meta.headers,
|
|
6802
|
+
body: responseBody,
|
|
6803
|
+
requestHeaders,
|
|
6804
|
+
requestBody,
|
|
6805
|
+
resourceType
|
|
6806
|
+
});
|
|
6807
|
+
requestData.delete(p.requestId);
|
|
6808
|
+
responseMeta.delete(p.requestId);
|
|
6809
|
+
} catch {
|
|
6810
|
+
}
|
|
6811
|
+
});
|
|
6812
|
+
}
|
|
6813
|
+
async function createSession(name, url, options) {
|
|
6814
|
+
return createSessionImpl(name, url, options, {
|
|
6815
|
+
closeSessionByName,
|
|
6816
|
+
installNetworkCapture,
|
|
6817
|
+
registerSession,
|
|
6818
|
+
logSessionEvent: logSessionEvent2,
|
|
6819
|
+
getCDPTargets: getCDPTargets2
|
|
6820
|
+
});
|
|
6821
|
+
}
|
|
6117
6822
|
async function closeSessionByName(name) {
|
|
6118
6823
|
for (const session of sessions) {
|
|
6119
6824
|
if (session.name === name || session.id === name) {
|
|
6120
|
-
|
|
6825
|
+
logSessionEvent2("close_session", `name="${session.name}" id="${session.id}" url="${session.page.url()}"`);
|
|
6121
6826
|
if (session.isCDP) {
|
|
6122
|
-
if (session.
|
|
6123
|
-
|
|
6827
|
+
if (session.reusedExistingPage) {
|
|
6828
|
+
logSessionEvent2("close_session", `name="${session.name}" \u2014 reused existing tab, disconnecting only`);
|
|
6829
|
+
await session.browser.disconnect().catch(() => {
|
|
6830
|
+
});
|
|
6831
|
+
} else {
|
|
6832
|
+
await session.page.close().catch(() => {
|
|
6833
|
+
});
|
|
6834
|
+
await session.browser.disconnect().catch(() => {
|
|
6124
6835
|
});
|
|
6125
6836
|
}
|
|
6126
6837
|
} else {
|
|
@@ -6133,7 +6844,7 @@ async function closeSessionByName(name) {
|
|
|
6133
6844
|
sessions.removeById(session.id);
|
|
6134
6845
|
const file2 = sessionFile(session.name);
|
|
6135
6846
|
try {
|
|
6136
|
-
|
|
6847
|
+
unlinkSync2(file2);
|
|
6137
6848
|
} catch {
|
|
6138
6849
|
}
|
|
6139
6850
|
try {
|
|
@@ -6143,7 +6854,7 @@ async function closeSessionByName(name) {
|
|
|
6143
6854
|
} catch {
|
|
6144
6855
|
}
|
|
6145
6856
|
try {
|
|
6146
|
-
const { SessionRecorder } = await import("./session-recorder-
|
|
6857
|
+
const { SessionRecorder } = await import("./session-recorder-RUNQOJ7T.js");
|
|
6147
6858
|
SessionRecorder.cleanup(session.name);
|
|
6148
6859
|
} catch {
|
|
6149
6860
|
}
|
|
@@ -6152,14 +6863,14 @@ async function closeSessionByName(name) {
|
|
|
6152
6863
|
}
|
|
6153
6864
|
const file = sessionFile(name);
|
|
6154
6865
|
try {
|
|
6155
|
-
|
|
6866
|
+
unlinkSync2(file);
|
|
6156
6867
|
} catch {
|
|
6157
6868
|
}
|
|
6158
6869
|
return false;
|
|
6159
6870
|
}
|
|
6160
6871
|
async function closeAllSessions() {
|
|
6161
6872
|
const names = sessions.list().map((s) => `${s.name}(${s.page.url()})`).join(", ");
|
|
6162
|
-
if (names)
|
|
6873
|
+
if (names) logSessionEvent2("close_all_sessions", `Closing ${sessions.size} sessions: ${names}`);
|
|
6163
6874
|
for (const session of sessions.list()) {
|
|
6164
6875
|
try {
|
|
6165
6876
|
if (session.isCDP) {
|
|
@@ -6181,38 +6892,37 @@ async function closeAllSessions() {
|
|
|
6181
6892
|
}
|
|
6182
6893
|
}
|
|
6183
6894
|
async function destroyBrowser() {
|
|
6184
|
-
|
|
6185
|
-
if (idleTimer) {
|
|
6186
|
-
clearTimeout(idleTimer);
|
|
6187
|
-
idleTimer = null;
|
|
6895
|
+
logSessionEvent2("destroy_browser", `Sessions count: ${sessions.size}. Clearing idle timer and closing all sessions.`);
|
|
6896
|
+
if (sharedState.idleTimer) {
|
|
6897
|
+
clearTimeout(sharedState.idleTimer);
|
|
6898
|
+
sharedState.idleTimer = null;
|
|
6188
6899
|
}
|
|
6189
6900
|
await closeAllSessions();
|
|
6190
|
-
if (
|
|
6191
|
-
await
|
|
6901
|
+
if (sharedState.browser) {
|
|
6902
|
+
await sharedState.browser.close().catch(() => {
|
|
6192
6903
|
});
|
|
6193
|
-
|
|
6904
|
+
sharedState.browser = null;
|
|
6194
6905
|
}
|
|
6195
|
-
if (
|
|
6196
|
-
await
|
|
6906
|
+
if (getSharedCdpProxy()) {
|
|
6907
|
+
await getSharedCdpProxy().stop().catch(() => {
|
|
6197
6908
|
});
|
|
6198
|
-
|
|
6909
|
+
setSharedCdpProxy(null);
|
|
6199
6910
|
}
|
|
6200
6911
|
}
|
|
6201
6912
|
function resetForTesting() {
|
|
6202
6913
|
sessions.clear();
|
|
6203
|
-
|
|
6204
|
-
|
|
6914
|
+
sharedState.browser = null;
|
|
6915
|
+
sharedState.idleTimer = null;
|
|
6916
|
+
setSharedCdpProxy(null);
|
|
6205
6917
|
try {
|
|
6206
|
-
for (const
|
|
6207
|
-
unlinkSync(join2(SESSION_DIR, f));
|
|
6208
|
-
}
|
|
6918
|
+
for (const file of readdirSync2(SESSION_DIR)) unlinkSync2(join3(SESSION_DIR, file));
|
|
6209
6919
|
} catch {
|
|
6210
6920
|
}
|
|
6211
6921
|
}
|
|
6212
6922
|
async function ensureProcessCanExit() {
|
|
6213
|
-
if (idleTimer) {
|
|
6214
|
-
clearTimeout(idleTimer);
|
|
6215
|
-
idleTimer = null;
|
|
6923
|
+
if (sharedState.idleTimer) {
|
|
6924
|
+
clearTimeout(sharedState.idleTimer);
|
|
6925
|
+
sharedState.idleTimer = null;
|
|
6216
6926
|
}
|
|
6217
6927
|
for (const session of sessions.list()) {
|
|
6218
6928
|
if (session.browser) {
|
|
@@ -6224,35 +6934,36 @@ async function ensureProcessCanExit() {
|
|
|
6224
6934
|
}
|
|
6225
6935
|
}
|
|
6226
6936
|
sessions.clear();
|
|
6227
|
-
if (
|
|
6228
|
-
await
|
|
6937
|
+
if (sharedState.browser) {
|
|
6938
|
+
await sharedState.browser.close().catch(() => {
|
|
6229
6939
|
});
|
|
6230
|
-
|
|
6940
|
+
sharedState.browser = null;
|
|
6231
6941
|
}
|
|
6232
|
-
if (
|
|
6233
|
-
await
|
|
6942
|
+
if (getSharedCdpProxy()) {
|
|
6943
|
+
await getSharedCdpProxy().stop().catch(() => {
|
|
6234
6944
|
});
|
|
6235
|
-
|
|
6945
|
+
setSharedCdpProxy(null);
|
|
6236
6946
|
}
|
|
6237
6947
|
}
|
|
6238
6948
|
|
|
6239
6949
|
export {
|
|
6240
6950
|
createRuleEngine,
|
|
6241
|
-
touchSession,
|
|
6242
6951
|
findTargetPage,
|
|
6243
6952
|
resolveLaunchOpts,
|
|
6244
6953
|
createBrowser,
|
|
6245
|
-
getBrowser,
|
|
6246
|
-
findSession,
|
|
6247
|
-
getSessionById,
|
|
6248
|
-
setActivePage,
|
|
6249
6954
|
saveSessionDiskMeta,
|
|
6250
6955
|
readSessionDiskMeta,
|
|
6251
6956
|
deleteSessionDiskMeta,
|
|
6252
|
-
|
|
6957
|
+
resetIdleTimer,
|
|
6958
|
+
findOrRestoreSession2 as findOrRestoreSession,
|
|
6959
|
+
touchSession,
|
|
6960
|
+
getBrowser,
|
|
6961
|
+
findSession,
|
|
6962
|
+
getSessionById2 as getSessionById,
|
|
6963
|
+
setActivePage2 as setActivePage,
|
|
6253
6964
|
createEphemeralContext,
|
|
6254
6965
|
closeEphemeralContext,
|
|
6255
|
-
getAllSessions,
|
|
6966
|
+
getAllSessions2 as getAllSessions,
|
|
6256
6967
|
createSession,
|
|
6257
6968
|
closeSessionByName,
|
|
6258
6969
|
closeAllSessions,
|