@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.
Files changed (48) hide show
  1. package/README.md +2 -2
  2. package/dist/{browser-4IYIHZ6R.js → browser-6PFTHZI3.js} +8 -6
  3. package/dist/{browser-NYYCR4O7.js → browser-I2NLJN2A.js} +5 -3
  4. package/dist/{browser-ZD53IMUJ.js → browser-KOUA4ZDA.js} +6 -4
  5. package/dist/{cdp-driver-EFEW4ZEN.js → cdp-driver-3ETNFQA4.js} +4 -4
  6. package/dist/{cdp-driver-HB744QB4.js → cdp-driver-U7HDQMQ5.js} +1578 -896
  7. package/dist/{cdp-driver-4X6Q62WI.js → cdp-driver-WBFJNOLD.js} +3 -3
  8. package/dist/{chunk-SEEWE5SJ.js → chunk-2KPI5GKP.js} +3 -0
  9. package/dist/{chunk-OEC7ZSFW.js → chunk-3K57RYVC.js} +1942 -1580
  10. package/dist/{chunk-75DNUI6M.js → chunk-6UJU2FJK.js} +146 -0
  11. package/dist/{chunk-FNXA6FDM.js → chunk-BND5O5KC.js} +2 -1
  12. package/dist/{chunk-KECYFWJO.js → chunk-BOZTIIBT.js} +441 -427
  13. package/dist/{chunk-WK3INZLA.js → chunk-KPTD3SNJ.js} +1121 -759
  14. package/dist/{chunk-OSZNJT4U.js → chunk-LM32MNBB.js} +79 -8
  15. package/dist/{chunk-T2AI24A5.js → chunk-NAIHOVDZ.js} +3 -0
  16. package/dist/{chunk-WYETQ5C7.js → chunk-NEE6EMYA.js} +14 -1
  17. package/dist/{chunk-3PUOISKE.js → chunk-NINETOM4.js} +524 -495
  18. package/dist/{chunk-SOPN4XDK.js → chunk-O5PASNI7.js} +2 -1
  19. package/dist/{chunk-ME5FO5YV.js → chunk-OCECE22C.js} +1578 -896
  20. package/dist/{chunk-HSYRAV3H.js → chunk-OSIDUT4H.js} +2151 -1440
  21. package/dist/{chunk-HBMEFSTB.js → chunk-QCV2PI7U.js} +2 -1
  22. package/dist/{chunk-IR6C24P7.js → chunk-RMYKVZIZ.js} +1103 -1043
  23. package/dist/{chunk-R3F4K2SB.js → chunk-SMYSNO4M.js} +10 -0
  24. package/dist/{chunk-J3HXZVSN.js → chunk-SPNWUUHA.js} +1452 -916
  25. package/dist/{chunk-PGKV24QN.js → chunk-TBJUSUKF.js} +1 -1
  26. package/dist/{chunk-V6KGBU5J.js → chunk-VYTQLZAX.js} +1091 -1040
  27. package/dist/cli.js +3447 -3377
  28. package/dist/daemon-main.js +1240 -786
  29. package/dist/{human-interaction-CTZ4IWXJ.js → human-interaction-ISMMOJOK.js} +2 -2
  30. package/dist/{human-interaction-HJCK45SL.js → human-interaction-STTZZZ5N.js} +1 -1
  31. package/dist/{human-interaction-V3VDGHHI.js → human-interaction-UXFYV7DU.js} +1 -1
  32. package/dist/index.d.ts +458 -476
  33. package/dist/index.js +3766 -3576
  34. package/dist/{launcher-SJ44X25U.js → launcher-TOLF23ET.js} +1 -1
  35. package/dist/{launcher-XHKIC4GP.js → launcher-ZYB32LSZ.js} +1 -1
  36. package/dist/{plugin-singleton-GGSBI3EG.js → plugin-singleton-A6RNITJW.js} +1 -1
  37. package/dist/{proxy-NKCYE76M.js → proxy-H3RIUOCN.js} +2 -2
  38. package/dist/{recovery-EBKORYEU.js → recovery-JFGV3DBX.js} +1 -1
  39. package/dist/{recovery-5C4FBA5O.js → recovery-ORHJSBDN.js} +2 -2
  40. package/dist/{recovery-IMZUGWSS.js → recovery-XDKN63O5.js} +1 -1
  41. package/dist/{server-26SE6YZR.js → server-TG47W7MV.js} +7 -7
  42. package/dist/{server-JXF3JOAM.js → server-U3YAX5MJ.js} +4 -4
  43. package/dist/{session-recorder-GEZVQBKW.js → session-recorder-N7VEKJVW.js} +1 -1
  44. package/dist/{session-recorder-563ISSJK.js → session-recorder-RUNQOJ7T.js} +1 -1
  45. package/dist/{session-replayer-TXTNTG33.js → session-replayer-XLWQ47BB.js} +1 -1
  46. package/dist/{stealth-QNSMIHQK.js → stealth-FMPZO2OB.js} +1 -1
  47. package/dist/{stealth-MHJNBJY7.js → stealth-MCKFKPZ6.js} +1 -1
  48. package/package.json +9 -3
@@ -5,17 +5,17 @@ import {
5
5
  landingOffset,
6
6
  rand,
7
7
  typingDelay
8
- } from "./chunk-R3F4K2SB.js";
8
+ } from "./chunk-SMYSNO4M.js";
9
9
  import {
10
10
  connectToCDP,
11
11
  launchChrome
12
- } from "./chunk-SEEWE5SJ.js";
12
+ } from "./chunk-2KPI5GKP.js";
13
13
  import {
14
14
  errMsg
15
15
  } from "./chunk-GDKLH7ZY.js";
16
16
  import {
17
17
  createRuleEngine
18
- } from "./chunk-75DNUI6M.js";
18
+ } from "./chunk-6UJU2FJK.js";
19
19
  import {
20
20
  __require
21
21
  } from "./chunk-KFQGP6VL.js";
@@ -33,12 +33,16 @@ import { EventEmitter as EventEmitter2 } from "events";
33
33
  import { EventEmitter } from "events";
34
34
 
35
35
  // src/cdp-driver/mouse.ts
36
+ function buttonBit(button) {
37
+ return button === "left" ? 1 : button === "right" ? 2 : 4;
38
+ }
36
39
  var XBMouseImpl = class {
37
40
  conn;
38
41
  sessionId;
39
42
  _x = 0;
40
43
  _y = 0;
41
44
  _button = "none";
45
+ _buttons = 0;
42
46
  constructor(conn, sessionId) {
43
47
  this.conn = conn;
44
48
  this.sessionId = sessionId;
@@ -69,7 +73,7 @@ var XBMouseImpl = class {
69
73
  _truncated = true;
70
74
  break;
71
75
  }
72
- await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x, y: p.y, button: this._button });
76
+ await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x, y: p.y, button: this._button, buttons: this._buttons });
73
77
  this._x = p.x;
74
78
  this._y = p.y;
75
79
  await sleep(p.delay);
@@ -77,7 +81,7 @@ var XBMouseImpl = class {
77
81
  this._x = tx;
78
82
  this._y = ty;
79
83
  if (_truncated) {
80
- await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: tx, y: ty, button: this._button });
84
+ await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: tx, y: ty, button: this._button, buttons: this._buttons });
81
85
  }
82
86
  await sleep(rand(...DEFAULT_STEALTH_CONFIG.aimPause));
83
87
  } else {
@@ -89,7 +93,7 @@ var XBMouseImpl = class {
89
93
  const ry = stealth ? this._y + rand(...DEFAULT_STEALTH_CONFIG.releaseDrift) * (Math.random() < 0.5 ? -1 : 1) : this._y;
90
94
  this._x = rx;
91
95
  this._y = ry;
92
- await this.send("Input.dispatchMouseEvent", { type: "mouseReleased", x: rx, y: ry, button, clickCount: opts.clickCount ?? 1 });
96
+ await this.send("Input.dispatchMouseEvent", { type: "mouseReleased", x: rx, y: ry, button, buttons: this._buttons, clickCount: opts.clickCount ?? 1 });
93
97
  for (let i = 1; i < (opts.clickCount ?? 1); i++) {
94
98
  if (opts.delay) await sleep(opts.delay);
95
99
  await this.down({ button });
@@ -102,11 +106,13 @@ var XBMouseImpl = class {
102
106
  async down(opts = {}) {
103
107
  const button = opts.button ?? "left";
104
108
  this._button = button;
109
+ this._buttons |= buttonBit(button);
105
110
  await this.send("Input.dispatchMouseEvent", {
106
111
  type: "mousePressed",
107
112
  x: this._x,
108
113
  y: this._y,
109
114
  button,
115
+ buttons: this._buttons,
110
116
  // r23: press 必须与 release 声明同一 clickCount——Chrome 按序列计数
111
117
  // 合成 click/dblclick,press 缺声明会把计数器重置(dblclick 永不合成)
112
118
  clickCount: opts.clickCount ?? 1
@@ -120,8 +126,11 @@ var XBMouseImpl = class {
120
126
  x: this._x,
121
127
  y: this._y,
122
128
  button,
129
+ // release 先带位发送再清位(Puppeteer 同序——DOM mouseup 的 buttons 反映释放后状态)
130
+ buttons: this._buttons,
123
131
  clickCount: opts.clickCount ?? 1
124
132
  });
133
+ this._buttons &= ~buttonBit(button);
125
134
  }
126
135
  async move(x, y, opts = {}) {
127
136
  const stealth = opts.stealth ?? process.env.XBROWSER_STEALTH !== "off";
@@ -139,7 +148,8 @@ var XBMouseImpl = class {
139
148
  type: "mouseMoved",
140
149
  x: this._x,
141
150
  y: this._y,
142
- button: this._button
151
+ button: this._button,
152
+ buttons: this._buttons
143
153
  });
144
154
  }
145
155
  this._x = x;
@@ -159,9 +169,11 @@ var XBMouseImpl = class {
159
169
  x: this._x,
160
170
  y: this._y,
161
171
  button: "left",
172
+ buttons: 1,
162
173
  clickCount: 1
163
174
  });
164
175
  this._button = "left";
176
+ this._buttons |= 1;
165
177
  const steps = opts.steps ?? Math.max(10, Math.min(24, Math.round(Math.hypot(x - this._x, y - this._y) / 20)));
166
178
  const fx = this._x, fy = this._y;
167
179
  for (let i = 1; i <= steps; i++) {
@@ -173,7 +185,8 @@ var XBMouseImpl = class {
173
185
  type: "mouseMoved",
174
186
  x: this._x,
175
187
  y: this._y,
176
- button: this._button
188
+ button: this._button,
189
+ buttons: this._buttons
177
190
  });
178
191
  }
179
192
  this._x = x;
@@ -184,15 +197,22 @@ var XBMouseImpl = class {
184
197
  x,
185
198
  y,
186
199
  button: "left",
200
+ buttons: this._buttons,
187
201
  clickCount: 1
188
202
  });
189
203
  this._button = "none";
204
+ this._buttons &= ~1;
205
+ }
206
+ async wheelAt(x, y, deltaX, deltaY) {
207
+ await this.move(x, y);
208
+ await this.wheel(deltaX, deltaY);
190
209
  }
191
210
  async wheel(deltaX, deltaY) {
192
211
  await this.send("Input.dispatchMouseEvent", {
193
212
  type: "mouseWheel",
194
213
  x: this._x,
195
214
  y: this._y,
215
+ buttons: this._buttons,
196
216
  deltaX,
197
217
  deltaY
198
218
  });
@@ -1432,6 +1452,216 @@ var XBElementHandleImpl = class {
1432
1452
  }
1433
1453
  };
1434
1454
 
1455
+ // src/cdp-driver/page-media.ts
1456
+ var MediaService = class {
1457
+ constructor(options) {
1458
+ this.options = options;
1459
+ }
1460
+ options;
1461
+ async screenshot(opts = {}) {
1462
+ const params = {
1463
+ format: opts.type ?? "png"
1464
+ };
1465
+ if (opts.quality !== void 0 && (opts.type === "jpeg" || !opts.type && opts.quality)) {
1466
+ params.quality = opts.quality;
1467
+ }
1468
+ if (opts.fullPage) {
1469
+ params.captureBeyondViewport = true;
1470
+ }
1471
+ if (opts.clip) {
1472
+ const clip = {
1473
+ x: Math.round(opts.clip.x),
1474
+ y: Math.round(opts.clip.y),
1475
+ width: Math.round(Math.max(1, opts.clip.width)),
1476
+ height: Math.round(Math.max(1, opts.clip.height)),
1477
+ scale: opts.clip.scale ?? 1
1478
+ };
1479
+ params.clip = clip;
1480
+ }
1481
+ if (opts.omitBackground) {
1482
+ params.omitBackground = true;
1483
+ }
1484
+ const result = await this.options.conn.send(
1485
+ "Page.captureScreenshot",
1486
+ params,
1487
+ this.options.sessionId
1488
+ );
1489
+ return Buffer.from(result.data, "base64");
1490
+ }
1491
+ async pdf(opts = {}) {
1492
+ const params = {};
1493
+ if (opts.landscape !== void 0) params.landscape = opts.landscape;
1494
+ if (opts.printBackground !== void 0) params.printBackground = opts.printBackground;
1495
+ if (opts.scale !== void 0) params.scale = opts.scale;
1496
+ if (opts.format) params.paperFormat = opts.format;
1497
+ if (opts.preferCSSPageSize !== void 0) params.preferCSSPageSize = opts.preferCSSPageSize;
1498
+ if (opts.margin) {
1499
+ if (opts.margin.top) params.marginTop = parseFloat(opts.margin.top);
1500
+ if (opts.margin.bottom) params.marginBottom = parseFloat(opts.margin.bottom);
1501
+ if (opts.margin.left) params.marginLeft = parseFloat(opts.margin.left);
1502
+ if (opts.margin.right) params.marginRight = parseFloat(opts.margin.right);
1503
+ }
1504
+ const result = await this.options.conn.send("Page.printToPDF", params, this.options.sessionId);
1505
+ return Buffer.from(result.data, "base64");
1506
+ }
1507
+ viewportSize() {
1508
+ return this.options.viewportSize ?? null;
1509
+ }
1510
+ async setViewportSize(size) {
1511
+ await this.options.conn.send(
1512
+ "Emulation.setDeviceMetricsOverride",
1513
+ {
1514
+ width: size.width,
1515
+ height: size.height,
1516
+ deviceScaleFactor: 1,
1517
+ mobile: false
1518
+ },
1519
+ this.options.sessionId
1520
+ );
1521
+ this.options.onViewportSize(size);
1522
+ }
1523
+ /**
1524
+ * env-E2: 缩放变异——deviceScaleFactor 切换(CSS 像素坐标空间不变,
1525
+ * 物理像素翻倍)。保留当前 CSS 视口尺寸,只换 DSF。
1526
+ */
1527
+ async setDeviceScaleFactor(dsf) {
1528
+ const size = this.options.viewportSize ?? await this.options.evaluate(
1529
+ "({ width: window.innerWidth, height: window.innerHeight })"
1530
+ );
1531
+ await this.options.conn.send(
1532
+ "Emulation.setDeviceMetricsOverride",
1533
+ {
1534
+ width: size.width,
1535
+ height: size.height,
1536
+ deviceScaleFactor: dsf,
1537
+ mobile: false
1538
+ },
1539
+ this.options.sessionId
1540
+ );
1541
+ this.options.onViewportSize(size);
1542
+ }
1543
+ // ── Scripts ─────────────────────────────────────────────────
1544
+ };
1545
+
1546
+ // src/cdp-driver/page-file-input.ts
1547
+ var FileInputService = class {
1548
+ constructor(options) {
1549
+ this.options = options;
1550
+ }
1551
+ options;
1552
+ async dropFiles(selector, payload) {
1553
+ await this.options.evaluate(`
1554
+ (function() {
1555
+ var el = ${queryJS(selector)};
1556
+ if (!el) throw new Error('drop target not found: ' + ${JSON.stringify(selector)});
1557
+ var b64 = ${JSON.stringify(payload.buffer.toString("base64"))};
1558
+ var bin = atob(b64);
1559
+ var buf = new Uint8Array(bin.length);
1560
+ for (var i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
1561
+ var file = new File([buf], ${JSON.stringify(payload.name)}, { type: ${JSON.stringify(payload.mimeType)} });
1562
+ var dt = new DataTransfer();
1563
+ dt.items.add(file);
1564
+ var rect = el.getBoundingClientRect();
1565
+ var opts = {
1566
+ bubbles: true, cancelable: true,
1567
+ clientX: rect.x + rect.width / 2, clientY: rect.y + rect.height / 2,
1568
+ };
1569
+ el.dispatchEvent(new DragEvent('dragenter', Object.assign({ dataTransfer: dt }, opts)));
1570
+ el.dispatchEvent(new DragEvent('dragover', Object.assign({ dataTransfer: dt }, opts)));
1571
+ el.dispatchEvent(new DragEvent('drop', Object.assign({ dataTransfer: dt }, opts)));
1572
+ })()
1573
+ `);
1574
+ }
1575
+ async setInputFiles(selector, files) {
1576
+ const fileArr = Array.isArray(files) ? files : [files];
1577
+ const fileList = fileArr.map((f) => ({
1578
+ name: f.name,
1579
+ type: f.mimeType,
1580
+ dataBase64: f.buffer.toString("base64")
1581
+ }));
1582
+ await this.options.evaluate(`
1583
+ (function() {
1584
+ var selector = ${JSON.stringify(selector)};
1585
+ var input = ${queryJS(selector)};
1586
+ if (!input) throw new Error('Element not found: ' + selector);
1587
+
1588
+ var fileList = ${JSON.stringify(fileList)};
1589
+ var dt = new DataTransfer();
1590
+
1591
+ fileList.forEach(function(f) {
1592
+ var binary = atob(f.dataBase64);
1593
+ var bytes = new Uint8Array(binary.length);
1594
+ for (var i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
1595
+ var blob = new Blob([bytes], { type: f.type });
1596
+ var file = new File([blob], f.name, { type: f.type });
1597
+ dt.items.add(file);
1598
+ });
1599
+
1600
+ input.files = dt.files;
1601
+ input.dispatchEvent(new Event('input', { bubbles: true }));
1602
+ input.dispatchEvent(new Event('change', { bubbles: true }));
1603
+ })()
1604
+ `);
1605
+ }
1606
+ // ── dragAndDrop ─────────────────────────────────────────────
1607
+ async dragAndDrop(source, target) {
1608
+ const sourceRect = await this.options.evaluate(`
1609
+ (function() {
1610
+ const el = ${queryJS(source)};
1611
+ if (!el) throw new Error('Source not found: ${source}');
1612
+ el.scrollIntoView({ behavior: 'instant', block: 'center' });
1613
+ const r = el.getBoundingClientRect();
1614
+ return { x: r.x, y: r.y, width: r.width, height: r.height };
1615
+ })()
1616
+ `);
1617
+ const targetRect = await this.options.evaluate(`
1618
+ (function() {
1619
+ const el = ${queryJS(target)};
1620
+ if (!el) throw new Error('Target not found: ${target}');
1621
+ el.scrollIntoView({ behavior: 'instant', block: 'center' });
1622
+ const r = el.getBoundingClientRect();
1623
+ return { x: r.x, y: r.y, width: r.width, height: r.height };
1624
+ })()
1625
+ `);
1626
+ const sx = sourceRect.x + sourceRect.width / 2;
1627
+ const sy = sourceRect.y + sourceRect.height / 2;
1628
+ const tx = targetRect.x + targetRect.width / 2;
1629
+ const ty = targetRect.y + targetRect.height / 2;
1630
+ try {
1631
+ await this.options.conn.send("Input.dispatchDragEvent", {
1632
+ type: "dragStart",
1633
+ x: sx,
1634
+ y: sy,
1635
+ data: { items: [], dragOperations: ["copy", "move", "link"] }
1636
+ }, this.options.sessionId);
1637
+ await this.options.conn.send("Input.dispatchDragEvent", {
1638
+ type: "dragOver",
1639
+ x: tx,
1640
+ y: ty,
1641
+ data: { items: [], dragOperations: ["copy", "move", "link"] }
1642
+ }, this.options.sessionId);
1643
+ await this.options.conn.send("Input.dispatchDragEvent", {
1644
+ type: "drop",
1645
+ x: tx,
1646
+ y: ty,
1647
+ data: { items: [], dragOperations: ["copy", "move", "link"] }
1648
+ }, this.options.sessionId);
1649
+ await this.options.conn.send("Input.dispatchDragEvent", {
1650
+ type: "dragCancel",
1651
+ x: sx,
1652
+ y: sy,
1653
+ data: { items: [], dragOperations: ["copy", "move", "link"] }
1654
+ }, this.options.sessionId);
1655
+ } catch {
1656
+ await this.options.mouse.move(sx, sy);
1657
+ await this.options.mouse.down();
1658
+ await this.options.mouse.move(tx, ty, { steps: 10 });
1659
+ await this.options.mouse.up();
1660
+ }
1661
+ }
1662
+ // ── setOfflineMode ──────────────────────────────────────────
1663
+ };
1664
+
1435
1665
  // src/cdp-driver/page-helpers.ts
1436
1666
  function globToRegex(glob) {
1437
1667
  let pattern = glob.replace(/[\\^${}()|[\]+]/g, "\\$&").replace(/\./g, "\\.").replace(/\*\*/g, "{{DOUBLESTAR}}").replace(/\*/g, "[^/]*").replace(/{{DOUBLESTAR}}/g, ".*").replace(/\?/g, ".");
@@ -1583,65 +1813,1078 @@ function createXBRouteFetch(conn, sessionId, params, emitter) {
1583
1813
  };
1584
1814
  }
1585
1815
 
1586
- // src/cdp-driver/page.ts
1587
- var XBPageImpl = class _XBPageImpl {
1588
- conn;
1589
- _emitter = new EventEmitter();
1590
- _subscriptions = [];
1591
- sessionId;
1592
- _targetId;
1593
- _contextImpl;
1594
- _browserImpl;
1595
- _closed = false;
1596
- _url = "about:blank";
1597
- _title = "";
1598
- _viewportSize = null;
1599
- _loadState = {
1600
- loadFired: true,
1601
- domContentFired: true,
1602
- networkIdle: true
1603
- };
1604
- mouse;
1605
- keyboard;
1606
- // Network tracking for waitForLoadState('networkidle')
1607
- inflightRequests = /* @__PURE__ */ new Set();
1608
- networkIdleResolve = null;
1609
- networkIdleTimer = null;
1610
- static NETWORK_IDLE_MS = 500;
1611
- constructor(conn, sessionId, targetId, context, browser) {
1612
- this.conn = conn;
1613
- this.sessionId = sessionId;
1614
- this._targetId = targetId;
1615
- this._contextImpl = context;
1616
- this._browserImpl = browser;
1617
- this.mouse = new XBMouseImpl(conn, sessionId);
1618
- this.keyboard = new XBKeyboardImpl(conn, sessionId);
1619
- }
1620
- _emit(event, ...args) {
1621
- this._emitter.emit(event, ...args);
1622
- }
1623
- /** Internal initialization — must be called after construction */
1624
- async _init() {
1625
- await this.conn.send("Page.enable", void 0, this.sessionId);
1626
- await this.conn.send("Runtime.enable", void 0, this.sessionId);
1627
- await this.conn.send("Network.enable", void 0, this.sessionId);
1628
- await this.conn.send("DOM.enable", void 0, this.sessionId).catch(() => {
1629
- });
1630
- if (this._contextImpl.ignoreHTTPSErrors) {
1631
- await this.conn.send("Security.enable", void 0, this.sessionId).catch(() => {
1816
+ // src/cdp-driver/page-network-events.ts
1817
+ function setupNetworkEvents(options) {
1818
+ options.addSubscription(
1819
+ options.conn.subscribe("Network.requestWillBeSent", options.sessionId, (params) => {
1820
+ const p = params;
1821
+ options.state.inflightRequests.add(p.requestId);
1822
+ options.storeRequest(p.requestId, {
1823
+ url: p.request.url,
1824
+ method: p.request.method,
1825
+ headers: p.request.headers,
1826
+ postData: p.request.postData ?? null,
1827
+ resourceType: p.type
1632
1828
  });
1633
- await this.conn.send("Security.setIgnoreCertificateErrors", { ignore: true }, this.sessionId).catch(() => {
1829
+ options.emit("request", createXBRequest(
1830
+ null,
1831
+ {
1832
+ requestId: p.requestId,
1833
+ url: p.request.url,
1834
+ method: p.request.method,
1835
+ headers: p.request.headers,
1836
+ postData: p.request.postData ?? null,
1837
+ resourceType: p.type
1838
+ }
1839
+ ));
1840
+ options.checkNetworkIdle();
1841
+ })
1842
+ );
1843
+ options.addSubscription(
1844
+ options.conn.subscribe("Network.responseReceived", options.sessionId, (params) => {
1845
+ const p = params;
1846
+ options.storeResponse(p.requestId, {
1847
+ status: p.response.status,
1848
+ url: p.response.url,
1849
+ headers: p.response.headers
1634
1850
  });
1851
+ options.emit("response", createXBResponse(
1852
+ { requestId: p.requestId, status: p.response.status, url: p.response.url, headers: p.response.headers },
1853
+ options.conn,
1854
+ options.sessionId
1855
+ ));
1856
+ })
1857
+ );
1858
+ options.addSubscription(
1859
+ options.conn.subscribe("Network.loadingFinished", options.sessionId, (params) => {
1860
+ const p = params;
1861
+ options.state.inflightRequests.delete(p.requestId);
1862
+ options.emit("requestfinished", p);
1863
+ options.checkNetworkIdle();
1864
+ })
1865
+ );
1866
+ options.addSubscription(
1867
+ options.conn.subscribe("Network.loadingFailed", options.sessionId, (params) => {
1868
+ const p = params;
1869
+ options.state.inflightRequests.delete(p.requestId);
1870
+ options.checkNetworkIdle();
1871
+ })
1872
+ );
1873
+ }
1874
+
1875
+ // src/cdp-driver/page-lifecycle-events.ts
1876
+ function setupPageEvents(options) {
1877
+ options.addSubscription(
1878
+ options.conn.subscribe("Page.frameNavigated", options.sessionId, (params) => {
1879
+ const p = params;
1880
+ if (p.frame) {
1881
+ options.setUrl(p.frame.url);
1882
+ }
1883
+ options.emit("framenavigated", options.mainFrame());
1884
+ })
1885
+ );
1886
+ options.addSubscription(
1887
+ options.conn.subscribe("Page.loadEventFired", options.sessionId, () => {
1888
+ options.markLoadFired();
1889
+ })
1890
+ );
1891
+ options.addSubscription(
1892
+ options.conn.subscribe("Page.domContentEventFired", options.sessionId, () => {
1893
+ options.markDomContentFired();
1894
+ })
1895
+ );
1896
+ options.addSubscription(
1897
+ options.conn.subscribe("Page.javascriptDialogOpening", options.sessionId, (params) => {
1898
+ const p = params;
1899
+ const dialog = {
1900
+ type: p.type,
1901
+ message: () => p.message,
1902
+ defaultValue: () => p.defaultValue,
1903
+ accept: async (text) => {
1904
+ await options.conn.send("Page.handleJavaScriptDialog", {
1905
+ accept: true,
1906
+ promptText: text
1907
+ }, options.sessionId);
1908
+ },
1909
+ dismiss: async () => {
1910
+ await options.conn.send("Page.handleJavaScriptDialog", {
1911
+ accept: false
1912
+ }, options.sessionId);
1913
+ }
1914
+ };
1915
+ options.emit("dialog", dialog);
1916
+ const autoAccept = p.type === "beforeunload" ? options.getBeforeUnloadAccept() : false;
1917
+ setTimeout(() => {
1918
+ options.conn.send("Page.handleJavaScriptDialog", { accept: autoAccept }, options.sessionId).catch(() => {
1919
+ });
1920
+ }, 0);
1921
+ })
1922
+ );
1923
+ options.addSubscription(
1924
+ options.conn.subscribe("Page.fileChooserOpened", options.sessionId, async (params) => {
1925
+ const p = params;
1926
+ let selector = "";
1927
+ try {
1928
+ const result = await options.conn.send("DOM.describeNode", { backendNodeId: p.backendNodeId }, options.sessionId);
1929
+ const attrs = result.node?.attributes || [];
1930
+ const idIdx = attrs.indexOf("id");
1931
+ if (idIdx >= 0) selector = "#" + attrs[idIdx + 1];
1932
+ } catch {
1933
+ }
1934
+ if (!selector) {
1935
+ try {
1936
+ const result = await options.conn.send("DOM.resolveNode", { backendNodeId: p.backendNodeId }, options.sessionId);
1937
+ const evalResult = await options.conn.send("Runtime.callFunctionOn", {
1938
+ objectId: result.objectId,
1939
+ functionDeclaration: 'function() { return this.id || this.name || "" }',
1940
+ returnByValue: true
1941
+ }, options.sessionId);
1942
+ if (evalResult.result?.value) selector = "#" + evalResult.result.value;
1943
+ } catch {
1944
+ }
1945
+ }
1946
+ const fileChooser = {
1947
+ selector,
1948
+ isMultiple: p.mode === "selectMultiple",
1949
+ setFiles: async (files) => {
1950
+ const fileArray = Array.isArray(files) ? files : [files];
1951
+ await options.setInputFiles(selector || 'input[type="file"]', fileArray);
1952
+ }
1953
+ };
1954
+ options.emit("filechooser", fileChooser);
1955
+ })
1956
+ );
1957
+ }
1958
+
1959
+ // src/cdp-driver/page-network-waits.ts
1960
+ var NetworkWaitService = class {
1961
+ constructor(options) {
1962
+ this.options = options;
1963
+ }
1964
+ options;
1965
+ // ── waitForResponse ─────────────────────────────────────────
1966
+ async waitForResponse(urlOrPredicate, opts = {}) {
1967
+ const timeout = opts.timeout ?? 3e4;
1968
+ const predicate = createResponsePredicate(urlOrPredicate);
1969
+ for (const [, data] of this.options.responses) {
1970
+ const response = createXBResponse(data, this.options.conn, this.options.sessionId);
1971
+ if (predicate(response)) return response;
1635
1972
  }
1636
- if (this._contextImpl.httpCredentials) {
1637
- await this.conn.send("Fetch.enable", {
1638
- patterns: [{ urlPattern: "*", requestStage: "Request" }],
1973
+ return new Promise((resolve, reject) => {
1974
+ const timer = setTimeout(() => {
1975
+ this.options.off("response", handler);
1976
+ reject(new Error(`waitForResponse timed out after ${timeout}ms`));
1977
+ }, timeout);
1978
+ const handler = (params) => {
1979
+ let response;
1980
+ const respObj = params;
1981
+ if (respObj.response) {
1982
+ const data = {
1983
+ requestId: respObj.requestId || "",
1984
+ status: respObj.response.status || 0,
1985
+ url: respObj.response.url || "",
1986
+ headers: respObj.response.headers || {}
1987
+ };
1988
+ response = createXBResponse(data, this.options.conn, this.options.sessionId);
1989
+ } else if (typeof params.status === "function") {
1990
+ response = params;
1991
+ } else {
1992
+ return;
1993
+ }
1994
+ if (predicate(response)) {
1995
+ clearTimeout(timer);
1996
+ this.options.off("response", handler);
1997
+ resolve(response);
1998
+ }
1999
+ };
2000
+ this.options.on("response", handler);
2001
+ });
2002
+ }
2003
+ // ── waitForRequest ──────────────────────────────────────────
2004
+ async waitForRequest(urlOrPredicate, opts = {}) {
2005
+ const timeout = opts.timeout ?? 3e4;
2006
+ const predicate = createRequestPredicate(urlOrPredicate);
2007
+ for (const [, data] of this.options.requests) {
2008
+ const request = createXBRequest(this.pageLike(), data);
2009
+ if (predicate(request)) return request;
2010
+ }
2011
+ return new Promise((resolve, reject) => {
2012
+ const timer = setTimeout(() => {
2013
+ this.options.off("request", handler);
2014
+ reject(new Error(`waitForRequest timed out after ${timeout}ms`));
2015
+ }, timeout);
2016
+ const handler = (params) => {
2017
+ let request;
2018
+ const reqObj = params;
2019
+ if (reqObj.request) {
2020
+ request = createXBRequest(this.pageLike(), {
2021
+ requestId: reqObj.requestId || "",
2022
+ url: reqObj.request.url || "",
2023
+ method: reqObj.request.method || "",
2024
+ headers: reqObj.request.headers || {},
2025
+ postData: reqObj.request.postData ?? null,
2026
+ resourceType: reqObj.type || ""
2027
+ });
2028
+ } else if (typeof params.url === "function") {
2029
+ request = params;
2030
+ } else {
2031
+ return;
2032
+ }
2033
+ if (predicate(request)) {
2034
+ clearTimeout(timer);
2035
+ this.options.off("request", handler);
2036
+ resolve(request);
2037
+ }
2038
+ };
2039
+ this.options.on("request", handler);
2040
+ });
2041
+ }
2042
+ // ── waitForURL ──────────────────────────────────────────────
2043
+ async waitForURL(url, opts = {}) {
2044
+ const timeout = opts.timeout ?? 3e4;
2045
+ const checkFn = typeof url === "function" ? url : typeof url === "string" ? (current) => matchGlob(url, current) : (current) => url.test(current);
2046
+ if (checkFn(this.options.currentUrl())) return;
2047
+ return new Promise((resolve, reject) => {
2048
+ const timer = setTimeout(() => {
2049
+ this.options.off("framenavigated", handler);
2050
+ reject(new Error(`waitForURL timed out after ${timeout}ms`));
2051
+ }, timeout);
2052
+ const handler = () => {
2053
+ if (checkFn(this.options.currentUrl())) {
2054
+ clearTimeout(timer);
2055
+ this.options.off("framenavigated", handler);
2056
+ resolve();
2057
+ }
2058
+ };
2059
+ this.options.on("framenavigated", handler);
2060
+ });
2061
+ }
2062
+ pageLike() {
2063
+ return {
2064
+ _networkResponses: this.options.responses,
2065
+ _connection: this.options.conn,
2066
+ sessionId: this.options.sessionId
2067
+ };
2068
+ }
2069
+ };
2070
+
2071
+ // src/cdp-driver/page-routes.ts
2072
+ var NetworkRouteService = class {
2073
+ constructor(options) {
2074
+ this.options = options;
2075
+ }
2076
+ options;
2077
+ routeHandlers = [];
2078
+ interceptionEnabled = false;
2079
+ get isInterceptionEnabled() {
2080
+ return this.interceptionEnabled;
2081
+ }
2082
+ subscriptions = [];
2083
+ async route(url, handler) {
2084
+ const regex = typeof url === "string" ? globToRegex(url) : url;
2085
+ this.routeHandlers.push({ pattern: String(url), regex, handler });
2086
+ if (!this.interceptionEnabled) {
2087
+ this.interceptionEnabled = true;
2088
+ await this.options.conn.send("Fetch.enable", {
2089
+ patterns: [{ urlPattern: "*", requestStage: "Request" }],
2090
+ // sup-s9: 保留认证自动响应(Fetch.enable 为替换语义,不带此参数
2091
+ // 会顶掉 _init 的 auth 配置)
2092
+ handleAuthRequests: true
2093
+ }, this.options.sessionId);
2094
+ this.subscriptions.push(
2095
+ this.options.conn.subscribe("Fetch.requestPaused", this.options.sessionId, (params) => {
2096
+ this._handleRequestPaused(params);
2097
+ })
2098
+ );
2099
+ }
2100
+ }
2101
+ async unroute(url, handler) {
2102
+ const regex = typeof url === "string" ? globToRegex(url) : url;
2103
+ this.routeHandlers = this.routeHandlers.filter(
2104
+ (h) => !(regex.source === h.regex.source && (!handler || h.handler === handler))
2105
+ );
2106
+ if (this.routeHandlers.length === 0 && this.interceptionEnabled) {
2107
+ this.interceptionEnabled = false;
2108
+ await this.options.conn.send("Fetch.disable", void 0, this.options.sessionId).catch(() => {
2109
+ });
2110
+ }
2111
+ }
2112
+ async _handleRequestPaused(params) {
2113
+ const requestUrl = params.request.url;
2114
+ for (const { regex, handler } of this.routeHandlers) {
2115
+ if (regex.test(requestUrl)) {
2116
+ this.options.emit("request", createXBRequest(
2117
+ null,
2118
+ {
2119
+ requestId: params.requestId,
2120
+ url: params.request.url,
2121
+ method: params.request.method,
2122
+ headers: params.request.headers,
2123
+ postData: params.request.postData ?? null,
2124
+ resourceType: params.resourceType
2125
+ }
2126
+ ));
2127
+ const route = createXBRouteFetch(this.options.conn, this.options.sessionId, params, void 0);
2128
+ try {
2129
+ await handler(route);
2130
+ } catch {
2131
+ await this.options.conn.send("Fetch.continueRequest", {
2132
+ requestId: params.requestId
2133
+ }, this.options.sessionId).catch(() => {
2134
+ });
2135
+ }
2136
+ return;
2137
+ }
2138
+ }
2139
+ await this.options.conn.send("Fetch.continueRequest", {
2140
+ requestId: params.requestId
2141
+ }, this.options.sessionId).catch(() => {
2142
+ });
2143
+ }
2144
+ };
2145
+
2146
+ // src/cdp-driver/page-navigation.ts
2147
+ var NavigationService = class {
2148
+ constructor(options) {
2149
+ this.options = options;
2150
+ }
2151
+ options;
2152
+ async goto(url, opts = {}) {
2153
+ if (this.options.isClosed()) throw new Error("Page is closed");
2154
+ const waitUntil = opts.waitUntil ?? "load";
2155
+ const timeout = opts.timeout ?? 3e4;
2156
+ this.options.state.loadFired = false;
2157
+ this.options.state.domContentFired = false;
2158
+ this.options.state.networkIdle = false;
2159
+ if (process.env.XBROWSER_STEALTH !== "off") {
2160
+ try {
2161
+ await this.options.conn.send(
2162
+ "Page.addScriptToEvaluateOnNewDocument",
2163
+ { source: buildStealthInitScript({ ...DEFAULT_STEALTH_CONFIG, ...this.options.stealthConfig ?? {} }) },
2164
+ this.options.sessionId
2165
+ );
2166
+ } catch {
2167
+ }
2168
+ try {
2169
+ const rawUa = await this.options.conn.send(
2170
+ "Runtime.evaluate",
2171
+ { expression: "navigator.userAgent", returnByValue: true },
2172
+ this.options.sessionId
2173
+ );
2174
+ const ua = rawUa?.value || "";
2175
+ const cleaned = ua.replace(/HeadlessChrome/g, "Chrome");
2176
+ if (cleaned !== ua) {
2177
+ await this.options.conn.send(
2178
+ "Network.setUserAgentOverride",
2179
+ { userAgent: cleaned },
2180
+ this.options.sessionId
2181
+ );
2182
+ }
2183
+ } catch {
2184
+ }
2185
+ }
2186
+ const result = await this.options.conn.send(
2187
+ "Page.navigate",
2188
+ { url, referrer: opts.referer },
2189
+ this.options.sessionId
2190
+ );
2191
+ if (result.errorText) {
2192
+ throw new Error(`Navigation failed: ${result.errorText}`);
2193
+ }
2194
+ if (waitUntil === "commit") {
2195
+ this.options.setUrl(url);
2196
+ return {
2197
+ status: () => 0,
2198
+ ok: () => false,
2199
+ url: () => url,
2200
+ headers: () => ({})
2201
+ };
2202
+ }
2203
+ await this.options.waitForLoadState(waitUntil, timeout);
2204
+ this.options.setUrl(url);
2205
+ const statusCode = 200;
2206
+ const finalUrl = url;
2207
+ const headers = {};
2208
+ return {
2209
+ status: () => statusCode,
2210
+ ok: () => statusCode >= 200 && statusCode < 300,
2211
+ url: () => finalUrl,
2212
+ headers: () => headers
2213
+ };
2214
+ }
2215
+ async goBack(opts = {}) {
2216
+ try {
2217
+ const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
2218
+ if (navHistory.currentIndex > 0) {
2219
+ const prevUrl = navHistory.entries[navHistory.currentIndex - 1]?.url;
2220
+ if (prevUrl && prevUrl !== "about:blank") {
2221
+ await this.options.conn.send("Page.navigate", { url: prevUrl }, this.options.sessionId);
2222
+ await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
2223
+ });
2224
+ this.options.setUrl(prevUrl);
2225
+ return;
2226
+ }
2227
+ }
2228
+ } catch {
2229
+ }
2230
+ await this.options.evaluate("() => history.back()");
2231
+ await this.options.waitForTimeout(3e3);
2232
+ this.options.setUrl(await this.options.evaluate("location.href").catch(() => this.options.currentUrl()));
2233
+ }
2234
+ async goForward(opts = {}) {
2235
+ try {
2236
+ const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
2237
+ if (navHistory.currentIndex < navHistory.entries.length - 1) {
2238
+ const nextUrl = navHistory.entries[navHistory.currentIndex + 1]?.url;
2239
+ if (nextUrl && nextUrl !== "about:blank") {
2240
+ await this.options.conn.send("Page.navigate", { url: nextUrl }, this.options.sessionId);
2241
+ await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
2242
+ });
2243
+ this.options.setUrl(nextUrl);
2244
+ return;
2245
+ }
2246
+ }
2247
+ } catch {
2248
+ }
2249
+ await this.options.evaluate("() => history.forward()");
2250
+ await this.options.waitForTimeout(3e3);
2251
+ this.options.setUrl(await this.options.evaluate("location.href").catch(() => this.options.currentUrl()));
2252
+ }
2253
+ async reload(opts = {}) {
2254
+ this.options.state.loadFired = false;
2255
+ this.options.state.domContentFired = false;
2256
+ this.options.state.networkIdle = false;
2257
+ await this.options.conn.send("Page.reload", void 0, this.options.sessionId);
2258
+ await this.options.waitForLoadState(opts.waitUntil ?? "load", opts.timeout);
2259
+ }
2260
+ async waitForLoadState(state = "load", timeout = 3e4) {
2261
+ if (this.options.isClosed()) throw new Error("Page is closed");
2262
+ const checkState = () => {
2263
+ switch (state) {
2264
+ case "domcontentloaded":
2265
+ return this.options.state.domContentFired;
2266
+ case "load":
2267
+ return this.options.state.loadFired;
2268
+ case "networkidle":
2269
+ return this.options.state.networkIdle;
2270
+ case "commit":
2271
+ return this.options.state.domContentFired;
2272
+ default:
2273
+ return true;
2274
+ }
2275
+ };
2276
+ if (checkState()) return;
2277
+ return new Promise((resolve, reject) => {
2278
+ const timer = setTimeout(() => {
2279
+ reject(new Error(`waitForLoadState('${state}') timeout after ${timeout}ms`));
2280
+ }, timeout);
2281
+ const check = () => {
2282
+ if (checkState()) {
2283
+ clearTimeout(timer);
2284
+ resolve();
2285
+ } else {
2286
+ setTimeout(check, 50);
2287
+ }
2288
+ };
2289
+ check();
2290
+ });
2291
+ }
2292
+ async waitForTimeout(ms) {
2293
+ await new Promise((resolve) => {
2294
+ const timer = setTimeout(resolve, ms);
2295
+ if (typeof timer.unref === "function") timer.unref();
2296
+ });
2297
+ }
2298
+ };
2299
+
2300
+ // src/cdp-driver/page-dom.ts
2301
+ var DomQueryService = class {
2302
+ constructor(options) {
2303
+ this.options = options;
2304
+ }
2305
+ options;
2306
+ /** Query a single element, returns CDP nodeId or 0 if not found */
2307
+ async querySelector(selector) {
2308
+ if (selector.startsWith("xpath=")) {
2309
+ const found = await this.options.evaluate(`
2310
+ (() => { const el = ${queryJS(selector)}; return !!el; })()
2311
+ `).catch(() => false);
2312
+ if (!found) return 0;
2313
+ try {
2314
+ const search = await this.options.conn.send(
2315
+ "DOM.performSearch",
2316
+ { query: selector.slice(6) },
2317
+ this.options.sessionId
2318
+ );
2319
+ if (search.nodeId) return search.nodeId;
2320
+ } catch {
2321
+ }
2322
+ return 1;
2323
+ }
2324
+ const withTimeout = (p, ms) => Promise.race([p, new Promise((r) => setTimeout(() => r(null), ms))]);
2325
+ const doc = await withTimeout(
2326
+ this.options.conn.send("DOM.getDocument", { depth: 0 }, this.options.sessionId),
2327
+ 8e3
2328
+ );
2329
+ if (!doc) return 0;
2330
+ const result = await withTimeout(
2331
+ this.options.conn.send(
2332
+ "DOM.querySelector",
2333
+ { nodeId: doc.root.nodeId, selector },
2334
+ this.options.sessionId
2335
+ ),
2336
+ 8e3
2337
+ );
2338
+ if (!result) return 0;
2339
+ return result.nodeId;
2340
+ }
2341
+ /** Query all matching elements, returns array of CDP nodeIds */
2342
+ async querySelectorAll(selector) {
2343
+ const doc = await this.options.conn.send(
2344
+ "DOM.getDocument",
2345
+ { depth: 0 },
2346
+ this.options.sessionId
2347
+ );
2348
+ const result = await this.options.conn.send(
2349
+ "DOM.querySelectorAll",
2350
+ { nodeId: doc.root.nodeId, selector },
2351
+ this.options.sessionId
2352
+ );
2353
+ return result.nodeIds ?? [];
2354
+ }
2355
+ /** Resolve a CDP nodeId to a RemoteObject for evaluate */
2356
+ async resolveNode(nodeId) {
2357
+ const result = await this.options.conn.send(
2358
+ "DOM.resolveNode",
2359
+ { nodeId },
2360
+ this.options.sessionId
2361
+ );
2362
+ return result.object.objectId;
2363
+ }
2364
+ /** Get the box model for a nodeId */
2365
+ async getBoxModel(nodeId) {
2366
+ try {
2367
+ const result = await this.options.conn.send("DOM.getBoxModel", { nodeId }, this.options.sessionId);
2368
+ const c = result.model?.content;
2369
+ if (!c || c.length < 8) return null;
2370
+ const x1 = c[0];
2371
+ const y1 = c[1];
2372
+ const x2 = c[4];
2373
+ const y2 = c[5];
2374
+ return {
2375
+ x: Math.min(x1, x2),
2376
+ y: Math.min(y1, y2),
2377
+ width: Math.abs(x2 - x1),
2378
+ height: Math.abs(y2 - y1)
2379
+ };
2380
+ } catch {
2381
+ return null;
2382
+ }
2383
+ }
2384
+ /** Call a function on a RemoteObject */
2385
+ async callFunctionOn(objectId, functionDeclaration, args = []) {
2386
+ const result = await this.options.conn.send("Runtime.callFunctionOn", {
2387
+ objectId,
2388
+ functionDeclaration,
2389
+ arguments: args.map((a) => ({ value: a })),
2390
+ returnByValue: true
2391
+ }, this.options.sessionId);
2392
+ if (result.exceptionDetails) {
2393
+ throw new Error(`CallFunctionOn error: ${result.exceptionDetails.text}`);
2394
+ }
2395
+ return result.result?.value;
2396
+ }
2397
+ /** Send a CDP command scoped to this page's session */
2398
+ async _cdpSend(method, params) {
2399
+ return this.options.conn.send(method, params, this.options.sessionId);
2400
+ }
2401
+ /** sup-s11: beforeunload 自动应答语义——'accept'(默认,离开页面,与录制
2402
+ * 意图一致)或 'dismiss'(取消导航留守原页,尽力而为:此构建上 CDP
2403
+ * accept:false 对浏览器侧导航的取消语义不稳定,不保证)。 */
2404
+ };
2405
+
2406
+ // src/cdp-driver/page-runtime.ts
2407
+ var RuntimeEvaluationService = class {
2408
+ constructor(options) {
2409
+ this.options = options;
2410
+ }
2411
+ options;
2412
+ async title() {
2413
+ let title = "";
2414
+ for (let attempt = 0; attempt < 20; attempt++) {
2415
+ try {
2416
+ title = await this.evaluate("document.title");
2417
+ if (title) return title;
2418
+ } catch {
2419
+ }
2420
+ await new Promise((resolve) => setTimeout(resolve, 50));
2421
+ }
2422
+ return title;
2423
+ }
2424
+ async content() {
2425
+ return this.evaluate("document.documentElement.outerHTML");
2426
+ }
2427
+ // ── Evaluation ──────────────────────────────────────────────
2428
+ async evaluate(fn, ...args) {
2429
+ if (this.options.isClosed()) throw new Error("Page is closed");
2430
+ this.options.conn.send("Page.handleJavaScriptDialog", { accept: false }, this.options.sessionId).catch(() => {
2431
+ });
2432
+ let expression;
2433
+ if (typeof fn === "string") {
2434
+ expression = fn;
2435
+ } else {
2436
+ const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
2437
+ expression = `(()=>{const __fn=(${fn.toString()});return __fn(${argStr});})()`;
2438
+ }
2439
+ const result = await this.options.conn.send("Runtime.evaluate", {
2440
+ expression,
2441
+ returnByValue: true,
2442
+ awaitPromise: true
2443
+ }, this.options.sessionId);
2444
+ if (result.exceptionDetails) {
2445
+ const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
2446
+ throw new Error(`${detail}`);
2447
+ }
2448
+ return result.result?.value;
2449
+ }
2450
+ /**
2451
+ * 在指定 iframe 上下文中执行表达式(攻防 D16 能力建设,2026-08-19)。
2452
+ *
2453
+ * 双路径:
2454
+ * 1. 同进程 iframe —— Runtime.enable 收集 executionContextCreated,
2455
+ * 找到目标 frameId 的 contextId,用 contextId 定向执行;
2456
+ * 2. 跨域 OOPIF(独立 target)—— Target.setAutoAttach(flatten) 监听
2457
+ * attachedToTarget 中 type==='iframe' 的会话,用其 sessionId 执行。
2458
+ *
2459
+ * 这绕过了页面同源策略(那是页面 JS 的约束,CDP 是调试通道)——
2460
+ * 支付窗/验证码/第三方嵌入内容的读写都靠它。
2461
+ */
2462
+ async evaluateInFrame(urlIncludes, expression) {
2463
+ if (this.options.isClosed()) throw new Error("Page is closed");
2464
+ const evalIn = async (sessionId, contextId) => {
2465
+ const params = { expression, returnByValue: true, awaitPromise: true };
2466
+ if (contextId !== void 0) params.contextId = contextId;
2467
+ const result = await this.options.conn.send("Runtime.evaluate", params, sessionId);
2468
+ if (result.exceptionDetails) {
2469
+ const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
2470
+ throw new Error(`[frame ${urlIncludes}] ${detail}`);
2471
+ }
2472
+ return result.result?.value;
2473
+ };
2474
+ const attachedA = await this.tryAttachViaTargets(urlIncludes);
2475
+ if (attachedA) {
2476
+ try {
2477
+ return await evalIn(attachedA);
2478
+ } finally {
2479
+ this.detachQuietly(attachedA);
2480
+ }
2481
+ }
2482
+ const tree = await this.options.conn.send("Page.getFrameTree", void 0, this.options.sessionId);
2483
+ const all = [];
2484
+ const walk = (node) => {
2485
+ all.push({ id: node.frame.id, url: node.frame.url });
2486
+ for (const child of node.childFrames || []) walk(child);
2487
+ };
2488
+ walk(tree.frameTree);
2489
+ const mainId = tree.frameTree?.frame?.id;
2490
+ const target = all.find((f) => f.id !== mainId && f.url.includes(urlIncludes));
2491
+ if (target) {
2492
+ const contexts = [];
2493
+ const onCtx = (raw) => {
2494
+ const c = raw?.context;
2495
+ if (c?.id && c?.auxData?.frameId) contexts.push({ id: c.id, frameId: c.auxData.frameId });
2496
+ };
2497
+ this.options.conn.on("Runtime.executionContextCreated", onCtx);
2498
+ try {
2499
+ await this.options.conn.send("Runtime.enable", void 0, this.options.sessionId).catch(() => {
2500
+ });
2501
+ await new Promise((r) => setTimeout(r, 400));
2502
+ } finally {
2503
+ this.options.conn.off("Runtime.executionContextCreated", onCtx);
2504
+ }
2505
+ const ctx = contexts.find((c) => c.frameId === target.id);
2506
+ if (ctx) return evalIn(this.options.sessionId, ctx.id);
2507
+ }
2508
+ const attachedC = await this.tryAttachViaAutoAttach(urlIncludes);
2509
+ if (attachedC) {
2510
+ try {
2511
+ return await evalIn(attachedC);
2512
+ } finally {
2513
+ this.detachQuietly(attachedC);
2514
+ }
2515
+ }
2516
+ 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`);
2517
+ }
2518
+ /**
2519
+ * 输入专用 frame session 解析(mouse/click/fill --frame)。
2520
+ *
2521
+ * 与 evaluateInFrame 的区别:必须拿到**真实 target session**(Input 域
2522
+ * 事件派发到该 session 才会进入 iframe 的渲染进程——主页面 session 上
2523
+ * 派发的输入进不去 OOPIF,qqmail 验证码 4 次页面级拖动全败的实证)。
2524
+ * 因此只走 A(getTargets attach)/ C(auto-attach)两路;同进程 frame
2525
+ * 没有 session,但 locator 层的坐标偏移本就支持同源 iframe,直接用普通
2526
+ * click/fill 即可。
2527
+ *
2528
+ * 坐标语义:返回的 session 上派发 Input 事件用 **iframe 局部坐标**
2529
+ * (与该 session 内 getBoundingClientRect 一致)。
2530
+ */
2531
+ async resolveFrameSession(urlIncludes) {
2532
+ if (this.options.isClosed()) throw new Error("Page is closed");
2533
+ const viaTargets = await this.tryAttachViaTargets(urlIncludes);
2534
+ if (viaTargets) return viaTargets;
2535
+ const viaAuto = await this.tryAttachViaAutoAttach(urlIncludes);
2536
+ if (viaAuto) return viaAuto;
2537
+ try {
2538
+ const tree = await this.options.conn.send("Page.getFrameTree", void 0, this.options.sessionId);
2539
+ const urls = [];
2540
+ const walk = (node) => {
2541
+ urls.push(node.frame.url);
2542
+ for (const child of node.childFrames || []) walk(child);
2543
+ };
2544
+ walk(tree.frameTree);
2545
+ if (urls.some((u) => u.includes(urlIncludes))) {
2546
+ 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`);
2547
+ }
2548
+ } catch (err) {
2549
+ if (err instanceof Error && err.message.includes("\u540C\u8FDB\u7A0B")) throw err;
2550
+ }
2551
+ 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`);
2552
+ }
2553
+ /** 浏览器级 iframe target 列表(OOPIF 可见性——Page.getFrameTree 看不到它们) */
2554
+ async listFrameTargets() {
2555
+ try {
2556
+ const tg = await this.options.conn.send("Target.getTargets", void 0);
2557
+ return (tg.targetInfos || []).filter((t) => t.type === "iframe").map((t) => ({ url: t.url || "", targetId: t.targetId }));
2558
+ } catch {
2559
+ return [];
2560
+ }
2561
+ }
2562
+ /** 路径 A:浏览器级 Target.getTargets 平铺 iframe target,按 URL 子串 attach。
2563
+ * 多次导航后列表里可能残留正在销毁的陈旧 target——attach 后用 location.href
2564
+ * 验证候选确实是活目标,不匹配则换下一个(验证码 iframe 重建场景实测会撞上)。 */
2565
+ async tryAttachViaTargets(urlIncludes) {
2566
+ try {
2567
+ const tg = await this.options.conn.send("Target.getTargets", void 0);
2568
+ const candidates = (tg.targetInfos || []).filter((t) => t.type === "iframe" && (t.url || "").includes(urlIncludes));
2569
+ for (const hit of candidates) {
2570
+ try {
2571
+ const att = await this.options.conn.send("Target.attachToTarget", { targetId: hit.targetId, flatten: true });
2572
+ const probe = await this.options.conn.send("Runtime.evaluate", { expression: "location.href", returnByValue: true }, att.sessionId);
2573
+ const href = typeof probe.result?.value === "string" ? probe.result.value : "";
2574
+ if (probe.exceptionDetails || !href.includes(urlIncludes)) {
2575
+ this.detachQuietly(att.sessionId);
2576
+ continue;
2577
+ }
2578
+ return att.sessionId;
2579
+ } catch {
2580
+ continue;
2581
+ }
2582
+ }
2583
+ } catch {
2584
+ }
2585
+ return null;
2586
+ }
2587
+ /** 路径 C:Target.setAutoAttach 监听后续 attach 的 iframe target(兜底) */
2588
+ async tryAttachViaAutoAttach(urlIncludes) {
2589
+ const attached = [];
2590
+ const onAttach = (raw) => {
2591
+ const ev = raw;
2592
+ if (ev?.sessionId && ev.targetInfo?.type === "iframe") {
2593
+ attached.push({ sessionId: ev.sessionId, url: ev.targetInfo.url || "" });
2594
+ }
2595
+ };
2596
+ this.options.conn.on("Target.attachedToTarget", onAttach);
2597
+ try {
2598
+ await this.options.conn.send("Target.setAutoAttach", {
2599
+ autoAttach: true,
2600
+ waitForDebuggerOnStart: false,
2601
+ flatten: true
2602
+ }, this.options.sessionId);
2603
+ await new Promise((r) => setTimeout(r, 600));
2604
+ } finally {
2605
+ this.options.conn.off("Target.attachedToTarget", onAttach);
2606
+ this.options.conn.send("Target.setAutoAttach", { autoAttach: false, waitForDebuggerOnStart: false, flatten: true }, this.options.sessionId).catch(() => {
2607
+ });
2608
+ }
2609
+ const hit = attached.find((a) => a.url.includes(urlIncludes));
2610
+ return hit ? hit.sessionId : null;
2611
+ }
2612
+ detachQuietly(sessionId) {
2613
+ this.options.conn.send("Target.detachFromTarget", { sessionId }).catch(() => {
2614
+ });
2615
+ }
2616
+ /** evaluateHandle — evaluates fn and returns a handle for element bounding box */
2617
+ async evaluateHandle(fn, ...args) {
2618
+ let expression;
2619
+ if (typeof fn === "string") {
2620
+ expression = fn;
2621
+ } else {
2622
+ const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
2623
+ 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;})()`;
2624
+ }
2625
+ const result = await this.options.conn.send("Runtime.evaluate", { expression, returnByValue: true }).catch(() => ({ result: { value: null } }));
2626
+ let box = null;
2627
+ try {
2628
+ box = JSON.parse(result.result?.value);
2629
+ } catch {
2630
+ }
2631
+ return {
2632
+ asElement: () => box ? { boundingBox: async () => box } : null
2633
+ };
2634
+ }
2635
+ async $eval(selector, fn, ...args) {
2636
+ const fnBody = typeof fn === "function" ? fn.toString() : fn;
2637
+ const selJSON = JSON.stringify(selector);
2638
+ const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
2639
+ return this.evaluate(
2640
+ `(function(sel, xpathExpr, fnStr, ...evalArgs) {
2641
+ const el = xpathExpr
2642
+ ? document.evaluate(xpathExpr, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
2643
+ : document.querySelector(sel);
2644
+ if (!el) throw new Error('No element found for selector: ' + sel);
2645
+ const fn = new Function('return ' + fnStr)();
2646
+ return fn(el, ...evalArgs);
2647
+ })(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
2648
+ );
2649
+ }
2650
+ async $$eval(selector, fn, ...args) {
2651
+ const fnBody = typeof fn === "function" ? fn.toString() : fn;
2652
+ const selJSON = JSON.stringify(selector);
2653
+ const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
2654
+ return this.evaluate(
2655
+ `(function(sel, xpathExpr, fnStr, ...evalArgs) {
2656
+ const els = xpathExpr
2657
+ ? (() => { 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; })()
2658
+ : Array.from(document.querySelectorAll(sel));
2659
+ const fn = new Function('return ' + fnStr)();
2660
+ return fn(els, ...evalArgs);
2661
+ })(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
2662
+ );
2663
+ }
2664
+ };
2665
+
2666
+ // src/cdp-driver/page-frame-input.ts
2667
+ function isSessionDeadError(err) {
2668
+ return /session (with given id )?not found|no session with given id/i.test(errMsg(err));
2669
+ }
2670
+ var FrameInputService = class {
2671
+ constructor(deps) {
2672
+ this.deps = deps;
2673
+ }
2674
+ deps;
2675
+ /** urlIncludes → 已 attach 的 session + 鼠标实例(跨命令保持位置状态) */
2676
+ cache = /* @__PURE__ */ new Map();
2677
+ /**
2678
+ * 拿到指定 OOPIF 的鼠标(Input 域派发进 iframe 渲染进程,isTrusted=true)。
2679
+ * 缓存的 session 失效(iframe 重建/刷新)时自动重 attach;重 attach 会
2680
+ * 重置鼠标位置——调用方需重新读取目标元素坐标。
2681
+ */
2682
+ async frameMouse(urlIncludes, opts = {}) {
2683
+ if (opts.fresh) this.cache.delete(urlIncludes);
2684
+ const cached = this.cache.get(urlIncludes);
2685
+ if (cached) {
2686
+ try {
2687
+ await this.deps.conn.send("Runtime.evaluate", { expression: "1", returnByValue: true }, cached.sessionId);
2688
+ return cached.mouse;
2689
+ } catch {
2690
+ this.cache.delete(urlIncludes);
2691
+ }
2692
+ }
2693
+ const sessionId = await this.deps.resolveFrameSession(urlIncludes);
2694
+ const mouse = new XBMouseImpl(this.deps.conn, sessionId);
2695
+ this.cache.set(urlIncludes, { sessionId, mouse });
2696
+ return mouse;
2697
+ }
2698
+ /**
2699
+ * 带重试的 frame 鼠标操作:Chrome 异步销毁旧 OOPIF target 的窗口期里
2700
+ * (连续导航/验证码 iframe 重建),probe 通过后 dispatch 仍可能撞上死
2701
+ * session——session 失效时强制重 attach 再做一次。
2702
+ */
2703
+ async runFrameMouse(urlIncludes, fn) {
2704
+ try {
2705
+ return await fn(await this.frameMouse(urlIncludes));
2706
+ } catch (err) {
2707
+ if (!isSessionDeadError(err)) throw err;
2708
+ this.cache.delete(urlIncludes);
2709
+ return fn(await this.frameMouse(urlIncludes, { fresh: true }));
2710
+ }
2711
+ }
2712
+ /** 在 OOPIF 内点击选择器命中的元素(frame 局部坐标,stealth 落点偏移继承) */
2713
+ async clickInFrame(urlIncludes, selector, opts = {}) {
2714
+ const rect = await this.pollFrameRect(urlIncludes, selector, opts.timeoutMs ?? 5e3);
2715
+ const x = rect.x + rect.width / 2;
2716
+ const y = rect.y + rect.height / 2;
2717
+ await this.runFrameMouse(urlIncludes, (mouse) => mouse.click(x, y, { elementWidth: rect.width, elementHeight: rect.height }));
2718
+ return { x, y };
2719
+ }
2720
+ /** 在 OOPIF 内填输入框:点击聚焦 → el.select() 全选 → insertText 整体替换 → 回读验证 */
2721
+ async fillInFrame(urlIncludes, selector, text, opts = {}) {
2722
+ try {
2723
+ return await this.fillInFrameInner(urlIncludes, selector, text, opts);
2724
+ } catch (err) {
2725
+ if (!isSessionDeadError(err)) throw err;
2726
+ this.cache.delete(urlIncludes);
2727
+ return this.fillInFrameInner(urlIncludes, selector, text, opts);
2728
+ }
2729
+ }
2730
+ async fillInFrameInner(urlIncludes, selector, text, opts = {}) {
2731
+ await this.clickInFrame(urlIncludes, selector, opts);
2732
+ const cached = this.cache.get(urlIncludes);
2733
+ if (!cached) throw new Error(`frame session lost for "${urlIncludes}"`);
2734
+ await this.deps.evaluateInFrame(
2735
+ urlIncludes,
2736
+ `(() => { const el = document.querySelector(${JSON.stringify(selector)}); if (el && typeof el.select === 'function') el.select(); return true; })()`
2737
+ );
2738
+ await this.deps.conn.send("Input.insertText", { text }, cached.sessionId);
2739
+ const readback = await this.deps.evaluateInFrame(
2740
+ urlIncludes,
2741
+ `(() => { const el = document.querySelector(${JSON.stringify(selector)}); return el ? String(el.value ?? '') : ''; })()`
2742
+ );
2743
+ return { value: readback ?? "" };
2744
+ }
2745
+ /** 轮询 OOPIF 内元素 rect(等待元素出现/可测量) */
2746
+ async pollFrameRect(urlIncludes, selector, timeoutMs) {
2747
+ 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 }; })()`;
2748
+ const deadline = Date.now() + timeoutMs;
2749
+ let lastErr;
2750
+ while (Date.now() < deadline) {
2751
+ try {
2752
+ const rect = await this.deps.evaluateInFrame(urlIncludes, expr);
2753
+ if (rect) return rect;
2754
+ } catch (err) {
2755
+ lastErr = err;
2756
+ }
2757
+ await new Promise((r) => setTimeout(r, 200));
2758
+ }
2759
+ throw new Error(`[frame ${urlIncludes}] element "${selector}" not found/visible within ${timeoutMs}ms${lastErr instanceof Error ? `\uFF08last: ${lastErr.message}\uFF09` : ""}`);
2760
+ }
2761
+ };
2762
+
2763
+ // src/cdp-driver/page.ts
2764
+ var XBPageImpl = class _XBPageImpl {
2765
+ conn;
2766
+ _emitter = new EventEmitter();
2767
+ _subscriptions = [];
2768
+ sessionId;
2769
+ _targetId;
2770
+ _contextImpl;
2771
+ _browserImpl;
2772
+ _closed = false;
2773
+ _url = "about:blank";
2774
+ _viewportSize = null;
2775
+ _loadState = {
2776
+ loadFired: true,
2777
+ domContentFired: true,
2778
+ networkIdle: true
2779
+ };
2780
+ mouse;
2781
+ keyboard;
2782
+ mediaService;
2783
+ fileInputService;
2784
+ networkWaitService;
2785
+ networkRouteService;
2786
+ navigationService;
2787
+ domQueryService;
2788
+ runtimeEvaluationService;
2789
+ frameInputService;
2790
+ // Network tracking for waitForLoadState('networkidle')
2791
+ inflightRequests = /* @__PURE__ */ new Set();
2792
+ networkIdleResolve = null;
2793
+ networkIdleTimer = null;
2794
+ static NETWORK_IDLE_MS = 500;
2795
+ constructor(conn, sessionId, targetId, context, browser) {
2796
+ this.conn = conn;
2797
+ this.sessionId = sessionId;
2798
+ this._targetId = targetId;
2799
+ this._contextImpl = context;
2800
+ this._browserImpl = browser;
2801
+ this.mouse = new XBMouseImpl(conn, sessionId);
2802
+ this.keyboard = new XBKeyboardImpl(conn, sessionId);
2803
+ this.mediaService = new MediaService({
2804
+ conn,
2805
+ sessionId,
2806
+ viewportSize: this._viewportSize,
2807
+ evaluate: (script) => this.evaluate(script),
2808
+ onViewportSize: (size) => {
2809
+ this._viewportSize = size;
2810
+ }
2811
+ });
2812
+ this.fileInputService = new FileInputService({
2813
+ conn,
2814
+ sessionId,
2815
+ evaluate: (script) => this.evaluate(script),
2816
+ mouse: this.mouse
2817
+ });
2818
+ this.networkWaitService = new NetworkWaitService({
2819
+ conn,
2820
+ sessionId,
2821
+ responses: this._networkResponses,
2822
+ requests: this._networkRequests,
2823
+ on: (event, handler) => this._emitter.on(event, handler),
2824
+ off: (event, handler) => this._emitter.removeListener(event, handler),
2825
+ currentUrl: () => this.url()
2826
+ });
2827
+ this.networkRouteService = new NetworkRouteService({
2828
+ conn,
2829
+ sessionId,
2830
+ emit: (event, ...args) => this._emit(event, ...args)
2831
+ });
2832
+ this.navigationService = new NavigationService({
2833
+ conn,
2834
+ sessionId,
2835
+ state: this._loadState,
2836
+ stealthConfig: this._contextImpl.stealthConfig,
2837
+ isClosed: () => this._closed,
2838
+ setUrl: (url) => {
2839
+ this._url = url;
2840
+ },
2841
+ currentUrl: () => this.url(),
2842
+ waitForLoadState: (state, timeout) => this.waitForLoadState(state, timeout),
2843
+ waitForTimeout: (ms) => this.waitForTimeout(ms),
2844
+ evaluate: (script) => this.evaluate(script)
2845
+ });
2846
+ this.runtimeEvaluationService = new RuntimeEvaluationService({
2847
+ conn,
2848
+ sessionId,
2849
+ isClosed: () => this._closed,
2850
+ url: () => this.url()
2851
+ });
2852
+ this.frameInputService = new FrameInputService({
2853
+ conn,
2854
+ resolveFrameSession: (urlIncludes) => this.runtimeEvaluationService.resolveFrameSession(urlIncludes),
2855
+ evaluateInFrame: (urlIncludes, expression) => this.evaluateInFrame(urlIncludes, expression)
2856
+ });
2857
+ this.domQueryService = new DomQueryService({
2858
+ conn,
2859
+ sessionId,
2860
+ evaluate: (script) => this.evaluate(script)
2861
+ });
2862
+ }
2863
+ _emit(event, ...args) {
2864
+ this._emitter.emit(event, ...args);
2865
+ }
2866
+ /** Internal initialization — must be called after construction */
2867
+ async _init() {
2868
+ await this.conn.send("Page.enable", void 0, this.sessionId);
2869
+ await this.conn.send("Runtime.enable", void 0, this.sessionId);
2870
+ await this.conn.send("Network.enable", void 0, this.sessionId);
2871
+ await this.conn.send("DOM.enable", void 0, this.sessionId).catch(() => {
2872
+ });
2873
+ if (this._contextImpl.ignoreHTTPSErrors) {
2874
+ await this.conn.send("Security.enable", void 0, this.sessionId).catch(() => {
2875
+ });
2876
+ await this.conn.send("Security.setIgnoreCertificateErrors", { ignore: true }, this.sessionId).catch(() => {
2877
+ });
2878
+ }
2879
+ if (this._contextImpl.httpCredentials) {
2880
+ await this.conn.send("Fetch.enable", {
2881
+ patterns: [{ urlPattern: "*", requestStage: "Request" }],
1639
2882
  handleAuthRequests: true
1640
2883
  }, this.sessionId).catch(() => {
1641
2884
  });
1642
2885
  this._subscriptions.push(
1643
2886
  this.conn.subscribe("Fetch.requestPaused", this.sessionId, (params) => {
1644
- if (this._interceptionEnabled) return;
2887
+ if (this.networkRouteService.isInterceptionEnabled) return;
1645
2888
  const p = params;
1646
2889
  this.conn.send("Fetch.continueRequest", { requestId: p.requestId }, this.sessionId).catch(() => {
1647
2890
  });
@@ -1820,9 +3063,9 @@ var XBPageImpl = class _XBPageImpl {
1820
3063
  "Target.getTargetInfo",
1821
3064
  { targetId: this._targetId }
1822
3065
  );
1823
- this._url = info.url;
1824
- this._title = info.title;
1825
- if (info.url && info.url !== "about:blank" && info.url !== "") {
3066
+ const curUrl = info.targetInfo?.url ?? info.url;
3067
+ if (curUrl) this._url = curUrl;
3068
+ if (curUrl && curUrl !== "about:blank" && curUrl !== "") {
1826
3069
  this._loadState = { loadFired: true, domContentFired: true, networkIdle: true };
1827
3070
  }
1828
3071
  } catch {
@@ -1833,108 +3076,16 @@ var XBPageImpl = class _XBPageImpl {
1833
3076
  }
1834
3077
  // ── Navigation ──────────────────────────────────────────────
1835
3078
  async goto(url, opts = {}) {
1836
- if (this._closed) throw new Error("Page is closed");
1837
- const waitUntil = opts.waitUntil ?? "load";
1838
- const timeout = opts.timeout ?? 3e4;
1839
- this._loadState = { loadFired: false, domContentFired: false, networkIdle: false };
1840
- if (process.env.XBROWSER_STEALTH !== "off") {
1841
- try {
1842
- await this.conn.send(
1843
- "Page.addScriptToEvaluateOnNewDocument",
1844
- { source: buildStealthInitScript({ ...DEFAULT_STEALTH_CONFIG, ...this._contextImpl.stealthConfig ?? {} }) },
1845
- this.sessionId
1846
- );
1847
- } catch {
1848
- }
1849
- try {
1850
- const rawUa = await this.conn.send(
1851
- "Runtime.evaluate",
1852
- { expression: "navigator.userAgent", returnByValue: true },
1853
- this.sessionId
1854
- );
1855
- const ua = rawUa?.value || "";
1856
- const cleaned = ua.replace(/HeadlessChrome/g, "Chrome");
1857
- if (cleaned !== ua) {
1858
- await this.conn.send(
1859
- "Network.setUserAgentOverride",
1860
- { userAgent: cleaned },
1861
- this.sessionId
1862
- );
1863
- }
1864
- } catch {
1865
- }
1866
- }
1867
- const result = await this.conn.send(
1868
- "Page.navigate",
1869
- { url, referrer: opts.referer },
1870
- this.sessionId
1871
- );
1872
- if (result.errorText) {
1873
- throw new Error(`Navigation failed: ${result.errorText}`);
1874
- }
1875
- if (waitUntil === "commit") {
1876
- this._url = url;
1877
- return {
1878
- status: () => 0,
1879
- ok: () => false,
1880
- url: () => url,
1881
- headers: () => ({})
1882
- };
1883
- }
1884
- await this.waitForLoadState(waitUntil, timeout);
1885
- this._url = url;
1886
- const statusCode = 200;
1887
- const finalUrl = url;
1888
- const headers = {};
1889
- return {
1890
- status: () => statusCode,
1891
- ok: () => statusCode >= 200 && statusCode < 300,
1892
- url: () => finalUrl,
1893
- headers: () => headers
1894
- };
3079
+ return this.navigationService.goto(url, opts);
1895
3080
  }
1896
3081
  async goBack(opts = {}) {
1897
- try {
1898
- const navHistory = await this.conn.send("Page.getNavigationHistory", void 0, this.sessionId);
1899
- if (navHistory.currentIndex > 0) {
1900
- const prevUrl = navHistory.entries[navHistory.currentIndex - 1]?.url;
1901
- if (prevUrl && prevUrl !== "about:blank") {
1902
- await this.conn.send("Page.navigate", { url: prevUrl }, this.sessionId);
1903
- await this.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
1904
- });
1905
- this._url = prevUrl;
1906
- return;
1907
- }
1908
- }
1909
- } catch {
1910
- }
1911
- await this.evaluate("() => history.back()");
1912
- await this.waitForTimeout(3e3);
1913
- this._url = await this.evaluate("location.href").catch(() => this._url);
3082
+ return this.navigationService.goBack(opts);
1914
3083
  }
1915
3084
  async goForward(opts = {}) {
1916
- try {
1917
- const navHistory = await this.conn.send("Page.getNavigationHistory", void 0, this.sessionId);
1918
- if (navHistory.currentIndex < navHistory.entries.length - 1) {
1919
- const nextUrl = navHistory.entries[navHistory.currentIndex + 1]?.url;
1920
- if (nextUrl && nextUrl !== "about:blank") {
1921
- await this.conn.send("Page.navigate", { url: nextUrl }, this.sessionId);
1922
- await this.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
1923
- });
1924
- this._url = nextUrl;
1925
- return;
1926
- }
1927
- }
1928
- } catch {
1929
- }
1930
- await this.evaluate("() => history.forward()");
1931
- await this.waitForTimeout(3e3);
1932
- this._url = await this.evaluate("location.href").catch(() => this._url);
3085
+ return this.navigationService.goForward(opts);
1933
3086
  }
1934
3087
  async reload(opts = {}) {
1935
- this._loadState = { loadFired: false, domContentFired: false, networkIdle: false };
1936
- await this.conn.send("Page.reload", void 0, this.sessionId);
1937
- await this.waitForLoadState(opts.waitUntil ?? "load", opts.timeout);
3088
+ return this.navigationService.reload(opts);
1938
3089
  }
1939
3090
  async waitForLoadState(state = "load", timeout = 3e4) {
1940
3091
  if (this._closed) throw new Error("Page is closed");
@@ -1988,223 +3139,88 @@ var XBPageImpl = class _XBPageImpl {
1988
3139
  const visible = await this.evaluate(
1989
3140
  `(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'; })()`
1990
3141
  );
1991
- if (visible) return;
1992
- }
1993
- if (state === "hidden") {
1994
- if (!exists) return;
1995
- const visible = await this.evaluate(
1996
- `(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'; })()`
1997
- );
1998
- if (!visible) return;
1999
- }
2000
- await this.waitForTimeout(100);
2001
- }
2002
- throw new Error(`waitForSelector('${selector}', state='${state}') timeout after ${timeout}ms`);
2003
- }
2004
- async waitForFunction(fn, opts = {}, ...args) {
2005
- const timeout = opts.timeout ?? 3e4;
2006
- const polling = opts.polling ?? 100;
2007
- const deadline = Date.now() + timeout;
2008
- const fnBody = typeof fn === "function" ? fn.toString() : fn;
2009
- let lastError = null;
2010
- while (Date.now() < deadline) {
2011
- try {
2012
- const result = await this.evaluate(
2013
- `(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(", ") : ""})`
2014
- );
2015
- if (result) return result;
2016
- } catch (err) {
2017
- lastError = err instanceof Error ? err : new Error(errMsg(err));
2018
- }
2019
- const pollMs = typeof polling === "number" ? polling : 16;
2020
- await this.waitForTimeout(pollMs);
2021
- }
2022
- const detail = lastError ? `
2023
- Last error: ${lastError.message}` : "";
2024
- throw new Error(`waitForFunction timeout after ${timeout}ms${detail}`);
2025
- }
2026
- url() {
2027
- return this._url;
2028
- }
2029
- async title() {
2030
- for (let i = 0; i < 20; i++) {
2031
- try {
2032
- this._title = await this.evaluate("document.title");
2033
- if (this._title) return this._title;
2034
- } catch {
2035
- }
2036
- await new Promise((r) => setTimeout(r, 50));
2037
- }
2038
- try {
2039
- const info = await this._cdpSend("Target.getTargetInfo", { targetId: this._targetId });
2040
- if (info?.title) {
2041
- this._title = info.title;
2042
- return this._title;
2043
- }
2044
- } catch {
2045
- }
2046
- return this._title;
2047
- }
2048
- async content() {
2049
- return this.evaluate("document.documentElement.outerHTML");
2050
- }
2051
- // ── Evaluation ──────────────────────────────────────────────
2052
- async evaluate(fn, ...args) {
2053
- if (this._closed) throw new Error("Page is closed");
2054
- this.conn.send("Page.handleJavaScriptDialog", { accept: false }, this.sessionId).catch(() => {
2055
- });
2056
- let expression;
2057
- if (typeof fn === "string") {
2058
- expression = fn;
2059
- } else {
2060
- const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
2061
- expression = `(()=>{const __fn=(${fn.toString()});return __fn(${argStr});})()`;
2062
- }
2063
- const result = await this.conn.send("Runtime.evaluate", {
2064
- expression,
2065
- returnByValue: true,
2066
- awaitPromise: true
2067
- }, this.sessionId);
2068
- if (result.exceptionDetails) {
2069
- const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
2070
- throw new Error(`${detail}`);
2071
- }
2072
- return result.result?.value;
2073
- }
2074
- /**
2075
- * 在指定 iframe 上下文中执行表达式(攻防 D16 能力建设,2026-08-19)。
2076
- *
2077
- * 双路径:
2078
- * 1. 同进程 iframe —— Runtime.enable 收集 executionContextCreated,
2079
- * 找到目标 frameId 的 contextId,用 contextId 定向执行;
2080
- * 2. 跨域 OOPIF(独立 target)—— Target.setAutoAttach(flatten) 监听
2081
- * attachedToTarget 中 type==='iframe' 的会话,用其 sessionId 执行。
2082
- *
2083
- * 这绕过了页面同源策略(那是页面 JS 的约束,CDP 是调试通道)——
2084
- * 支付窗/验证码/第三方嵌入内容的读写都靠它。
2085
- */
2086
- async evaluateInFrame(urlIncludes, expression) {
2087
- if (this._closed) throw new Error("Page is closed");
2088
- const evalIn = async (sessionId, contextId) => {
2089
- const params = { expression, returnByValue: true, awaitPromise: true };
2090
- if (contextId !== void 0) params.contextId = contextId;
2091
- const result = await this.conn.send("Runtime.evaluate", params, sessionId);
2092
- if (result.exceptionDetails) {
2093
- const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
2094
- throw new Error(`[frame ${urlIncludes}] ${detail}`);
2095
- }
2096
- return result.result?.value;
2097
- };
2098
- try {
2099
- const tg = await this.conn.send("Target.getTargets", void 0);
2100
- const hit2 = (tg.targetInfos || []).find((t) => t.type === "iframe" && (t.url || "").includes(urlIncludes));
2101
- if (hit2) {
2102
- const att = await this.conn.send("Target.attachToTarget", { targetId: hit2.targetId, flatten: true });
2103
- return evalIn(att.sessionId);
2104
- }
2105
- } catch {
2106
- }
2107
- const tree = await this.conn.send("Page.getFrameTree", void 0, this.sessionId);
2108
- const all = [];
2109
- const walk = (node) => {
2110
- all.push({ id: node.frame.id, url: node.frame.url });
2111
- for (const child of node.childFrames || []) walk(child);
2112
- };
2113
- walk(tree.frameTree);
2114
- const mainId = tree.frameTree?.frame?.id;
2115
- const target = all.find((f) => f.id !== mainId && f.url.includes(urlIncludes));
2116
- if (target) {
2117
- const contexts = [];
2118
- const onCtx = (raw) => {
2119
- const c = raw?.context;
2120
- if (c?.id && c?.auxData?.frameId) contexts.push({ id: c.id, frameId: c.auxData.frameId });
2121
- };
2122
- this.conn.on("Runtime.executionContextCreated", onCtx);
2123
- try {
2124
- await this.conn.send("Runtime.enable", void 0, this.sessionId).catch(() => {
2125
- });
2126
- await new Promise((r) => setTimeout(r, 400));
2127
- } finally {
2128
- this.conn.off("Runtime.executionContextCreated", onCtx);
2129
- }
2130
- const ctx = contexts.find((c) => c.frameId === target.id);
2131
- if (ctx) return evalIn(this.sessionId, ctx.id);
2132
- }
2133
- const attached = [];
2134
- const onAttach = (raw) => {
2135
- const ev = raw;
2136
- if (ev?.sessionId && ev.targetInfo?.type === "iframe") {
2137
- attached.push({ sessionId: ev.sessionId, url: ev.targetInfo.url || "" });
2138
- }
2139
- };
2140
- this.conn.on("Target.attachedToTarget", onAttach);
2141
- try {
2142
- await this.conn.send("Target.setAutoAttach", {
2143
- autoAttach: true,
2144
- waitForDebuggerOnStart: false,
2145
- flatten: true
2146
- }, this.sessionId);
2147
- await new Promise((r) => setTimeout(r, 600));
2148
- } finally {
2149
- this.conn.off("Target.attachedToTarget", onAttach);
2150
- this.conn.send("Target.setAutoAttach", { autoAttach: false, waitForDebuggerOnStart: false, flatten: true }, this.sessionId).catch(() => {
2151
- });
2152
- }
2153
- const hit = attached.find((a) => a.url.includes(urlIncludes));
2154
- if (!hit) {
2155
- 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`);
3142
+ if (visible) return;
3143
+ }
3144
+ if (state === "hidden") {
3145
+ if (!exists) return;
3146
+ const visible = await this.evaluate(
3147
+ `(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'; })()`
3148
+ );
3149
+ if (!visible) return;
3150
+ }
3151
+ await this.waitForTimeout(100);
2156
3152
  }
2157
- return evalIn(hit.sessionId);
3153
+ throw new Error(`waitForSelector('${selector}', state='${state}') timeout after ${timeout}ms`);
2158
3154
  }
2159
- /** evaluateHandle — evaluates fn and returns a handle for element bounding box */
2160
- async evaluateHandle(fn, ...args) {
2161
- let expression;
2162
- if (typeof fn === "string") {
2163
- expression = fn;
2164
- } else {
2165
- const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
2166
- 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;})()`;
2167
- }
2168
- const result = await this.conn.send("Runtime.evaluate", { expression, returnByValue: true }).catch(() => ({ result: { value: null } }));
2169
- let box = null;
2170
- try {
2171
- box = JSON.parse(result.result?.value);
2172
- } catch {
3155
+ async waitForFunction(fn, opts = {}, ...args) {
3156
+ const timeout = opts.timeout ?? 3e4;
3157
+ const polling = opts.polling ?? 100;
3158
+ const deadline = Date.now() + timeout;
3159
+ const fnBody = typeof fn === "function" ? fn.toString() : fn;
3160
+ let lastError = null;
3161
+ while (Date.now() < deadline) {
3162
+ try {
3163
+ const result = await this.evaluate(
3164
+ `(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(", ") : ""})`
3165
+ );
3166
+ if (result) return result;
3167
+ } catch (err) {
3168
+ lastError = err instanceof Error ? err : new Error(errMsg(err));
3169
+ }
3170
+ const pollMs = typeof polling === "number" ? polling : 16;
3171
+ await this.waitForTimeout(pollMs);
2173
3172
  }
2174
- return {
2175
- asElement: () => box ? { boundingBox: async () => box } : null
2176
- };
3173
+ const detail = lastError ? `
3174
+ Last error: ${lastError.message}` : "";
3175
+ throw new Error(`waitForFunction timeout after ${timeout}ms${detail}`);
3176
+ }
3177
+ url() {
3178
+ return this._url;
3179
+ }
3180
+ async title() {
3181
+ return this.runtimeEvaluationService.title();
3182
+ }
3183
+ async content() {
3184
+ return this.runtimeEvaluationService.content();
3185
+ }
3186
+ async evaluate(fn, ...args) {
3187
+ return this.runtimeEvaluationService.evaluate(fn, ...args);
3188
+ }
3189
+ async evaluateInFrame(urlIncludes, expression) {
3190
+ return this.runtimeEvaluationService.evaluateInFrame(urlIncludes, expression);
3191
+ }
3192
+ /** 浏览器级 iframe target 列表(OOPIF 可见——frames 命令用) */
3193
+ async listFrameTargets() {
3194
+ return this.runtimeEvaluationService.listFrameTargets();
3195
+ }
3196
+ /**
3197
+ * 拿到指定 OOPIF 的鼠标(Input 域派发进 iframe 渲染进程,isTrusted=true)。
3198
+ * 坐标语义:iframe 局部坐标(与该 session 内 getBoundingClientRect 一致)。
3199
+ * session 失效自动重 attach(鼠标位置会重置,需重读目标坐标)。
3200
+ */
3201
+ async frameMouse(urlIncludes, opts) {
3202
+ return this.frameInputService.frameMouse(urlIncludes, opts);
3203
+ }
3204
+ async runFrameMouse(urlIncludes, fn) {
3205
+ return this.frameInputService.runFrameMouse(urlIncludes, fn);
3206
+ }
3207
+ /** 在 OOPIF 内点击选择器命中的元素(轮询等待 + stealth 落点) */
3208
+ async clickInFrame(urlIncludes, selector, opts) {
3209
+ return this.frameInputService.clickInFrame(urlIncludes, selector, opts);
3210
+ }
3211
+ /** 在 OOPIF 内填输入框(点击聚焦 + insertText + 回读) */
3212
+ async fillInFrame(urlIncludes, selector, text, opts) {
3213
+ return this.frameInputService.fillInFrame(urlIncludes, selector, text, opts);
3214
+ }
3215
+ async evaluateHandle(script, ...args) {
3216
+ return this.runtimeEvaluationService.evaluateHandle(script, ...args);
2177
3217
  }
2178
3218
  async $eval(selector, fn, ...args) {
2179
- const fnBody = typeof fn === "function" ? fn.toString() : fn;
2180
- const selJSON = JSON.stringify(selector);
2181
- const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
2182
- return this.evaluate(
2183
- `(function(sel, xpathExpr, fnStr, ...evalArgs) {
2184
- const el = xpathExpr
2185
- ? document.evaluate(xpathExpr, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
2186
- : document.querySelector(sel);
2187
- if (!el) throw new Error('No element found for selector: ' + sel);
2188
- const fn = new Function('return ' + fnStr)();
2189
- return fn(el, ...evalArgs);
2190
- })(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
2191
- );
3219
+ return this.runtimeEvaluationService.$eval(selector, fn, ...args);
2192
3220
  }
2193
3221
  async $$eval(selector, fn, ...args) {
2194
- const fnBody = typeof fn === "function" ? fn.toString() : fn;
2195
- const selJSON = JSON.stringify(selector);
2196
- const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
2197
- return this.evaluate(
2198
- `(function(sel, xpathExpr, fnStr, ...evalArgs) {
2199
- const els = xpathExpr
2200
- ? (() => { 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; })()
2201
- : Array.from(document.querySelectorAll(sel));
2202
- const fn = new Function('return ' + fnStr)();
2203
- return fn(els, ...evalArgs);
2204
- })(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
2205
- );
3222
+ return this.runtimeEvaluationService.$$eval(selector, fn, ...args);
2206
3223
  }
2207
- // ── Locator ─────────────────────────────────────────────────
2208
3224
  locator(selector) {
2209
3225
  return new XBLocatorImpl(this, selector);
2210
3226
  }
@@ -2325,88 +3341,20 @@ Last error: ${lastError.message}` : "";
2325
3341
  }
2326
3342
  // ── Screen ──────────────────────────────────────────────────
2327
3343
  async screenshot(opts = {}) {
2328
- const params = {
2329
- format: opts.type ?? "png"
2330
- };
2331
- if (opts.quality !== void 0 && (opts.type === "jpeg" || !opts.type && opts.quality)) {
2332
- params.quality = opts.quality;
2333
- }
2334
- if (opts.fullPage) {
2335
- params.captureBeyondViewport = true;
2336
- }
2337
- if (opts.clip) {
2338
- const clip = {
2339
- x: Math.round(opts.clip.x),
2340
- y: Math.round(opts.clip.y),
2341
- width: Math.round(Math.max(1, opts.clip.width)),
2342
- height: Math.round(Math.max(1, opts.clip.height)),
2343
- scale: 1
2344
- };
2345
- params.clip = clip;
2346
- }
2347
- if (opts.omitBackground) {
2348
- params.omitBackground = true;
2349
- }
2350
- const result = await this.conn.send(
2351
- "Page.captureScreenshot",
2352
- params,
2353
- this.sessionId
2354
- );
2355
- return Buffer.from(result.data, "base64");
3344
+ return this.mediaService.screenshot(opts);
2356
3345
  }
2357
3346
  async pdf(opts = {}) {
2358
- const params = {};
2359
- if (opts.landscape !== void 0) params.landscape = opts.landscape;
2360
- if (opts.printBackground !== void 0) params.printBackground = opts.printBackground;
2361
- if (opts.scale !== void 0) params.scale = opts.scale;
2362
- if (opts.format) params.paperFormat = opts.format;
2363
- if (opts.preferCSSPageSize !== void 0) params.preferCSSPageSize = opts.preferCSSPageSize;
2364
- if (opts.margin) {
2365
- if (opts.margin.top) params.marginTop = parseFloat(opts.margin.top);
2366
- if (opts.margin.bottom) params.marginBottom = parseFloat(opts.margin.bottom);
2367
- if (opts.margin.left) params.marginLeft = parseFloat(opts.margin.left);
2368
- if (opts.margin.right) params.marginRight = parseFloat(opts.margin.right);
2369
- }
2370
- const result = await this.conn.send("Page.printToPDF", params, this.sessionId);
2371
- return Buffer.from(result.data, "base64");
3347
+ return this.mediaService.pdf(opts);
2372
3348
  }
2373
3349
  viewportSize() {
2374
- return this._viewportSize ?? null;
3350
+ return this._viewportSize;
2375
3351
  }
2376
3352
  async setViewportSize(size) {
2377
- await this.conn.send(
2378
- "Emulation.setDeviceMetricsOverride",
2379
- {
2380
- width: size.width,
2381
- height: size.height,
2382
- deviceScaleFactor: 1,
2383
- mobile: false
2384
- },
2385
- this.sessionId
2386
- );
2387
- this._viewportSize = size;
3353
+ return this.mediaService.setViewportSize(size);
2388
3354
  }
2389
- /**
2390
- * env-E2: 缩放变异——deviceScaleFactor 切换(CSS 像素坐标空间不变,
2391
- * 物理像素翻倍)。保留当前 CSS 视口尺寸,只换 DSF。
2392
- */
2393
3355
  async setDeviceScaleFactor(dsf) {
2394
- const size = this._viewportSize ?? await this.evaluate(
2395
- "({ width: window.innerWidth, height: window.innerHeight })"
2396
- );
2397
- await this.conn.send(
2398
- "Emulation.setDeviceMetricsOverride",
2399
- {
2400
- width: size.width,
2401
- height: size.height,
2402
- deviceScaleFactor: dsf,
2403
- mobile: false
2404
- },
2405
- this.sessionId
2406
- );
2407
- this._viewportSize = size;
3356
+ return this.mediaService.setDeviceScaleFactor(dsf);
2408
3357
  }
2409
- // ── Scripts ─────────────────────────────────────────────────
2410
3358
  async addInitScript(script) {
2411
3359
  await this.conn.send(
2412
3360
  "Page.addScriptToEvaluateOnNewDocument",
@@ -2534,83 +3482,17 @@ Last error: ${lastError.message}` : "";
2534
3482
  }
2535
3483
  }
2536
3484
  // ── CDP helpers exposed for locator/element ─────────────────
2537
- /** Query a single element, returns CDP nodeId or 0 if not found */
2538
3485
  async querySelector(selector) {
2539
- if (selector.startsWith("xpath=")) {
2540
- const found = await this.evaluate(`
2541
- (() => { const el = ${queryJS(selector)}; return !!el; })()
2542
- `).catch(() => false);
2543
- if (!found) return 0;
2544
- try {
2545
- const search = await this.conn.send(
2546
- "DOM.performSearch",
2547
- { query: selector.slice(6) },
2548
- this.sessionId
2549
- );
2550
- if (search.nodeId) return search.nodeId;
2551
- } catch {
2552
- }
2553
- return 1;
2554
- }
2555
- const withTimeout = (p, ms) => Promise.race([p, new Promise((r) => setTimeout(() => r(null), ms))]);
2556
- const doc = await withTimeout(
2557
- this.conn.send("DOM.getDocument", { depth: 0 }, this.sessionId),
2558
- 8e3
2559
- );
2560
- if (!doc) return 0;
2561
- const result = await withTimeout(
2562
- this.conn.send(
2563
- "DOM.querySelector",
2564
- { nodeId: doc.root.nodeId, selector },
2565
- this.sessionId
2566
- ),
2567
- 8e3
2568
- );
2569
- if (!result) return 0;
2570
- return result.nodeId;
3486
+ return this.domQueryService.querySelector(selector);
2571
3487
  }
2572
- /** Query all matching elements, returns array of CDP nodeIds */
2573
3488
  async querySelectorAll(selector) {
2574
- const doc = await this.conn.send(
2575
- "DOM.getDocument",
2576
- { depth: 0 },
2577
- this.sessionId
2578
- );
2579
- const result = await this.conn.send(
2580
- "DOM.querySelectorAll",
2581
- { nodeId: doc.root.nodeId, selector },
2582
- this.sessionId
2583
- );
2584
- return result.nodeIds ?? [];
3489
+ return this.domQueryService.querySelectorAll(selector);
2585
3490
  }
2586
- /** Resolve a CDP nodeId to a RemoteObject for evaluate */
2587
3491
  async resolveNode(nodeId) {
2588
- const result = await this.conn.send(
2589
- "DOM.resolveNode",
2590
- { nodeId },
2591
- this.sessionId
2592
- );
2593
- return result.object.objectId;
3492
+ return this.domQueryService.resolveNode(nodeId);
2594
3493
  }
2595
- /** Get the box model for a nodeId */
2596
3494
  async getBoxModel(nodeId) {
2597
- try {
2598
- const result = await this.conn.send("DOM.getBoxModel", { nodeId }, this.sessionId);
2599
- const c = result.model?.content;
2600
- if (!c || c.length < 8) return null;
2601
- const x1 = c[0];
2602
- const y1 = c[1];
2603
- const x2 = c[4];
2604
- const y2 = c[5];
2605
- return {
2606
- x: Math.min(x1, x2),
2607
- y: Math.min(y1, y2),
2608
- width: Math.abs(x2 - x1),
2609
- height: Math.abs(y2 - y1)
2610
- };
2611
- } catch {
2612
- return null;
2613
- }
3495
+ return this.domQueryService.getBoxModel(nodeId);
2614
3496
  }
2615
3497
  /** Call a function on a RemoteObject */
2616
3498
  async callFunctionOn(objectId, functionDeclaration, args = []) {
@@ -2629,9 +3511,6 @@ Last error: ${lastError.message}` : "";
2629
3511
  async _cdpSend(method, params) {
2630
3512
  return this.conn.send(method, params, this.sessionId);
2631
3513
  }
2632
- /** sup-s11: beforeunload 自动应答语义——'accept'(默认,离开页面,与录制
2633
- * 意图一致)或 'dismiss'(取消导航留守原页,尽力而为:此构建上 CDP
2634
- * accept:false 对浏览器侧导航的取消语义不稳定,不保证)。 */
2635
3514
  setBeforeUnloadBehavior(mode) {
2636
3515
  this._beforeUnloadAccept = mode === "accept";
2637
3516
  }
@@ -2654,143 +3533,37 @@ Last error: ${lastError.message}` : "";
2654
3533
  }
2655
3534
  // ── Private: Event Setup ────────────────────────────────────
2656
3535
  setupPageEvents() {
2657
- this._subscriptions.push(
2658
- this.conn.subscribe("Page.frameNavigated", this.sessionId, (params) => {
2659
- const p = params;
2660
- if (p.frame) {
2661
- this._url = p.frame.url;
2662
- }
2663
- this._emit("framenavigated", this.mainFrame());
2664
- })
2665
- );
2666
- this._subscriptions.push(
2667
- this.conn.subscribe("Page.loadEventFired", this.sessionId, () => {
3536
+ setupPageEvents({
3537
+ conn: this.conn,
3538
+ sessionId: this.sessionId,
3539
+ addSubscription: (unsubscribe) => this._subscriptions.push(unsubscribe),
3540
+ emit: (event, ...args) => this._emit(event, ...args),
3541
+ setUrl: (url) => {
3542
+ this._url = url;
3543
+ },
3544
+ currentUrl: () => this.url(),
3545
+ mainFrame: () => this.mainFrame(),
3546
+ markLoadFired: () => {
2668
3547
  this._loadState.loadFired = true;
2669
- })
2670
- );
2671
- this._subscriptions.push(
2672
- this.conn.subscribe("Page.domContentEventFired", this.sessionId, () => {
2673
- this._loadState.domContentFired = true;
2674
- })
2675
- );
2676
- this._subscriptions.push(
2677
- this.conn.subscribe("Page.javascriptDialogOpening", this.sessionId, (params) => {
2678
- const p = params;
2679
- const dialog = {
2680
- type: p.type,
2681
- message: () => p.message,
2682
- defaultValue: () => p.defaultValue,
2683
- accept: async (text) => {
2684
- await this.conn.send("Page.handleJavaScriptDialog", {
2685
- accept: true,
2686
- promptText: text
2687
- }, this.sessionId);
2688
- },
2689
- dismiss: async () => {
2690
- await this.conn.send("Page.handleJavaScriptDialog", {
2691
- accept: false
2692
- }, this.sessionId);
2693
- }
2694
- };
2695
- this._emit("dialog", dialog);
2696
- const autoAccept = p.type === "beforeunload" ? this._beforeUnloadAccept : false;
2697
- setTimeout(() => {
2698
- this.conn.send("Page.handleJavaScriptDialog", { accept: autoAccept }, this.sessionId).catch(() => {
2699
- });
2700
- }, 0);
2701
- })
2702
- );
2703
- this._subscriptions.push(
2704
- this.conn.subscribe("Page.fileChooserOpened", this.sessionId, async (params) => {
2705
- const p = params;
2706
- let selector = "";
2707
- try {
2708
- const result = await this.conn.send("DOM.describeNode", { backendNodeId: p.backendNodeId }, this.sessionId);
2709
- const attrs = result.node?.attributes || [];
2710
- const idIdx = attrs.indexOf("id");
2711
- if (idIdx >= 0) selector = "#" + attrs[idIdx + 1];
2712
- } catch {
2713
- }
2714
- if (!selector) {
2715
- try {
2716
- const result = await this.conn.send("DOM.resolveNode", { backendNodeId: p.backendNodeId }, this.sessionId);
2717
- const evalResult = await this.conn.send("Runtime.callFunctionOn", {
2718
- objectId: result.objectId,
2719
- functionDeclaration: 'function() { return this.id || this.name || "" }',
2720
- returnByValue: true
2721
- }, this.sessionId);
2722
- if (evalResult.result?.value) selector = "#" + evalResult.result.value;
2723
- } catch {
2724
- }
2725
- }
2726
- const fileChooser = {
2727
- selector,
2728
- isMultiple: p.mode === "selectMultiple",
2729
- setFiles: async (files) => {
2730
- const fileArray = Array.isArray(files) ? files : [files];
2731
- await this.setInputFiles(selector || 'input[type="file"]', fileArray);
2732
- }
2733
- };
2734
- this._emit("filechooser", fileChooser);
2735
- })
2736
- );
3548
+ },
3549
+ markDomContentFired: () => {
3550
+ this._loadState.domContentFired = true;
3551
+ },
3552
+ getBeforeUnloadAccept: () => this._beforeUnloadAccept,
3553
+ setInputFiles: (selector, files) => this.setInputFiles(selector, files)
3554
+ });
2737
3555
  }
2738
3556
  setupNetworkEvents() {
2739
- this._subscriptions.push(
2740
- this.conn.subscribe("Network.requestWillBeSent", this.sessionId, (params) => {
2741
- const p = params;
2742
- this.inflightRequests.add(p.requestId);
2743
- this._storeNetworkRequest(p.requestId, {
2744
- url: p.request.url,
2745
- method: p.request.method,
2746
- headers: p.request.headers,
2747
- postData: p.request.postData ?? null,
2748
- resourceType: p.type
2749
- });
2750
- this._emit("request", createXBRequest(
2751
- null,
2752
- {
2753
- requestId: p.requestId,
2754
- url: p.request.url,
2755
- method: p.request.method,
2756
- headers: p.request.headers,
2757
- postData: p.request.postData ?? null,
2758
- resourceType: p.type
2759
- }
2760
- ));
2761
- this.checkNetworkIdle();
2762
- })
2763
- );
2764
- this._subscriptions.push(
2765
- this.conn.subscribe("Network.responseReceived", this.sessionId, (params) => {
2766
- const p = params;
2767
- this._storeNetworkResponse(p.requestId, {
2768
- status: p.response.status,
2769
- url: p.response.url,
2770
- headers: p.response.headers
2771
- });
2772
- this._emit("response", createXBResponse(
2773
- { requestId: p.requestId, status: p.response.status, url: p.response.url, headers: p.response.headers },
2774
- this.conn,
2775
- this.sessionId
2776
- ));
2777
- })
2778
- );
2779
- this._subscriptions.push(
2780
- this.conn.subscribe("Network.loadingFinished", this.sessionId, (params) => {
2781
- const p = params;
2782
- this.inflightRequests.delete(p.requestId);
2783
- this._emit("requestfinished", p);
2784
- this.checkNetworkIdle();
2785
- })
2786
- );
2787
- this._subscriptions.push(
2788
- this.conn.subscribe("Network.loadingFailed", this.sessionId, (params) => {
2789
- const p = params;
2790
- this.inflightRequests.delete(p.requestId);
2791
- this.checkNetworkIdle();
2792
- })
2793
- );
3557
+ setupNetworkEvents({
3558
+ conn: this.conn,
3559
+ sessionId: this.sessionId,
3560
+ state: { inflightRequests: this.inflightRequests },
3561
+ emit: (event, ...args) => this._emit(event, ...args),
3562
+ storeRequest: (id, data) => this._storeNetworkRequest(id, data),
3563
+ storeResponse: (id, data) => this._storeNetworkResponse(id, data),
3564
+ checkNetworkIdle: () => this.checkNetworkIdle(),
3565
+ addSubscription: (unsubscribe) => this._subscriptions.push(unsubscribe)
3566
+ });
2794
3567
  }
2795
3568
  setupConsoleEvents() {
2796
3569
  this._subscriptions.push(
@@ -2836,8 +3609,6 @@ Last error: ${lastError.message}` : "";
2836
3609
  // ── Network Data Store (for waitForResponse/waitForRequest) ──
2837
3610
  _networkResponses = /* @__PURE__ */ new Map();
2838
3611
  _networkRequests = /* @__PURE__ */ new Map();
2839
- _routeHandlers = [];
2840
- _interceptionEnabled = false;
2841
3612
  _beforeUnloadAccept = true;
2842
3613
  /** Store network data — called by browser.ts installNetworkCapture or internal event handlers */
2843
3614
  _storeNetworkRequest(requestId, data) {
@@ -2846,284 +3617,30 @@ Last error: ${lastError.message}` : "";
2846
3617
  _storeNetworkResponse(requestId, data) {
2847
3618
  this._networkResponses.set(requestId, { requestId, ...data });
2848
3619
  }
2849
- // ── waitForResponse ─────────────────────────────────────────
2850
3620
  async waitForResponse(urlOrPredicate, opts = {}) {
2851
- const timeout = opts.timeout ?? 3e4;
2852
- const predicate = createResponsePredicate(urlOrPredicate);
2853
- for (const [, data] of this._networkResponses) {
2854
- const response = createXBResponse(data, this.conn, this.sessionId);
2855
- if (predicate(response)) return response;
2856
- }
2857
- return new Promise((resolve, reject) => {
2858
- const timer = setTimeout(() => {
2859
- this._emitter.removeListener("response", handler);
2860
- reject(new Error(`waitForResponse timed out after ${timeout}ms`));
2861
- }, timeout);
2862
- const handler = (params) => {
2863
- let response;
2864
- const respObj = params;
2865
- if (respObj.response) {
2866
- const data = {
2867
- requestId: respObj.requestId || "",
2868
- status: respObj.response.status || 0,
2869
- url: respObj.response.url || "",
2870
- headers: respObj.response.headers || {}
2871
- };
2872
- response = createXBResponse(data, this.conn, this.sessionId);
2873
- } else if (typeof params.status === "function") {
2874
- response = params;
2875
- } else {
2876
- return;
2877
- }
2878
- if (predicate(response)) {
2879
- clearTimeout(timer);
2880
- this._emitter.removeListener("response", handler);
2881
- resolve(response);
2882
- }
2883
- };
2884
- this._emitter.on("response", handler);
2885
- });
3621
+ return this.networkWaitService.waitForResponse(urlOrPredicate, opts);
2886
3622
  }
2887
- // ── waitForRequest ──────────────────────────────────────────
2888
3623
  async waitForRequest(urlOrPredicate, opts = {}) {
2889
- const timeout = opts.timeout ?? 3e4;
2890
- const predicate = createRequestPredicate(urlOrPredicate);
2891
- for (const [, data] of this._networkRequests) {
2892
- const request = createXBRequest(this, data);
2893
- if (predicate(request)) return request;
2894
- }
2895
- return new Promise((resolve, reject) => {
2896
- const timer = setTimeout(() => {
2897
- this._emitter.removeListener("request", handler);
2898
- reject(new Error(`waitForRequest timed out after ${timeout}ms`));
2899
- }, timeout);
2900
- const handler = (params) => {
2901
- let request;
2902
- const reqObj = params;
2903
- if (reqObj.request) {
2904
- request = createXBRequest(this, {
2905
- requestId: reqObj.requestId || "",
2906
- url: reqObj.request.url || "",
2907
- method: reqObj.request.method || "",
2908
- headers: reqObj.request.headers || {},
2909
- postData: reqObj.request.postData ?? null,
2910
- resourceType: reqObj.type || ""
2911
- });
2912
- } else if (typeof params.url === "function") {
2913
- request = params;
2914
- } else {
2915
- return;
2916
- }
2917
- if (predicate(request)) {
2918
- clearTimeout(timer);
2919
- this._emitter.removeListener("request", handler);
2920
- resolve(request);
2921
- }
2922
- };
2923
- this._emitter.on("request", handler);
2924
- });
3624
+ return this.networkWaitService.waitForRequest(urlOrPredicate, opts);
2925
3625
  }
2926
- // ── waitForURL ──────────────────────────────────────────────
2927
3626
  async waitForURL(url, opts = {}) {
2928
- const timeout = opts.timeout ?? 3e4;
2929
- const checkFn = typeof url === "function" ? url : typeof url === "string" ? (current) => matchGlob(url, current) : (current) => url.test(current);
2930
- if (checkFn(this._url)) return;
2931
- return new Promise((resolve, reject) => {
2932
- const timer = setTimeout(() => {
2933
- this._emitter.removeListener("framenavigated", handler);
2934
- reject(new Error(`waitForURL timed out after ${timeout}ms`));
2935
- }, timeout);
2936
- const handler = () => {
2937
- if (checkFn(this._url)) {
2938
- clearTimeout(timer);
2939
- this._emitter.removeListener("framenavigated", handler);
2940
- resolve();
2941
- }
2942
- };
2943
- this._emitter.on("framenavigated", handler);
2944
- });
2945
- }
2946
- // ── route / unroute ─────────────────────────────────────────
2947
- async route(url, handler) {
2948
- const regex = typeof url === "string" ? globToRegex(url) : url;
2949
- this._routeHandlers.push({ pattern: String(url), regex, handler });
2950
- if (!this._interceptionEnabled) {
2951
- this._interceptionEnabled = true;
2952
- await this.conn.send("Fetch.enable", {
2953
- patterns: [{ urlPattern: "*", requestStage: "Request" }],
2954
- // sup-s9: 保留认证自动响应(Fetch.enable 为替换语义,不带此参数
2955
- // 会顶掉 _init 的 auth 配置)
2956
- handleAuthRequests: true
2957
- }, this.sessionId);
2958
- this._subscriptions.push(
2959
- this.conn.subscribe("Fetch.requestPaused", this.sessionId, (params) => {
2960
- this._handleRequestPaused(params);
2961
- })
2962
- );
2963
- }
3627
+ return this.networkWaitService.waitForURL(url, opts);
2964
3628
  }
2965
- async unroute(url, handler) {
2966
- const regex = typeof url === "string" ? globToRegex(url) : url;
2967
- this._routeHandlers = this._routeHandlers.filter(
2968
- (h) => !(regex.source === h.regex.source && (!handler || h.handler === handler))
2969
- );
2970
- if (this._routeHandlers.length === 0 && this._interceptionEnabled) {
2971
- this._interceptionEnabled = false;
2972
- await this.conn.send("Fetch.disable", void 0, this.sessionId).catch(() => {
2973
- });
2974
- }
3629
+ async route(pattern, handler) {
3630
+ return this.networkRouteService.route(pattern, handler);
2975
3631
  }
2976
- async _handleRequestPaused(params) {
2977
- const requestUrl = params.request.url;
2978
- for (const { regex, handler } of this._routeHandlers) {
2979
- if (regex.test(requestUrl)) {
2980
- this._emit("request", createXBRequest(
2981
- null,
2982
- {
2983
- requestId: params.requestId,
2984
- url: params.request.url,
2985
- method: params.request.method,
2986
- headers: params.request.headers,
2987
- postData: params.request.postData ?? null,
2988
- resourceType: params.resourceType
2989
- }
2990
- ));
2991
- const route = createXBRouteFetch(this.conn, this.sessionId, params, this._emitter);
2992
- try {
2993
- await handler(route);
2994
- } catch {
2995
- await this.conn.send("Fetch.continueRequest", {
2996
- requestId: params.requestId
2997
- }, this.sessionId).catch(() => {
2998
- });
2999
- }
3000
- return;
3001
- }
3002
- }
3003
- await this.conn.send("Fetch.continueRequest", {
3004
- requestId: params.requestId
3005
- }, this.sessionId).catch(() => {
3006
- });
3632
+ async unroute(pattern) {
3633
+ return this.networkRouteService.unroute(pattern);
3007
3634
  }
3008
- // ── setInputFiles ───────────────────────────────────────────
3009
- /**
3010
- * sup-s4: Dropzone 拖拽上传模拟——Dropzone/Uppy/自绘上传区只监听
3011
- * dragover/drop(无 input[type=file] 可点),真实用户靠 OS 文件拖入
3012
- * 触发,自动化无法产生 OS 拖拽。页内构造 DataTransfer+File,按拖放
3013
- * 协议派发 dragenter/dragover/drop(bubbles+cancelable,坐标取目标
3014
- * 中心)。
3015
- */
3016
3635
  async dropFiles(selector, payload) {
3017
- await this.evaluate(`
3018
- (function() {
3019
- var el = ${queryJS(selector)};
3020
- if (!el) throw new Error('drop target not found: ' + ${JSON.stringify(selector)});
3021
- var b64 = ${JSON.stringify(payload.buffer.toString("base64"))};
3022
- var bin = atob(b64);
3023
- var buf = new Uint8Array(bin.length);
3024
- for (var i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
3025
- var file = new File([buf], ${JSON.stringify(payload.name)}, { type: ${JSON.stringify(payload.mimeType)} });
3026
- var dt = new DataTransfer();
3027
- dt.items.add(file);
3028
- var rect = el.getBoundingClientRect();
3029
- var opts = {
3030
- bubbles: true, cancelable: true,
3031
- clientX: rect.x + rect.width / 2, clientY: rect.y + rect.height / 2,
3032
- };
3033
- el.dispatchEvent(new DragEvent('dragenter', Object.assign({ dataTransfer: dt }, opts)));
3034
- el.dispatchEvent(new DragEvent('dragover', Object.assign({ dataTransfer: dt }, opts)));
3035
- el.dispatchEvent(new DragEvent('drop', Object.assign({ dataTransfer: dt }, opts)));
3036
- })()
3037
- `);
3636
+ return this.fileInputService.dropFiles(selector, payload);
3038
3637
  }
3039
3638
  async setInputFiles(selector, files) {
3040
- const fileArr = Array.isArray(files) ? files : [files];
3041
- const fileList = fileArr.map((f) => ({
3042
- name: f.name,
3043
- type: f.mimeType,
3044
- dataBase64: f.buffer.toString("base64")
3045
- }));
3046
- await this.evaluate(`
3047
- (function() {
3048
- var selector = ${JSON.stringify(selector)};
3049
- var input = ${queryJS(selector)};
3050
- if (!input) throw new Error('Element not found: ' + selector);
3051
-
3052
- var fileList = ${JSON.stringify(fileList)};
3053
- var dt = new DataTransfer();
3054
-
3055
- fileList.forEach(function(f) {
3056
- var binary = atob(f.dataBase64);
3057
- var bytes = new Uint8Array(binary.length);
3058
- for (var i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
3059
- var blob = new Blob([bytes], { type: f.type });
3060
- var file = new File([blob], f.name, { type: f.type });
3061
- dt.items.add(file);
3062
- });
3063
-
3064
- input.files = dt.files;
3065
- input.dispatchEvent(new Event('input', { bubbles: true }));
3066
- input.dispatchEvent(new Event('change', { bubbles: true }));
3067
- })()
3068
- `);
3639
+ return this.fileInputService.setInputFiles(selector, files);
3069
3640
  }
3070
- // ── dragAndDrop ─────────────────────────────────────────────
3071
3641
  async dragAndDrop(source, target) {
3072
- const sourceRect = await this.evaluate(`
3073
- (function() {
3074
- const el = ${queryJS(source)};
3075
- if (!el) throw new Error('Source not found: ${source}');
3076
- el.scrollIntoView({ behavior: 'instant', block: 'center' });
3077
- const r = el.getBoundingClientRect();
3078
- return { x: r.x, y: r.y, width: r.width, height: r.height };
3079
- })()
3080
- `);
3081
- const targetRect = await this.evaluate(`
3082
- (function() {
3083
- const el = ${queryJS(target)};
3084
- if (!el) throw new Error('Target not found: ${target}');
3085
- el.scrollIntoView({ behavior: 'instant', block: 'center' });
3086
- const r = el.getBoundingClientRect();
3087
- return { x: r.x, y: r.y, width: r.width, height: r.height };
3088
- })()
3089
- `);
3090
- const sx = sourceRect.x + sourceRect.width / 2;
3091
- const sy = sourceRect.y + sourceRect.height / 2;
3092
- const tx = targetRect.x + targetRect.width / 2;
3093
- const ty = targetRect.y + targetRect.height / 2;
3094
- try {
3095
- await this.conn.send("Input.dispatchDragEvent", {
3096
- type: "dragStart",
3097
- x: sx,
3098
- y: sy,
3099
- data: { items: [], dragOperations: ["copy", "move", "link"] }
3100
- }, this.sessionId);
3101
- await this.conn.send("Input.dispatchDragEvent", {
3102
- type: "dragOver",
3103
- x: tx,
3104
- y: ty,
3105
- data: { items: [], dragOperations: ["copy", "move", "link"] }
3106
- }, this.sessionId);
3107
- await this.conn.send("Input.dispatchDragEvent", {
3108
- type: "drop",
3109
- x: tx,
3110
- y: ty,
3111
- data: { items: [], dragOperations: ["copy", "move", "link"] }
3112
- }, this.sessionId);
3113
- await this.conn.send("Input.dispatchDragEvent", {
3114
- type: "dragCancel",
3115
- x: sx,
3116
- y: sy,
3117
- data: { items: [], dragOperations: ["copy", "move", "link"] }
3118
- }, this.sessionId);
3119
- } catch {
3120
- await this.mouse.move(sx, sy);
3121
- await this.mouse.down();
3122
- await this.mouse.move(tx, ty, { steps: 10 });
3123
- await this.mouse.up();
3124
- }
3642
+ return this.fileInputService.dragAndDrop(source, target);
3125
3643
  }
3126
- // ── setOfflineMode ──────────────────────────────────────────
3127
3644
  async setOfflineMode(offline) {
3128
3645
  await this.conn.send("Network.emulateNetworkConditions", {
3129
3646
  offline,
@@ -3419,12 +3936,22 @@ var XBBrowserImpl = class {
3419
3936
  this._exitHandler = null;
3420
3937
  }
3421
3938
  if (this.childProcess) {
3422
- const { killChrome: killChrome2 } = await import("./launcher-XHKIC4GP.js");
3939
+ const { killChrome: killChrome2 } = await import("./launcher-ZYB32LSZ.js");
3423
3940
  await killChrome2(this.childProcess, this.tmpDir);
3424
3941
  }
3425
3942
  await this.conn.close();
3426
3943
  this._emitter.emit("disconnected");
3427
3944
  }
3945
+ async disconnect() {
3946
+ if (this._disconnected) return;
3947
+ this._disconnected = true;
3948
+ if (this._exitHandler) {
3949
+ process.removeListener("exit", this._exitHandler);
3950
+ this._exitHandler = null;
3951
+ }
3952
+ await this.conn.close();
3953
+ this._emitter.emit("disconnected");
3954
+ }
3428
3955
  async newContext(opts = {}) {
3429
3956
  if (this.launchOpts?.stealthConfig && !opts.stealthConfig) {
3430
3957
  opts = { ...opts, stealthConfig: this.launchOpts.stealthConfig };
@@ -3589,7 +4116,7 @@ var XBBrowserImpl = class {
3589
4116
  if (pageTargets.length === 0 && httpFallbackUrl) {
3590
4117
  console.log(`[discoverContexts] Target.getTargets returned ${targetInfos.length} targets (0 page type). Falling back to HTTP /json/list at ${httpFallbackUrl}`);
3591
4118
  try {
3592
- const { getCDPTargets: getCDPTargets2 } = await import("./launcher-XHKIC4GP.js");
4119
+ const { getCDPTargets: getCDPTargets2 } = await import("./launcher-ZYB32LSZ.js");
3593
4120
  const httpPages = await getCDPTargets2(httpFallbackUrl);
3594
4121
  console.log(`[discoverContexts] HTTP /json/list returned ${httpPages.length} pages`);
3595
4122
  for (const p of httpPages) {
@@ -3776,6 +4303,15 @@ var CDPConnection = class _CDPConnection extends EventEmitter4 {
3776
4303
  if (decision && decision.action === "block") {
3777
4304
  throw new Error(`[CDP-Guard] ${decision.reason}${decision.suggestion ? " | \u66FF\u4EE3: " + decision.suggestion : ""} [${decision.ruleId}]`);
3778
4305
  }
4306
+ if (decision && decision.action === "transform" && Array.isArray(decision.transformedParams?.__sequence)) {
4307
+ const sequence = decision.transformedParams.__sequence;
4308
+ let last;
4309
+ for (const step of sequence) {
4310
+ if (step.delayMs) await new Promise((resolve) => setTimeout(resolve, step.delayMs));
4311
+ last = await this.send(step.method, step.params, sessionId, effectiveTimeout);
4312
+ }
4313
+ return last;
4314
+ }
3779
4315
  }
3780
4316
  if (this.closed) {
3781
4317
  throw new Error(`CDP connection closed: ${this.closeReason ?? "unknown"}`);
@@ -4018,7 +4554,7 @@ async function launch(options = {}) {
4018
4554
  const bv = await conn.send("Browser.getVersion");
4019
4555
  const m = bv.product.match(/(\d+)\.(\d+)\.(\d+)\.(\d+)/);
4020
4556
  if (m && !options.stealthConfig?.uaChProfile) {
4021
- const { deriveUaChProfileForBinary } = await import("./stealth-MHJNBJY7.js");
4557
+ const { deriveUaChProfileForBinary } = await import("./stealth-MCKFKPZ6.js");
4022
4558
  stealthOpts = { stealthConfig: { uaChProfile: deriveUaChProfileForBinary(m[0], m[1]) } };
4023
4559
  }
4024
4560
  } catch {