@xbrowser/cli 1.27.0 → 1.29.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 (37) hide show
  1. package/dist/{browser-NYYCR4O7.js → browser-2K3XYAKM.js} +5 -3
  2. package/dist/{browser-ZD53IMUJ.js → browser-OTEMG5NL.js} +6 -4
  3. package/dist/{browser-4IYIHZ6R.js → browser-XD3IOU5I.js} +8 -6
  4. package/dist/{cdp-driver-EFEW4ZEN.js → cdp-driver-AAS55KT2.js} +4 -4
  5. package/dist/{cdp-driver-4X6Q62WI.js → cdp-driver-O5I7SJ24.js} +3 -3
  6. package/dist/{cdp-driver-HB744QB4.js → cdp-driver-XTPY7EXP.js} +1296 -852
  7. package/dist/{chunk-SEEWE5SJ.js → chunk-2KPI5GKP.js} +3 -0
  8. package/dist/{chunk-75DNUI6M.js → chunk-6UJU2FJK.js} +146 -0
  9. package/dist/{chunk-3PUOISKE.js → chunk-CO2ZVOVT.js} +496 -452
  10. package/dist/{chunk-V6KGBU5J.js → chunk-FCPVQFTQ.js} +1011 -1038
  11. package/dist/{chunk-IDXOIXQR.js → chunk-GDKKVT2P.js} +773 -655
  12. package/dist/{chunk-HSYRAV3H.js → chunk-LFSLNHW5.js} +1846 -1358
  13. package/dist/{chunk-OSZNJT4U.js → chunk-LM32MNBB.js} +79 -8
  14. package/dist/{chunk-J3HXZVSN.js → chunk-N5XTLNKS.js} +1166 -868
  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-ME5FO5YV.js → chunk-NQPXZ74W.js} +1296 -852
  18. package/dist/{chunk-KECYFWJO.js → chunk-P33R7F2D.js} +413 -384
  19. package/dist/{chunk-YITK42HZ.js → chunk-SCYBNSOG.js} +1596 -1478
  20. package/dist/{chunk-R3F4K2SB.js → chunk-SMYSNO4M.js} +10 -0
  21. package/dist/{chunk-IR6C24P7.js → chunk-UZ6XPUBD.js} +1030 -1048
  22. package/dist/cli.js +3398 -3357
  23. package/dist/daemon-main.js +749 -700
  24. package/dist/index.d.ts +362 -474
  25. package/dist/index.js +5730 -5689
  26. package/dist/{launcher-SJ44X25U.js → launcher-TOLF23ET.js} +1 -1
  27. package/dist/{launcher-XHKIC4GP.js → launcher-ZYB32LSZ.js} +1 -1
  28. package/dist/{plugin-singleton-GGSBI3EG.js → plugin-singleton-A6RNITJW.js} +1 -1
  29. package/dist/{proxy-NKCYE76M.js → proxy-H3RIUOCN.js} +2 -2
  30. package/dist/{server-YKMRFDEM.js → server-LNZTDAKT.js} +4 -4
  31. package/dist/{server-WDDGIV3C.js → server-ZTI2K5YJ.js} +7 -7
  32. package/dist/{session-recorder-GEZVQBKW.js → session-recorder-DF2YGH2E.js} +1 -1
  33. package/dist/{session-recorder-563ISSJK.js → session-recorder-R3GDGXLJ.js} +1 -1
  34. package/dist/{session-replayer-TXTNTG33.js → session-replayer-CLTZ2URU.js} +1 -1
  35. package/dist/{stealth-QNSMIHQK.js → stealth-FMPZO2OB.js} +1 -1
  36. package/dist/{stealth-MHJNBJY7.js → stealth-MCKFKPZ6.js} +1 -1
  37. package/package.json +6 -3
@@ -5,7 +5,7 @@ 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
  errMsg,
@@ -13,7 +13,7 @@ import {
13
13
  getCDPTargets,
14
14
  killChrome,
15
15
  launchChrome
16
- } from "./chunk-T2AI24A5.js";
16
+ } from "./chunk-NAIHOVDZ.js";
17
17
  import {
18
18
  __require
19
19
  } from "./chunk-3RG5ZIWI.js";
@@ -1430,6 +1430,216 @@ var XBElementHandleImpl = class {
1430
1430
  }
1431
1431
  };
1432
1432
 
1433
+ // src/cdp-driver/page-media.ts
1434
+ var MediaService = class {
1435
+ constructor(options) {
1436
+ this.options = options;
1437
+ }
1438
+ options;
1439
+ async screenshot(opts = {}) {
1440
+ const params = {
1441
+ format: opts.type ?? "png"
1442
+ };
1443
+ if (opts.quality !== void 0 && (opts.type === "jpeg" || !opts.type && opts.quality)) {
1444
+ params.quality = opts.quality;
1445
+ }
1446
+ if (opts.fullPage) {
1447
+ params.captureBeyondViewport = true;
1448
+ }
1449
+ if (opts.clip) {
1450
+ const clip = {
1451
+ x: Math.round(opts.clip.x),
1452
+ y: Math.round(opts.clip.y),
1453
+ width: Math.round(Math.max(1, opts.clip.width)),
1454
+ height: Math.round(Math.max(1, opts.clip.height)),
1455
+ scale: 1
1456
+ };
1457
+ params.clip = clip;
1458
+ }
1459
+ if (opts.omitBackground) {
1460
+ params.omitBackground = true;
1461
+ }
1462
+ const result = await this.options.conn.send(
1463
+ "Page.captureScreenshot",
1464
+ params,
1465
+ this.options.sessionId
1466
+ );
1467
+ return Buffer.from(result.data, "base64");
1468
+ }
1469
+ async pdf(opts = {}) {
1470
+ const params = {};
1471
+ if (opts.landscape !== void 0) params.landscape = opts.landscape;
1472
+ if (opts.printBackground !== void 0) params.printBackground = opts.printBackground;
1473
+ if (opts.scale !== void 0) params.scale = opts.scale;
1474
+ if (opts.format) params.paperFormat = opts.format;
1475
+ if (opts.preferCSSPageSize !== void 0) params.preferCSSPageSize = opts.preferCSSPageSize;
1476
+ if (opts.margin) {
1477
+ if (opts.margin.top) params.marginTop = parseFloat(opts.margin.top);
1478
+ if (opts.margin.bottom) params.marginBottom = parseFloat(opts.margin.bottom);
1479
+ if (opts.margin.left) params.marginLeft = parseFloat(opts.margin.left);
1480
+ if (opts.margin.right) params.marginRight = parseFloat(opts.margin.right);
1481
+ }
1482
+ const result = await this.options.conn.send("Page.printToPDF", params, this.options.sessionId);
1483
+ return Buffer.from(result.data, "base64");
1484
+ }
1485
+ viewportSize() {
1486
+ return this.options.viewportSize ?? null;
1487
+ }
1488
+ async setViewportSize(size) {
1489
+ await this.options.conn.send(
1490
+ "Emulation.setDeviceMetricsOverride",
1491
+ {
1492
+ width: size.width,
1493
+ height: size.height,
1494
+ deviceScaleFactor: 1,
1495
+ mobile: false
1496
+ },
1497
+ this.options.sessionId
1498
+ );
1499
+ this.options.onViewportSize(size);
1500
+ }
1501
+ /**
1502
+ * env-E2: 缩放变异——deviceScaleFactor 切换(CSS 像素坐标空间不变,
1503
+ * 物理像素翻倍)。保留当前 CSS 视口尺寸,只换 DSF。
1504
+ */
1505
+ async setDeviceScaleFactor(dsf) {
1506
+ const size = this.options.viewportSize ?? await this.options.evaluate(
1507
+ "({ width: window.innerWidth, height: window.innerHeight })"
1508
+ );
1509
+ await this.options.conn.send(
1510
+ "Emulation.setDeviceMetricsOverride",
1511
+ {
1512
+ width: size.width,
1513
+ height: size.height,
1514
+ deviceScaleFactor: dsf,
1515
+ mobile: false
1516
+ },
1517
+ this.options.sessionId
1518
+ );
1519
+ this.options.onViewportSize(size);
1520
+ }
1521
+ // ── Scripts ─────────────────────────────────────────────────
1522
+ };
1523
+
1524
+ // src/cdp-driver/page-file-input.ts
1525
+ var FileInputService = class {
1526
+ constructor(options) {
1527
+ this.options = options;
1528
+ }
1529
+ options;
1530
+ async dropFiles(selector, payload) {
1531
+ await this.options.evaluate(`
1532
+ (function() {
1533
+ var el = ${queryJS(selector)};
1534
+ if (!el) throw new Error('drop target not found: ' + ${JSON.stringify(selector)});
1535
+ var b64 = ${JSON.stringify(payload.buffer.toString("base64"))};
1536
+ var bin = atob(b64);
1537
+ var buf = new Uint8Array(bin.length);
1538
+ for (var i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
1539
+ var file = new File([buf], ${JSON.stringify(payload.name)}, { type: ${JSON.stringify(payload.mimeType)} });
1540
+ var dt = new DataTransfer();
1541
+ dt.items.add(file);
1542
+ var rect = el.getBoundingClientRect();
1543
+ var opts = {
1544
+ bubbles: true, cancelable: true,
1545
+ clientX: rect.x + rect.width / 2, clientY: rect.y + rect.height / 2,
1546
+ };
1547
+ el.dispatchEvent(new DragEvent('dragenter', Object.assign({ dataTransfer: dt }, opts)));
1548
+ el.dispatchEvent(new DragEvent('dragover', Object.assign({ dataTransfer: dt }, opts)));
1549
+ el.dispatchEvent(new DragEvent('drop', Object.assign({ dataTransfer: dt }, opts)));
1550
+ })()
1551
+ `);
1552
+ }
1553
+ async setInputFiles(selector, files) {
1554
+ const fileArr = Array.isArray(files) ? files : [files];
1555
+ const fileList = fileArr.map((f) => ({
1556
+ name: f.name,
1557
+ type: f.mimeType,
1558
+ dataBase64: f.buffer.toString("base64")
1559
+ }));
1560
+ await this.options.evaluate(`
1561
+ (function() {
1562
+ var selector = ${JSON.stringify(selector)};
1563
+ var input = ${queryJS(selector)};
1564
+ if (!input) throw new Error('Element not found: ' + selector);
1565
+
1566
+ var fileList = ${JSON.stringify(fileList)};
1567
+ var dt = new DataTransfer();
1568
+
1569
+ fileList.forEach(function(f) {
1570
+ var binary = atob(f.dataBase64);
1571
+ var bytes = new Uint8Array(binary.length);
1572
+ for (var i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
1573
+ var blob = new Blob([bytes], { type: f.type });
1574
+ var file = new File([blob], f.name, { type: f.type });
1575
+ dt.items.add(file);
1576
+ });
1577
+
1578
+ input.files = dt.files;
1579
+ input.dispatchEvent(new Event('input', { bubbles: true }));
1580
+ input.dispatchEvent(new Event('change', { bubbles: true }));
1581
+ })()
1582
+ `);
1583
+ }
1584
+ // ── dragAndDrop ─────────────────────────────────────────────
1585
+ async dragAndDrop(source, target) {
1586
+ const sourceRect = await this.options.evaluate(`
1587
+ (function() {
1588
+ const el = ${queryJS(source)};
1589
+ if (!el) throw new Error('Source not found: ${source}');
1590
+ el.scrollIntoView({ behavior: 'instant', block: 'center' });
1591
+ const r = el.getBoundingClientRect();
1592
+ return { x: r.x, y: r.y, width: r.width, height: r.height };
1593
+ })()
1594
+ `);
1595
+ const targetRect = await this.options.evaluate(`
1596
+ (function() {
1597
+ const el = ${queryJS(target)};
1598
+ if (!el) throw new Error('Target not found: ${target}');
1599
+ el.scrollIntoView({ behavior: 'instant', block: 'center' });
1600
+ const r = el.getBoundingClientRect();
1601
+ return { x: r.x, y: r.y, width: r.width, height: r.height };
1602
+ })()
1603
+ `);
1604
+ const sx = sourceRect.x + sourceRect.width / 2;
1605
+ const sy = sourceRect.y + sourceRect.height / 2;
1606
+ const tx = targetRect.x + targetRect.width / 2;
1607
+ const ty = targetRect.y + targetRect.height / 2;
1608
+ try {
1609
+ await this.options.conn.send("Input.dispatchDragEvent", {
1610
+ type: "dragStart",
1611
+ x: sx,
1612
+ y: sy,
1613
+ data: { items: [], dragOperations: ["copy", "move", "link"] }
1614
+ }, this.options.sessionId);
1615
+ await this.options.conn.send("Input.dispatchDragEvent", {
1616
+ type: "dragOver",
1617
+ x: tx,
1618
+ y: ty,
1619
+ data: { items: [], dragOperations: ["copy", "move", "link"] }
1620
+ }, this.options.sessionId);
1621
+ await this.options.conn.send("Input.dispatchDragEvent", {
1622
+ type: "drop",
1623
+ x: tx,
1624
+ y: ty,
1625
+ data: { items: [], dragOperations: ["copy", "move", "link"] }
1626
+ }, this.options.sessionId);
1627
+ await this.options.conn.send("Input.dispatchDragEvent", {
1628
+ type: "dragCancel",
1629
+ x: sx,
1630
+ y: sy,
1631
+ data: { items: [], dragOperations: ["copy", "move", "link"] }
1632
+ }, this.options.sessionId);
1633
+ } catch {
1634
+ await this.options.mouse.move(sx, sy);
1635
+ await this.options.mouse.down();
1636
+ await this.options.mouse.move(tx, ty, { steps: 10 });
1637
+ await this.options.mouse.up();
1638
+ }
1639
+ }
1640
+ // ── setOfflineMode ──────────────────────────────────────────
1641
+ };
1642
+
1433
1643
  // src/cdp-driver/page-helpers.ts
1434
1644
  function globToRegex(glob) {
1435
1645
  let pattern = glob.replace(/[\\^${}()|[\]+]/g, "\\$&").replace(/\./g, "\\.").replace(/\*\*/g, "{{DOUBLESTAR}}").replace(/\*/g, "[^/]*").replace(/{{DOUBLESTAR}}/g, ".*").replace(/\?/g, ".");
@@ -1578,8 +1788,777 @@ function createXBRouteFetch(conn, sessionId, params, emitter) {
1578
1788
  emitter.emit("response", response);
1579
1789
  }
1580
1790
  }
1581
- };
1582
- }
1791
+ };
1792
+ }
1793
+
1794
+ // src/cdp-driver/page-network-events.ts
1795
+ function setupNetworkEvents(options) {
1796
+ options.addSubscription(
1797
+ options.conn.subscribe("Network.requestWillBeSent", options.sessionId, (params) => {
1798
+ const p = params;
1799
+ options.state.inflightRequests.add(p.requestId);
1800
+ options.storeRequest(p.requestId, {
1801
+ url: p.request.url,
1802
+ method: p.request.method,
1803
+ headers: p.request.headers,
1804
+ postData: p.request.postData ?? null,
1805
+ resourceType: p.type
1806
+ });
1807
+ options.emit("request", createXBRequest(
1808
+ null,
1809
+ {
1810
+ requestId: p.requestId,
1811
+ url: p.request.url,
1812
+ method: p.request.method,
1813
+ headers: p.request.headers,
1814
+ postData: p.request.postData ?? null,
1815
+ resourceType: p.type
1816
+ }
1817
+ ));
1818
+ options.checkNetworkIdle();
1819
+ })
1820
+ );
1821
+ options.addSubscription(
1822
+ options.conn.subscribe("Network.responseReceived", options.sessionId, (params) => {
1823
+ const p = params;
1824
+ options.storeResponse(p.requestId, {
1825
+ status: p.response.status,
1826
+ url: p.response.url,
1827
+ headers: p.response.headers
1828
+ });
1829
+ options.emit("response", createXBResponse(
1830
+ { requestId: p.requestId, status: p.response.status, url: p.response.url, headers: p.response.headers },
1831
+ options.conn,
1832
+ options.sessionId
1833
+ ));
1834
+ })
1835
+ );
1836
+ options.addSubscription(
1837
+ options.conn.subscribe("Network.loadingFinished", options.sessionId, (params) => {
1838
+ const p = params;
1839
+ options.state.inflightRequests.delete(p.requestId);
1840
+ options.emit("requestfinished", p);
1841
+ options.checkNetworkIdle();
1842
+ })
1843
+ );
1844
+ options.addSubscription(
1845
+ options.conn.subscribe("Network.loadingFailed", options.sessionId, (params) => {
1846
+ const p = params;
1847
+ options.state.inflightRequests.delete(p.requestId);
1848
+ options.checkNetworkIdle();
1849
+ })
1850
+ );
1851
+ }
1852
+
1853
+ // src/cdp-driver/page-lifecycle-events.ts
1854
+ function setupPageEvents(options) {
1855
+ options.addSubscription(
1856
+ options.conn.subscribe("Page.frameNavigated", options.sessionId, (params) => {
1857
+ const p = params;
1858
+ if (p.frame) {
1859
+ options.setUrl(p.frame.url);
1860
+ }
1861
+ options.emit("framenavigated", options.mainFrame());
1862
+ })
1863
+ );
1864
+ options.addSubscription(
1865
+ options.conn.subscribe("Page.loadEventFired", options.sessionId, () => {
1866
+ options.markLoadFired();
1867
+ })
1868
+ );
1869
+ options.addSubscription(
1870
+ options.conn.subscribe("Page.domContentEventFired", options.sessionId, () => {
1871
+ options.markDomContentFired();
1872
+ })
1873
+ );
1874
+ options.addSubscription(
1875
+ options.conn.subscribe("Page.javascriptDialogOpening", options.sessionId, (params) => {
1876
+ const p = params;
1877
+ const dialog = {
1878
+ type: p.type,
1879
+ message: () => p.message,
1880
+ defaultValue: () => p.defaultValue,
1881
+ accept: async (text) => {
1882
+ await options.conn.send("Page.handleJavaScriptDialog", {
1883
+ accept: true,
1884
+ promptText: text
1885
+ }, options.sessionId);
1886
+ },
1887
+ dismiss: async () => {
1888
+ await options.conn.send("Page.handleJavaScriptDialog", {
1889
+ accept: false
1890
+ }, options.sessionId);
1891
+ }
1892
+ };
1893
+ options.emit("dialog", dialog);
1894
+ const autoAccept = p.type === "beforeunload" ? options.getBeforeUnloadAccept() : false;
1895
+ setTimeout(() => {
1896
+ options.conn.send("Page.handleJavaScriptDialog", { accept: autoAccept }, options.sessionId).catch(() => {
1897
+ });
1898
+ }, 0);
1899
+ })
1900
+ );
1901
+ options.addSubscription(
1902
+ options.conn.subscribe("Page.fileChooserOpened", options.sessionId, async (params) => {
1903
+ const p = params;
1904
+ let selector = "";
1905
+ try {
1906
+ const result = await options.conn.send("DOM.describeNode", { backendNodeId: p.backendNodeId }, options.sessionId);
1907
+ const attrs = result.node?.attributes || [];
1908
+ const idIdx = attrs.indexOf("id");
1909
+ if (idIdx >= 0) selector = "#" + attrs[idIdx + 1];
1910
+ } catch {
1911
+ }
1912
+ if (!selector) {
1913
+ try {
1914
+ const result = await options.conn.send("DOM.resolveNode", { backendNodeId: p.backendNodeId }, options.sessionId);
1915
+ const evalResult = await options.conn.send("Runtime.callFunctionOn", {
1916
+ objectId: result.objectId,
1917
+ functionDeclaration: 'function() { return this.id || this.name || "" }',
1918
+ returnByValue: true
1919
+ }, options.sessionId);
1920
+ if (evalResult.result?.value) selector = "#" + evalResult.result.value;
1921
+ } catch {
1922
+ }
1923
+ }
1924
+ const fileChooser = {
1925
+ selector,
1926
+ isMultiple: p.mode === "selectMultiple",
1927
+ setFiles: async (files) => {
1928
+ const fileArray = Array.isArray(files) ? files : [files];
1929
+ await options.setInputFiles(selector || 'input[type="file"]', fileArray);
1930
+ }
1931
+ };
1932
+ options.emit("filechooser", fileChooser);
1933
+ })
1934
+ );
1935
+ }
1936
+
1937
+ // src/cdp-driver/page-network-waits.ts
1938
+ var NetworkWaitService = class {
1939
+ constructor(options) {
1940
+ this.options = options;
1941
+ }
1942
+ options;
1943
+ // ── waitForResponse ─────────────────────────────────────────
1944
+ async waitForResponse(urlOrPredicate, opts = {}) {
1945
+ const timeout = opts.timeout ?? 3e4;
1946
+ const predicate = createResponsePredicate(urlOrPredicate);
1947
+ for (const [, data] of this.options.responses) {
1948
+ const response = createXBResponse(data, this.options.conn, this.options.sessionId);
1949
+ if (predicate(response)) return response;
1950
+ }
1951
+ return new Promise((resolve, reject) => {
1952
+ const timer = setTimeout(() => {
1953
+ this.options.off("response", handler);
1954
+ reject(new Error(`waitForResponse timed out after ${timeout}ms`));
1955
+ }, timeout);
1956
+ const handler = (params) => {
1957
+ let response;
1958
+ const respObj = params;
1959
+ if (respObj.response) {
1960
+ const data = {
1961
+ requestId: respObj.requestId || "",
1962
+ status: respObj.response.status || 0,
1963
+ url: respObj.response.url || "",
1964
+ headers: respObj.response.headers || {}
1965
+ };
1966
+ response = createXBResponse(data, this.options.conn, this.options.sessionId);
1967
+ } else if (typeof params.status === "function") {
1968
+ response = params;
1969
+ } else {
1970
+ return;
1971
+ }
1972
+ if (predicate(response)) {
1973
+ clearTimeout(timer);
1974
+ this.options.off("response", handler);
1975
+ resolve(response);
1976
+ }
1977
+ };
1978
+ this.options.on("response", handler);
1979
+ });
1980
+ }
1981
+ // ── waitForRequest ──────────────────────────────────────────
1982
+ async waitForRequest(urlOrPredicate, opts = {}) {
1983
+ const timeout = opts.timeout ?? 3e4;
1984
+ const predicate = createRequestPredicate(urlOrPredicate);
1985
+ for (const [, data] of this.options.requests) {
1986
+ const request = createXBRequest(this.pageLike(), data);
1987
+ if (predicate(request)) return request;
1988
+ }
1989
+ return new Promise((resolve, reject) => {
1990
+ const timer = setTimeout(() => {
1991
+ this.options.off("request", handler);
1992
+ reject(new Error(`waitForRequest timed out after ${timeout}ms`));
1993
+ }, timeout);
1994
+ const handler = (params) => {
1995
+ let request;
1996
+ const reqObj = params;
1997
+ if (reqObj.request) {
1998
+ request = createXBRequest(this.pageLike(), {
1999
+ requestId: reqObj.requestId || "",
2000
+ url: reqObj.request.url || "",
2001
+ method: reqObj.request.method || "",
2002
+ headers: reqObj.request.headers || {},
2003
+ postData: reqObj.request.postData ?? null,
2004
+ resourceType: reqObj.type || ""
2005
+ });
2006
+ } else if (typeof params.url === "function") {
2007
+ request = params;
2008
+ } else {
2009
+ return;
2010
+ }
2011
+ if (predicate(request)) {
2012
+ clearTimeout(timer);
2013
+ this.options.off("request", handler);
2014
+ resolve(request);
2015
+ }
2016
+ };
2017
+ this.options.on("request", handler);
2018
+ });
2019
+ }
2020
+ // ── waitForURL ──────────────────────────────────────────────
2021
+ async waitForURL(url, opts = {}) {
2022
+ const timeout = opts.timeout ?? 3e4;
2023
+ const checkFn = typeof url === "function" ? url : typeof url === "string" ? (current) => matchGlob(url, current) : (current) => url.test(current);
2024
+ if (checkFn(this.options.currentUrl())) return;
2025
+ return new Promise((resolve, reject) => {
2026
+ const timer = setTimeout(() => {
2027
+ this.options.off("framenavigated", handler);
2028
+ reject(new Error(`waitForURL timed out after ${timeout}ms`));
2029
+ }, timeout);
2030
+ const handler = () => {
2031
+ if (checkFn(this.options.currentUrl())) {
2032
+ clearTimeout(timer);
2033
+ this.options.off("framenavigated", handler);
2034
+ resolve();
2035
+ }
2036
+ };
2037
+ this.options.on("framenavigated", handler);
2038
+ });
2039
+ }
2040
+ pageLike() {
2041
+ return {
2042
+ _networkResponses: this.options.responses,
2043
+ _connection: this.options.conn,
2044
+ sessionId: this.options.sessionId
2045
+ };
2046
+ }
2047
+ };
2048
+
2049
+ // src/cdp-driver/page-routes.ts
2050
+ var NetworkRouteService = class {
2051
+ constructor(options) {
2052
+ this.options = options;
2053
+ }
2054
+ options;
2055
+ routeHandlers = [];
2056
+ interceptionEnabled = false;
2057
+ get isInterceptionEnabled() {
2058
+ return this.interceptionEnabled;
2059
+ }
2060
+ subscriptions = [];
2061
+ async route(url, handler) {
2062
+ const regex = typeof url === "string" ? globToRegex(url) : url;
2063
+ this.routeHandlers.push({ pattern: String(url), regex, handler });
2064
+ if (!this.interceptionEnabled) {
2065
+ this.interceptionEnabled = true;
2066
+ await this.options.conn.send("Fetch.enable", {
2067
+ patterns: [{ urlPattern: "*", requestStage: "Request" }],
2068
+ // sup-s9: 保留认证自动响应(Fetch.enable 为替换语义,不带此参数
2069
+ // 会顶掉 _init 的 auth 配置)
2070
+ handleAuthRequests: true
2071
+ }, this.options.sessionId);
2072
+ this.subscriptions.push(
2073
+ this.options.conn.subscribe("Fetch.requestPaused", this.options.sessionId, (params) => {
2074
+ this._handleRequestPaused(params);
2075
+ })
2076
+ );
2077
+ }
2078
+ }
2079
+ async unroute(url, handler) {
2080
+ const regex = typeof url === "string" ? globToRegex(url) : url;
2081
+ this.routeHandlers = this.routeHandlers.filter(
2082
+ (h) => !(regex.source === h.regex.source && (!handler || h.handler === handler))
2083
+ );
2084
+ if (this.routeHandlers.length === 0 && this.interceptionEnabled) {
2085
+ this.interceptionEnabled = false;
2086
+ await this.options.conn.send("Fetch.disable", void 0, this.options.sessionId).catch(() => {
2087
+ });
2088
+ }
2089
+ }
2090
+ async _handleRequestPaused(params) {
2091
+ const requestUrl = params.request.url;
2092
+ for (const { regex, handler } of this.routeHandlers) {
2093
+ if (regex.test(requestUrl)) {
2094
+ this.options.emit("request", createXBRequest(
2095
+ null,
2096
+ {
2097
+ requestId: params.requestId,
2098
+ url: params.request.url,
2099
+ method: params.request.method,
2100
+ headers: params.request.headers,
2101
+ postData: params.request.postData ?? null,
2102
+ resourceType: params.resourceType
2103
+ }
2104
+ ));
2105
+ const route = createXBRouteFetch(this.options.conn, this.options.sessionId, params, void 0);
2106
+ try {
2107
+ await handler(route);
2108
+ } catch {
2109
+ await this.options.conn.send("Fetch.continueRequest", {
2110
+ requestId: params.requestId
2111
+ }, this.options.sessionId).catch(() => {
2112
+ });
2113
+ }
2114
+ return;
2115
+ }
2116
+ }
2117
+ await this.options.conn.send("Fetch.continueRequest", {
2118
+ requestId: params.requestId
2119
+ }, this.options.sessionId).catch(() => {
2120
+ });
2121
+ }
2122
+ };
2123
+
2124
+ // src/cdp-driver/page-navigation.ts
2125
+ var NavigationService = class {
2126
+ constructor(options) {
2127
+ this.options = options;
2128
+ }
2129
+ options;
2130
+ async goto(url, opts = {}) {
2131
+ if (this.options.isClosed()) throw new Error("Page is closed");
2132
+ const waitUntil = opts.waitUntil ?? "load";
2133
+ const timeout = opts.timeout ?? 3e4;
2134
+ this.options.state.loadFired = false;
2135
+ this.options.state.domContentFired = false;
2136
+ this.options.state.networkIdle = false;
2137
+ if (process.env.XBROWSER_STEALTH !== "off") {
2138
+ try {
2139
+ await this.options.conn.send(
2140
+ "Page.addScriptToEvaluateOnNewDocument",
2141
+ { source: buildStealthInitScript({ ...DEFAULT_STEALTH_CONFIG, ...this.options.stealthConfig ?? {} }) },
2142
+ this.options.sessionId
2143
+ );
2144
+ } catch {
2145
+ }
2146
+ try {
2147
+ const rawUa = await this.options.conn.send(
2148
+ "Runtime.evaluate",
2149
+ { expression: "navigator.userAgent", returnByValue: true },
2150
+ this.options.sessionId
2151
+ );
2152
+ const ua = rawUa?.value || "";
2153
+ const cleaned = ua.replace(/HeadlessChrome/g, "Chrome");
2154
+ if (cleaned !== ua) {
2155
+ await this.options.conn.send(
2156
+ "Network.setUserAgentOverride",
2157
+ { userAgent: cleaned },
2158
+ this.options.sessionId
2159
+ );
2160
+ }
2161
+ } catch {
2162
+ }
2163
+ }
2164
+ const result = await this.options.conn.send(
2165
+ "Page.navigate",
2166
+ { url, referrer: opts.referer },
2167
+ this.options.sessionId
2168
+ );
2169
+ if (result.errorText) {
2170
+ throw new Error(`Navigation failed: ${result.errorText}`);
2171
+ }
2172
+ if (waitUntil === "commit") {
2173
+ this.options.setUrl(url);
2174
+ return {
2175
+ status: () => 0,
2176
+ ok: () => false,
2177
+ url: () => url,
2178
+ headers: () => ({})
2179
+ };
2180
+ }
2181
+ await this.options.waitForLoadState(waitUntil, timeout);
2182
+ this.options.setUrl(url);
2183
+ const statusCode = 200;
2184
+ const finalUrl = url;
2185
+ const headers = {};
2186
+ return {
2187
+ status: () => statusCode,
2188
+ ok: () => statusCode >= 200 && statusCode < 300,
2189
+ url: () => finalUrl,
2190
+ headers: () => headers
2191
+ };
2192
+ }
2193
+ async goBack(opts = {}) {
2194
+ try {
2195
+ const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
2196
+ if (navHistory.currentIndex > 0) {
2197
+ const prevUrl = navHistory.entries[navHistory.currentIndex - 1]?.url;
2198
+ if (prevUrl && prevUrl !== "about:blank") {
2199
+ await this.options.conn.send("Page.navigate", { url: prevUrl }, this.options.sessionId);
2200
+ await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
2201
+ });
2202
+ this.options.setUrl(prevUrl);
2203
+ return;
2204
+ }
2205
+ }
2206
+ } catch {
2207
+ }
2208
+ await this.options.evaluate("() => history.back()");
2209
+ await this.options.waitForTimeout(3e3);
2210
+ this.options.setUrl(await this.options.evaluate("location.href").catch(() => this.options.currentUrl()));
2211
+ }
2212
+ async goForward(opts = {}) {
2213
+ try {
2214
+ const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
2215
+ if (navHistory.currentIndex < navHistory.entries.length - 1) {
2216
+ const nextUrl = navHistory.entries[navHistory.currentIndex + 1]?.url;
2217
+ if (nextUrl && nextUrl !== "about:blank") {
2218
+ await this.options.conn.send("Page.navigate", { url: nextUrl }, this.options.sessionId);
2219
+ await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
2220
+ });
2221
+ this.options.setUrl(nextUrl);
2222
+ return;
2223
+ }
2224
+ }
2225
+ } catch {
2226
+ }
2227
+ await this.options.evaluate("() => history.forward()");
2228
+ await this.options.waitForTimeout(3e3);
2229
+ this.options.setUrl(await this.options.evaluate("location.href").catch(() => this.options.currentUrl()));
2230
+ }
2231
+ async reload(opts = {}) {
2232
+ this.options.state.loadFired = false;
2233
+ this.options.state.domContentFired = false;
2234
+ this.options.state.networkIdle = false;
2235
+ await this.options.conn.send("Page.reload", void 0, this.options.sessionId);
2236
+ await this.options.waitForLoadState(opts.waitUntil ?? "load", opts.timeout);
2237
+ }
2238
+ async waitForLoadState(state = "load", timeout = 3e4) {
2239
+ if (this.options.isClosed()) throw new Error("Page is closed");
2240
+ const checkState = () => {
2241
+ switch (state) {
2242
+ case "domcontentloaded":
2243
+ return this.options.state.domContentFired;
2244
+ case "load":
2245
+ return this.options.state.loadFired;
2246
+ case "networkidle":
2247
+ return this.options.state.networkIdle;
2248
+ case "commit":
2249
+ return this.options.state.domContentFired;
2250
+ default:
2251
+ return true;
2252
+ }
2253
+ };
2254
+ if (checkState()) return;
2255
+ return new Promise((resolve, reject) => {
2256
+ const timer = setTimeout(() => {
2257
+ reject(new Error(`waitForLoadState('${state}') timeout after ${timeout}ms`));
2258
+ }, timeout);
2259
+ const check = () => {
2260
+ if (checkState()) {
2261
+ clearTimeout(timer);
2262
+ resolve();
2263
+ } else {
2264
+ setTimeout(check, 50);
2265
+ }
2266
+ };
2267
+ check();
2268
+ });
2269
+ }
2270
+ async waitForTimeout(ms) {
2271
+ await new Promise((resolve) => {
2272
+ const timer = setTimeout(resolve, ms);
2273
+ if (typeof timer.unref === "function") timer.unref();
2274
+ });
2275
+ }
2276
+ };
2277
+
2278
+ // src/cdp-driver/page-dom.ts
2279
+ var DomQueryService = class {
2280
+ constructor(options) {
2281
+ this.options = options;
2282
+ }
2283
+ options;
2284
+ /** Query a single element, returns CDP nodeId or 0 if not found */
2285
+ async querySelector(selector) {
2286
+ if (selector.startsWith("xpath=")) {
2287
+ const found = await this.options.evaluate(`
2288
+ (() => { const el = ${queryJS(selector)}; return !!el; })()
2289
+ `).catch(() => false);
2290
+ if (!found) return 0;
2291
+ try {
2292
+ const search = await this.options.conn.send(
2293
+ "DOM.performSearch",
2294
+ { query: selector.slice(6) },
2295
+ this.options.sessionId
2296
+ );
2297
+ if (search.nodeId) return search.nodeId;
2298
+ } catch {
2299
+ }
2300
+ return 1;
2301
+ }
2302
+ const withTimeout = (p, ms) => Promise.race([p, new Promise((r) => setTimeout(() => r(null), ms))]);
2303
+ const doc = await withTimeout(
2304
+ this.options.conn.send("DOM.getDocument", { depth: 0 }, this.options.sessionId),
2305
+ 8e3
2306
+ );
2307
+ if (!doc) return 0;
2308
+ const result = await withTimeout(
2309
+ this.options.conn.send(
2310
+ "DOM.querySelector",
2311
+ { nodeId: doc.root.nodeId, selector },
2312
+ this.options.sessionId
2313
+ ),
2314
+ 8e3
2315
+ );
2316
+ if (!result) return 0;
2317
+ return result.nodeId;
2318
+ }
2319
+ /** Query all matching elements, returns array of CDP nodeIds */
2320
+ async querySelectorAll(selector) {
2321
+ const doc = await this.options.conn.send(
2322
+ "DOM.getDocument",
2323
+ { depth: 0 },
2324
+ this.options.sessionId
2325
+ );
2326
+ const result = await this.options.conn.send(
2327
+ "DOM.querySelectorAll",
2328
+ { nodeId: doc.root.nodeId, selector },
2329
+ this.options.sessionId
2330
+ );
2331
+ return result.nodeIds ?? [];
2332
+ }
2333
+ /** Resolve a CDP nodeId to a RemoteObject for evaluate */
2334
+ async resolveNode(nodeId) {
2335
+ const result = await this.options.conn.send(
2336
+ "DOM.resolveNode",
2337
+ { nodeId },
2338
+ this.options.sessionId
2339
+ );
2340
+ return result.object.objectId;
2341
+ }
2342
+ /** Get the box model for a nodeId */
2343
+ async getBoxModel(nodeId) {
2344
+ try {
2345
+ const result = await this.options.conn.send("DOM.getBoxModel", { nodeId }, this.options.sessionId);
2346
+ const c = result.model?.content;
2347
+ if (!c || c.length < 8) return null;
2348
+ const x1 = c[0];
2349
+ const y1 = c[1];
2350
+ const x2 = c[4];
2351
+ const y2 = c[5];
2352
+ return {
2353
+ x: Math.min(x1, x2),
2354
+ y: Math.min(y1, y2),
2355
+ width: Math.abs(x2 - x1),
2356
+ height: Math.abs(y2 - y1)
2357
+ };
2358
+ } catch {
2359
+ return null;
2360
+ }
2361
+ }
2362
+ /** Call a function on a RemoteObject */
2363
+ async callFunctionOn(objectId, functionDeclaration, args = []) {
2364
+ const result = await this.options.conn.send("Runtime.callFunctionOn", {
2365
+ objectId,
2366
+ functionDeclaration,
2367
+ arguments: args.map((a) => ({ value: a })),
2368
+ returnByValue: true
2369
+ }, this.options.sessionId);
2370
+ if (result.exceptionDetails) {
2371
+ throw new Error(`CallFunctionOn error: ${result.exceptionDetails.text}`);
2372
+ }
2373
+ return result.result?.value;
2374
+ }
2375
+ /** Send a CDP command scoped to this page's session */
2376
+ async _cdpSend(method, params) {
2377
+ return this.options.conn.send(method, params, this.options.sessionId);
2378
+ }
2379
+ /** sup-s11: beforeunload 自动应答语义——'accept'(默认,离开页面,与录制
2380
+ * 意图一致)或 'dismiss'(取消导航留守原页,尽力而为:此构建上 CDP
2381
+ * accept:false 对浏览器侧导航的取消语义不稳定,不保证)。 */
2382
+ };
2383
+
2384
+ // src/cdp-driver/page-runtime.ts
2385
+ var RuntimeEvaluationService = class {
2386
+ constructor(options) {
2387
+ this.options = options;
2388
+ }
2389
+ options;
2390
+ async title() {
2391
+ let title = "";
2392
+ for (let attempt = 0; attempt < 20; attempt++) {
2393
+ try {
2394
+ title = await this.evaluate("document.title");
2395
+ if (title) return title;
2396
+ } catch {
2397
+ }
2398
+ await new Promise((resolve) => setTimeout(resolve, 50));
2399
+ }
2400
+ return title;
2401
+ }
2402
+ async content() {
2403
+ return this.evaluate("document.documentElement.outerHTML");
2404
+ }
2405
+ // ── Evaluation ──────────────────────────────────────────────
2406
+ async evaluate(fn, ...args) {
2407
+ if (this.options.isClosed()) throw new Error("Page is closed");
2408
+ this.options.conn.send("Page.handleJavaScriptDialog", { accept: false }, this.options.sessionId).catch(() => {
2409
+ });
2410
+ let expression;
2411
+ if (typeof fn === "string") {
2412
+ expression = fn;
2413
+ } else {
2414
+ const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
2415
+ expression = `(()=>{const __fn=(${fn.toString()});return __fn(${argStr});})()`;
2416
+ }
2417
+ const result = await this.options.conn.send("Runtime.evaluate", {
2418
+ expression,
2419
+ returnByValue: true,
2420
+ awaitPromise: true
2421
+ }, this.options.sessionId);
2422
+ if (result.exceptionDetails) {
2423
+ const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
2424
+ throw new Error(`${detail}`);
2425
+ }
2426
+ return result.result?.value;
2427
+ }
2428
+ /**
2429
+ * 在指定 iframe 上下文中执行表达式(攻防 D16 能力建设,2026-08-19)。
2430
+ *
2431
+ * 双路径:
2432
+ * 1. 同进程 iframe —— Runtime.enable 收集 executionContextCreated,
2433
+ * 找到目标 frameId 的 contextId,用 contextId 定向执行;
2434
+ * 2. 跨域 OOPIF(独立 target)—— Target.setAutoAttach(flatten) 监听
2435
+ * attachedToTarget 中 type==='iframe' 的会话,用其 sessionId 执行。
2436
+ *
2437
+ * 这绕过了页面同源策略(那是页面 JS 的约束,CDP 是调试通道)——
2438
+ * 支付窗/验证码/第三方嵌入内容的读写都靠它。
2439
+ */
2440
+ async evaluateInFrame(urlIncludes, expression) {
2441
+ if (this.options.isClosed()) throw new Error("Page is closed");
2442
+ const evalIn = async (sessionId, contextId) => {
2443
+ const params = { expression, returnByValue: true, awaitPromise: true };
2444
+ if (contextId !== void 0) params.contextId = contextId;
2445
+ const result = await this.options.conn.send("Runtime.evaluate", params, sessionId);
2446
+ if (result.exceptionDetails) {
2447
+ const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
2448
+ throw new Error(`[frame ${urlIncludes}] ${detail}`);
2449
+ }
2450
+ return result.result?.value;
2451
+ };
2452
+ try {
2453
+ const tg = await this.options.conn.send("Target.getTargets", void 0);
2454
+ const hit2 = (tg.targetInfos || []).find((t) => t.type === "iframe" && (t.url || "").includes(urlIncludes));
2455
+ if (hit2) {
2456
+ const att = await this.options.conn.send("Target.attachToTarget", { targetId: hit2.targetId, flatten: true });
2457
+ return evalIn(att.sessionId);
2458
+ }
2459
+ } catch {
2460
+ }
2461
+ const tree = await this.options.conn.send("Page.getFrameTree", void 0, this.options.sessionId);
2462
+ const all = [];
2463
+ const walk = (node) => {
2464
+ all.push({ id: node.frame.id, url: node.frame.url });
2465
+ for (const child of node.childFrames || []) walk(child);
2466
+ };
2467
+ walk(tree.frameTree);
2468
+ const mainId = tree.frameTree?.frame?.id;
2469
+ const target = all.find((f) => f.id !== mainId && f.url.includes(urlIncludes));
2470
+ if (target) {
2471
+ const contexts = [];
2472
+ const onCtx = (raw) => {
2473
+ const c = raw?.context;
2474
+ if (c?.id && c?.auxData?.frameId) contexts.push({ id: c.id, frameId: c.auxData.frameId });
2475
+ };
2476
+ this.options.conn.on("Runtime.executionContextCreated", onCtx);
2477
+ try {
2478
+ await this.options.conn.send("Runtime.enable", void 0, this.options.sessionId).catch(() => {
2479
+ });
2480
+ await new Promise((r) => setTimeout(r, 400));
2481
+ } finally {
2482
+ this.options.conn.off("Runtime.executionContextCreated", onCtx);
2483
+ }
2484
+ const ctx = contexts.find((c) => c.frameId === target.id);
2485
+ if (ctx) return evalIn(this.options.sessionId, ctx.id);
2486
+ }
2487
+ const attached = [];
2488
+ const onAttach = (raw) => {
2489
+ const ev = raw;
2490
+ if (ev?.sessionId && ev.targetInfo?.type === "iframe") {
2491
+ attached.push({ sessionId: ev.sessionId, url: ev.targetInfo.url || "" });
2492
+ }
2493
+ };
2494
+ this.options.conn.on("Target.attachedToTarget", onAttach);
2495
+ try {
2496
+ await this.options.conn.send("Target.setAutoAttach", {
2497
+ autoAttach: true,
2498
+ waitForDebuggerOnStart: false,
2499
+ flatten: true
2500
+ }, this.options.sessionId);
2501
+ await new Promise((r) => setTimeout(r, 600));
2502
+ } finally {
2503
+ this.options.conn.off("Target.attachedToTarget", onAttach);
2504
+ this.options.conn.send("Target.setAutoAttach", { autoAttach: false, waitForDebuggerOnStart: false, flatten: true }, this.options.sessionId).catch(() => {
2505
+ });
2506
+ }
2507
+ const hit = attached.find((a) => a.url.includes(urlIncludes));
2508
+ if (!hit) {
2509
+ 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`);
2510
+ }
2511
+ return evalIn(hit.sessionId);
2512
+ }
2513
+ /** evaluateHandle — evaluates fn and returns a handle for element bounding box */
2514
+ async evaluateHandle(fn, ...args) {
2515
+ let expression;
2516
+ if (typeof fn === "string") {
2517
+ expression = fn;
2518
+ } else {
2519
+ const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
2520
+ 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;})()`;
2521
+ }
2522
+ const result = await this.options.conn.send("Runtime.evaluate", { expression, returnByValue: true }).catch(() => ({ result: { value: null } }));
2523
+ let box = null;
2524
+ try {
2525
+ box = JSON.parse(result.result?.value);
2526
+ } catch {
2527
+ }
2528
+ return {
2529
+ asElement: () => box ? { boundingBox: async () => box } : null
2530
+ };
2531
+ }
2532
+ async $eval(selector, fn, ...args) {
2533
+ const fnBody = typeof fn === "function" ? fn.toString() : fn;
2534
+ const selJSON = JSON.stringify(selector);
2535
+ const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
2536
+ return this.evaluate(
2537
+ `(function(sel, xpathExpr, fnStr, ...evalArgs) {
2538
+ const el = xpathExpr
2539
+ ? document.evaluate(xpathExpr, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
2540
+ : document.querySelector(sel);
2541
+ if (!el) throw new Error('No element found for selector: ' + sel);
2542
+ const fn = new Function('return ' + fnStr)();
2543
+ return fn(el, ...evalArgs);
2544
+ })(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
2545
+ );
2546
+ }
2547
+ async $$eval(selector, fn, ...args) {
2548
+ const fnBody = typeof fn === "function" ? fn.toString() : fn;
2549
+ const selJSON = JSON.stringify(selector);
2550
+ const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
2551
+ return this.evaluate(
2552
+ `(function(sel, xpathExpr, fnStr, ...evalArgs) {
2553
+ const els = xpathExpr
2554
+ ? (() => { 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; })()
2555
+ : Array.from(document.querySelectorAll(sel));
2556
+ const fn = new Function('return ' + fnStr)();
2557
+ return fn(els, ...evalArgs);
2558
+ })(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
2559
+ );
2560
+ }
2561
+ };
1583
2562
 
1584
2563
  // src/cdp-driver/page.ts
1585
2564
  var XBPageImpl = class _XBPageImpl {
@@ -1592,7 +2571,6 @@ var XBPageImpl = class _XBPageImpl {
1592
2571
  _browserImpl;
1593
2572
  _closed = false;
1594
2573
  _url = "about:blank";
1595
- _title = "";
1596
2574
  _viewportSize = null;
1597
2575
  _loadState = {
1598
2576
  loadFired: true,
@@ -1601,6 +2579,13 @@ var XBPageImpl = class _XBPageImpl {
1601
2579
  };
1602
2580
  mouse;
1603
2581
  keyboard;
2582
+ mediaService;
2583
+ fileInputService;
2584
+ networkWaitService;
2585
+ networkRouteService;
2586
+ navigationService;
2587
+ domQueryService;
2588
+ runtimeEvaluationService;
1604
2589
  // Network tracking for waitForLoadState('networkidle')
1605
2590
  inflightRequests = /* @__PURE__ */ new Set();
1606
2591
  networkIdleResolve = null;
@@ -1614,6 +2599,60 @@ var XBPageImpl = class _XBPageImpl {
1614
2599
  this._browserImpl = browser;
1615
2600
  this.mouse = new XBMouseImpl(conn, sessionId);
1616
2601
  this.keyboard = new XBKeyboardImpl(conn, sessionId);
2602
+ this.mediaService = new MediaService({
2603
+ conn,
2604
+ sessionId,
2605
+ viewportSize: this._viewportSize,
2606
+ evaluate: (script) => this.evaluate(script),
2607
+ onViewportSize: (size) => {
2608
+ this._viewportSize = size;
2609
+ }
2610
+ });
2611
+ this.fileInputService = new FileInputService({
2612
+ conn,
2613
+ sessionId,
2614
+ evaluate: (script) => this.evaluate(script),
2615
+ mouse: this.mouse
2616
+ });
2617
+ this.networkWaitService = new NetworkWaitService({
2618
+ conn,
2619
+ sessionId,
2620
+ responses: this._networkResponses,
2621
+ requests: this._networkRequests,
2622
+ on: (event, handler) => this._emitter.on(event, handler),
2623
+ off: (event, handler) => this._emitter.removeListener(event, handler),
2624
+ currentUrl: () => this.url()
2625
+ });
2626
+ this.networkRouteService = new NetworkRouteService({
2627
+ conn,
2628
+ sessionId,
2629
+ emit: (event, ...args) => this._emit(event, ...args)
2630
+ });
2631
+ this.navigationService = new NavigationService({
2632
+ conn,
2633
+ sessionId,
2634
+ state: this._loadState,
2635
+ stealthConfig: this._contextImpl.stealthConfig,
2636
+ isClosed: () => this._closed,
2637
+ setUrl: (url) => {
2638
+ this._url = url;
2639
+ },
2640
+ currentUrl: () => this.url(),
2641
+ waitForLoadState: (state, timeout) => this.waitForLoadState(state, timeout),
2642
+ waitForTimeout: (ms) => this.waitForTimeout(ms),
2643
+ evaluate: (script) => this.evaluate(script)
2644
+ });
2645
+ this.runtimeEvaluationService = new RuntimeEvaluationService({
2646
+ conn,
2647
+ sessionId,
2648
+ isClosed: () => this._closed,
2649
+ url: () => this.url()
2650
+ });
2651
+ this.domQueryService = new DomQueryService({
2652
+ conn,
2653
+ sessionId,
2654
+ evaluate: (script) => this.evaluate(script)
2655
+ });
1617
2656
  }
1618
2657
  _emit(event, ...args) {
1619
2658
  this._emitter.emit(event, ...args);
@@ -1639,7 +2678,7 @@ var XBPageImpl = class _XBPageImpl {
1639
2678
  });
1640
2679
  this._subscriptions.push(
1641
2680
  this.conn.subscribe("Fetch.requestPaused", this.sessionId, (params) => {
1642
- if (this._interceptionEnabled) return;
2681
+ if (this.networkRouteService.isInterceptionEnabled) return;
1643
2682
  const p = params;
1644
2683
  this.conn.send("Fetch.continueRequest", { requestId: p.requestId }, this.sessionId).catch(() => {
1645
2684
  });
@@ -1819,7 +2858,6 @@ var XBPageImpl = class _XBPageImpl {
1819
2858
  { targetId: this._targetId }
1820
2859
  );
1821
2860
  this._url = info.url;
1822
- this._title = info.title;
1823
2861
  if (info.url && info.url !== "about:blank" && info.url !== "") {
1824
2862
  this._loadState = { loadFired: true, domContentFired: true, networkIdle: true };
1825
2863
  }
@@ -1831,108 +2869,16 @@ var XBPageImpl = class _XBPageImpl {
1831
2869
  }
1832
2870
  // ── Navigation ──────────────────────────────────────────────
1833
2871
  async goto(url, opts = {}) {
1834
- if (this._closed) throw new Error("Page is closed");
1835
- const waitUntil = opts.waitUntil ?? "load";
1836
- const timeout = opts.timeout ?? 3e4;
1837
- this._loadState = { loadFired: false, domContentFired: false, networkIdle: false };
1838
- if (process.env.XBROWSER_STEALTH !== "off") {
1839
- try {
1840
- await this.conn.send(
1841
- "Page.addScriptToEvaluateOnNewDocument",
1842
- { source: buildStealthInitScript({ ...DEFAULT_STEALTH_CONFIG, ...this._contextImpl.stealthConfig ?? {} }) },
1843
- this.sessionId
1844
- );
1845
- } catch {
1846
- }
1847
- try {
1848
- const rawUa = await this.conn.send(
1849
- "Runtime.evaluate",
1850
- { expression: "navigator.userAgent", returnByValue: true },
1851
- this.sessionId
1852
- );
1853
- const ua = rawUa?.value || "";
1854
- const cleaned = ua.replace(/HeadlessChrome/g, "Chrome");
1855
- if (cleaned !== ua) {
1856
- await this.conn.send(
1857
- "Network.setUserAgentOverride",
1858
- { userAgent: cleaned },
1859
- this.sessionId
1860
- );
1861
- }
1862
- } catch {
1863
- }
1864
- }
1865
- const result = await this.conn.send(
1866
- "Page.navigate",
1867
- { url, referrer: opts.referer },
1868
- this.sessionId
1869
- );
1870
- if (result.errorText) {
1871
- throw new Error(`Navigation failed: ${result.errorText}`);
1872
- }
1873
- if (waitUntil === "commit") {
1874
- this._url = url;
1875
- return {
1876
- status: () => 0,
1877
- ok: () => false,
1878
- url: () => url,
1879
- headers: () => ({})
1880
- };
1881
- }
1882
- await this.waitForLoadState(waitUntil, timeout);
1883
- this._url = url;
1884
- const statusCode = 200;
1885
- const finalUrl = url;
1886
- const headers = {};
1887
- return {
1888
- status: () => statusCode,
1889
- ok: () => statusCode >= 200 && statusCode < 300,
1890
- url: () => finalUrl,
1891
- headers: () => headers
1892
- };
2872
+ return this.navigationService.goto(url, opts);
1893
2873
  }
1894
2874
  async goBack(opts = {}) {
1895
- try {
1896
- const navHistory = await this.conn.send("Page.getNavigationHistory", void 0, this.sessionId);
1897
- if (navHistory.currentIndex > 0) {
1898
- const prevUrl = navHistory.entries[navHistory.currentIndex - 1]?.url;
1899
- if (prevUrl && prevUrl !== "about:blank") {
1900
- await this.conn.send("Page.navigate", { url: prevUrl }, this.sessionId);
1901
- await this.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
1902
- });
1903
- this._url = prevUrl;
1904
- return;
1905
- }
1906
- }
1907
- } catch {
1908
- }
1909
- await this.evaluate("() => history.back()");
1910
- await this.waitForTimeout(3e3);
1911
- this._url = await this.evaluate("location.href").catch(() => this._url);
2875
+ return this.navigationService.goBack(opts);
1912
2876
  }
1913
2877
  async goForward(opts = {}) {
1914
- try {
1915
- const navHistory = await this.conn.send("Page.getNavigationHistory", void 0, this.sessionId);
1916
- if (navHistory.currentIndex < navHistory.entries.length - 1) {
1917
- const nextUrl = navHistory.entries[navHistory.currentIndex + 1]?.url;
1918
- if (nextUrl && nextUrl !== "about:blank") {
1919
- await this.conn.send("Page.navigate", { url: nextUrl }, this.sessionId);
1920
- await this.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
1921
- });
1922
- this._url = nextUrl;
1923
- return;
1924
- }
1925
- }
1926
- } catch {
1927
- }
1928
- await this.evaluate("() => history.forward()");
1929
- await this.waitForTimeout(3e3);
1930
- this._url = await this.evaluate("location.href").catch(() => this._url);
2878
+ return this.navigationService.goForward(opts);
1931
2879
  }
1932
2880
  async reload(opts = {}) {
1933
- this._loadState = { loadFired: false, domContentFired: false, networkIdle: false };
1934
- await this.conn.send("Page.reload", void 0, this.sessionId);
1935
- await this.waitForLoadState(opts.waitUntil ?? "load", opts.timeout);
2881
+ return this.navigationService.reload(opts);
1936
2882
  }
1937
2883
  async waitForLoadState(state = "load", timeout = 3e4) {
1938
2884
  if (this._closed) throw new Error("Page is closed");
@@ -2003,206 +2949,48 @@ var XBPageImpl = class _XBPageImpl {
2003
2949
  const timeout = opts.timeout ?? 3e4;
2004
2950
  const polling = opts.polling ?? 100;
2005
2951
  const deadline = Date.now() + timeout;
2006
- const fnBody = typeof fn === "function" ? fn.toString() : fn;
2007
- let lastError = null;
2008
- while (Date.now() < deadline) {
2009
- try {
2010
- const result = await this.evaluate(
2011
- `(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(", ") : ""})`
2012
- );
2013
- if (result) return result;
2014
- } catch (err) {
2015
- lastError = err instanceof Error ? err : new Error(errMsg(err));
2016
- }
2017
- const pollMs = typeof polling === "number" ? polling : 16;
2018
- await this.waitForTimeout(pollMs);
2019
- }
2020
- const detail = lastError ? `
2021
- Last error: ${lastError.message}` : "";
2022
- throw new Error(`waitForFunction timeout after ${timeout}ms${detail}`);
2023
- }
2024
- url() {
2025
- return this._url;
2026
- }
2027
- async title() {
2028
- for (let i = 0; i < 20; i++) {
2029
- try {
2030
- this._title = await this.evaluate("document.title");
2031
- if (this._title) return this._title;
2032
- } catch {
2033
- }
2034
- await new Promise((r) => setTimeout(r, 50));
2035
- }
2036
- try {
2037
- const info = await this._cdpSend("Target.getTargetInfo", { targetId: this._targetId });
2038
- if (info?.title) {
2039
- this._title = info.title;
2040
- return this._title;
2041
- }
2042
- } catch {
2043
- }
2044
- return this._title;
2045
- }
2046
- async content() {
2047
- return this.evaluate("document.documentElement.outerHTML");
2048
- }
2049
- // ── Evaluation ──────────────────────────────────────────────
2050
- async evaluate(fn, ...args) {
2051
- if (this._closed) throw new Error("Page is closed");
2052
- this.conn.send("Page.handleJavaScriptDialog", { accept: false }, this.sessionId).catch(() => {
2053
- });
2054
- let expression;
2055
- if (typeof fn === "string") {
2056
- expression = fn;
2057
- } else {
2058
- const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
2059
- expression = `(()=>{const __fn=(${fn.toString()});return __fn(${argStr});})()`;
2060
- }
2061
- const result = await this.conn.send("Runtime.evaluate", {
2062
- expression,
2063
- returnByValue: true,
2064
- awaitPromise: true
2065
- }, this.sessionId);
2066
- if (result.exceptionDetails) {
2067
- const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
2068
- throw new Error(`${detail}`);
2069
- }
2070
- return result.result?.value;
2071
- }
2072
- /**
2073
- * 在指定 iframe 上下文中执行表达式(攻防 D16 能力建设,2026-08-19)。
2074
- *
2075
- * 双路径:
2076
- * 1. 同进程 iframe —— Runtime.enable 收集 executionContextCreated,
2077
- * 找到目标 frameId 的 contextId,用 contextId 定向执行;
2078
- * 2. 跨域 OOPIF(独立 target)—— Target.setAutoAttach(flatten) 监听
2079
- * attachedToTarget 中 type==='iframe' 的会话,用其 sessionId 执行。
2080
- *
2081
- * 这绕过了页面同源策略(那是页面 JS 的约束,CDP 是调试通道)——
2082
- * 支付窗/验证码/第三方嵌入内容的读写都靠它。
2083
- */
2084
- async evaluateInFrame(urlIncludes, expression) {
2085
- if (this._closed) throw new Error("Page is closed");
2086
- const evalIn = async (sessionId, contextId) => {
2087
- const params = { expression, returnByValue: true, awaitPromise: true };
2088
- if (contextId !== void 0) params.contextId = contextId;
2089
- const result = await this.conn.send("Runtime.evaluate", params, sessionId);
2090
- if (result.exceptionDetails) {
2091
- const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
2092
- throw new Error(`[frame ${urlIncludes}] ${detail}`);
2093
- }
2094
- return result.result?.value;
2095
- };
2096
- try {
2097
- const tg = await this.conn.send("Target.getTargets", void 0);
2098
- const hit2 = (tg.targetInfos || []).find((t) => t.type === "iframe" && (t.url || "").includes(urlIncludes));
2099
- if (hit2) {
2100
- const att = await this.conn.send("Target.attachToTarget", { targetId: hit2.targetId, flatten: true });
2101
- return evalIn(att.sessionId);
2102
- }
2103
- } catch {
2104
- }
2105
- const tree = await this.conn.send("Page.getFrameTree", void 0, this.sessionId);
2106
- const all = [];
2107
- const walk = (node) => {
2108
- all.push({ id: node.frame.id, url: node.frame.url });
2109
- for (const child of node.childFrames || []) walk(child);
2110
- };
2111
- walk(tree.frameTree);
2112
- const mainId = tree.frameTree?.frame?.id;
2113
- const target = all.find((f) => f.id !== mainId && f.url.includes(urlIncludes));
2114
- if (target) {
2115
- const contexts = [];
2116
- const onCtx = (raw) => {
2117
- const c = raw?.context;
2118
- if (c?.id && c?.auxData?.frameId) contexts.push({ id: c.id, frameId: c.auxData.frameId });
2119
- };
2120
- this.conn.on("Runtime.executionContextCreated", onCtx);
2121
- try {
2122
- await this.conn.send("Runtime.enable", void 0, this.sessionId).catch(() => {
2123
- });
2124
- await new Promise((r) => setTimeout(r, 400));
2125
- } finally {
2126
- this.conn.off("Runtime.executionContextCreated", onCtx);
2127
- }
2128
- const ctx = contexts.find((c) => c.frameId === target.id);
2129
- if (ctx) return evalIn(this.sessionId, ctx.id);
2130
- }
2131
- const attached = [];
2132
- const onAttach = (raw) => {
2133
- const ev = raw;
2134
- if (ev?.sessionId && ev.targetInfo?.type === "iframe") {
2135
- attached.push({ sessionId: ev.sessionId, url: ev.targetInfo.url || "" });
2136
- }
2137
- };
2138
- this.conn.on("Target.attachedToTarget", onAttach);
2139
- try {
2140
- await this.conn.send("Target.setAutoAttach", {
2141
- autoAttach: true,
2142
- waitForDebuggerOnStart: false,
2143
- flatten: true
2144
- }, this.sessionId);
2145
- await new Promise((r) => setTimeout(r, 600));
2146
- } finally {
2147
- this.conn.off("Target.attachedToTarget", onAttach);
2148
- this.conn.send("Target.setAutoAttach", { autoAttach: false, waitForDebuggerOnStart: false, flatten: true }, this.sessionId).catch(() => {
2149
- });
2150
- }
2151
- const hit = attached.find((a) => a.url.includes(urlIncludes));
2152
- if (!hit) {
2153
- 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`);
2154
- }
2155
- return evalIn(hit.sessionId);
2156
- }
2157
- /** evaluateHandle — evaluates fn and returns a handle for element bounding box */
2158
- async evaluateHandle(fn, ...args) {
2159
- let expression;
2160
- if (typeof fn === "string") {
2161
- expression = fn;
2162
- } else {
2163
- const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
2164
- 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;})()`;
2165
- }
2166
- const result = await this.conn.send("Runtime.evaluate", { expression, returnByValue: true }).catch(() => ({ result: { value: null } }));
2167
- let box = null;
2168
- try {
2169
- box = JSON.parse(result.result?.value);
2170
- } catch {
2952
+ const fnBody = typeof fn === "function" ? fn.toString() : fn;
2953
+ let lastError = null;
2954
+ while (Date.now() < deadline) {
2955
+ try {
2956
+ const result = await this.evaluate(
2957
+ `(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(", ") : ""})`
2958
+ );
2959
+ if (result) return result;
2960
+ } catch (err) {
2961
+ lastError = err instanceof Error ? err : new Error(errMsg(err));
2962
+ }
2963
+ const pollMs = typeof polling === "number" ? polling : 16;
2964
+ await this.waitForTimeout(pollMs);
2171
2965
  }
2172
- return {
2173
- asElement: () => box ? { boundingBox: async () => box } : null
2174
- };
2966
+ const detail = lastError ? `
2967
+ Last error: ${lastError.message}` : "";
2968
+ throw new Error(`waitForFunction timeout after ${timeout}ms${detail}`);
2969
+ }
2970
+ url() {
2971
+ return this._url;
2972
+ }
2973
+ async title() {
2974
+ return this.runtimeEvaluationService.title();
2975
+ }
2976
+ async content() {
2977
+ return this.runtimeEvaluationService.content();
2978
+ }
2979
+ async evaluate(fn, ...args) {
2980
+ return this.runtimeEvaluationService.evaluate(fn, ...args);
2981
+ }
2982
+ async evaluateInFrame(urlIncludes, expression) {
2983
+ return this.runtimeEvaluationService.evaluateInFrame(urlIncludes, expression);
2984
+ }
2985
+ async evaluateHandle(script, ...args) {
2986
+ return this.runtimeEvaluationService.evaluateHandle(script, ...args);
2175
2987
  }
2176
2988
  async $eval(selector, fn, ...args) {
2177
- const fnBody = typeof fn === "function" ? fn.toString() : fn;
2178
- const selJSON = JSON.stringify(selector);
2179
- const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
2180
- return this.evaluate(
2181
- `(function(sel, xpathExpr, fnStr, ...evalArgs) {
2182
- const el = xpathExpr
2183
- ? document.evaluate(xpathExpr, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
2184
- : document.querySelector(sel);
2185
- if (!el) throw new Error('No element found for selector: ' + sel);
2186
- const fn = new Function('return ' + fnStr)();
2187
- return fn(el, ...evalArgs);
2188
- })(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
2189
- );
2989
+ return this.runtimeEvaluationService.$eval(selector, fn, ...args);
2190
2990
  }
2191
2991
  async $$eval(selector, fn, ...args) {
2192
- const fnBody = typeof fn === "function" ? fn.toString() : fn;
2193
- const selJSON = JSON.stringify(selector);
2194
- const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
2195
- return this.evaluate(
2196
- `(function(sel, xpathExpr, fnStr, ...evalArgs) {
2197
- const els = xpathExpr
2198
- ? (() => { 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; })()
2199
- : Array.from(document.querySelectorAll(sel));
2200
- const fn = new Function('return ' + fnStr)();
2201
- return fn(els, ...evalArgs);
2202
- })(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
2203
- );
2992
+ return this.runtimeEvaluationService.$$eval(selector, fn, ...args);
2204
2993
  }
2205
- // ── Locator ─────────────────────────────────────────────────
2206
2994
  locator(selector) {
2207
2995
  return new XBLocatorImpl(this, selector);
2208
2996
  }
@@ -2323,88 +3111,20 @@ Last error: ${lastError.message}` : "";
2323
3111
  }
2324
3112
  // ── Screen ──────────────────────────────────────────────────
2325
3113
  async screenshot(opts = {}) {
2326
- const params = {
2327
- format: opts.type ?? "png"
2328
- };
2329
- if (opts.quality !== void 0 && (opts.type === "jpeg" || !opts.type && opts.quality)) {
2330
- params.quality = opts.quality;
2331
- }
2332
- if (opts.fullPage) {
2333
- params.captureBeyondViewport = true;
2334
- }
2335
- if (opts.clip) {
2336
- const clip = {
2337
- x: Math.round(opts.clip.x),
2338
- y: Math.round(opts.clip.y),
2339
- width: Math.round(Math.max(1, opts.clip.width)),
2340
- height: Math.round(Math.max(1, opts.clip.height)),
2341
- scale: 1
2342
- };
2343
- params.clip = clip;
2344
- }
2345
- if (opts.omitBackground) {
2346
- params.omitBackground = true;
2347
- }
2348
- const result = await this.conn.send(
2349
- "Page.captureScreenshot",
2350
- params,
2351
- this.sessionId
2352
- );
2353
- return Buffer.from(result.data, "base64");
3114
+ return this.mediaService.screenshot(opts);
2354
3115
  }
2355
3116
  async pdf(opts = {}) {
2356
- const params = {};
2357
- if (opts.landscape !== void 0) params.landscape = opts.landscape;
2358
- if (opts.printBackground !== void 0) params.printBackground = opts.printBackground;
2359
- if (opts.scale !== void 0) params.scale = opts.scale;
2360
- if (opts.format) params.paperFormat = opts.format;
2361
- if (opts.preferCSSPageSize !== void 0) params.preferCSSPageSize = opts.preferCSSPageSize;
2362
- if (opts.margin) {
2363
- if (opts.margin.top) params.marginTop = parseFloat(opts.margin.top);
2364
- if (opts.margin.bottom) params.marginBottom = parseFloat(opts.margin.bottom);
2365
- if (opts.margin.left) params.marginLeft = parseFloat(opts.margin.left);
2366
- if (opts.margin.right) params.marginRight = parseFloat(opts.margin.right);
2367
- }
2368
- const result = await this.conn.send("Page.printToPDF", params, this.sessionId);
2369
- return Buffer.from(result.data, "base64");
3117
+ return this.mediaService.pdf(opts);
2370
3118
  }
2371
3119
  viewportSize() {
2372
- return this._viewportSize ?? null;
3120
+ return this._viewportSize;
2373
3121
  }
2374
3122
  async setViewportSize(size) {
2375
- await this.conn.send(
2376
- "Emulation.setDeviceMetricsOverride",
2377
- {
2378
- width: size.width,
2379
- height: size.height,
2380
- deviceScaleFactor: 1,
2381
- mobile: false
2382
- },
2383
- this.sessionId
2384
- );
2385
- this._viewportSize = size;
3123
+ return this.mediaService.setViewportSize(size);
2386
3124
  }
2387
- /**
2388
- * env-E2: 缩放变异——deviceScaleFactor 切换(CSS 像素坐标空间不变,
2389
- * 物理像素翻倍)。保留当前 CSS 视口尺寸,只换 DSF。
2390
- */
2391
3125
  async setDeviceScaleFactor(dsf) {
2392
- const size = this._viewportSize ?? await this.evaluate(
2393
- "({ width: window.innerWidth, height: window.innerHeight })"
2394
- );
2395
- await this.conn.send(
2396
- "Emulation.setDeviceMetricsOverride",
2397
- {
2398
- width: size.width,
2399
- height: size.height,
2400
- deviceScaleFactor: dsf,
2401
- mobile: false
2402
- },
2403
- this.sessionId
2404
- );
2405
- this._viewportSize = size;
3126
+ return this.mediaService.setDeviceScaleFactor(dsf);
2406
3127
  }
2407
- // ── Scripts ─────────────────────────────────────────────────
2408
3128
  async addInitScript(script) {
2409
3129
  await this.conn.send(
2410
3130
  "Page.addScriptToEvaluateOnNewDocument",
@@ -2532,83 +3252,17 @@ Last error: ${lastError.message}` : "";
2532
3252
  }
2533
3253
  }
2534
3254
  // ── CDP helpers exposed for locator/element ─────────────────
2535
- /** Query a single element, returns CDP nodeId or 0 if not found */
2536
3255
  async querySelector(selector) {
2537
- if (selector.startsWith("xpath=")) {
2538
- const found = await this.evaluate(`
2539
- (() => { const el = ${queryJS(selector)}; return !!el; })()
2540
- `).catch(() => false);
2541
- if (!found) return 0;
2542
- try {
2543
- const search = await this.conn.send(
2544
- "DOM.performSearch",
2545
- { query: selector.slice(6) },
2546
- this.sessionId
2547
- );
2548
- if (search.nodeId) return search.nodeId;
2549
- } catch {
2550
- }
2551
- return 1;
2552
- }
2553
- const withTimeout = (p, ms) => Promise.race([p, new Promise((r) => setTimeout(() => r(null), ms))]);
2554
- const doc = await withTimeout(
2555
- this.conn.send("DOM.getDocument", { depth: 0 }, this.sessionId),
2556
- 8e3
2557
- );
2558
- if (!doc) return 0;
2559
- const result = await withTimeout(
2560
- this.conn.send(
2561
- "DOM.querySelector",
2562
- { nodeId: doc.root.nodeId, selector },
2563
- this.sessionId
2564
- ),
2565
- 8e3
2566
- );
2567
- if (!result) return 0;
2568
- return result.nodeId;
3256
+ return this.domQueryService.querySelector(selector);
2569
3257
  }
2570
- /** Query all matching elements, returns array of CDP nodeIds */
2571
3258
  async querySelectorAll(selector) {
2572
- const doc = await this.conn.send(
2573
- "DOM.getDocument",
2574
- { depth: 0 },
2575
- this.sessionId
2576
- );
2577
- const result = await this.conn.send(
2578
- "DOM.querySelectorAll",
2579
- { nodeId: doc.root.nodeId, selector },
2580
- this.sessionId
2581
- );
2582
- return result.nodeIds ?? [];
3259
+ return this.domQueryService.querySelectorAll(selector);
2583
3260
  }
2584
- /** Resolve a CDP nodeId to a RemoteObject for evaluate */
2585
3261
  async resolveNode(nodeId) {
2586
- const result = await this.conn.send(
2587
- "DOM.resolveNode",
2588
- { nodeId },
2589
- this.sessionId
2590
- );
2591
- return result.object.objectId;
3262
+ return this.domQueryService.resolveNode(nodeId);
2592
3263
  }
2593
- /** Get the box model for a nodeId */
2594
3264
  async getBoxModel(nodeId) {
2595
- try {
2596
- const result = await this.conn.send("DOM.getBoxModel", { nodeId }, this.sessionId);
2597
- const c = result.model?.content;
2598
- if (!c || c.length < 8) return null;
2599
- const x1 = c[0];
2600
- const y1 = c[1];
2601
- const x2 = c[4];
2602
- const y2 = c[5];
2603
- return {
2604
- x: Math.min(x1, x2),
2605
- y: Math.min(y1, y2),
2606
- width: Math.abs(x2 - x1),
2607
- height: Math.abs(y2 - y1)
2608
- };
2609
- } catch {
2610
- return null;
2611
- }
3265
+ return this.domQueryService.getBoxModel(nodeId);
2612
3266
  }
2613
3267
  /** Call a function on a RemoteObject */
2614
3268
  async callFunctionOn(objectId, functionDeclaration, args = []) {
@@ -2627,9 +3281,6 @@ Last error: ${lastError.message}` : "";
2627
3281
  async _cdpSend(method, params) {
2628
3282
  return this.conn.send(method, params, this.sessionId);
2629
3283
  }
2630
- /** sup-s11: beforeunload 自动应答语义——'accept'(默认,离开页面,与录制
2631
- * 意图一致)或 'dismiss'(取消导航留守原页,尽力而为:此构建上 CDP
2632
- * accept:false 对浏览器侧导航的取消语义不稳定,不保证)。 */
2633
3284
  setBeforeUnloadBehavior(mode) {
2634
3285
  this._beforeUnloadAccept = mode === "accept";
2635
3286
  }
@@ -2650,146 +3301,40 @@ Last error: ${lastError.message}` : "";
2650
3301
  _subscribe(event, handler) {
2651
3302
  return this.conn.subscribe(event, this.sessionId, handler);
2652
3303
  }
2653
- // ── Private: Event Setup ────────────────────────────────────
2654
- setupPageEvents() {
2655
- this._subscriptions.push(
2656
- this.conn.subscribe("Page.frameNavigated", this.sessionId, (params) => {
2657
- const p = params;
2658
- if (p.frame) {
2659
- this._url = p.frame.url;
2660
- }
2661
- this._emit("framenavigated", this.mainFrame());
2662
- })
2663
- );
2664
- this._subscriptions.push(
2665
- this.conn.subscribe("Page.loadEventFired", this.sessionId, () => {
2666
- this._loadState.loadFired = true;
2667
- })
2668
- );
2669
- this._subscriptions.push(
2670
- this.conn.subscribe("Page.domContentEventFired", this.sessionId, () => {
2671
- this._loadState.domContentFired = true;
2672
- })
2673
- );
2674
- this._subscriptions.push(
2675
- this.conn.subscribe("Page.javascriptDialogOpening", this.sessionId, (params) => {
2676
- const p = params;
2677
- const dialog = {
2678
- type: p.type,
2679
- message: () => p.message,
2680
- defaultValue: () => p.defaultValue,
2681
- accept: async (text) => {
2682
- await this.conn.send("Page.handleJavaScriptDialog", {
2683
- accept: true,
2684
- promptText: text
2685
- }, this.sessionId);
2686
- },
2687
- dismiss: async () => {
2688
- await this.conn.send("Page.handleJavaScriptDialog", {
2689
- accept: false
2690
- }, this.sessionId);
2691
- }
2692
- };
2693
- this._emit("dialog", dialog);
2694
- const autoAccept = p.type === "beforeunload" ? this._beforeUnloadAccept : false;
2695
- setTimeout(() => {
2696
- this.conn.send("Page.handleJavaScriptDialog", { accept: autoAccept }, this.sessionId).catch(() => {
2697
- });
2698
- }, 0);
2699
- })
2700
- );
2701
- this._subscriptions.push(
2702
- this.conn.subscribe("Page.fileChooserOpened", this.sessionId, async (params) => {
2703
- const p = params;
2704
- let selector = "";
2705
- try {
2706
- const result = await this.conn.send("DOM.describeNode", { backendNodeId: p.backendNodeId }, this.sessionId);
2707
- const attrs = result.node?.attributes || [];
2708
- const idIdx = attrs.indexOf("id");
2709
- if (idIdx >= 0) selector = "#" + attrs[idIdx + 1];
2710
- } catch {
2711
- }
2712
- if (!selector) {
2713
- try {
2714
- const result = await this.conn.send("DOM.resolveNode", { backendNodeId: p.backendNodeId }, this.sessionId);
2715
- const evalResult = await this.conn.send("Runtime.callFunctionOn", {
2716
- objectId: result.objectId,
2717
- functionDeclaration: 'function() { return this.id || this.name || "" }',
2718
- returnByValue: true
2719
- }, this.sessionId);
2720
- if (evalResult.result?.value) selector = "#" + evalResult.result.value;
2721
- } catch {
2722
- }
2723
- }
2724
- const fileChooser = {
2725
- selector,
2726
- isMultiple: p.mode === "selectMultiple",
2727
- setFiles: async (files) => {
2728
- const fileArray = Array.isArray(files) ? files : [files];
2729
- await this.setInputFiles(selector || 'input[type="file"]', fileArray);
2730
- }
2731
- };
2732
- this._emit("filechooser", fileChooser);
2733
- })
2734
- );
2735
- }
2736
- setupNetworkEvents() {
2737
- this._subscriptions.push(
2738
- this.conn.subscribe("Network.requestWillBeSent", this.sessionId, (params) => {
2739
- const p = params;
2740
- this.inflightRequests.add(p.requestId);
2741
- this._storeNetworkRequest(p.requestId, {
2742
- url: p.request.url,
2743
- method: p.request.method,
2744
- headers: p.request.headers,
2745
- postData: p.request.postData ?? null,
2746
- resourceType: p.type
2747
- });
2748
- this._emit("request", createXBRequest(
2749
- null,
2750
- {
2751
- requestId: p.requestId,
2752
- url: p.request.url,
2753
- method: p.request.method,
2754
- headers: p.request.headers,
2755
- postData: p.request.postData ?? null,
2756
- resourceType: p.type
2757
- }
2758
- ));
2759
- this.checkNetworkIdle();
2760
- })
2761
- );
2762
- this._subscriptions.push(
2763
- this.conn.subscribe("Network.responseReceived", this.sessionId, (params) => {
2764
- const p = params;
2765
- this._storeNetworkResponse(p.requestId, {
2766
- status: p.response.status,
2767
- url: p.response.url,
2768
- headers: p.response.headers
2769
- });
2770
- this._emit("response", createXBResponse(
2771
- { requestId: p.requestId, status: p.response.status, url: p.response.url, headers: p.response.headers },
2772
- this.conn,
2773
- this.sessionId
2774
- ));
2775
- })
2776
- );
2777
- this._subscriptions.push(
2778
- this.conn.subscribe("Network.loadingFinished", this.sessionId, (params) => {
2779
- const p = params;
2780
- this.inflightRequests.delete(p.requestId);
2781
- this._emit("requestfinished", p);
2782
- this.checkNetworkIdle();
2783
- })
2784
- );
2785
- this._subscriptions.push(
2786
- this.conn.subscribe("Network.loadingFailed", this.sessionId, (params) => {
2787
- const p = params;
2788
- this.inflightRequests.delete(p.requestId);
2789
- this.checkNetworkIdle();
2790
- })
2791
- );
2792
- }
3304
+ // ── Private: Event Setup ────────────────────────────────────
3305
+ setupPageEvents() {
3306
+ setupPageEvents({
3307
+ conn: this.conn,
3308
+ sessionId: this.sessionId,
3309
+ addSubscription: (unsubscribe) => this._subscriptions.push(unsubscribe),
3310
+ emit: (event, ...args) => this._emit(event, ...args),
3311
+ setUrl: (url) => {
3312
+ this._url = url;
3313
+ },
3314
+ currentUrl: () => this.url(),
3315
+ mainFrame: () => this.mainFrame(),
3316
+ markLoadFired: () => {
3317
+ this._loadState.loadFired = true;
3318
+ },
3319
+ markDomContentFired: () => {
3320
+ this._loadState.domContentFired = true;
3321
+ },
3322
+ getBeforeUnloadAccept: () => this._beforeUnloadAccept,
3323
+ setInputFiles: (selector, files) => this.setInputFiles(selector, files)
3324
+ });
3325
+ }
3326
+ setupNetworkEvents() {
3327
+ setupNetworkEvents({
3328
+ conn: this.conn,
3329
+ sessionId: this.sessionId,
3330
+ state: { inflightRequests: this.inflightRequests },
3331
+ emit: (event, ...args) => this._emit(event, ...args),
3332
+ storeRequest: (id, data) => this._storeNetworkRequest(id, data),
3333
+ storeResponse: (id, data) => this._storeNetworkResponse(id, data),
3334
+ checkNetworkIdle: () => this.checkNetworkIdle(),
3335
+ addSubscription: (unsubscribe) => this._subscriptions.push(unsubscribe)
3336
+ });
3337
+ }
2793
3338
  setupConsoleEvents() {
2794
3339
  this._subscriptions.push(
2795
3340
  this.conn.subscribe("Runtime.consoleAPICalled", this.sessionId, (params) => {
@@ -2834,8 +3379,6 @@ Last error: ${lastError.message}` : "";
2834
3379
  // ── Network Data Store (for waitForResponse/waitForRequest) ──
2835
3380
  _networkResponses = /* @__PURE__ */ new Map();
2836
3381
  _networkRequests = /* @__PURE__ */ new Map();
2837
- _routeHandlers = [];
2838
- _interceptionEnabled = false;
2839
3382
  _beforeUnloadAccept = true;
2840
3383
  /** Store network data — called by browser.ts installNetworkCapture or internal event handlers */
2841
3384
  _storeNetworkRequest(requestId, data) {
@@ -2844,284 +3387,30 @@ Last error: ${lastError.message}` : "";
2844
3387
  _storeNetworkResponse(requestId, data) {
2845
3388
  this._networkResponses.set(requestId, { requestId, ...data });
2846
3389
  }
2847
- // ── waitForResponse ─────────────────────────────────────────
2848
3390
  async waitForResponse(urlOrPredicate, opts = {}) {
2849
- const timeout = opts.timeout ?? 3e4;
2850
- const predicate = createResponsePredicate(urlOrPredicate);
2851
- for (const [, data] of this._networkResponses) {
2852
- const response = createXBResponse(data, this.conn, this.sessionId);
2853
- if (predicate(response)) return response;
2854
- }
2855
- return new Promise((resolve, reject) => {
2856
- const timer = setTimeout(() => {
2857
- this._emitter.removeListener("response", handler);
2858
- reject(new Error(`waitForResponse timed out after ${timeout}ms`));
2859
- }, timeout);
2860
- const handler = (params) => {
2861
- let response;
2862
- const respObj = params;
2863
- if (respObj.response) {
2864
- const data = {
2865
- requestId: respObj.requestId || "",
2866
- status: respObj.response.status || 0,
2867
- url: respObj.response.url || "",
2868
- headers: respObj.response.headers || {}
2869
- };
2870
- response = createXBResponse(data, this.conn, this.sessionId);
2871
- } else if (typeof params.status === "function") {
2872
- response = params;
2873
- } else {
2874
- return;
2875
- }
2876
- if (predicate(response)) {
2877
- clearTimeout(timer);
2878
- this._emitter.removeListener("response", handler);
2879
- resolve(response);
2880
- }
2881
- };
2882
- this._emitter.on("response", handler);
2883
- });
3391
+ return this.networkWaitService.waitForResponse(urlOrPredicate, opts);
2884
3392
  }
2885
- // ── waitForRequest ──────────────────────────────────────────
2886
3393
  async waitForRequest(urlOrPredicate, opts = {}) {
2887
- const timeout = opts.timeout ?? 3e4;
2888
- const predicate = createRequestPredicate(urlOrPredicate);
2889
- for (const [, data] of this._networkRequests) {
2890
- const request = createXBRequest(this, data);
2891
- if (predicate(request)) return request;
2892
- }
2893
- return new Promise((resolve, reject) => {
2894
- const timer = setTimeout(() => {
2895
- this._emitter.removeListener("request", handler);
2896
- reject(new Error(`waitForRequest timed out after ${timeout}ms`));
2897
- }, timeout);
2898
- const handler = (params) => {
2899
- let request;
2900
- const reqObj = params;
2901
- if (reqObj.request) {
2902
- request = createXBRequest(this, {
2903
- requestId: reqObj.requestId || "",
2904
- url: reqObj.request.url || "",
2905
- method: reqObj.request.method || "",
2906
- headers: reqObj.request.headers || {},
2907
- postData: reqObj.request.postData ?? null,
2908
- resourceType: reqObj.type || ""
2909
- });
2910
- } else if (typeof params.url === "function") {
2911
- request = params;
2912
- } else {
2913
- return;
2914
- }
2915
- if (predicate(request)) {
2916
- clearTimeout(timer);
2917
- this._emitter.removeListener("request", handler);
2918
- resolve(request);
2919
- }
2920
- };
2921
- this._emitter.on("request", handler);
2922
- });
3394
+ return this.networkWaitService.waitForRequest(urlOrPredicate, opts);
2923
3395
  }
2924
- // ── waitForURL ──────────────────────────────────────────────
2925
3396
  async waitForURL(url, opts = {}) {
2926
- const timeout = opts.timeout ?? 3e4;
2927
- const checkFn = typeof url === "function" ? url : typeof url === "string" ? (current) => matchGlob(url, current) : (current) => url.test(current);
2928
- if (checkFn(this._url)) return;
2929
- return new Promise((resolve, reject) => {
2930
- const timer = setTimeout(() => {
2931
- this._emitter.removeListener("framenavigated", handler);
2932
- reject(new Error(`waitForURL timed out after ${timeout}ms`));
2933
- }, timeout);
2934
- const handler = () => {
2935
- if (checkFn(this._url)) {
2936
- clearTimeout(timer);
2937
- this._emitter.removeListener("framenavigated", handler);
2938
- resolve();
2939
- }
2940
- };
2941
- this._emitter.on("framenavigated", handler);
2942
- });
2943
- }
2944
- // ── route / unroute ─────────────────────────────────────────
2945
- async route(url, handler) {
2946
- const regex = typeof url === "string" ? globToRegex(url) : url;
2947
- this._routeHandlers.push({ pattern: String(url), regex, handler });
2948
- if (!this._interceptionEnabled) {
2949
- this._interceptionEnabled = true;
2950
- await this.conn.send("Fetch.enable", {
2951
- patterns: [{ urlPattern: "*", requestStage: "Request" }],
2952
- // sup-s9: 保留认证自动响应(Fetch.enable 为替换语义,不带此参数
2953
- // 会顶掉 _init 的 auth 配置)
2954
- handleAuthRequests: true
2955
- }, this.sessionId);
2956
- this._subscriptions.push(
2957
- this.conn.subscribe("Fetch.requestPaused", this.sessionId, (params) => {
2958
- this._handleRequestPaused(params);
2959
- })
2960
- );
2961
- }
3397
+ return this.networkWaitService.waitForURL(url, opts);
2962
3398
  }
2963
- async unroute(url, handler) {
2964
- const regex = typeof url === "string" ? globToRegex(url) : url;
2965
- this._routeHandlers = this._routeHandlers.filter(
2966
- (h) => !(regex.source === h.regex.source && (!handler || h.handler === handler))
2967
- );
2968
- if (this._routeHandlers.length === 0 && this._interceptionEnabled) {
2969
- this._interceptionEnabled = false;
2970
- await this.conn.send("Fetch.disable", void 0, this.sessionId).catch(() => {
2971
- });
2972
- }
3399
+ async route(pattern, handler) {
3400
+ return this.networkRouteService.route(pattern, handler);
2973
3401
  }
2974
- async _handleRequestPaused(params) {
2975
- const requestUrl = params.request.url;
2976
- for (const { regex, handler } of this._routeHandlers) {
2977
- if (regex.test(requestUrl)) {
2978
- this._emit("request", createXBRequest(
2979
- null,
2980
- {
2981
- requestId: params.requestId,
2982
- url: params.request.url,
2983
- method: params.request.method,
2984
- headers: params.request.headers,
2985
- postData: params.request.postData ?? null,
2986
- resourceType: params.resourceType
2987
- }
2988
- ));
2989
- const route = createXBRouteFetch(this.conn, this.sessionId, params, this._emitter);
2990
- try {
2991
- await handler(route);
2992
- } catch {
2993
- await this.conn.send("Fetch.continueRequest", {
2994
- requestId: params.requestId
2995
- }, this.sessionId).catch(() => {
2996
- });
2997
- }
2998
- return;
2999
- }
3000
- }
3001
- await this.conn.send("Fetch.continueRequest", {
3002
- requestId: params.requestId
3003
- }, this.sessionId).catch(() => {
3004
- });
3402
+ async unroute(pattern) {
3403
+ return this.networkRouteService.unroute(pattern);
3005
3404
  }
3006
- // ── setInputFiles ───────────────────────────────────────────
3007
- /**
3008
- * sup-s4: Dropzone 拖拽上传模拟——Dropzone/Uppy/自绘上传区只监听
3009
- * dragover/drop(无 input[type=file] 可点),真实用户靠 OS 文件拖入
3010
- * 触发,自动化无法产生 OS 拖拽。页内构造 DataTransfer+File,按拖放
3011
- * 协议派发 dragenter/dragover/drop(bubbles+cancelable,坐标取目标
3012
- * 中心)。
3013
- */
3014
3405
  async dropFiles(selector, payload) {
3015
- await this.evaluate(`
3016
- (function() {
3017
- var el = ${queryJS(selector)};
3018
- if (!el) throw new Error('drop target not found: ' + ${JSON.stringify(selector)});
3019
- var b64 = ${JSON.stringify(payload.buffer.toString("base64"))};
3020
- var bin = atob(b64);
3021
- var buf = new Uint8Array(bin.length);
3022
- for (var i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
3023
- var file = new File([buf], ${JSON.stringify(payload.name)}, { type: ${JSON.stringify(payload.mimeType)} });
3024
- var dt = new DataTransfer();
3025
- dt.items.add(file);
3026
- var rect = el.getBoundingClientRect();
3027
- var opts = {
3028
- bubbles: true, cancelable: true,
3029
- clientX: rect.x + rect.width / 2, clientY: rect.y + rect.height / 2,
3030
- };
3031
- el.dispatchEvent(new DragEvent('dragenter', Object.assign({ dataTransfer: dt }, opts)));
3032
- el.dispatchEvent(new DragEvent('dragover', Object.assign({ dataTransfer: dt }, opts)));
3033
- el.dispatchEvent(new DragEvent('drop', Object.assign({ dataTransfer: dt }, opts)));
3034
- })()
3035
- `);
3406
+ return this.fileInputService.dropFiles(selector, payload);
3036
3407
  }
3037
3408
  async setInputFiles(selector, files) {
3038
- const fileArr = Array.isArray(files) ? files : [files];
3039
- const fileList = fileArr.map((f) => ({
3040
- name: f.name,
3041
- type: f.mimeType,
3042
- dataBase64: f.buffer.toString("base64")
3043
- }));
3044
- await this.evaluate(`
3045
- (function() {
3046
- var selector = ${JSON.stringify(selector)};
3047
- var input = ${queryJS(selector)};
3048
- if (!input) throw new Error('Element not found: ' + selector);
3049
-
3050
- var fileList = ${JSON.stringify(fileList)};
3051
- var dt = new DataTransfer();
3052
-
3053
- fileList.forEach(function(f) {
3054
- var binary = atob(f.dataBase64);
3055
- var bytes = new Uint8Array(binary.length);
3056
- for (var i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
3057
- var blob = new Blob([bytes], { type: f.type });
3058
- var file = new File([blob], f.name, { type: f.type });
3059
- dt.items.add(file);
3060
- });
3061
-
3062
- input.files = dt.files;
3063
- input.dispatchEvent(new Event('input', { bubbles: true }));
3064
- input.dispatchEvent(new Event('change', { bubbles: true }));
3065
- })()
3066
- `);
3409
+ return this.fileInputService.setInputFiles(selector, files);
3067
3410
  }
3068
- // ── dragAndDrop ─────────────────────────────────────────────
3069
3411
  async dragAndDrop(source, target) {
3070
- const sourceRect = await this.evaluate(`
3071
- (function() {
3072
- const el = ${queryJS(source)};
3073
- if (!el) throw new Error('Source not found: ${source}');
3074
- el.scrollIntoView({ behavior: 'instant', block: 'center' });
3075
- const r = el.getBoundingClientRect();
3076
- return { x: r.x, y: r.y, width: r.width, height: r.height };
3077
- })()
3078
- `);
3079
- const targetRect = await this.evaluate(`
3080
- (function() {
3081
- const el = ${queryJS(target)};
3082
- if (!el) throw new Error('Target not found: ${target}');
3083
- el.scrollIntoView({ behavior: 'instant', block: 'center' });
3084
- const r = el.getBoundingClientRect();
3085
- return { x: r.x, y: r.y, width: r.width, height: r.height };
3086
- })()
3087
- `);
3088
- const sx = sourceRect.x + sourceRect.width / 2;
3089
- const sy = sourceRect.y + sourceRect.height / 2;
3090
- const tx = targetRect.x + targetRect.width / 2;
3091
- const ty = targetRect.y + targetRect.height / 2;
3092
- try {
3093
- await this.conn.send("Input.dispatchDragEvent", {
3094
- type: "dragStart",
3095
- x: sx,
3096
- y: sy,
3097
- data: { items: [], dragOperations: ["copy", "move", "link"] }
3098
- }, this.sessionId);
3099
- await this.conn.send("Input.dispatchDragEvent", {
3100
- type: "dragOver",
3101
- x: tx,
3102
- y: ty,
3103
- data: { items: [], dragOperations: ["copy", "move", "link"] }
3104
- }, this.sessionId);
3105
- await this.conn.send("Input.dispatchDragEvent", {
3106
- type: "drop",
3107
- x: tx,
3108
- y: ty,
3109
- data: { items: [], dragOperations: ["copy", "move", "link"] }
3110
- }, this.sessionId);
3111
- await this.conn.send("Input.dispatchDragEvent", {
3112
- type: "dragCancel",
3113
- x: sx,
3114
- y: sy,
3115
- data: { items: [], dragOperations: ["copy", "move", "link"] }
3116
- }, this.sessionId);
3117
- } catch {
3118
- await this.mouse.move(sx, sy);
3119
- await this.mouse.down();
3120
- await this.mouse.move(tx, ty, { steps: 10 });
3121
- await this.mouse.up();
3122
- }
3412
+ return this.fileInputService.dragAndDrop(source, target);
3123
3413
  }
3124
- // ── setOfflineMode ──────────────────────────────────────────
3125
3414
  async setOfflineMode(offline) {
3126
3415
  await this.conn.send("Network.emulateNetworkConditions", {
3127
3416
  offline,
@@ -3417,7 +3706,7 @@ var XBBrowserImpl = class {
3417
3706
  this._exitHandler = null;
3418
3707
  }
3419
3708
  if (this.childProcess) {
3420
- const { killChrome: killChrome2 } = await import("./launcher-SJ44X25U.js");
3709
+ const { killChrome: killChrome2 } = await import("./launcher-TOLF23ET.js");
3421
3710
  await killChrome2(this.childProcess, this.tmpDir);
3422
3711
  }
3423
3712
  await this.conn.close();
@@ -3587,7 +3876,7 @@ var XBBrowserImpl = class {
3587
3876
  if (pageTargets.length === 0 && httpFallbackUrl) {
3588
3877
  console.log(`[discoverContexts] Target.getTargets returned ${targetInfos.length} targets (0 page type). Falling back to HTTP /json/list at ${httpFallbackUrl}`);
3589
3878
  try {
3590
- const { getCDPTargets: getCDPTargets2 } = await import("./launcher-SJ44X25U.js");
3879
+ const { getCDPTargets: getCDPTargets2 } = await import("./launcher-TOLF23ET.js");
3591
3880
  const httpPages = await getCDPTargets2(httpFallbackUrl);
3592
3881
  console.log(`[discoverContexts] HTTP /json/list returned ${httpPages.length} pages`);
3593
3882
  for (const p of httpPages) {
@@ -4033,6 +4322,149 @@ Or add random variation: page.type(selector, text, {delay: 50 + Math.random() *
4033
4322
  return null;
4034
4323
  }
4035
4324
 
4325
+ // src/cdp-interceptor/rules/humanize-transform.ts
4326
+ var CURSOR_KEY = "humanize-cursor";
4327
+ var KEYS_KEY = "humanize-keys";
4328
+ var MOUSE_STEP_DELAYS = [16, 19, 23, 28];
4329
+ var TYPE_DELAYS = [42, 58, 74, 96, 118, 155, 210];
4330
+ function rand2(min, max) {
4331
+ return min + Math.random() * (max - min);
4332
+ }
4333
+ function roundCoordinate(value) {
4334
+ return Math.round(value * 100) / 100;
4335
+ }
4336
+ function humanMousePath(fromX, fromY, toX, toY) {
4337
+ const dist = Math.hypot(toX - fromX, toY - fromY);
4338
+ const n = Math.max(8, Math.min(28, Math.round(dist / 15)));
4339
+ const shortMove = dist < 120;
4340
+ const curvature = shortMove ? rand2(2, 6) : Math.max(dist * rand2(0.12, 0.22), rand2(18, 35));
4341
+ const dir = Math.random() < 0.5 ? 1 : -1;
4342
+ const dx = toX - fromX;
4343
+ const dy = toY - fromY;
4344
+ const d = dist || 1;
4345
+ const c1x = fromX + dx * 0.3 - dy / d * curvature * 0.5 * dir;
4346
+ const c1y = fromY + dy * 0.3 + dx / d * curvature * 0.5 * dir;
4347
+ const c2x = fromX + dx * 0.7 - dy / d * curvature * 0.8 * dir;
4348
+ const c2y = fromY + dy * 0.7 + dx / d * curvature * 0.8 * dir;
4349
+ const amp = shortMove ? Math.min(2, 3.2) : 3.2;
4350
+ const points = [];
4351
+ for (let i = 1; i <= n; i++) {
4352
+ const t = i / n;
4353
+ const eased = t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;
4354
+ const mt = 1 - eased;
4355
+ const px = mt ** 3 * fromX + 3 * mt ** 2 * eased * c1x + 3 * mt * eased ** 2 * c2x + eased ** 3 * toX;
4356
+ const py = mt ** 3 * fromY + 3 * mt ** 2 * eased * c1y + 3 * mt * eased ** 2 * c2y + eased ** 3 * toY;
4357
+ points.push({
4358
+ x: roundCoordinate(px + rand2(-amp, amp)),
4359
+ y: roundCoordinate(py + rand2(-amp, amp)),
4360
+ delay: MOUSE_STEP_DELAYS[Math.floor(Math.random() * MOUSE_STEP_DELAYS.length)]
4361
+ });
4362
+ }
4363
+ if (!shortMove) {
4364
+ const over = rand2(6, 14);
4365
+ points.push({
4366
+ x: roundCoordinate(toX + dx / d * over + rand2(-2, 2)),
4367
+ y: roundCoordinate(toY + dy / d * over + rand2(-2, 2)),
4368
+ delay: Math.round(rand2(14, 30))
4369
+ });
4370
+ points.push({
4371
+ x: roundCoordinate(toX + dx / d * over * 0.4),
4372
+ y: roundCoordinate(toY + dy / d * over * 0.4),
4373
+ delay: Math.round(rand2(14, 30))
4374
+ });
4375
+ }
4376
+ points.push({
4377
+ x: roundCoordinate(toX + rand2(-1, 1)),
4378
+ y: roundCoordinate(toY + rand2(-1, 1)),
4379
+ delay: Math.round(rand2(14, 30))
4380
+ });
4381
+ return points;
4382
+ }
4383
+ function characterKeyEvents(text) {
4384
+ const events = [];
4385
+ for (const char of text) {
4386
+ if (char === "\n") {
4387
+ events.push(
4388
+ { type: "rawKeyDown", key: "Enter", code: "Enter", windowsVirtualKeyCode: 13 },
4389
+ { type: "char", text: "\r" },
4390
+ { type: "keyUp", key: "Enter", code: "Enter", windowsVirtualKeyCode: 13 }
4391
+ );
4392
+ continue;
4393
+ }
4394
+ events.push(
4395
+ { type: "rawKeyDown", key: char, text: char, unmodifiedText: char },
4396
+ { type: "char", text: char },
4397
+ { type: "keyUp", key: char }
4398
+ );
4399
+ }
4400
+ return events;
4401
+ }
4402
+ function isMouseEvent(method) {
4403
+ return method === "Input.dispatchMouseEvent";
4404
+ }
4405
+ var humanizeTransformRule = {
4406
+ id: "humanize-transform",
4407
+ name: "Humanize Trusted Input Transform",
4408
+ priority: 45,
4409
+ canHandle(ctx) {
4410
+ return isMouseEvent(ctx.method) || ctx.method === "Input.insertText";
4411
+ },
4412
+ evaluate(ctx) {
4413
+ if (ctx.method === "Input.insertText") return this.transformInsertText(ctx);
4414
+ return this.transformMouseEvent(ctx);
4415
+ },
4416
+ transformMouseEvent(ctx) {
4417
+ const params = ctx.params;
4418
+ if (params.type !== "mouseMoved" || typeof params.x !== "number" || typeof params.y !== "number") {
4419
+ const x = params.x;
4420
+ const y = params.y;
4421
+ if (typeof x === "number" && typeof y === "number") {
4422
+ ctx.sessionState.set(CURSOR_KEY, { x, y });
4423
+ }
4424
+ return null;
4425
+ }
4426
+ const cursor = ctx.sessionState.get(CURSOR_KEY) ?? { x: 0, y: 0 };
4427
+ const jump = Math.hypot(params.x - cursor.x, params.y - cursor.y);
4428
+ ctx.sessionState.set(CURSOR_KEY, { x: params.x, y: params.y });
4429
+ if (jump < 32) return null;
4430
+ const path = humanMousePath(cursor.x, cursor.y, params.x, params.y);
4431
+ return {
4432
+ ruleId: this.id,
4433
+ action: "transform",
4434
+ severity: "info",
4435
+ reason: `Expanded instant mouse jump of ${jump.toFixed(0)}px into ${path.length} trusted bezier moves.`,
4436
+ suggestion: "Use page.mouse.move with steps for explicit control; this transform preserves isTrusted=true.",
4437
+ transformedParams: { __sequence: path.map((point) => ({
4438
+ method: "Input.dispatchMouseEvent",
4439
+ params: { type: "mouseMoved", x: point.x, y: point.y, button: params.button ?? "none" },
4440
+ delayMs: point.delay
4441
+ })) }
4442
+ };
4443
+ },
4444
+ transformInsertText(ctx) {
4445
+ const params = ctx.params;
4446
+ const text = params.text ?? "";
4447
+ if (!text) return null;
4448
+ const timing = ctx.sessionState.get(KEYS_KEY) ?? { lastDelay: TYPE_DELAYS[1] };
4449
+ const bucket = TYPE_DELAYS[Math.floor(Math.random() * TYPE_DELAYS.length)];
4450
+ const events = characterKeyEvents(text).map((event, index) => ({
4451
+ method: "Input.dispatchKeyEvent",
4452
+ params: event,
4453
+ delayMs: index === 0 ? 0 : Math.max(24, Math.round(bucket + rand2(-bucket * 0.45, bucket * 0.55)))
4454
+ }));
4455
+ timing.lastDelay = bucket;
4456
+ ctx.sessionState.set(KEYS_KEY, timing);
4457
+ return {
4458
+ ruleId: this.id,
4459
+ action: "transform",
4460
+ severity: "info",
4461
+ reason: `Expanded Input.insertText (${text.length} chars) into ${events.length} trusted key events with variable rhythm.`,
4462
+ suggestion: "Use page.type for explicit control; this transform preserves the native keyboard command stream.",
4463
+ transformedParams: { __sequence: events }
4464
+ };
4465
+ }
4466
+ };
4467
+
4036
4468
  // src/cdp-interceptor/rules/automation-signals.ts
4037
4469
  var AUTOMATION_PATTERNS = [
4038
4470
  // ── Playwright markers ─────────────────────────
@@ -4551,6 +4983,7 @@ var BUILTIN_RULES = [
4551
4983
  eventSimulationRule,
4552
4984
  mouseTrajectoryRule,
4553
4985
  inputKeystrokeRule,
4986
+ humanizeTransformRule,
4554
4987
  emulationOverrideRule,
4555
4988
  networkAnomalyRule,
4556
4989
  pageLifecycleRule
@@ -4583,8 +5016,10 @@ function createRuleEngine(customRules) {
4583
5016
  if (isProbeMarked(code)) return null;
4584
5017
  } catch {
4585
5018
  }
5019
+ const humanizeEnabled = process.env.XBROWSER_HUMANIZE_CDP === "on";
4586
5020
  for (const rule of rules) {
4587
5021
  if (rule.canHandle && !rule.canHandle(fullCtx)) continue;
5022
+ if (rule.id === "humanize-transform" && !humanizeEnabled) continue;
4588
5023
  const decision = rule.evaluate(fullCtx);
4589
5024
  if (!decision) continue;
4590
5025
  if (decision.action !== "pass") return decision;
@@ -4726,6 +5161,15 @@ var CDPConnection = class _CDPConnection extends EventEmitter4 {
4726
5161
  if (decision && decision.action === "block") {
4727
5162
  throw new Error(`[CDP-Guard] ${decision.reason}${decision.suggestion ? " | \u66FF\u4EE3: " + decision.suggestion : ""} [${decision.ruleId}]`);
4728
5163
  }
5164
+ if (decision && decision.action === "transform" && Array.isArray(decision.transformedParams?.__sequence)) {
5165
+ const sequence = decision.transformedParams.__sequence;
5166
+ let last;
5167
+ for (const step of sequence) {
5168
+ if (step.delayMs) await new Promise((resolve) => setTimeout(resolve, step.delayMs));
5169
+ last = await this.send(step.method, step.params, sessionId, effectiveTimeout);
5170
+ }
5171
+ return last;
5172
+ }
4729
5173
  }
4730
5174
  if (this.closed) {
4731
5175
  throw new Error(`CDP connection closed: ${this.closeReason ?? "unknown"}`);
@@ -4968,7 +5412,7 @@ async function launch(options = {}) {
4968
5412
  const bv = await conn.send("Browser.getVersion");
4969
5413
  const m = bv.product.match(/(\d+)\.(\d+)\.(\d+)\.(\d+)/);
4970
5414
  if (m && !options.stealthConfig?.uaChProfile) {
4971
- const { deriveUaChProfileForBinary } = await import("./stealth-QNSMIHQK.js");
5415
+ const { deriveUaChProfileForBinary } = await import("./stealth-FMPZO2OB.js");
4972
5416
  stealthOpts = { stealthConfig: { uaChProfile: deriveUaChProfileForBinary(m[0], m[1]) } };
4973
5417
  }
4974
5418
  } catch {