@xbrowser/cli 1.28.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-WK3INZLA.js → chunk-GDKKVT2P.js} +750 -651
  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-OEC7ZSFW.js → chunk-SCYBNSOG.js} +1560 -1461
  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 +737 -707
  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-JXF3JOAM.js → server-LNZTDAKT.js} +4 -4
  31. package/dist/{server-26SE6YZR.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,11 +5,11 @@ import {
5
5
  landingOffset,
6
6
  rand,
7
7
  typingDelay
8
- } from "./chunk-R3F4K2SB.js";
8
+ } from "./chunk-SMYSNO4M.js";
9
9
  import {
10
10
  connectToCDP,
11
11
  launchChrome
12
- } from "./chunk-SEEWE5SJ.js";
12
+ } from "./chunk-2KPI5GKP.js";
13
13
  import {
14
14
  errMsg
15
15
  } from "./chunk-GDKLH7ZY.js";
@@ -18,10 +18,78 @@ import {
18
18
  } from "./chunk-KFQGP6VL.js";
19
19
 
20
20
  // src/browser.ts
21
- import { randomUUID } from "crypto";
22
- import { existsSync, mkdirSync as mkdirSync2, readFileSync, readdirSync, unlinkSync, writeFileSync } from "fs";
23
- import { join as join2 } from "path";
24
- import { homedir } from "os";
21
+ import { readdirSync as readdirSync2, unlinkSync as unlinkSync2 } from "fs";
22
+ import { join as join3 } from "path";
23
+
24
+ // src/utils/cdp.ts
25
+ async function fetchNoProxy(url) {
26
+ const savedProxy = {
27
+ http_proxy: process.env.http_proxy,
28
+ https_proxy: process.env.https_proxy,
29
+ HTTP_PROXY: process.env.HTTP_PROXY,
30
+ HTTPS_PROXY: process.env.HTTPS_PROXY,
31
+ all_proxy: process.env.all_proxy,
32
+ ALL_PROXY: process.env.ALL_PROXY
33
+ };
34
+ for (const key of Object.keys(savedProxy)) delete process.env[key];
35
+ try {
36
+ return await fetch(url);
37
+ } finally {
38
+ for (const [key, val] of Object.entries(savedProxy)) {
39
+ if (val !== void 0) process.env[key] = val;
40
+ }
41
+ }
42
+ }
43
+ async function resolveCDPEndpoint(raw) {
44
+ if (raw === "auto") {
45
+ const ports = [9222, 9221, 9223, 9224];
46
+ for (const port of ports) {
47
+ try {
48
+ const httpResp = await fetchNoProxy(`http://localhost:${port}/json/version`);
49
+ if (httpResp.ok) {
50
+ const data = await httpResp.json();
51
+ if (data.webSocketDebuggerUrl) {
52
+ return data.webSocketDebuggerUrl;
53
+ }
54
+ }
55
+ } catch {
56
+ }
57
+ }
58
+ throw new Error(
59
+ `Could not auto-discover CDP endpoint. Tried ports: ${ports.join(", ")}.
60
+ \u53EF\u80FD\u539F\u56E0\uFF1A\u6CA1\u6709 Chrome \u4EE5 --remote-debugging-port \u542F\u52A8\u3002
61
+ \u89E3\u51B3\u65B9\u6CD5\uFF1A
62
+ 1. \u542F\u52A8 Chrome: google-chrome --remote-debugging-port=9222
63
+ 2. \u6216\u7528 cdp-tunnel: npx cdp-tunnel setup
64
+ 3. \u6216\u6307\u5B9A\u7AEF\u53E3: --cdp <port>`
65
+ );
66
+ }
67
+ if (/^\d+$/.test(raw)) {
68
+ const port = raw;
69
+ const httpResp = await fetchNoProxy(`http://localhost:${port}/json/version`);
70
+ const data = await httpResp.json();
71
+ if (!data.webSocketDebuggerUrl) {
72
+ throw new Error(`Could not discover CDP endpoint from localhost:${port}`);
73
+ }
74
+ return data.webSocketDebuggerUrl;
75
+ }
76
+ if (raw.startsWith("http://") || raw.startsWith("https://")) {
77
+ try {
78
+ const u = new URL(raw);
79
+ u.pathname = (u.pathname.replace(/\/+$/, "") || "") + "/json/version";
80
+ const httpResp = await fetchNoProxy(u.toString());
81
+ const data = await httpResp.json();
82
+ if (!data.webSocketDebuggerUrl) {
83
+ throw new Error(`Could not discover CDP endpoint from ${raw}`);
84
+ }
85
+ return data.webSocketDebuggerUrl;
86
+ } catch (error) {
87
+ console.warn(`Failed to fetch WebSocket URL from ${raw}, using endpoint directly: ${error instanceof Error ? error.message : String(error)}`);
88
+ return raw;
89
+ }
90
+ }
91
+ return raw;
92
+ }
25
93
 
26
94
  // src/cdp-driver/browser.ts
27
95
  import { EventEmitter as EventEmitter3 } from "events";
@@ -1435,6 +1503,216 @@ var XBElementHandleImpl = class {
1435
1503
  }
1436
1504
  };
1437
1505
 
1506
+ // src/cdp-driver/page-media.ts
1507
+ var MediaService = class {
1508
+ constructor(options) {
1509
+ this.options = options;
1510
+ }
1511
+ options;
1512
+ async screenshot(opts = {}) {
1513
+ const params = {
1514
+ format: opts.type ?? "png"
1515
+ };
1516
+ if (opts.quality !== void 0 && (opts.type === "jpeg" || !opts.type && opts.quality)) {
1517
+ params.quality = opts.quality;
1518
+ }
1519
+ if (opts.fullPage) {
1520
+ params.captureBeyondViewport = true;
1521
+ }
1522
+ if (opts.clip) {
1523
+ const clip = {
1524
+ x: Math.round(opts.clip.x),
1525
+ y: Math.round(opts.clip.y),
1526
+ width: Math.round(Math.max(1, opts.clip.width)),
1527
+ height: Math.round(Math.max(1, opts.clip.height)),
1528
+ scale: 1
1529
+ };
1530
+ params.clip = clip;
1531
+ }
1532
+ if (opts.omitBackground) {
1533
+ params.omitBackground = true;
1534
+ }
1535
+ const result = await this.options.conn.send(
1536
+ "Page.captureScreenshot",
1537
+ params,
1538
+ this.options.sessionId
1539
+ );
1540
+ return Buffer.from(result.data, "base64");
1541
+ }
1542
+ async pdf(opts = {}) {
1543
+ const params = {};
1544
+ if (opts.landscape !== void 0) params.landscape = opts.landscape;
1545
+ if (opts.printBackground !== void 0) params.printBackground = opts.printBackground;
1546
+ if (opts.scale !== void 0) params.scale = opts.scale;
1547
+ if (opts.format) params.paperFormat = opts.format;
1548
+ if (opts.preferCSSPageSize !== void 0) params.preferCSSPageSize = opts.preferCSSPageSize;
1549
+ if (opts.margin) {
1550
+ if (opts.margin.top) params.marginTop = parseFloat(opts.margin.top);
1551
+ if (opts.margin.bottom) params.marginBottom = parseFloat(opts.margin.bottom);
1552
+ if (opts.margin.left) params.marginLeft = parseFloat(opts.margin.left);
1553
+ if (opts.margin.right) params.marginRight = parseFloat(opts.margin.right);
1554
+ }
1555
+ const result = await this.options.conn.send("Page.printToPDF", params, this.options.sessionId);
1556
+ return Buffer.from(result.data, "base64");
1557
+ }
1558
+ viewportSize() {
1559
+ return this.options.viewportSize ?? null;
1560
+ }
1561
+ async setViewportSize(size) {
1562
+ await this.options.conn.send(
1563
+ "Emulation.setDeviceMetricsOverride",
1564
+ {
1565
+ width: size.width,
1566
+ height: size.height,
1567
+ deviceScaleFactor: 1,
1568
+ mobile: false
1569
+ },
1570
+ this.options.sessionId
1571
+ );
1572
+ this.options.onViewportSize(size);
1573
+ }
1574
+ /**
1575
+ * env-E2: 缩放变异——deviceScaleFactor 切换(CSS 像素坐标空间不变,
1576
+ * 物理像素翻倍)。保留当前 CSS 视口尺寸,只换 DSF。
1577
+ */
1578
+ async setDeviceScaleFactor(dsf) {
1579
+ const size = this.options.viewportSize ?? await this.options.evaluate(
1580
+ "({ width: window.innerWidth, height: window.innerHeight })"
1581
+ );
1582
+ await this.options.conn.send(
1583
+ "Emulation.setDeviceMetricsOverride",
1584
+ {
1585
+ width: size.width,
1586
+ height: size.height,
1587
+ deviceScaleFactor: dsf,
1588
+ mobile: false
1589
+ },
1590
+ this.options.sessionId
1591
+ );
1592
+ this.options.onViewportSize(size);
1593
+ }
1594
+ // ── Scripts ─────────────────────────────────────────────────
1595
+ };
1596
+
1597
+ // src/cdp-driver/page-file-input.ts
1598
+ var FileInputService = class {
1599
+ constructor(options) {
1600
+ this.options = options;
1601
+ }
1602
+ options;
1603
+ async dropFiles(selector, payload) {
1604
+ await this.options.evaluate(`
1605
+ (function() {
1606
+ var el = ${queryJS(selector)};
1607
+ if (!el) throw new Error('drop target not found: ' + ${JSON.stringify(selector)});
1608
+ var b64 = ${JSON.stringify(payload.buffer.toString("base64"))};
1609
+ var bin = atob(b64);
1610
+ var buf = new Uint8Array(bin.length);
1611
+ for (var i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
1612
+ var file = new File([buf], ${JSON.stringify(payload.name)}, { type: ${JSON.stringify(payload.mimeType)} });
1613
+ var dt = new DataTransfer();
1614
+ dt.items.add(file);
1615
+ var rect = el.getBoundingClientRect();
1616
+ var opts = {
1617
+ bubbles: true, cancelable: true,
1618
+ clientX: rect.x + rect.width / 2, clientY: rect.y + rect.height / 2,
1619
+ };
1620
+ el.dispatchEvent(new DragEvent('dragenter', Object.assign({ dataTransfer: dt }, opts)));
1621
+ el.dispatchEvent(new DragEvent('dragover', Object.assign({ dataTransfer: dt }, opts)));
1622
+ el.dispatchEvent(new DragEvent('drop', Object.assign({ dataTransfer: dt }, opts)));
1623
+ })()
1624
+ `);
1625
+ }
1626
+ async setInputFiles(selector, files) {
1627
+ const fileArr = Array.isArray(files) ? files : [files];
1628
+ const fileList = fileArr.map((f) => ({
1629
+ name: f.name,
1630
+ type: f.mimeType,
1631
+ dataBase64: f.buffer.toString("base64")
1632
+ }));
1633
+ await this.options.evaluate(`
1634
+ (function() {
1635
+ var selector = ${JSON.stringify(selector)};
1636
+ var input = ${queryJS(selector)};
1637
+ if (!input) throw new Error('Element not found: ' + selector);
1638
+
1639
+ var fileList = ${JSON.stringify(fileList)};
1640
+ var dt = new DataTransfer();
1641
+
1642
+ fileList.forEach(function(f) {
1643
+ var binary = atob(f.dataBase64);
1644
+ var bytes = new Uint8Array(binary.length);
1645
+ for (var i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
1646
+ var blob = new Blob([bytes], { type: f.type });
1647
+ var file = new File([blob], f.name, { type: f.type });
1648
+ dt.items.add(file);
1649
+ });
1650
+
1651
+ input.files = dt.files;
1652
+ input.dispatchEvent(new Event('input', { bubbles: true }));
1653
+ input.dispatchEvent(new Event('change', { bubbles: true }));
1654
+ })()
1655
+ `);
1656
+ }
1657
+ // ── dragAndDrop ─────────────────────────────────────────────
1658
+ async dragAndDrop(source, target) {
1659
+ const sourceRect = await this.options.evaluate(`
1660
+ (function() {
1661
+ const el = ${queryJS(source)};
1662
+ if (!el) throw new Error('Source not found: ${source}');
1663
+ el.scrollIntoView({ behavior: 'instant', block: 'center' });
1664
+ const r = el.getBoundingClientRect();
1665
+ return { x: r.x, y: r.y, width: r.width, height: r.height };
1666
+ })()
1667
+ `);
1668
+ const targetRect = await this.options.evaluate(`
1669
+ (function() {
1670
+ const el = ${queryJS(target)};
1671
+ if (!el) throw new Error('Target not found: ${target}');
1672
+ el.scrollIntoView({ behavior: 'instant', block: 'center' });
1673
+ const r = el.getBoundingClientRect();
1674
+ return { x: r.x, y: r.y, width: r.width, height: r.height };
1675
+ })()
1676
+ `);
1677
+ const sx = sourceRect.x + sourceRect.width / 2;
1678
+ const sy = sourceRect.y + sourceRect.height / 2;
1679
+ const tx = targetRect.x + targetRect.width / 2;
1680
+ const ty = targetRect.y + targetRect.height / 2;
1681
+ try {
1682
+ await this.options.conn.send("Input.dispatchDragEvent", {
1683
+ type: "dragStart",
1684
+ x: sx,
1685
+ y: sy,
1686
+ data: { items: [], dragOperations: ["copy", "move", "link"] }
1687
+ }, this.options.sessionId);
1688
+ await this.options.conn.send("Input.dispatchDragEvent", {
1689
+ type: "dragOver",
1690
+ x: tx,
1691
+ y: ty,
1692
+ data: { items: [], dragOperations: ["copy", "move", "link"] }
1693
+ }, this.options.sessionId);
1694
+ await this.options.conn.send("Input.dispatchDragEvent", {
1695
+ type: "drop",
1696
+ x: tx,
1697
+ y: ty,
1698
+ data: { items: [], dragOperations: ["copy", "move", "link"] }
1699
+ }, this.options.sessionId);
1700
+ await this.options.conn.send("Input.dispatchDragEvent", {
1701
+ type: "dragCancel",
1702
+ x: sx,
1703
+ y: sy,
1704
+ data: { items: [], dragOperations: ["copy", "move", "link"] }
1705
+ }, this.options.sessionId);
1706
+ } catch {
1707
+ await this.options.mouse.move(sx, sy);
1708
+ await this.options.mouse.down();
1709
+ await this.options.mouse.move(tx, ty, { steps: 10 });
1710
+ await this.options.mouse.up();
1711
+ }
1712
+ }
1713
+ // ── setOfflineMode ──────────────────────────────────────────
1714
+ };
1715
+
1438
1716
  // src/cdp-driver/page-helpers.ts
1439
1717
  function globToRegex(glob) {
1440
1718
  let pattern = glob.replace(/[\\^${}()|[\]+]/g, "\\$&").replace(/\./g, "\\.").replace(/\*\*/g, "{{DOUBLESTAR}}").replace(/\*/g, "[^/]*").replace(/{{DOUBLESTAR}}/g, ".*").replace(/\?/g, ".");
@@ -1586,18 +1864,786 @@ function createXBRouteFetch(conn, sessionId, params, emitter) {
1586
1864
  };
1587
1865
  }
1588
1866
 
1589
- // src/cdp-driver/page.ts
1590
- var XBPageImpl = class _XBPageImpl {
1591
- conn;
1592
- _emitter = new EventEmitter();
1593
- _subscriptions = [];
1594
- sessionId;
1595
- _targetId;
1596
- _contextImpl;
1867
+ // src/cdp-driver/page-network-events.ts
1868
+ function setupNetworkEvents(options) {
1869
+ options.addSubscription(
1870
+ options.conn.subscribe("Network.requestWillBeSent", options.sessionId, (params) => {
1871
+ const p = params;
1872
+ options.state.inflightRequests.add(p.requestId);
1873
+ options.storeRequest(p.requestId, {
1874
+ url: p.request.url,
1875
+ method: p.request.method,
1876
+ headers: p.request.headers,
1877
+ postData: p.request.postData ?? null,
1878
+ resourceType: p.type
1879
+ });
1880
+ options.emit("request", createXBRequest(
1881
+ null,
1882
+ {
1883
+ requestId: p.requestId,
1884
+ url: p.request.url,
1885
+ method: p.request.method,
1886
+ headers: p.request.headers,
1887
+ postData: p.request.postData ?? null,
1888
+ resourceType: p.type
1889
+ }
1890
+ ));
1891
+ options.checkNetworkIdle();
1892
+ })
1893
+ );
1894
+ options.addSubscription(
1895
+ options.conn.subscribe("Network.responseReceived", options.sessionId, (params) => {
1896
+ const p = params;
1897
+ options.storeResponse(p.requestId, {
1898
+ status: p.response.status,
1899
+ url: p.response.url,
1900
+ headers: p.response.headers
1901
+ });
1902
+ options.emit("response", createXBResponse(
1903
+ { requestId: p.requestId, status: p.response.status, url: p.response.url, headers: p.response.headers },
1904
+ options.conn,
1905
+ options.sessionId
1906
+ ));
1907
+ })
1908
+ );
1909
+ options.addSubscription(
1910
+ options.conn.subscribe("Network.loadingFinished", options.sessionId, (params) => {
1911
+ const p = params;
1912
+ options.state.inflightRequests.delete(p.requestId);
1913
+ options.emit("requestfinished", p);
1914
+ options.checkNetworkIdle();
1915
+ })
1916
+ );
1917
+ options.addSubscription(
1918
+ options.conn.subscribe("Network.loadingFailed", options.sessionId, (params) => {
1919
+ const p = params;
1920
+ options.state.inflightRequests.delete(p.requestId);
1921
+ options.checkNetworkIdle();
1922
+ })
1923
+ );
1924
+ }
1925
+
1926
+ // src/cdp-driver/page-lifecycle-events.ts
1927
+ function setupPageEvents(options) {
1928
+ options.addSubscription(
1929
+ options.conn.subscribe("Page.frameNavigated", options.sessionId, (params) => {
1930
+ const p = params;
1931
+ if (p.frame) {
1932
+ options.setUrl(p.frame.url);
1933
+ }
1934
+ options.emit("framenavigated", options.mainFrame());
1935
+ })
1936
+ );
1937
+ options.addSubscription(
1938
+ options.conn.subscribe("Page.loadEventFired", options.sessionId, () => {
1939
+ options.markLoadFired();
1940
+ })
1941
+ );
1942
+ options.addSubscription(
1943
+ options.conn.subscribe("Page.domContentEventFired", options.sessionId, () => {
1944
+ options.markDomContentFired();
1945
+ })
1946
+ );
1947
+ options.addSubscription(
1948
+ options.conn.subscribe("Page.javascriptDialogOpening", options.sessionId, (params) => {
1949
+ const p = params;
1950
+ const dialog = {
1951
+ type: p.type,
1952
+ message: () => p.message,
1953
+ defaultValue: () => p.defaultValue,
1954
+ accept: async (text) => {
1955
+ await options.conn.send("Page.handleJavaScriptDialog", {
1956
+ accept: true,
1957
+ promptText: text
1958
+ }, options.sessionId);
1959
+ },
1960
+ dismiss: async () => {
1961
+ await options.conn.send("Page.handleJavaScriptDialog", {
1962
+ accept: false
1963
+ }, options.sessionId);
1964
+ }
1965
+ };
1966
+ options.emit("dialog", dialog);
1967
+ const autoAccept = p.type === "beforeunload" ? options.getBeforeUnloadAccept() : false;
1968
+ setTimeout(() => {
1969
+ options.conn.send("Page.handleJavaScriptDialog", { accept: autoAccept }, options.sessionId).catch(() => {
1970
+ });
1971
+ }, 0);
1972
+ })
1973
+ );
1974
+ options.addSubscription(
1975
+ options.conn.subscribe("Page.fileChooserOpened", options.sessionId, async (params) => {
1976
+ const p = params;
1977
+ let selector = "";
1978
+ try {
1979
+ const result = await options.conn.send("DOM.describeNode", { backendNodeId: p.backendNodeId }, options.sessionId);
1980
+ const attrs = result.node?.attributes || [];
1981
+ const idIdx = attrs.indexOf("id");
1982
+ if (idIdx >= 0) selector = "#" + attrs[idIdx + 1];
1983
+ } catch {
1984
+ }
1985
+ if (!selector) {
1986
+ try {
1987
+ const result = await options.conn.send("DOM.resolveNode", { backendNodeId: p.backendNodeId }, options.sessionId);
1988
+ const evalResult = await options.conn.send("Runtime.callFunctionOn", {
1989
+ objectId: result.objectId,
1990
+ functionDeclaration: 'function() { return this.id || this.name || "" }',
1991
+ returnByValue: true
1992
+ }, options.sessionId);
1993
+ if (evalResult.result?.value) selector = "#" + evalResult.result.value;
1994
+ } catch {
1995
+ }
1996
+ }
1997
+ const fileChooser = {
1998
+ selector,
1999
+ isMultiple: p.mode === "selectMultiple",
2000
+ setFiles: async (files) => {
2001
+ const fileArray = Array.isArray(files) ? files : [files];
2002
+ await options.setInputFiles(selector || 'input[type="file"]', fileArray);
2003
+ }
2004
+ };
2005
+ options.emit("filechooser", fileChooser);
2006
+ })
2007
+ );
2008
+ }
2009
+
2010
+ // src/cdp-driver/page-network-waits.ts
2011
+ var NetworkWaitService = class {
2012
+ constructor(options) {
2013
+ this.options = options;
2014
+ }
2015
+ options;
2016
+ // ── waitForResponse ─────────────────────────────────────────
2017
+ async waitForResponse(urlOrPredicate, opts = {}) {
2018
+ const timeout = opts.timeout ?? 3e4;
2019
+ const predicate = createResponsePredicate(urlOrPredicate);
2020
+ for (const [, data] of this.options.responses) {
2021
+ const response = createXBResponse(data, this.options.conn, this.options.sessionId);
2022
+ if (predicate(response)) return response;
2023
+ }
2024
+ return new Promise((resolve, reject) => {
2025
+ const timer = setTimeout(() => {
2026
+ this.options.off("response", handler);
2027
+ reject(new Error(`waitForResponse timed out after ${timeout}ms`));
2028
+ }, timeout);
2029
+ const handler = (params) => {
2030
+ let response;
2031
+ const respObj = params;
2032
+ if (respObj.response) {
2033
+ const data = {
2034
+ requestId: respObj.requestId || "",
2035
+ status: respObj.response.status || 0,
2036
+ url: respObj.response.url || "",
2037
+ headers: respObj.response.headers || {}
2038
+ };
2039
+ response = createXBResponse(data, this.options.conn, this.options.sessionId);
2040
+ } else if (typeof params.status === "function") {
2041
+ response = params;
2042
+ } else {
2043
+ return;
2044
+ }
2045
+ if (predicate(response)) {
2046
+ clearTimeout(timer);
2047
+ this.options.off("response", handler);
2048
+ resolve(response);
2049
+ }
2050
+ };
2051
+ this.options.on("response", handler);
2052
+ });
2053
+ }
2054
+ // ── waitForRequest ──────────────────────────────────────────
2055
+ async waitForRequest(urlOrPredicate, opts = {}) {
2056
+ const timeout = opts.timeout ?? 3e4;
2057
+ const predicate = createRequestPredicate(urlOrPredicate);
2058
+ for (const [, data] of this.options.requests) {
2059
+ const request = createXBRequest(this.pageLike(), data);
2060
+ if (predicate(request)) return request;
2061
+ }
2062
+ return new Promise((resolve, reject) => {
2063
+ const timer = setTimeout(() => {
2064
+ this.options.off("request", handler);
2065
+ reject(new Error(`waitForRequest timed out after ${timeout}ms`));
2066
+ }, timeout);
2067
+ const handler = (params) => {
2068
+ let request;
2069
+ const reqObj = params;
2070
+ if (reqObj.request) {
2071
+ request = createXBRequest(this.pageLike(), {
2072
+ requestId: reqObj.requestId || "",
2073
+ url: reqObj.request.url || "",
2074
+ method: reqObj.request.method || "",
2075
+ headers: reqObj.request.headers || {},
2076
+ postData: reqObj.request.postData ?? null,
2077
+ resourceType: reqObj.type || ""
2078
+ });
2079
+ } else if (typeof params.url === "function") {
2080
+ request = params;
2081
+ } else {
2082
+ return;
2083
+ }
2084
+ if (predicate(request)) {
2085
+ clearTimeout(timer);
2086
+ this.options.off("request", handler);
2087
+ resolve(request);
2088
+ }
2089
+ };
2090
+ this.options.on("request", handler);
2091
+ });
2092
+ }
2093
+ // ── waitForURL ──────────────────────────────────────────────
2094
+ async waitForURL(url, opts = {}) {
2095
+ const timeout = opts.timeout ?? 3e4;
2096
+ const checkFn = typeof url === "function" ? url : typeof url === "string" ? (current) => matchGlob(url, current) : (current) => url.test(current);
2097
+ if (checkFn(this.options.currentUrl())) return;
2098
+ return new Promise((resolve, reject) => {
2099
+ const timer = setTimeout(() => {
2100
+ this.options.off("framenavigated", handler);
2101
+ reject(new Error(`waitForURL timed out after ${timeout}ms`));
2102
+ }, timeout);
2103
+ const handler = () => {
2104
+ if (checkFn(this.options.currentUrl())) {
2105
+ clearTimeout(timer);
2106
+ this.options.off("framenavigated", handler);
2107
+ resolve();
2108
+ }
2109
+ };
2110
+ this.options.on("framenavigated", handler);
2111
+ });
2112
+ }
2113
+ pageLike() {
2114
+ return {
2115
+ _networkResponses: this.options.responses,
2116
+ _connection: this.options.conn,
2117
+ sessionId: this.options.sessionId
2118
+ };
2119
+ }
2120
+ };
2121
+
2122
+ // src/cdp-driver/page-routes.ts
2123
+ var NetworkRouteService = class {
2124
+ constructor(options) {
2125
+ this.options = options;
2126
+ }
2127
+ options;
2128
+ routeHandlers = [];
2129
+ interceptionEnabled = false;
2130
+ get isInterceptionEnabled() {
2131
+ return this.interceptionEnabled;
2132
+ }
2133
+ subscriptions = [];
2134
+ async route(url, handler) {
2135
+ const regex = typeof url === "string" ? globToRegex(url) : url;
2136
+ this.routeHandlers.push({ pattern: String(url), regex, handler });
2137
+ if (!this.interceptionEnabled) {
2138
+ this.interceptionEnabled = true;
2139
+ await this.options.conn.send("Fetch.enable", {
2140
+ patterns: [{ urlPattern: "*", requestStage: "Request" }],
2141
+ // sup-s9: 保留认证自动响应(Fetch.enable 为替换语义,不带此参数
2142
+ // 会顶掉 _init 的 auth 配置)
2143
+ handleAuthRequests: true
2144
+ }, this.options.sessionId);
2145
+ this.subscriptions.push(
2146
+ this.options.conn.subscribe("Fetch.requestPaused", this.options.sessionId, (params) => {
2147
+ this._handleRequestPaused(params);
2148
+ })
2149
+ );
2150
+ }
2151
+ }
2152
+ async unroute(url, handler) {
2153
+ const regex = typeof url === "string" ? globToRegex(url) : url;
2154
+ this.routeHandlers = this.routeHandlers.filter(
2155
+ (h) => !(regex.source === h.regex.source && (!handler || h.handler === handler))
2156
+ );
2157
+ if (this.routeHandlers.length === 0 && this.interceptionEnabled) {
2158
+ this.interceptionEnabled = false;
2159
+ await this.options.conn.send("Fetch.disable", void 0, this.options.sessionId).catch(() => {
2160
+ });
2161
+ }
2162
+ }
2163
+ async _handleRequestPaused(params) {
2164
+ const requestUrl = params.request.url;
2165
+ for (const { regex, handler } of this.routeHandlers) {
2166
+ if (regex.test(requestUrl)) {
2167
+ this.options.emit("request", createXBRequest(
2168
+ null,
2169
+ {
2170
+ requestId: params.requestId,
2171
+ url: params.request.url,
2172
+ method: params.request.method,
2173
+ headers: params.request.headers,
2174
+ postData: params.request.postData ?? null,
2175
+ resourceType: params.resourceType
2176
+ }
2177
+ ));
2178
+ const route = createXBRouteFetch(this.options.conn, this.options.sessionId, params, void 0);
2179
+ try {
2180
+ await handler(route);
2181
+ } catch {
2182
+ await this.options.conn.send("Fetch.continueRequest", {
2183
+ requestId: params.requestId
2184
+ }, this.options.sessionId).catch(() => {
2185
+ });
2186
+ }
2187
+ return;
2188
+ }
2189
+ }
2190
+ await this.options.conn.send("Fetch.continueRequest", {
2191
+ requestId: params.requestId
2192
+ }, this.options.sessionId).catch(() => {
2193
+ });
2194
+ }
2195
+ };
2196
+
2197
+ // src/cdp-driver/page-navigation.ts
2198
+ var NavigationService = class {
2199
+ constructor(options) {
2200
+ this.options = options;
2201
+ }
2202
+ options;
2203
+ async goto(url, opts = {}) {
2204
+ if (this.options.isClosed()) throw new Error("Page is closed");
2205
+ const waitUntil = opts.waitUntil ?? "load";
2206
+ const timeout = opts.timeout ?? 3e4;
2207
+ this.options.state.loadFired = false;
2208
+ this.options.state.domContentFired = false;
2209
+ this.options.state.networkIdle = false;
2210
+ if (process.env.XBROWSER_STEALTH !== "off") {
2211
+ try {
2212
+ await this.options.conn.send(
2213
+ "Page.addScriptToEvaluateOnNewDocument",
2214
+ { source: buildStealthInitScript({ ...DEFAULT_STEALTH_CONFIG, ...this.options.stealthConfig ?? {} }) },
2215
+ this.options.sessionId
2216
+ );
2217
+ } catch {
2218
+ }
2219
+ try {
2220
+ const rawUa = await this.options.conn.send(
2221
+ "Runtime.evaluate",
2222
+ { expression: "navigator.userAgent", returnByValue: true },
2223
+ this.options.sessionId
2224
+ );
2225
+ const ua = rawUa?.value || "";
2226
+ const cleaned = ua.replace(/HeadlessChrome/g, "Chrome");
2227
+ if (cleaned !== ua) {
2228
+ await this.options.conn.send(
2229
+ "Network.setUserAgentOverride",
2230
+ { userAgent: cleaned },
2231
+ this.options.sessionId
2232
+ );
2233
+ }
2234
+ } catch {
2235
+ }
2236
+ }
2237
+ const result = await this.options.conn.send(
2238
+ "Page.navigate",
2239
+ { url, referrer: opts.referer },
2240
+ this.options.sessionId
2241
+ );
2242
+ if (result.errorText) {
2243
+ throw new Error(`Navigation failed: ${result.errorText}`);
2244
+ }
2245
+ if (waitUntil === "commit") {
2246
+ this.options.setUrl(url);
2247
+ return {
2248
+ status: () => 0,
2249
+ ok: () => false,
2250
+ url: () => url,
2251
+ headers: () => ({})
2252
+ };
2253
+ }
2254
+ await this.options.waitForLoadState(waitUntil, timeout);
2255
+ this.options.setUrl(url);
2256
+ const statusCode = 200;
2257
+ const finalUrl = url;
2258
+ const headers = {};
2259
+ return {
2260
+ status: () => statusCode,
2261
+ ok: () => statusCode >= 200 && statusCode < 300,
2262
+ url: () => finalUrl,
2263
+ headers: () => headers
2264
+ };
2265
+ }
2266
+ async goBack(opts = {}) {
2267
+ try {
2268
+ const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
2269
+ if (navHistory.currentIndex > 0) {
2270
+ const prevUrl = navHistory.entries[navHistory.currentIndex - 1]?.url;
2271
+ if (prevUrl && prevUrl !== "about:blank") {
2272
+ await this.options.conn.send("Page.navigate", { url: prevUrl }, this.options.sessionId);
2273
+ await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
2274
+ });
2275
+ this.options.setUrl(prevUrl);
2276
+ return;
2277
+ }
2278
+ }
2279
+ } catch {
2280
+ }
2281
+ await this.options.evaluate("() => history.back()");
2282
+ await this.options.waitForTimeout(3e3);
2283
+ this.options.setUrl(await this.options.evaluate("location.href").catch(() => this.options.currentUrl()));
2284
+ }
2285
+ async goForward(opts = {}) {
2286
+ try {
2287
+ const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
2288
+ if (navHistory.currentIndex < navHistory.entries.length - 1) {
2289
+ const nextUrl = navHistory.entries[navHistory.currentIndex + 1]?.url;
2290
+ if (nextUrl && nextUrl !== "about:blank") {
2291
+ await this.options.conn.send("Page.navigate", { url: nextUrl }, this.options.sessionId);
2292
+ await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
2293
+ });
2294
+ this.options.setUrl(nextUrl);
2295
+ return;
2296
+ }
2297
+ }
2298
+ } catch {
2299
+ }
2300
+ await this.options.evaluate("() => history.forward()");
2301
+ await this.options.waitForTimeout(3e3);
2302
+ this.options.setUrl(await this.options.evaluate("location.href").catch(() => this.options.currentUrl()));
2303
+ }
2304
+ async reload(opts = {}) {
2305
+ this.options.state.loadFired = false;
2306
+ this.options.state.domContentFired = false;
2307
+ this.options.state.networkIdle = false;
2308
+ await this.options.conn.send("Page.reload", void 0, this.options.sessionId);
2309
+ await this.options.waitForLoadState(opts.waitUntil ?? "load", opts.timeout);
2310
+ }
2311
+ async waitForLoadState(state = "load", timeout = 3e4) {
2312
+ if (this.options.isClosed()) throw new Error("Page is closed");
2313
+ const checkState = () => {
2314
+ switch (state) {
2315
+ case "domcontentloaded":
2316
+ return this.options.state.domContentFired;
2317
+ case "load":
2318
+ return this.options.state.loadFired;
2319
+ case "networkidle":
2320
+ return this.options.state.networkIdle;
2321
+ case "commit":
2322
+ return this.options.state.domContentFired;
2323
+ default:
2324
+ return true;
2325
+ }
2326
+ };
2327
+ if (checkState()) return;
2328
+ return new Promise((resolve, reject) => {
2329
+ const timer = setTimeout(() => {
2330
+ reject(new Error(`waitForLoadState('${state}') timeout after ${timeout}ms`));
2331
+ }, timeout);
2332
+ const check = () => {
2333
+ if (checkState()) {
2334
+ clearTimeout(timer);
2335
+ resolve();
2336
+ } else {
2337
+ setTimeout(check, 50);
2338
+ }
2339
+ };
2340
+ check();
2341
+ });
2342
+ }
2343
+ async waitForTimeout(ms) {
2344
+ await new Promise((resolve) => {
2345
+ const timer = setTimeout(resolve, ms);
2346
+ if (typeof timer.unref === "function") timer.unref();
2347
+ });
2348
+ }
2349
+ };
2350
+
2351
+ // src/cdp-driver/page-dom.ts
2352
+ var DomQueryService = class {
2353
+ constructor(options) {
2354
+ this.options = options;
2355
+ }
2356
+ options;
2357
+ /** Query a single element, returns CDP nodeId or 0 if not found */
2358
+ async querySelector(selector) {
2359
+ if (selector.startsWith("xpath=")) {
2360
+ const found = await this.options.evaluate(`
2361
+ (() => { const el = ${queryJS(selector)}; return !!el; })()
2362
+ `).catch(() => false);
2363
+ if (!found) return 0;
2364
+ try {
2365
+ const search = await this.options.conn.send(
2366
+ "DOM.performSearch",
2367
+ { query: selector.slice(6) },
2368
+ this.options.sessionId
2369
+ );
2370
+ if (search.nodeId) return search.nodeId;
2371
+ } catch {
2372
+ }
2373
+ return 1;
2374
+ }
2375
+ const withTimeout = (p, ms) => Promise.race([p, new Promise((r) => setTimeout(() => r(null), ms))]);
2376
+ const doc = await withTimeout(
2377
+ this.options.conn.send("DOM.getDocument", { depth: 0 }, this.options.sessionId),
2378
+ 8e3
2379
+ );
2380
+ if (!doc) return 0;
2381
+ const result = await withTimeout(
2382
+ this.options.conn.send(
2383
+ "DOM.querySelector",
2384
+ { nodeId: doc.root.nodeId, selector },
2385
+ this.options.sessionId
2386
+ ),
2387
+ 8e3
2388
+ );
2389
+ if (!result) return 0;
2390
+ return result.nodeId;
2391
+ }
2392
+ /** Query all matching elements, returns array of CDP nodeIds */
2393
+ async querySelectorAll(selector) {
2394
+ const doc = await this.options.conn.send(
2395
+ "DOM.getDocument",
2396
+ { depth: 0 },
2397
+ this.options.sessionId
2398
+ );
2399
+ const result = await this.options.conn.send(
2400
+ "DOM.querySelectorAll",
2401
+ { nodeId: doc.root.nodeId, selector },
2402
+ this.options.sessionId
2403
+ );
2404
+ return result.nodeIds ?? [];
2405
+ }
2406
+ /** Resolve a CDP nodeId to a RemoteObject for evaluate */
2407
+ async resolveNode(nodeId) {
2408
+ const result = await this.options.conn.send(
2409
+ "DOM.resolveNode",
2410
+ { nodeId },
2411
+ this.options.sessionId
2412
+ );
2413
+ return result.object.objectId;
2414
+ }
2415
+ /** Get the box model for a nodeId */
2416
+ async getBoxModel(nodeId) {
2417
+ try {
2418
+ const result = await this.options.conn.send("DOM.getBoxModel", { nodeId }, this.options.sessionId);
2419
+ const c = result.model?.content;
2420
+ if (!c || c.length < 8) return null;
2421
+ const x1 = c[0];
2422
+ const y1 = c[1];
2423
+ const x2 = c[4];
2424
+ const y2 = c[5];
2425
+ return {
2426
+ x: Math.min(x1, x2),
2427
+ y: Math.min(y1, y2),
2428
+ width: Math.abs(x2 - x1),
2429
+ height: Math.abs(y2 - y1)
2430
+ };
2431
+ } catch {
2432
+ return null;
2433
+ }
2434
+ }
2435
+ /** Call a function on a RemoteObject */
2436
+ async callFunctionOn(objectId, functionDeclaration, args = []) {
2437
+ const result = await this.options.conn.send("Runtime.callFunctionOn", {
2438
+ objectId,
2439
+ functionDeclaration,
2440
+ arguments: args.map((a) => ({ value: a })),
2441
+ returnByValue: true
2442
+ }, this.options.sessionId);
2443
+ if (result.exceptionDetails) {
2444
+ throw new Error(`CallFunctionOn error: ${result.exceptionDetails.text}`);
2445
+ }
2446
+ return result.result?.value;
2447
+ }
2448
+ /** Send a CDP command scoped to this page's session */
2449
+ async _cdpSend(method, params) {
2450
+ return this.options.conn.send(method, params, this.options.sessionId);
2451
+ }
2452
+ /** sup-s11: beforeunload 自动应答语义——'accept'(默认,离开页面,与录制
2453
+ * 意图一致)或 'dismiss'(取消导航留守原页,尽力而为:此构建上 CDP
2454
+ * accept:false 对浏览器侧导航的取消语义不稳定,不保证)。 */
2455
+ };
2456
+
2457
+ // src/cdp-driver/page-runtime.ts
2458
+ var RuntimeEvaluationService = class {
2459
+ constructor(options) {
2460
+ this.options = options;
2461
+ }
2462
+ options;
2463
+ async title() {
2464
+ let title = "";
2465
+ for (let attempt = 0; attempt < 20; attempt++) {
2466
+ try {
2467
+ title = await this.evaluate("document.title");
2468
+ if (title) return title;
2469
+ } catch {
2470
+ }
2471
+ await new Promise((resolve) => setTimeout(resolve, 50));
2472
+ }
2473
+ return title;
2474
+ }
2475
+ async content() {
2476
+ return this.evaluate("document.documentElement.outerHTML");
2477
+ }
2478
+ // ── Evaluation ──────────────────────────────────────────────
2479
+ async evaluate(fn, ...args) {
2480
+ if (this.options.isClosed()) throw new Error("Page is closed");
2481
+ this.options.conn.send("Page.handleJavaScriptDialog", { accept: false }, this.options.sessionId).catch(() => {
2482
+ });
2483
+ let expression;
2484
+ if (typeof fn === "string") {
2485
+ expression = fn;
2486
+ } else {
2487
+ const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
2488
+ expression = `(()=>{const __fn=(${fn.toString()});return __fn(${argStr});})()`;
2489
+ }
2490
+ const result = await this.options.conn.send("Runtime.evaluate", {
2491
+ expression,
2492
+ returnByValue: true,
2493
+ awaitPromise: true
2494
+ }, this.options.sessionId);
2495
+ if (result.exceptionDetails) {
2496
+ const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
2497
+ throw new Error(`${detail}`);
2498
+ }
2499
+ return result.result?.value;
2500
+ }
2501
+ /**
2502
+ * 在指定 iframe 上下文中执行表达式(攻防 D16 能力建设,2026-08-19)。
2503
+ *
2504
+ * 双路径:
2505
+ * 1. 同进程 iframe —— Runtime.enable 收集 executionContextCreated,
2506
+ * 找到目标 frameId 的 contextId,用 contextId 定向执行;
2507
+ * 2. 跨域 OOPIF(独立 target)—— Target.setAutoAttach(flatten) 监听
2508
+ * attachedToTarget 中 type==='iframe' 的会话,用其 sessionId 执行。
2509
+ *
2510
+ * 这绕过了页面同源策略(那是页面 JS 的约束,CDP 是调试通道)——
2511
+ * 支付窗/验证码/第三方嵌入内容的读写都靠它。
2512
+ */
2513
+ async evaluateInFrame(urlIncludes, expression) {
2514
+ if (this.options.isClosed()) throw new Error("Page is closed");
2515
+ const evalIn = async (sessionId, contextId) => {
2516
+ const params = { expression, returnByValue: true, awaitPromise: true };
2517
+ if (contextId !== void 0) params.contextId = contextId;
2518
+ const result = await this.options.conn.send("Runtime.evaluate", params, sessionId);
2519
+ if (result.exceptionDetails) {
2520
+ const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
2521
+ throw new Error(`[frame ${urlIncludes}] ${detail}`);
2522
+ }
2523
+ return result.result?.value;
2524
+ };
2525
+ try {
2526
+ const tg = await this.options.conn.send("Target.getTargets", void 0);
2527
+ const hit2 = (tg.targetInfos || []).find((t) => t.type === "iframe" && (t.url || "").includes(urlIncludes));
2528
+ if (hit2) {
2529
+ const att = await this.options.conn.send("Target.attachToTarget", { targetId: hit2.targetId, flatten: true });
2530
+ return evalIn(att.sessionId);
2531
+ }
2532
+ } catch {
2533
+ }
2534
+ const tree = await this.options.conn.send("Page.getFrameTree", void 0, this.options.sessionId);
2535
+ const all = [];
2536
+ const walk = (node) => {
2537
+ all.push({ id: node.frame.id, url: node.frame.url });
2538
+ for (const child of node.childFrames || []) walk(child);
2539
+ };
2540
+ walk(tree.frameTree);
2541
+ const mainId = tree.frameTree?.frame?.id;
2542
+ const target = all.find((f) => f.id !== mainId && f.url.includes(urlIncludes));
2543
+ if (target) {
2544
+ const contexts = [];
2545
+ const onCtx = (raw) => {
2546
+ const c = raw?.context;
2547
+ if (c?.id && c?.auxData?.frameId) contexts.push({ id: c.id, frameId: c.auxData.frameId });
2548
+ };
2549
+ this.options.conn.on("Runtime.executionContextCreated", onCtx);
2550
+ try {
2551
+ await this.options.conn.send("Runtime.enable", void 0, this.options.sessionId).catch(() => {
2552
+ });
2553
+ await new Promise((r) => setTimeout(r, 400));
2554
+ } finally {
2555
+ this.options.conn.off("Runtime.executionContextCreated", onCtx);
2556
+ }
2557
+ const ctx = contexts.find((c) => c.frameId === target.id);
2558
+ if (ctx) return evalIn(this.options.sessionId, ctx.id);
2559
+ }
2560
+ const attached = [];
2561
+ const onAttach = (raw) => {
2562
+ const ev = raw;
2563
+ if (ev?.sessionId && ev.targetInfo?.type === "iframe") {
2564
+ attached.push({ sessionId: ev.sessionId, url: ev.targetInfo.url || "" });
2565
+ }
2566
+ };
2567
+ this.options.conn.on("Target.attachedToTarget", onAttach);
2568
+ try {
2569
+ await this.options.conn.send("Target.setAutoAttach", {
2570
+ autoAttach: true,
2571
+ waitForDebuggerOnStart: false,
2572
+ flatten: true
2573
+ }, this.options.sessionId);
2574
+ await new Promise((r) => setTimeout(r, 600));
2575
+ } finally {
2576
+ this.options.conn.off("Target.attachedToTarget", onAttach);
2577
+ this.options.conn.send("Target.setAutoAttach", { autoAttach: false, waitForDebuggerOnStart: false, flatten: true }, this.options.sessionId).catch(() => {
2578
+ });
2579
+ }
2580
+ const hit = attached.find((a) => a.url.includes(urlIncludes));
2581
+ if (!hit) {
2582
+ 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`);
2583
+ }
2584
+ return evalIn(hit.sessionId);
2585
+ }
2586
+ /** evaluateHandle — evaluates fn and returns a handle for element bounding box */
2587
+ async evaluateHandle(fn, ...args) {
2588
+ let expression;
2589
+ if (typeof fn === "string") {
2590
+ expression = fn;
2591
+ } else {
2592
+ const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
2593
+ 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;})()`;
2594
+ }
2595
+ const result = await this.options.conn.send("Runtime.evaluate", { expression, returnByValue: true }).catch(() => ({ result: { value: null } }));
2596
+ let box = null;
2597
+ try {
2598
+ box = JSON.parse(result.result?.value);
2599
+ } catch {
2600
+ }
2601
+ return {
2602
+ asElement: () => box ? { boundingBox: async () => box } : null
2603
+ };
2604
+ }
2605
+ async $eval(selector, fn, ...args) {
2606
+ const fnBody = typeof fn === "function" ? fn.toString() : fn;
2607
+ const selJSON = JSON.stringify(selector);
2608
+ const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
2609
+ return this.evaluate(
2610
+ `(function(sel, xpathExpr, fnStr, ...evalArgs) {
2611
+ const el = xpathExpr
2612
+ ? document.evaluate(xpathExpr, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
2613
+ : document.querySelector(sel);
2614
+ if (!el) throw new Error('No element found for selector: ' + sel);
2615
+ const fn = new Function('return ' + fnStr)();
2616
+ return fn(el, ...evalArgs);
2617
+ })(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
2618
+ );
2619
+ }
2620
+ async $$eval(selector, fn, ...args) {
2621
+ const fnBody = typeof fn === "function" ? fn.toString() : fn;
2622
+ const selJSON = JSON.stringify(selector);
2623
+ const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
2624
+ return this.evaluate(
2625
+ `(function(sel, xpathExpr, fnStr, ...evalArgs) {
2626
+ const els = xpathExpr
2627
+ ? (() => { 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; })()
2628
+ : Array.from(document.querySelectorAll(sel));
2629
+ const fn = new Function('return ' + fnStr)();
2630
+ return fn(els, ...evalArgs);
2631
+ })(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
2632
+ );
2633
+ }
2634
+ };
2635
+
2636
+ // src/cdp-driver/page.ts
2637
+ var XBPageImpl = class _XBPageImpl {
2638
+ conn;
2639
+ _emitter = new EventEmitter();
2640
+ _subscriptions = [];
2641
+ sessionId;
2642
+ _targetId;
2643
+ _contextImpl;
1597
2644
  _browserImpl;
1598
2645
  _closed = false;
1599
2646
  _url = "about:blank";
1600
- _title = "";
1601
2647
  _viewportSize = null;
1602
2648
  _loadState = {
1603
2649
  loadFired: true,
@@ -1606,6 +2652,13 @@ var XBPageImpl = class _XBPageImpl {
1606
2652
  };
1607
2653
  mouse;
1608
2654
  keyboard;
2655
+ mediaService;
2656
+ fileInputService;
2657
+ networkWaitService;
2658
+ networkRouteService;
2659
+ navigationService;
2660
+ domQueryService;
2661
+ runtimeEvaluationService;
1609
2662
  // Network tracking for waitForLoadState('networkidle')
1610
2663
  inflightRequests = /* @__PURE__ */ new Set();
1611
2664
  networkIdleResolve = null;
@@ -1619,6 +2672,60 @@ var XBPageImpl = class _XBPageImpl {
1619
2672
  this._browserImpl = browser;
1620
2673
  this.mouse = new XBMouseImpl(conn, sessionId);
1621
2674
  this.keyboard = new XBKeyboardImpl(conn, sessionId);
2675
+ this.mediaService = new MediaService({
2676
+ conn,
2677
+ sessionId,
2678
+ viewportSize: this._viewportSize,
2679
+ evaluate: (script) => this.evaluate(script),
2680
+ onViewportSize: (size) => {
2681
+ this._viewportSize = size;
2682
+ }
2683
+ });
2684
+ this.fileInputService = new FileInputService({
2685
+ conn,
2686
+ sessionId,
2687
+ evaluate: (script) => this.evaluate(script),
2688
+ mouse: this.mouse
2689
+ });
2690
+ this.networkWaitService = new NetworkWaitService({
2691
+ conn,
2692
+ sessionId,
2693
+ responses: this._networkResponses,
2694
+ requests: this._networkRequests,
2695
+ on: (event, handler) => this._emitter.on(event, handler),
2696
+ off: (event, handler) => this._emitter.removeListener(event, handler),
2697
+ currentUrl: () => this.url()
2698
+ });
2699
+ this.networkRouteService = new NetworkRouteService({
2700
+ conn,
2701
+ sessionId,
2702
+ emit: (event, ...args) => this._emit(event, ...args)
2703
+ });
2704
+ this.navigationService = new NavigationService({
2705
+ conn,
2706
+ sessionId,
2707
+ state: this._loadState,
2708
+ stealthConfig: this._contextImpl.stealthConfig,
2709
+ isClosed: () => this._closed,
2710
+ setUrl: (url) => {
2711
+ this._url = url;
2712
+ },
2713
+ currentUrl: () => this.url(),
2714
+ waitForLoadState: (state, timeout) => this.waitForLoadState(state, timeout),
2715
+ waitForTimeout: (ms) => this.waitForTimeout(ms),
2716
+ evaluate: (script) => this.evaluate(script)
2717
+ });
2718
+ this.runtimeEvaluationService = new RuntimeEvaluationService({
2719
+ conn,
2720
+ sessionId,
2721
+ isClosed: () => this._closed,
2722
+ url: () => this.url()
2723
+ });
2724
+ this.domQueryService = new DomQueryService({
2725
+ conn,
2726
+ sessionId,
2727
+ evaluate: (script) => this.evaluate(script)
2728
+ });
1622
2729
  }
1623
2730
  _emit(event, ...args) {
1624
2731
  this._emitter.emit(event, ...args);
@@ -1644,7 +2751,7 @@ var XBPageImpl = class _XBPageImpl {
1644
2751
  });
1645
2752
  this._subscriptions.push(
1646
2753
  this.conn.subscribe("Fetch.requestPaused", this.sessionId, (params) => {
1647
- if (this._interceptionEnabled) return;
2754
+ if (this.networkRouteService.isInterceptionEnabled) return;
1648
2755
  const p = params;
1649
2756
  this.conn.send("Fetch.continueRequest", { requestId: p.requestId }, this.sessionId).catch(() => {
1650
2757
  });
@@ -1820,124 +2927,31 @@ var XBPageImpl = class _XBPageImpl {
1820
2927
  });
1821
2928
  try {
1822
2929
  const info = await this.conn.send(
1823
- "Target.getTargetInfo",
1824
- { targetId: this._targetId }
1825
- );
1826
- this._url = info.url;
1827
- this._title = info.title;
1828
- if (info.url && info.url !== "about:blank" && info.url !== "") {
1829
- this._loadState = { loadFired: true, domContentFired: true, networkIdle: true };
1830
- }
1831
- } catch {
1832
- }
1833
- }
1834
- get _connection() {
1835
- return this.conn;
1836
- }
1837
- // ── Navigation ──────────────────────────────────────────────
1838
- async goto(url, opts = {}) {
1839
- if (this._closed) throw new Error("Page is closed");
1840
- const waitUntil = opts.waitUntil ?? "load";
1841
- const timeout = opts.timeout ?? 3e4;
1842
- this._loadState = { loadFired: false, domContentFired: false, networkIdle: false };
1843
- if (process.env.XBROWSER_STEALTH !== "off") {
1844
- try {
1845
- await this.conn.send(
1846
- "Page.addScriptToEvaluateOnNewDocument",
1847
- { source: buildStealthInitScript({ ...DEFAULT_STEALTH_CONFIG, ...this._contextImpl.stealthConfig ?? {} }) },
1848
- this.sessionId
1849
- );
1850
- } catch {
1851
- }
1852
- try {
1853
- const rawUa = await this.conn.send(
1854
- "Runtime.evaluate",
1855
- { expression: "navigator.userAgent", returnByValue: true },
1856
- this.sessionId
1857
- );
1858
- const ua = rawUa?.value || "";
1859
- const cleaned = ua.replace(/HeadlessChrome/g, "Chrome");
1860
- if (cleaned !== ua) {
1861
- await this.conn.send(
1862
- "Network.setUserAgentOverride",
1863
- { userAgent: cleaned },
1864
- this.sessionId
1865
- );
1866
- }
1867
- } catch {
1868
- }
1869
- }
1870
- const result = await this.conn.send(
1871
- "Page.navigate",
1872
- { url, referrer: opts.referer },
1873
- this.sessionId
1874
- );
1875
- if (result.errorText) {
1876
- throw new Error(`Navigation failed: ${result.errorText}`);
1877
- }
1878
- if (waitUntil === "commit") {
1879
- this._url = url;
1880
- return {
1881
- status: () => 0,
1882
- ok: () => false,
1883
- url: () => url,
1884
- headers: () => ({})
1885
- };
1886
- }
1887
- await this.waitForLoadState(waitUntil, timeout);
1888
- this._url = url;
1889
- const statusCode = 200;
1890
- const finalUrl = url;
1891
- const headers = {};
1892
- return {
1893
- status: () => statusCode,
1894
- ok: () => statusCode >= 200 && statusCode < 300,
1895
- url: () => finalUrl,
1896
- headers: () => headers
1897
- };
1898
- }
1899
- async goBack(opts = {}) {
1900
- try {
1901
- const navHistory = await this.conn.send("Page.getNavigationHistory", void 0, this.sessionId);
1902
- if (navHistory.currentIndex > 0) {
1903
- const prevUrl = navHistory.entries[navHistory.currentIndex - 1]?.url;
1904
- if (prevUrl && prevUrl !== "about:blank") {
1905
- await this.conn.send("Page.navigate", { url: prevUrl }, this.sessionId);
1906
- await this.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
1907
- });
1908
- this._url = prevUrl;
1909
- return;
1910
- }
1911
- }
1912
- } catch {
1913
- }
1914
- await this.evaluate("() => history.back()");
1915
- await this.waitForTimeout(3e3);
1916
- this._url = await this.evaluate("location.href").catch(() => this._url);
1917
- }
1918
- async goForward(opts = {}) {
1919
- try {
1920
- const navHistory = await this.conn.send("Page.getNavigationHistory", void 0, this.sessionId);
1921
- if (navHistory.currentIndex < navHistory.entries.length - 1) {
1922
- const nextUrl = navHistory.entries[navHistory.currentIndex + 1]?.url;
1923
- if (nextUrl && nextUrl !== "about:blank") {
1924
- await this.conn.send("Page.navigate", { url: nextUrl }, this.sessionId);
1925
- await this.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
1926
- });
1927
- this._url = nextUrl;
1928
- return;
1929
- }
2930
+ "Target.getTargetInfo",
2931
+ { targetId: this._targetId }
2932
+ );
2933
+ this._url = info.url;
2934
+ if (info.url && info.url !== "about:blank" && info.url !== "") {
2935
+ this._loadState = { loadFired: true, domContentFired: true, networkIdle: true };
1930
2936
  }
1931
2937
  } catch {
1932
2938
  }
1933
- await this.evaluate("() => history.forward()");
1934
- await this.waitForTimeout(3e3);
1935
- this._url = await this.evaluate("location.href").catch(() => this._url);
2939
+ }
2940
+ get _connection() {
2941
+ return this.conn;
2942
+ }
2943
+ // ── Navigation ──────────────────────────────────────────────
2944
+ async goto(url, opts = {}) {
2945
+ return this.navigationService.goto(url, opts);
2946
+ }
2947
+ async goBack(opts = {}) {
2948
+ return this.navigationService.goBack(opts);
2949
+ }
2950
+ async goForward(opts = {}) {
2951
+ return this.navigationService.goForward(opts);
1936
2952
  }
1937
2953
  async reload(opts = {}) {
1938
- this._loadState = { loadFired: false, domContentFired: false, networkIdle: false };
1939
- await this.conn.send("Page.reload", void 0, this.sessionId);
1940
- await this.waitForLoadState(opts.waitUntil ?? "load", opts.timeout);
2954
+ return this.navigationService.reload(opts);
1941
2955
  }
1942
2956
  async waitForLoadState(state = "load", timeout = 3e4) {
1943
2957
  if (this._closed) throw new Error("Page is closed");
@@ -2030,184 +3044,26 @@ Last error: ${lastError.message}` : "";
2030
3044
  return this._url;
2031
3045
  }
2032
3046
  async title() {
2033
- for (let i = 0; i < 20; i++) {
2034
- try {
2035
- this._title = await this.evaluate("document.title");
2036
- if (this._title) return this._title;
2037
- } catch {
2038
- }
2039
- await new Promise((r) => setTimeout(r, 50));
2040
- }
2041
- try {
2042
- const info = await this._cdpSend("Target.getTargetInfo", { targetId: this._targetId });
2043
- if (info?.title) {
2044
- this._title = info.title;
2045
- return this._title;
2046
- }
2047
- } catch {
2048
- }
2049
- return this._title;
3047
+ return this.runtimeEvaluationService.title();
2050
3048
  }
2051
3049
  async content() {
2052
- return this.evaluate("document.documentElement.outerHTML");
3050
+ return this.runtimeEvaluationService.content();
2053
3051
  }
2054
- // ── Evaluation ──────────────────────────────────────────────
2055
3052
  async evaluate(fn, ...args) {
2056
- if (this._closed) throw new Error("Page is closed");
2057
- this.conn.send("Page.handleJavaScriptDialog", { accept: false }, this.sessionId).catch(() => {
2058
- });
2059
- let expression;
2060
- if (typeof fn === "string") {
2061
- expression = fn;
2062
- } else {
2063
- const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
2064
- expression = `(()=>{const __fn=(${fn.toString()});return __fn(${argStr});})()`;
2065
- }
2066
- const result = await this.conn.send("Runtime.evaluate", {
2067
- expression,
2068
- returnByValue: true,
2069
- awaitPromise: true
2070
- }, this.sessionId);
2071
- if (result.exceptionDetails) {
2072
- const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
2073
- throw new Error(`${detail}`);
2074
- }
2075
- return result.result?.value;
3053
+ return this.runtimeEvaluationService.evaluate(fn, ...args);
2076
3054
  }
2077
- /**
2078
- * 在指定 iframe 上下文中执行表达式(攻防 D16 能力建设,2026-08-19)。
2079
- *
2080
- * 双路径:
2081
- * 1. 同进程 iframe —— Runtime.enable 收集 executionContextCreated,
2082
- * 找到目标 frameId 的 contextId,用 contextId 定向执行;
2083
- * 2. 跨域 OOPIF(独立 target)—— Target.setAutoAttach(flatten) 监听
2084
- * attachedToTarget 中 type==='iframe' 的会话,用其 sessionId 执行。
2085
- *
2086
- * 这绕过了页面同源策略(那是页面 JS 的约束,CDP 是调试通道)——
2087
- * 支付窗/验证码/第三方嵌入内容的读写都靠它。
2088
- */
2089
3055
  async evaluateInFrame(urlIncludes, expression) {
2090
- if (this._closed) throw new Error("Page is closed");
2091
- const evalIn = async (sessionId, contextId) => {
2092
- const params = { expression, returnByValue: true, awaitPromise: true };
2093
- if (contextId !== void 0) params.contextId = contextId;
2094
- const result = await this.conn.send("Runtime.evaluate", params, sessionId);
2095
- if (result.exceptionDetails) {
2096
- const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
2097
- throw new Error(`[frame ${urlIncludes}] ${detail}`);
2098
- }
2099
- return result.result?.value;
2100
- };
2101
- try {
2102
- const tg = await this.conn.send("Target.getTargets", void 0);
2103
- const hit2 = (tg.targetInfos || []).find((t) => t.type === "iframe" && (t.url || "").includes(urlIncludes));
2104
- if (hit2) {
2105
- const att = await this.conn.send("Target.attachToTarget", { targetId: hit2.targetId, flatten: true });
2106
- return evalIn(att.sessionId);
2107
- }
2108
- } catch {
2109
- }
2110
- const tree = await this.conn.send("Page.getFrameTree", void 0, this.sessionId);
2111
- const all = [];
2112
- const walk = (node) => {
2113
- all.push({ id: node.frame.id, url: node.frame.url });
2114
- for (const child of node.childFrames || []) walk(child);
2115
- };
2116
- walk(tree.frameTree);
2117
- const mainId = tree.frameTree?.frame?.id;
2118
- const target = all.find((f) => f.id !== mainId && f.url.includes(urlIncludes));
2119
- if (target) {
2120
- const contexts = [];
2121
- const onCtx = (raw) => {
2122
- const c = raw?.context;
2123
- if (c?.id && c?.auxData?.frameId) contexts.push({ id: c.id, frameId: c.auxData.frameId });
2124
- };
2125
- this.conn.on("Runtime.executionContextCreated", onCtx);
2126
- try {
2127
- await this.conn.send("Runtime.enable", void 0, this.sessionId).catch(() => {
2128
- });
2129
- await new Promise((r) => setTimeout(r, 400));
2130
- } finally {
2131
- this.conn.off("Runtime.executionContextCreated", onCtx);
2132
- }
2133
- const ctx = contexts.find((c) => c.frameId === target.id);
2134
- if (ctx) return evalIn(this.sessionId, ctx.id);
2135
- }
2136
- const attached = [];
2137
- const onAttach = (raw) => {
2138
- const ev = raw;
2139
- if (ev?.sessionId && ev.targetInfo?.type === "iframe") {
2140
- attached.push({ sessionId: ev.sessionId, url: ev.targetInfo.url || "" });
2141
- }
2142
- };
2143
- this.conn.on("Target.attachedToTarget", onAttach);
2144
- try {
2145
- await this.conn.send("Target.setAutoAttach", {
2146
- autoAttach: true,
2147
- waitForDebuggerOnStart: false,
2148
- flatten: true
2149
- }, this.sessionId);
2150
- await new Promise((r) => setTimeout(r, 600));
2151
- } finally {
2152
- this.conn.off("Target.attachedToTarget", onAttach);
2153
- this.conn.send("Target.setAutoAttach", { autoAttach: false, waitForDebuggerOnStart: false, flatten: true }, this.sessionId).catch(() => {
2154
- });
2155
- }
2156
- const hit = attached.find((a) => a.url.includes(urlIncludes));
2157
- if (!hit) {
2158
- throw new Error(`frame not found for "${urlIncludes}"\uFF08OOPIF target\u3001frame \u6811\u3001auto-attach \u4E09\u8DEF\u5747\u672A\u547D\u4E2D\uFF1B\u53EF\u80FD\u4ECD\u5728\u52A0\u8F7D\uFF09`);
2159
- }
2160
- return evalIn(hit.sessionId);
3056
+ return this.runtimeEvaluationService.evaluateInFrame(urlIncludes, expression);
2161
3057
  }
2162
- /** evaluateHandle — evaluates fn and returns a handle for element bounding box */
2163
- async evaluateHandle(fn, ...args) {
2164
- let expression;
2165
- if (typeof fn === "string") {
2166
- expression = fn;
2167
- } else {
2168
- const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
2169
- 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;})()`;
2170
- }
2171
- const result = await this.conn.send("Runtime.evaluate", { expression, returnByValue: true }).catch(() => ({ result: { value: null } }));
2172
- let box = null;
2173
- try {
2174
- box = JSON.parse(result.result?.value);
2175
- } catch {
2176
- }
2177
- return {
2178
- asElement: () => box ? { boundingBox: async () => box } : null
2179
- };
3058
+ async evaluateHandle(script, ...args) {
3059
+ return this.runtimeEvaluationService.evaluateHandle(script, ...args);
2180
3060
  }
2181
3061
  async $eval(selector, fn, ...args) {
2182
- const fnBody = typeof fn === "function" ? fn.toString() : fn;
2183
- const selJSON = JSON.stringify(selector);
2184
- const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
2185
- return this.evaluate(
2186
- `(function(sel, xpathExpr, fnStr, ...evalArgs) {
2187
- const el = xpathExpr
2188
- ? document.evaluate(xpathExpr, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
2189
- : document.querySelector(sel);
2190
- if (!el) throw new Error('No element found for selector: ' + sel);
2191
- const fn = new Function('return ' + fnStr)();
2192
- return fn(el, ...evalArgs);
2193
- })(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
2194
- );
3062
+ return this.runtimeEvaluationService.$eval(selector, fn, ...args);
2195
3063
  }
2196
3064
  async $$eval(selector, fn, ...args) {
2197
- const fnBody = typeof fn === "function" ? fn.toString() : fn;
2198
- const selJSON = JSON.stringify(selector);
2199
- const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
2200
- return this.evaluate(
2201
- `(function(sel, xpathExpr, fnStr, ...evalArgs) {
2202
- const els = xpathExpr
2203
- ? (() => { const it = document.evaluate(xpathExpr, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); const r=[]; for(let i=0;i<it.snapshotLength;i++) r.push(it.snapshotItem(i)); return r; })()
2204
- : Array.from(document.querySelectorAll(sel));
2205
- const fn = new Function('return ' + fnStr)();
2206
- return fn(els, ...evalArgs);
2207
- })(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
2208
- );
3065
+ return this.runtimeEvaluationService.$$eval(selector, fn, ...args);
2209
3066
  }
2210
- // ── Locator ─────────────────────────────────────────────────
2211
3067
  locator(selector) {
2212
3068
  return new XBLocatorImpl(this, selector);
2213
3069
  }
@@ -2328,88 +3184,20 @@ Last error: ${lastError.message}` : "";
2328
3184
  }
2329
3185
  // ── Screen ──────────────────────────────────────────────────
2330
3186
  async screenshot(opts = {}) {
2331
- const params = {
2332
- format: opts.type ?? "png"
2333
- };
2334
- if (opts.quality !== void 0 && (opts.type === "jpeg" || !opts.type && opts.quality)) {
2335
- params.quality = opts.quality;
2336
- }
2337
- if (opts.fullPage) {
2338
- params.captureBeyondViewport = true;
2339
- }
2340
- if (opts.clip) {
2341
- const clip = {
2342
- x: Math.round(opts.clip.x),
2343
- y: Math.round(opts.clip.y),
2344
- width: Math.round(Math.max(1, opts.clip.width)),
2345
- height: Math.round(Math.max(1, opts.clip.height)),
2346
- scale: 1
2347
- };
2348
- params.clip = clip;
2349
- }
2350
- if (opts.omitBackground) {
2351
- params.omitBackground = true;
2352
- }
2353
- const result = await this.conn.send(
2354
- "Page.captureScreenshot",
2355
- params,
2356
- this.sessionId
2357
- );
2358
- return Buffer.from(result.data, "base64");
3187
+ return this.mediaService.screenshot(opts);
2359
3188
  }
2360
3189
  async pdf(opts = {}) {
2361
- const params = {};
2362
- if (opts.landscape !== void 0) params.landscape = opts.landscape;
2363
- if (opts.printBackground !== void 0) params.printBackground = opts.printBackground;
2364
- if (opts.scale !== void 0) params.scale = opts.scale;
2365
- if (opts.format) params.paperFormat = opts.format;
2366
- if (opts.preferCSSPageSize !== void 0) params.preferCSSPageSize = opts.preferCSSPageSize;
2367
- if (opts.margin) {
2368
- if (opts.margin.top) params.marginTop = parseFloat(opts.margin.top);
2369
- if (opts.margin.bottom) params.marginBottom = parseFloat(opts.margin.bottom);
2370
- if (opts.margin.left) params.marginLeft = parseFloat(opts.margin.left);
2371
- if (opts.margin.right) params.marginRight = parseFloat(opts.margin.right);
2372
- }
2373
- const result = await this.conn.send("Page.printToPDF", params, this.sessionId);
2374
- return Buffer.from(result.data, "base64");
3190
+ return this.mediaService.pdf(opts);
2375
3191
  }
2376
3192
  viewportSize() {
2377
- return this._viewportSize ?? null;
3193
+ return this._viewportSize;
2378
3194
  }
2379
3195
  async setViewportSize(size) {
2380
- await this.conn.send(
2381
- "Emulation.setDeviceMetricsOverride",
2382
- {
2383
- width: size.width,
2384
- height: size.height,
2385
- deviceScaleFactor: 1,
2386
- mobile: false
2387
- },
2388
- this.sessionId
2389
- );
2390
- this._viewportSize = size;
3196
+ return this.mediaService.setViewportSize(size);
2391
3197
  }
2392
- /**
2393
- * env-E2: 缩放变异——deviceScaleFactor 切换(CSS 像素坐标空间不变,
2394
- * 物理像素翻倍)。保留当前 CSS 视口尺寸,只换 DSF。
2395
- */
2396
3198
  async setDeviceScaleFactor(dsf) {
2397
- const size = this._viewportSize ?? await this.evaluate(
2398
- "({ width: window.innerWidth, height: window.innerHeight })"
2399
- );
2400
- await this.conn.send(
2401
- "Emulation.setDeviceMetricsOverride",
2402
- {
2403
- width: size.width,
2404
- height: size.height,
2405
- deviceScaleFactor: dsf,
2406
- mobile: false
2407
- },
2408
- this.sessionId
2409
- );
2410
- this._viewportSize = size;
3199
+ return this.mediaService.setDeviceScaleFactor(dsf);
2411
3200
  }
2412
- // ── Scripts ─────────────────────────────────────────────────
2413
3201
  async addInitScript(script) {
2414
3202
  await this.conn.send(
2415
3203
  "Page.addScriptToEvaluateOnNewDocument",
@@ -2534,86 +3322,20 @@ Last error: ${lastError.message}` : "";
2534
3322
  return frames;
2535
3323
  } catch {
2536
3324
  return [this.mainFrame()];
2537
- }
2538
- }
2539
- // ── CDP helpers exposed for locator/element ─────────────────
2540
- /** Query a single element, returns CDP nodeId or 0 if not found */
2541
- async querySelector(selector) {
2542
- if (selector.startsWith("xpath=")) {
2543
- const found = await this.evaluate(`
2544
- (() => { const el = ${queryJS(selector)}; return !!el; })()
2545
- `).catch(() => false);
2546
- if (!found) return 0;
2547
- try {
2548
- const search = await this.conn.send(
2549
- "DOM.performSearch",
2550
- { query: selector.slice(6) },
2551
- this.sessionId
2552
- );
2553
- if (search.nodeId) return search.nodeId;
2554
- } catch {
2555
- }
2556
- return 1;
2557
- }
2558
- const withTimeout = (p, ms) => Promise.race([p, new Promise((r) => setTimeout(() => r(null), ms))]);
2559
- const doc = await withTimeout(
2560
- this.conn.send("DOM.getDocument", { depth: 0 }, this.sessionId),
2561
- 8e3
2562
- );
2563
- if (!doc) return 0;
2564
- const result = await withTimeout(
2565
- this.conn.send(
2566
- "DOM.querySelector",
2567
- { nodeId: doc.root.nodeId, selector },
2568
- this.sessionId
2569
- ),
2570
- 8e3
2571
- );
2572
- if (!result) return 0;
2573
- return result.nodeId;
3325
+ }
3326
+ }
3327
+ // ── CDP helpers exposed for locator/element ─────────────────
3328
+ async querySelector(selector) {
3329
+ return this.domQueryService.querySelector(selector);
2574
3330
  }
2575
- /** Query all matching elements, returns array of CDP nodeIds */
2576
3331
  async querySelectorAll(selector) {
2577
- const doc = await this.conn.send(
2578
- "DOM.getDocument",
2579
- { depth: 0 },
2580
- this.sessionId
2581
- );
2582
- const result = await this.conn.send(
2583
- "DOM.querySelectorAll",
2584
- { nodeId: doc.root.nodeId, selector },
2585
- this.sessionId
2586
- );
2587
- return result.nodeIds ?? [];
3332
+ return this.domQueryService.querySelectorAll(selector);
2588
3333
  }
2589
- /** Resolve a CDP nodeId to a RemoteObject for evaluate */
2590
3334
  async resolveNode(nodeId) {
2591
- const result = await this.conn.send(
2592
- "DOM.resolveNode",
2593
- { nodeId },
2594
- this.sessionId
2595
- );
2596
- return result.object.objectId;
3335
+ return this.domQueryService.resolveNode(nodeId);
2597
3336
  }
2598
- /** Get the box model for a nodeId */
2599
3337
  async getBoxModel(nodeId) {
2600
- try {
2601
- const result = await this.conn.send("DOM.getBoxModel", { nodeId }, this.sessionId);
2602
- const c = result.model?.content;
2603
- if (!c || c.length < 8) return null;
2604
- const x1 = c[0];
2605
- const y1 = c[1];
2606
- const x2 = c[4];
2607
- const y2 = c[5];
2608
- return {
2609
- x: Math.min(x1, x2),
2610
- y: Math.min(y1, y2),
2611
- width: Math.abs(x2 - x1),
2612
- height: Math.abs(y2 - y1)
2613
- };
2614
- } catch {
2615
- return null;
2616
- }
3338
+ return this.domQueryService.getBoxModel(nodeId);
2617
3339
  }
2618
3340
  /** Call a function on a RemoteObject */
2619
3341
  async callFunctionOn(objectId, functionDeclaration, args = []) {
@@ -2632,9 +3354,6 @@ Last error: ${lastError.message}` : "";
2632
3354
  async _cdpSend(method, params) {
2633
3355
  return this.conn.send(method, params, this.sessionId);
2634
3356
  }
2635
- /** sup-s11: beforeunload 自动应答语义——'accept'(默认,离开页面,与录制
2636
- * 意图一致)或 'dismiss'(取消导航留守原页,尽力而为:此构建上 CDP
2637
- * accept:false 对浏览器侧导航的取消语义不稳定,不保证)。 */
2638
3357
  setBeforeUnloadBehavior(mode) {
2639
3358
  this._beforeUnloadAccept = mode === "accept";
2640
3359
  }
@@ -2657,143 +3376,37 @@ Last error: ${lastError.message}` : "";
2657
3376
  }
2658
3377
  // ── Private: Event Setup ────────────────────────────────────
2659
3378
  setupPageEvents() {
2660
- this._subscriptions.push(
2661
- this.conn.subscribe("Page.frameNavigated", this.sessionId, (params) => {
2662
- const p = params;
2663
- if (p.frame) {
2664
- this._url = p.frame.url;
2665
- }
2666
- this._emit("framenavigated", this.mainFrame());
2667
- })
2668
- );
2669
- this._subscriptions.push(
2670
- this.conn.subscribe("Page.loadEventFired", this.sessionId, () => {
3379
+ setupPageEvents({
3380
+ conn: this.conn,
3381
+ sessionId: this.sessionId,
3382
+ addSubscription: (unsubscribe) => this._subscriptions.push(unsubscribe),
3383
+ emit: (event, ...args) => this._emit(event, ...args),
3384
+ setUrl: (url) => {
3385
+ this._url = url;
3386
+ },
3387
+ currentUrl: () => this.url(),
3388
+ mainFrame: () => this.mainFrame(),
3389
+ markLoadFired: () => {
2671
3390
  this._loadState.loadFired = true;
2672
- })
2673
- );
2674
- this._subscriptions.push(
2675
- this.conn.subscribe("Page.domContentEventFired", this.sessionId, () => {
3391
+ },
3392
+ markDomContentFired: () => {
2676
3393
  this._loadState.domContentFired = true;
2677
- })
2678
- );
2679
- this._subscriptions.push(
2680
- this.conn.subscribe("Page.javascriptDialogOpening", this.sessionId, (params) => {
2681
- const p = params;
2682
- const dialog = {
2683
- type: p.type,
2684
- message: () => p.message,
2685
- defaultValue: () => p.defaultValue,
2686
- accept: async (text) => {
2687
- await this.conn.send("Page.handleJavaScriptDialog", {
2688
- accept: true,
2689
- promptText: text
2690
- }, this.sessionId);
2691
- },
2692
- dismiss: async () => {
2693
- await this.conn.send("Page.handleJavaScriptDialog", {
2694
- accept: false
2695
- }, this.sessionId);
2696
- }
2697
- };
2698
- this._emit("dialog", dialog);
2699
- const autoAccept = p.type === "beforeunload" ? this._beforeUnloadAccept : false;
2700
- setTimeout(() => {
2701
- this.conn.send("Page.handleJavaScriptDialog", { accept: autoAccept }, this.sessionId).catch(() => {
2702
- });
2703
- }, 0);
2704
- })
2705
- );
2706
- this._subscriptions.push(
2707
- this.conn.subscribe("Page.fileChooserOpened", this.sessionId, async (params) => {
2708
- const p = params;
2709
- let selector = "";
2710
- try {
2711
- const result = await this.conn.send("DOM.describeNode", { backendNodeId: p.backendNodeId }, this.sessionId);
2712
- const attrs = result.node?.attributes || [];
2713
- const idIdx = attrs.indexOf("id");
2714
- if (idIdx >= 0) selector = "#" + attrs[idIdx + 1];
2715
- } catch {
2716
- }
2717
- if (!selector) {
2718
- try {
2719
- const result = await this.conn.send("DOM.resolveNode", { backendNodeId: p.backendNodeId }, this.sessionId);
2720
- const evalResult = await this.conn.send("Runtime.callFunctionOn", {
2721
- objectId: result.objectId,
2722
- functionDeclaration: 'function() { return this.id || this.name || "" }',
2723
- returnByValue: true
2724
- }, this.sessionId);
2725
- if (evalResult.result?.value) selector = "#" + evalResult.result.value;
2726
- } catch {
2727
- }
2728
- }
2729
- const fileChooser = {
2730
- selector,
2731
- isMultiple: p.mode === "selectMultiple",
2732
- setFiles: async (files) => {
2733
- const fileArray = Array.isArray(files) ? files : [files];
2734
- await this.setInputFiles(selector || 'input[type="file"]', fileArray);
2735
- }
2736
- };
2737
- this._emit("filechooser", fileChooser);
2738
- })
2739
- );
3394
+ },
3395
+ getBeforeUnloadAccept: () => this._beforeUnloadAccept,
3396
+ setInputFiles: (selector, files) => this.setInputFiles(selector, files)
3397
+ });
2740
3398
  }
2741
3399
  setupNetworkEvents() {
2742
- this._subscriptions.push(
2743
- this.conn.subscribe("Network.requestWillBeSent", this.sessionId, (params) => {
2744
- const p = params;
2745
- this.inflightRequests.add(p.requestId);
2746
- this._storeNetworkRequest(p.requestId, {
2747
- url: p.request.url,
2748
- method: p.request.method,
2749
- headers: p.request.headers,
2750
- postData: p.request.postData ?? null,
2751
- resourceType: p.type
2752
- });
2753
- this._emit("request", createXBRequest(
2754
- null,
2755
- {
2756
- requestId: p.requestId,
2757
- url: p.request.url,
2758
- method: p.request.method,
2759
- headers: p.request.headers,
2760
- postData: p.request.postData ?? null,
2761
- resourceType: p.type
2762
- }
2763
- ));
2764
- this.checkNetworkIdle();
2765
- })
2766
- );
2767
- this._subscriptions.push(
2768
- this.conn.subscribe("Network.responseReceived", this.sessionId, (params) => {
2769
- const p = params;
2770
- this._storeNetworkResponse(p.requestId, {
2771
- status: p.response.status,
2772
- url: p.response.url,
2773
- headers: p.response.headers
2774
- });
2775
- this._emit("response", createXBResponse(
2776
- { requestId: p.requestId, status: p.response.status, url: p.response.url, headers: p.response.headers },
2777
- this.conn,
2778
- this.sessionId
2779
- ));
2780
- })
2781
- );
2782
- this._subscriptions.push(
2783
- this.conn.subscribe("Network.loadingFinished", this.sessionId, (params) => {
2784
- const p = params;
2785
- this.inflightRequests.delete(p.requestId);
2786
- this._emit("requestfinished", p);
2787
- this.checkNetworkIdle();
2788
- })
2789
- );
2790
- this._subscriptions.push(
2791
- this.conn.subscribe("Network.loadingFailed", this.sessionId, (params) => {
2792
- const p = params;
2793
- this.inflightRequests.delete(p.requestId);
2794
- this.checkNetworkIdle();
2795
- })
2796
- );
3400
+ setupNetworkEvents({
3401
+ conn: this.conn,
3402
+ sessionId: this.sessionId,
3403
+ state: { inflightRequests: this.inflightRequests },
3404
+ emit: (event, ...args) => this._emit(event, ...args),
3405
+ storeRequest: (id, data) => this._storeNetworkRequest(id, data),
3406
+ storeResponse: (id, data) => this._storeNetworkResponse(id, data),
3407
+ checkNetworkIdle: () => this.checkNetworkIdle(),
3408
+ addSubscription: (unsubscribe) => this._subscriptions.push(unsubscribe)
3409
+ });
2797
3410
  }
2798
3411
  setupConsoleEvents() {
2799
3412
  this._subscriptions.push(
@@ -2839,8 +3452,6 @@ Last error: ${lastError.message}` : "";
2839
3452
  // ── Network Data Store (for waitForResponse/waitForRequest) ──
2840
3453
  _networkResponses = /* @__PURE__ */ new Map();
2841
3454
  _networkRequests = /* @__PURE__ */ new Map();
2842
- _routeHandlers = [];
2843
- _interceptionEnabled = false;
2844
3455
  _beforeUnloadAccept = true;
2845
3456
  /** Store network data — called by browser.ts installNetworkCapture or internal event handlers */
2846
3457
  _storeNetworkRequest(requestId, data) {
@@ -2849,284 +3460,30 @@ Last error: ${lastError.message}` : "";
2849
3460
  _storeNetworkResponse(requestId, data) {
2850
3461
  this._networkResponses.set(requestId, { requestId, ...data });
2851
3462
  }
2852
- // ── waitForResponse ─────────────────────────────────────────
2853
3463
  async waitForResponse(urlOrPredicate, opts = {}) {
2854
- const timeout = opts.timeout ?? 3e4;
2855
- const predicate = createResponsePredicate(urlOrPredicate);
2856
- for (const [, data] of this._networkResponses) {
2857
- const response = createXBResponse(data, this.conn, this.sessionId);
2858
- if (predicate(response)) return response;
2859
- }
2860
- return new Promise((resolve, reject) => {
2861
- const timer = setTimeout(() => {
2862
- this._emitter.removeListener("response", handler);
2863
- reject(new Error(`waitForResponse timed out after ${timeout}ms`));
2864
- }, timeout);
2865
- const handler = (params) => {
2866
- let response;
2867
- const respObj = params;
2868
- if (respObj.response) {
2869
- const data = {
2870
- requestId: respObj.requestId || "",
2871
- status: respObj.response.status || 0,
2872
- url: respObj.response.url || "",
2873
- headers: respObj.response.headers || {}
2874
- };
2875
- response = createXBResponse(data, this.conn, this.sessionId);
2876
- } else if (typeof params.status === "function") {
2877
- response = params;
2878
- } else {
2879
- return;
2880
- }
2881
- if (predicate(response)) {
2882
- clearTimeout(timer);
2883
- this._emitter.removeListener("response", handler);
2884
- resolve(response);
2885
- }
2886
- };
2887
- this._emitter.on("response", handler);
2888
- });
2889
- }
2890
- // ── waitForRequest ──────────────────────────────────────────
2891
- async waitForRequest(urlOrPredicate, opts = {}) {
2892
- const timeout = opts.timeout ?? 3e4;
2893
- const predicate = createRequestPredicate(urlOrPredicate);
2894
- for (const [, data] of this._networkRequests) {
2895
- const request = createXBRequest(this, data);
2896
- if (predicate(request)) return request;
2897
- }
2898
- return new Promise((resolve, reject) => {
2899
- const timer = setTimeout(() => {
2900
- this._emitter.removeListener("request", handler);
2901
- reject(new Error(`waitForRequest timed out after ${timeout}ms`));
2902
- }, timeout);
2903
- const handler = (params) => {
2904
- let request;
2905
- const reqObj = params;
2906
- if (reqObj.request) {
2907
- request = createXBRequest(this, {
2908
- requestId: reqObj.requestId || "",
2909
- url: reqObj.request.url || "",
2910
- method: reqObj.request.method || "",
2911
- headers: reqObj.request.headers || {},
2912
- postData: reqObj.request.postData ?? null,
2913
- resourceType: reqObj.type || ""
2914
- });
2915
- } else if (typeof params.url === "function") {
2916
- request = params;
2917
- } else {
2918
- return;
2919
- }
2920
- if (predicate(request)) {
2921
- clearTimeout(timer);
2922
- this._emitter.removeListener("request", handler);
2923
- resolve(request);
2924
- }
2925
- };
2926
- this._emitter.on("request", handler);
2927
- });
2928
- }
2929
- // ── waitForURL ──────────────────────────────────────────────
2930
- async waitForURL(url, opts = {}) {
2931
- const timeout = opts.timeout ?? 3e4;
2932
- const checkFn = typeof url === "function" ? url : typeof url === "string" ? (current) => matchGlob(url, current) : (current) => url.test(current);
2933
- if (checkFn(this._url)) return;
2934
- return new Promise((resolve, reject) => {
2935
- const timer = setTimeout(() => {
2936
- this._emitter.removeListener("framenavigated", handler);
2937
- reject(new Error(`waitForURL timed out after ${timeout}ms`));
2938
- }, timeout);
2939
- const handler = () => {
2940
- if (checkFn(this._url)) {
2941
- clearTimeout(timer);
2942
- this._emitter.removeListener("framenavigated", handler);
2943
- resolve();
2944
- }
2945
- };
2946
- this._emitter.on("framenavigated", handler);
2947
- });
2948
- }
2949
- // ── route / unroute ─────────────────────────────────────────
2950
- async route(url, handler) {
2951
- const regex = typeof url === "string" ? globToRegex(url) : url;
2952
- this._routeHandlers.push({ pattern: String(url), regex, handler });
2953
- if (!this._interceptionEnabled) {
2954
- this._interceptionEnabled = true;
2955
- await this.conn.send("Fetch.enable", {
2956
- patterns: [{ urlPattern: "*", requestStage: "Request" }],
2957
- // sup-s9: 保留认证自动响应(Fetch.enable 为替换语义,不带此参数
2958
- // 会顶掉 _init 的 auth 配置)
2959
- handleAuthRequests: true
2960
- }, this.sessionId);
2961
- this._subscriptions.push(
2962
- this.conn.subscribe("Fetch.requestPaused", this.sessionId, (params) => {
2963
- this._handleRequestPaused(params);
2964
- })
2965
- );
2966
- }
2967
- }
2968
- async unroute(url, handler) {
2969
- const regex = typeof url === "string" ? globToRegex(url) : url;
2970
- this._routeHandlers = this._routeHandlers.filter(
2971
- (h) => !(regex.source === h.regex.source && (!handler || h.handler === handler))
2972
- );
2973
- if (this._routeHandlers.length === 0 && this._interceptionEnabled) {
2974
- this._interceptionEnabled = false;
2975
- await this.conn.send("Fetch.disable", void 0, this.sessionId).catch(() => {
2976
- });
2977
- }
2978
- }
2979
- async _handleRequestPaused(params) {
2980
- const requestUrl = params.request.url;
2981
- for (const { regex, handler } of this._routeHandlers) {
2982
- if (regex.test(requestUrl)) {
2983
- this._emit("request", createXBRequest(
2984
- null,
2985
- {
2986
- requestId: params.requestId,
2987
- url: params.request.url,
2988
- method: params.request.method,
2989
- headers: params.request.headers,
2990
- postData: params.request.postData ?? null,
2991
- resourceType: params.resourceType
2992
- }
2993
- ));
2994
- const route = createXBRouteFetch(this.conn, this.sessionId, params, this._emitter);
2995
- try {
2996
- await handler(route);
2997
- } catch {
2998
- await this.conn.send("Fetch.continueRequest", {
2999
- requestId: params.requestId
3000
- }, this.sessionId).catch(() => {
3001
- });
3002
- }
3003
- return;
3004
- }
3005
- }
3006
- await this.conn.send("Fetch.continueRequest", {
3007
- requestId: params.requestId
3008
- }, this.sessionId).catch(() => {
3009
- });
3464
+ return this.networkWaitService.waitForResponse(urlOrPredicate, opts);
3010
3465
  }
3011
- // ── setInputFiles ───────────────────────────────────────────
3012
- /**
3013
- * sup-s4: Dropzone 拖拽上传模拟——Dropzone/Uppy/自绘上传区只监听
3014
- * dragover/drop(无 input[type=file] 可点),真实用户靠 OS 文件拖入
3015
- * 触发,自动化无法产生 OS 拖拽。页内构造 DataTransfer+File,按拖放
3016
- * 协议派发 dragenter/dragover/drop(bubbles+cancelable,坐标取目标
3017
- * 中心)。
3018
- */
3019
- async dropFiles(selector, payload) {
3020
- await this.evaluate(`
3021
- (function() {
3022
- var el = ${queryJS(selector)};
3023
- if (!el) throw new Error('drop target not found: ' + ${JSON.stringify(selector)});
3024
- var b64 = ${JSON.stringify(payload.buffer.toString("base64"))};
3025
- var bin = atob(b64);
3026
- var buf = new Uint8Array(bin.length);
3027
- for (var i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
3028
- var file = new File([buf], ${JSON.stringify(payload.name)}, { type: ${JSON.stringify(payload.mimeType)} });
3029
- var dt = new DataTransfer();
3030
- dt.items.add(file);
3031
- var rect = el.getBoundingClientRect();
3032
- var opts = {
3033
- bubbles: true, cancelable: true,
3034
- clientX: rect.x + rect.width / 2, clientY: rect.y + rect.height / 2,
3035
- };
3036
- el.dispatchEvent(new DragEvent('dragenter', Object.assign({ dataTransfer: dt }, opts)));
3037
- el.dispatchEvent(new DragEvent('dragover', Object.assign({ dataTransfer: dt }, opts)));
3038
- el.dispatchEvent(new DragEvent('drop', Object.assign({ dataTransfer: dt }, opts)));
3039
- })()
3040
- `);
3466
+ async waitForRequest(urlOrPredicate, opts = {}) {
3467
+ return this.networkWaitService.waitForRequest(urlOrPredicate, opts);
3468
+ }
3469
+ async waitForURL(url, opts = {}) {
3470
+ return this.networkWaitService.waitForURL(url, opts);
3471
+ }
3472
+ async route(pattern, handler) {
3473
+ return this.networkRouteService.route(pattern, handler);
3474
+ }
3475
+ async unroute(pattern) {
3476
+ return this.networkRouteService.unroute(pattern);
3477
+ }
3478
+ async dropFiles(selector, payload) {
3479
+ return this.fileInputService.dropFiles(selector, payload);
3041
3480
  }
3042
3481
  async setInputFiles(selector, files) {
3043
- const fileArr = Array.isArray(files) ? files : [files];
3044
- const fileList = fileArr.map((f) => ({
3045
- name: f.name,
3046
- type: f.mimeType,
3047
- dataBase64: f.buffer.toString("base64")
3048
- }));
3049
- await this.evaluate(`
3050
- (function() {
3051
- var selector = ${JSON.stringify(selector)};
3052
- var input = ${queryJS(selector)};
3053
- if (!input) throw new Error('Element not found: ' + selector);
3054
-
3055
- var fileList = ${JSON.stringify(fileList)};
3056
- var dt = new DataTransfer();
3057
-
3058
- fileList.forEach(function(f) {
3059
- var binary = atob(f.dataBase64);
3060
- var bytes = new Uint8Array(binary.length);
3061
- for (var i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
3062
- var blob = new Blob([bytes], { type: f.type });
3063
- var file = new File([blob], f.name, { type: f.type });
3064
- dt.items.add(file);
3065
- });
3066
-
3067
- input.files = dt.files;
3068
- input.dispatchEvent(new Event('input', { bubbles: true }));
3069
- input.dispatchEvent(new Event('change', { bubbles: true }));
3070
- })()
3071
- `);
3482
+ return this.fileInputService.setInputFiles(selector, files);
3072
3483
  }
3073
- // ── dragAndDrop ─────────────────────────────────────────────
3074
3484
  async dragAndDrop(source, target) {
3075
- const sourceRect = await this.evaluate(`
3076
- (function() {
3077
- const el = ${queryJS(source)};
3078
- if (!el) throw new Error('Source not found: ${source}');
3079
- el.scrollIntoView({ behavior: 'instant', block: 'center' });
3080
- const r = el.getBoundingClientRect();
3081
- return { x: r.x, y: r.y, width: r.width, height: r.height };
3082
- })()
3083
- `);
3084
- const targetRect = await this.evaluate(`
3085
- (function() {
3086
- const el = ${queryJS(target)};
3087
- if (!el) throw new Error('Target not found: ${target}');
3088
- el.scrollIntoView({ behavior: 'instant', block: 'center' });
3089
- const r = el.getBoundingClientRect();
3090
- return { x: r.x, y: r.y, width: r.width, height: r.height };
3091
- })()
3092
- `);
3093
- const sx = sourceRect.x + sourceRect.width / 2;
3094
- const sy = sourceRect.y + sourceRect.height / 2;
3095
- const tx = targetRect.x + targetRect.width / 2;
3096
- const ty = targetRect.y + targetRect.height / 2;
3097
- try {
3098
- await this.conn.send("Input.dispatchDragEvent", {
3099
- type: "dragStart",
3100
- x: sx,
3101
- y: sy,
3102
- data: { items: [], dragOperations: ["copy", "move", "link"] }
3103
- }, this.sessionId);
3104
- await this.conn.send("Input.dispatchDragEvent", {
3105
- type: "dragOver",
3106
- x: tx,
3107
- y: ty,
3108
- data: { items: [], dragOperations: ["copy", "move", "link"] }
3109
- }, this.sessionId);
3110
- await this.conn.send("Input.dispatchDragEvent", {
3111
- type: "drop",
3112
- x: tx,
3113
- y: ty,
3114
- data: { items: [], dragOperations: ["copy", "move", "link"] }
3115
- }, this.sessionId);
3116
- await this.conn.send("Input.dispatchDragEvent", {
3117
- type: "dragCancel",
3118
- x: sx,
3119
- y: sy,
3120
- data: { items: [], dragOperations: ["copy", "move", "link"] }
3121
- }, this.sessionId);
3122
- } catch {
3123
- await this.mouse.move(sx, sy);
3124
- await this.mouse.down();
3125
- await this.mouse.move(tx, ty, { steps: 10 });
3126
- await this.mouse.up();
3127
- }
3485
+ return this.fileInputService.dragAndDrop(source, target);
3128
3486
  }
3129
- // ── setOfflineMode ──────────────────────────────────────────
3130
3487
  async setOfflineMode(offline) {
3131
3488
  await this.conn.send("Network.emulateNetworkConditions", {
3132
3489
  offline,
@@ -3422,7 +3779,7 @@ var XBBrowserImpl = class {
3422
3779
  this._exitHandler = null;
3423
3780
  }
3424
3781
  if (this.childProcess) {
3425
- const { killChrome: killChrome2 } = await import("./launcher-XHKIC4GP.js");
3782
+ const { killChrome: killChrome2 } = await import("./launcher-ZYB32LSZ.js");
3426
3783
  await killChrome2(this.childProcess, this.tmpDir);
3427
3784
  }
3428
3785
  await this.conn.close();
@@ -3592,7 +3949,7 @@ var XBBrowserImpl = class {
3592
3949
  if (pageTargets.length === 0 && httpFallbackUrl) {
3593
3950
  console.log(`[discoverContexts] Target.getTargets returned ${targetInfos.length} targets (0 page type). Falling back to HTTP /json/list at ${httpFallbackUrl}`);
3594
3951
  try {
3595
- const { getCDPTargets: getCDPTargets3 } = await import("./launcher-XHKIC4GP.js");
3952
+ const { getCDPTargets: getCDPTargets3 } = await import("./launcher-ZYB32LSZ.js");
3596
3953
  const httpPages = await getCDPTargets3(httpFallbackUrl);
3597
3954
  console.log(`[discoverContexts] HTTP /json/list returned ${httpPages.length} pages`);
3598
3955
  for (const p of httpPages) {
@@ -4038,6 +4395,149 @@ Or add random variation: page.type(selector, text, {delay: 50 + Math.random() *
4038
4395
  return null;
4039
4396
  }
4040
4397
 
4398
+ // src/cdp-interceptor/rules/humanize-transform.ts
4399
+ var CURSOR_KEY = "humanize-cursor";
4400
+ var KEYS_KEY = "humanize-keys";
4401
+ var MOUSE_STEP_DELAYS = [16, 19, 23, 28];
4402
+ var TYPE_DELAYS = [42, 58, 74, 96, 118, 155, 210];
4403
+ function rand2(min, max) {
4404
+ return min + Math.random() * (max - min);
4405
+ }
4406
+ function roundCoordinate(value) {
4407
+ return Math.round(value * 100) / 100;
4408
+ }
4409
+ function humanMousePath(fromX, fromY, toX, toY) {
4410
+ const dist = Math.hypot(toX - fromX, toY - fromY);
4411
+ const n = Math.max(8, Math.min(28, Math.round(dist / 15)));
4412
+ const shortMove = dist < 120;
4413
+ const curvature = shortMove ? rand2(2, 6) : Math.max(dist * rand2(0.12, 0.22), rand2(18, 35));
4414
+ const dir = Math.random() < 0.5 ? 1 : -1;
4415
+ const dx = toX - fromX;
4416
+ const dy = toY - fromY;
4417
+ const d = dist || 1;
4418
+ const c1x = fromX + dx * 0.3 - dy / d * curvature * 0.5 * dir;
4419
+ const c1y = fromY + dy * 0.3 + dx / d * curvature * 0.5 * dir;
4420
+ const c2x = fromX + dx * 0.7 - dy / d * curvature * 0.8 * dir;
4421
+ const c2y = fromY + dy * 0.7 + dx / d * curvature * 0.8 * dir;
4422
+ const amp = shortMove ? Math.min(2, 3.2) : 3.2;
4423
+ const points = [];
4424
+ for (let i = 1; i <= n; i++) {
4425
+ const t = i / n;
4426
+ const eased = t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;
4427
+ const mt = 1 - eased;
4428
+ const px = mt ** 3 * fromX + 3 * mt ** 2 * eased * c1x + 3 * mt * eased ** 2 * c2x + eased ** 3 * toX;
4429
+ const py = mt ** 3 * fromY + 3 * mt ** 2 * eased * c1y + 3 * mt * eased ** 2 * c2y + eased ** 3 * toY;
4430
+ points.push({
4431
+ x: roundCoordinate(px + rand2(-amp, amp)),
4432
+ y: roundCoordinate(py + rand2(-amp, amp)),
4433
+ delay: MOUSE_STEP_DELAYS[Math.floor(Math.random() * MOUSE_STEP_DELAYS.length)]
4434
+ });
4435
+ }
4436
+ if (!shortMove) {
4437
+ const over = rand2(6, 14);
4438
+ points.push({
4439
+ x: roundCoordinate(toX + dx / d * over + rand2(-2, 2)),
4440
+ y: roundCoordinate(toY + dy / d * over + rand2(-2, 2)),
4441
+ delay: Math.round(rand2(14, 30))
4442
+ });
4443
+ points.push({
4444
+ x: roundCoordinate(toX + dx / d * over * 0.4),
4445
+ y: roundCoordinate(toY + dy / d * over * 0.4),
4446
+ delay: Math.round(rand2(14, 30))
4447
+ });
4448
+ }
4449
+ points.push({
4450
+ x: roundCoordinate(toX + rand2(-1, 1)),
4451
+ y: roundCoordinate(toY + rand2(-1, 1)),
4452
+ delay: Math.round(rand2(14, 30))
4453
+ });
4454
+ return points;
4455
+ }
4456
+ function characterKeyEvents(text) {
4457
+ const events = [];
4458
+ for (const char of text) {
4459
+ if (char === "\n") {
4460
+ events.push(
4461
+ { type: "rawKeyDown", key: "Enter", code: "Enter", windowsVirtualKeyCode: 13 },
4462
+ { type: "char", text: "\r" },
4463
+ { type: "keyUp", key: "Enter", code: "Enter", windowsVirtualKeyCode: 13 }
4464
+ );
4465
+ continue;
4466
+ }
4467
+ events.push(
4468
+ { type: "rawKeyDown", key: char, text: char, unmodifiedText: char },
4469
+ { type: "char", text: char },
4470
+ { type: "keyUp", key: char }
4471
+ );
4472
+ }
4473
+ return events;
4474
+ }
4475
+ function isMouseEvent(method) {
4476
+ return method === "Input.dispatchMouseEvent";
4477
+ }
4478
+ var humanizeTransformRule = {
4479
+ id: "humanize-transform",
4480
+ name: "Humanize Trusted Input Transform",
4481
+ priority: 45,
4482
+ canHandle(ctx) {
4483
+ return isMouseEvent(ctx.method) || ctx.method === "Input.insertText";
4484
+ },
4485
+ evaluate(ctx) {
4486
+ if (ctx.method === "Input.insertText") return this.transformInsertText(ctx);
4487
+ return this.transformMouseEvent(ctx);
4488
+ },
4489
+ transformMouseEvent(ctx) {
4490
+ const params = ctx.params;
4491
+ if (params.type !== "mouseMoved" || typeof params.x !== "number" || typeof params.y !== "number") {
4492
+ const x = params.x;
4493
+ const y = params.y;
4494
+ if (typeof x === "number" && typeof y === "number") {
4495
+ ctx.sessionState.set(CURSOR_KEY, { x, y });
4496
+ }
4497
+ return null;
4498
+ }
4499
+ const cursor = ctx.sessionState.get(CURSOR_KEY) ?? { x: 0, y: 0 };
4500
+ const jump = Math.hypot(params.x - cursor.x, params.y - cursor.y);
4501
+ ctx.sessionState.set(CURSOR_KEY, { x: params.x, y: params.y });
4502
+ if (jump < 32) return null;
4503
+ const path = humanMousePath(cursor.x, cursor.y, params.x, params.y);
4504
+ return {
4505
+ ruleId: this.id,
4506
+ action: "transform",
4507
+ severity: "info",
4508
+ reason: `Expanded instant mouse jump of ${jump.toFixed(0)}px into ${path.length} trusted bezier moves.`,
4509
+ suggestion: "Use page.mouse.move with steps for explicit control; this transform preserves isTrusted=true.",
4510
+ transformedParams: { __sequence: path.map((point) => ({
4511
+ method: "Input.dispatchMouseEvent",
4512
+ params: { type: "mouseMoved", x: point.x, y: point.y, button: params.button ?? "none" },
4513
+ delayMs: point.delay
4514
+ })) }
4515
+ };
4516
+ },
4517
+ transformInsertText(ctx) {
4518
+ const params = ctx.params;
4519
+ const text = params.text ?? "";
4520
+ if (!text) return null;
4521
+ const timing = ctx.sessionState.get(KEYS_KEY) ?? { lastDelay: TYPE_DELAYS[1] };
4522
+ const bucket = TYPE_DELAYS[Math.floor(Math.random() * TYPE_DELAYS.length)];
4523
+ const events = characterKeyEvents(text).map((event, index) => ({
4524
+ method: "Input.dispatchKeyEvent",
4525
+ params: event,
4526
+ delayMs: index === 0 ? 0 : Math.max(24, Math.round(bucket + rand2(-bucket * 0.45, bucket * 0.55)))
4527
+ }));
4528
+ timing.lastDelay = bucket;
4529
+ ctx.sessionState.set(KEYS_KEY, timing);
4530
+ return {
4531
+ ruleId: this.id,
4532
+ action: "transform",
4533
+ severity: "info",
4534
+ reason: `Expanded Input.insertText (${text.length} chars) into ${events.length} trusted key events with variable rhythm.`,
4535
+ suggestion: "Use page.type for explicit control; this transform preserves the native keyboard command stream.",
4536
+ transformedParams: { __sequence: events }
4537
+ };
4538
+ }
4539
+ };
4540
+
4041
4541
  // src/cdp-interceptor/rules/automation-signals.ts
4042
4542
  var AUTOMATION_PATTERNS = [
4043
4543
  // ── Playwright markers ─────────────────────────
@@ -4556,6 +5056,7 @@ var BUILTIN_RULES = [
4556
5056
  eventSimulationRule,
4557
5057
  mouseTrajectoryRule,
4558
5058
  inputKeystrokeRule,
5059
+ humanizeTransformRule,
4559
5060
  emulationOverrideRule,
4560
5061
  networkAnomalyRule,
4561
5062
  pageLifecycleRule
@@ -4588,8 +5089,10 @@ function createRuleEngine(customRules) {
4588
5089
  if (isProbeMarked(code)) return null;
4589
5090
  } catch {
4590
5091
  }
5092
+ const humanizeEnabled = process.env.XBROWSER_HUMANIZE_CDP === "on";
4591
5093
  for (const rule of rules) {
4592
5094
  if (rule.canHandle && !rule.canHandle(fullCtx)) continue;
5095
+ if (rule.id === "humanize-transform" && !humanizeEnabled) continue;
4593
5096
  const decision = rule.evaluate(fullCtx);
4594
5097
  if (!decision) continue;
4595
5098
  if (decision.action !== "pass") return decision;
@@ -4731,6 +5234,15 @@ var CDPConnection = class _CDPConnection extends EventEmitter4 {
4731
5234
  if (decision && decision.action === "block") {
4732
5235
  throw new Error(`[CDP-Guard] ${decision.reason}${decision.suggestion ? " | \u66FF\u4EE3: " + decision.suggestion : ""} [${decision.ruleId}]`);
4733
5236
  }
5237
+ if (decision && decision.action === "transform" && Array.isArray(decision.transformedParams?.__sequence)) {
5238
+ const sequence = decision.transformedParams.__sequence;
5239
+ let last;
5240
+ for (const step of sequence) {
5241
+ if (step.delayMs) await new Promise((resolve) => setTimeout(resolve, step.delayMs));
5242
+ last = await this.send(step.method, step.params, sessionId, effectiveTimeout);
5243
+ }
5244
+ return last;
5245
+ }
4734
5246
  }
4735
5247
  if (this.closed) {
4736
5248
  throw new Error(`CDP connection closed: ${this.closeReason ?? "unknown"}`);
@@ -4913,7 +5425,7 @@ async function launch(options = {}) {
4913
5425
  const bv = await conn.send("Browser.getVersion");
4914
5426
  const m = bv.product.match(/(\d+)\.(\d+)\.(\d+)\.(\d+)/);
4915
5427
  if (m && !options.stealthConfig?.uaChProfile) {
4916
- const { deriveUaChProfileForBinary } = await import("./stealth-MHJNBJY7.js");
5428
+ const { deriveUaChProfileForBinary } = await import("./stealth-MCKFKPZ6.js");
4917
5429
  stealthOpts = { stealthConfig: { uaChProfile: deriveUaChProfileForBinary(m[0], m[1]) } };
4918
5430
  }
4919
5431
  } catch {
@@ -4928,6 +5440,9 @@ async function launch(options = {}) {
4928
5440
  return { browser, wsEndpoint };
4929
5441
  }
4930
5442
 
5443
+ // src/browser/connection.ts
5444
+ import { existsSync } from "fs";
5445
+
4931
5446
  // src/cdp-interceptor/proxy.ts
4932
5447
  import { WebSocketServer, WebSocket as WebSocket2 } from "ws";
4933
5448
 
@@ -5307,236 +5822,101 @@ ${blockMsg}
5307
5822
  return;
5308
5823
  }
5309
5824
  if (decision?.action === "transform" && decision.transformedParams) {
5310
- const transformed = { ...request, params: decision.transformedParams };
5311
- this.stats.transformedMessages++;
5312
- browserWs.send(JSON.stringify(transformed));
5313
- return;
5314
- }
5315
- this.stats.passedMessages++;
5316
- browserWs.send(raw.toString());
5317
- }
5318
- handleBrowserMessage(clientWs, _browserWs, raw) {
5319
- const msg = this.parseMessage(raw);
5320
- if (!msg) {
5321
- clientWs.send(raw.toString());
5322
- return;
5323
- }
5324
- if ("method" in msg) {
5325
- const event = msg;
5326
- const ctx = {
5327
- method: event.method,
5328
- params: event.params ?? {},
5329
- sessionId: event.sessionId ?? "browser",
5330
- direction: "browser\u2192client"
5331
- };
5332
- const decision = this.engine.evaluate(ctx);
5333
- if (decision?.action === "block") {
5334
- return;
5335
- }
5336
- }
5337
- clientWs.send(raw.toString());
5338
- }
5339
- // ── Utilities ────────────────────────────────────────────────
5340
- parseMessage(raw) {
5341
- try {
5342
- return JSON.parse(raw.toString());
5343
- } catch {
5344
- return null;
5345
- }
5346
- }
5347
- recordDecision(decision) {
5348
- if (!this.stats.byRule[decision.ruleId]) {
5349
- this.stats.byRule[decision.ruleId] = { matched: 0, blocked: 0, transformed: 0 };
5350
- }
5351
- this.stats.byRule[decision.ruleId].matched++;
5352
- if (decision.action === "block") {
5353
- this.stats.byRule[decision.ruleId].blocked++;
5354
- } else if (decision.action === "transform") {
5355
- this.stats.byRule[decision.ruleId].transformed++;
5356
- }
5357
- }
5358
- };
5359
-
5360
- // src/utils/cdp.ts
5361
- async function fetchNoProxy(url) {
5362
- const savedProxy = {
5363
- http_proxy: process.env.http_proxy,
5364
- https_proxy: process.env.https_proxy,
5365
- HTTP_PROXY: process.env.HTTP_PROXY,
5366
- HTTPS_PROXY: process.env.HTTPS_PROXY,
5367
- all_proxy: process.env.all_proxy,
5368
- ALL_PROXY: process.env.ALL_PROXY
5369
- };
5370
- for (const key of Object.keys(savedProxy)) delete process.env[key];
5371
- try {
5372
- return await fetch(url);
5373
- } finally {
5374
- for (const [key, val] of Object.entries(savedProxy)) {
5375
- if (val !== void 0) process.env[key] = val;
5376
- }
5377
- }
5378
- }
5379
- async function resolveCDPEndpoint(raw) {
5380
- if (raw === "auto") {
5381
- const ports = [9222, 9221, 9223, 9224];
5382
- for (const port of ports) {
5383
- try {
5384
- const httpResp = await fetchNoProxy(`http://localhost:${port}/json/version`);
5385
- if (httpResp.ok) {
5386
- const data = await httpResp.json();
5387
- if (data.webSocketDebuggerUrl) {
5388
- return data.webSocketDebuggerUrl;
5825
+ const sequence = decision.transformedParams.__sequence;
5826
+ if (Array.isArray(sequence)) {
5827
+ this.stats.transformedMessages++;
5828
+ const dispatch = async () => {
5829
+ for (const step of sequence) {
5830
+ if (step.delayMs) await new Promise((resolve) => setTimeout(resolve, step.delayMs));
5831
+ const transformed2 = { id: request.id, method: step.method, params: step.params, sessionId: request.sessionId };
5832
+ browserWs.send(JSON.stringify(transformed2));
5389
5833
  }
5390
- }
5391
- } catch {
5392
- }
5393
- }
5394
- throw new Error(
5395
- `Could not auto-discover CDP endpoint. Tried ports: ${ports.join(", ")}.
5396
- \u53EF\u80FD\u539F\u56E0\uFF1A\u6CA1\u6709 Chrome \u4EE5 --remote-debugging-port \u542F\u52A8\u3002
5397
- \u89E3\u51B3\u65B9\u6CD5\uFF1A
5398
- 1. \u542F\u52A8 Chrome: google-chrome --remote-debugging-port=9222
5399
- 2. \u6216\u7528 cdp-tunnel: npx cdp-tunnel setup
5400
- 3. \u6216\u6307\u5B9A\u7AEF\u53E3: --cdp <port>`
5401
- );
5402
- }
5403
- if (/^\d+$/.test(raw)) {
5404
- const port = raw;
5405
- const httpResp = await fetchNoProxy(`http://localhost:${port}/json/version`);
5406
- const data = await httpResp.json();
5407
- if (!data.webSocketDebuggerUrl) {
5408
- throw new Error(`Could not discover CDP endpoint from localhost:${port}`);
5409
- }
5410
- return data.webSocketDebuggerUrl;
5411
- }
5412
- if (raw.startsWith("http://") || raw.startsWith("https://")) {
5413
- try {
5414
- const u = new URL(raw);
5415
- u.pathname = (u.pathname.replace(/\/+$/, "") || "") + "/json/version";
5416
- const httpResp = await fetchNoProxy(u.toString());
5417
- const data = await httpResp.json();
5418
- if (!data.webSocketDebuggerUrl) {
5419
- throw new Error(`Could not discover CDP endpoint from ${raw}`);
5420
- }
5421
- return data.webSocketDebuggerUrl;
5422
- } catch (error) {
5423
- console.warn(`Failed to fetch WebSocket URL from ${raw}, using endpoint directly: ${error instanceof Error ? error.message : String(error)}`);
5424
- return raw;
5425
- }
5426
- }
5427
- return raw;
5428
- }
5429
-
5430
- // src/browser.ts
5431
- import { SessionStore } from "@dyyz1993/xcli-core";
5432
- function logSessionEvent(event, details) {
5433
- const ts = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
5434
- const pid = process.pid;
5435
- console.error(`[SESSION] ${ts} [PID:${pid}] ${event} | ${details}`);
5436
- }
5437
- var SESSION_DIR = join2(homedir(), ".xbrowser", "sessions");
5438
- function sessionFile(name) {
5439
- return join2(SESSION_DIR, `${name}.json`);
5440
- }
5441
- function ensureSessionDir() {
5442
- mkdirSync2(SESSION_DIR, { recursive: true });
5443
- }
5444
- var sessions = new SessionStore();
5445
- var _sharedBrowser = null;
5446
- var _sharedCdpProxy = null;
5447
- var IDLE_TIMEOUT_MS = (process.env.XBROWSER_IDLE_TIMEOUT ? parseInt(process.env.XBROWSER_IDLE_TIMEOUT, 10) : 30) * 60 * 1e3;
5448
- var idleTimer = null;
5449
- function resetIdleTimer() {
5450
- if (idleTimer) clearTimeout(idleTimer);
5451
- idleTimer = setTimeout(async () => {
5452
- const now = Date.now();
5453
- let allIdle = true;
5454
- const idleSessions = [];
5455
- for (const s of sessions) {
5456
- if (now - s.lastActivityAt < IDLE_TIMEOUT_MS) {
5457
- allIdle = false;
5458
- } else {
5459
- idleSessions.push(`${s.name}(${(now - s.lastActivityAt) / 1e3}s idle)`);
5460
- }
5461
- }
5462
- if (allIdle && (sessions.size > 0 || _sharedBrowser)) {
5463
- logSessionEvent("idle_timeout", `Sessions idle for >${IDLE_TIMEOUT_MS / 6e4}min. Sessions: ${idleSessions.join(", ") || "all"}. Calling destroyBrowser()`);
5464
- await destroyBrowser().catch(() => {
5465
- });
5834
+ };
5835
+ void dispatch();
5836
+ return;
5837
+ }
5838
+ const transformed = { ...request, params: decision.transformedParams };
5839
+ this.stats.transformedMessages++;
5840
+ browserWs.send(JSON.stringify(transformed));
5841
+ return;
5466
5842
  }
5467
- }, IDLE_TIMEOUT_MS);
5468
- if (idleTimer && typeof idleTimer.unref === "function") {
5469
- idleTimer.unref();
5843
+ this.stats.passedMessages++;
5844
+ browserWs.send(raw.toString());
5470
5845
  }
5471
- }
5472
- function touchSession(id) {
5473
- const s = sessions.get(id);
5474
- if (s) s.lastActivityAt = Date.now();
5475
- resetIdleTimer();
5476
- }
5477
- process.on("exit", () => {
5478
- for (const session of sessions.list()) {
5479
- if (session.isCDP) {
5480
- logSessionEvent("process_exit", `Session "${session.name}": CDP connection (not closing external browser).`);
5481
- } else {
5482
- logSessionEvent("process_exit", `Session "${session.name}": Closing self-launched browser.`);
5483
- try {
5484
- session.browser?.close();
5485
- } catch {
5846
+ handleBrowserMessage(clientWs, _browserWs, raw) {
5847
+ const msg = this.parseMessage(raw);
5848
+ if (!msg) {
5849
+ clientWs.send(raw.toString());
5850
+ return;
5851
+ }
5852
+ if ("method" in msg) {
5853
+ const event = msg;
5854
+ const ctx = {
5855
+ method: event.method,
5856
+ params: event.params ?? {},
5857
+ sessionId: event.sessionId ?? "browser",
5858
+ direction: "browser\u2192client"
5859
+ };
5860
+ const decision = this.engine.evaluate(ctx);
5861
+ if (decision?.action === "block") {
5862
+ return;
5486
5863
  }
5487
5864
  }
5865
+ clientWs.send(raw.toString());
5488
5866
  }
5489
- if (_sharedBrowser) {
5490
- logSessionEvent("process_exit", "Closing shared browser (self-launched only, external CDP is safe).");
5867
+ // ── Utilities ────────────────────────────────────────────────
5868
+ parseMessage(raw) {
5491
5869
  try {
5492
- _sharedBrowser.close();
5870
+ return JSON.parse(raw.toString());
5493
5871
  } catch {
5872
+ return null;
5494
5873
  }
5495
- _sharedBrowser = null;
5496
5874
  }
5497
- if (_sharedCdpProxy) {
5498
- try {
5499
- _sharedCdpProxy.stop();
5500
- } catch {
5875
+ recordDecision(decision) {
5876
+ if (!this.stats.byRule[decision.ruleId]) {
5877
+ this.stats.byRule[decision.ruleId] = { matched: 0, blocked: 0, transformed: 0 };
5878
+ }
5879
+ this.stats.byRule[decision.ruleId].matched++;
5880
+ if (decision.action === "block") {
5881
+ this.stats.byRule[decision.ruleId].blocked++;
5882
+ } else if (decision.action === "transform") {
5883
+ this.stats.byRule[decision.ruleId].transformed++;
5501
5884
  }
5502
- _sharedCdpProxy = null;
5503
5885
  }
5504
- sessions.clear();
5505
- });
5886
+ };
5887
+
5888
+ // src/browser/connection.ts
5506
5889
  async function getCDPTargets2(cdpEndpoint) {
5507
5890
  try {
5508
- const ep = String(cdpEndpoint);
5891
+ const endpoint = String(cdpEndpoint);
5509
5892
  let url = "http://localhost:9222/json/list";
5510
- if (ep.startsWith("http://") || ep.startsWith("https://")) {
5511
- const u = new URL(ep);
5512
- u.pathname = (u.pathname.replace(/\/+$/, "") || "") + "/json/list";
5513
- url = u.toString();
5514
- } else if (/^\d+$/.test(ep)) {
5515
- url = `http://localhost:${ep}/json/list`;
5516
- }
5517
- const resp = await fetch(url);
5518
- return await resp.json();
5893
+ if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) {
5894
+ const parsed = new URL(endpoint);
5895
+ parsed.pathname = (parsed.pathname.replace(/\/+$/, "") || "") + "/json/list";
5896
+ url = parsed.toString();
5897
+ } else if (/^\d+$/.test(endpoint)) {
5898
+ url = `http://localhost:${endpoint}/json/list`;
5899
+ }
5900
+ const response = await fetch(url);
5901
+ return await response.json();
5519
5902
  } catch {
5520
5903
  return [];
5521
5904
  }
5522
5905
  }
5523
5906
  async function findTargetPage(cdpEndpoint, target) {
5524
5907
  const targets = await getCDPTargets2(cdpEndpoint);
5525
- const pages = targets.filter((t) => t.url && !t.url.startsWith("about:blank") && !t.url.startsWith("chrome://") && !t.url.startsWith("chrome-untrusted://") && !t.url.startsWith("chrome-error://"));
5526
- const byId = pages.find((t) => t.id === target);
5908
+ const pages = targets.filter((item) => item.url && !item.url.startsWith("about:blank") && !item.url.startsWith("chrome://") && !item.url.startsWith("chrome-untrusted://") && !item.url.startsWith("chrome-error://"));
5909
+ const byId = pages.find((item) => item.id === target);
5527
5910
  if (byId) return { pageId: byId.id, wsUrl: byId.webSocketDebuggerUrl, title: byId.title, url: byId.url };
5528
5911
  const lowerTarget = target.toLowerCase();
5529
- const byTitle = pages.find((t) => t.title && t.title.toLowerCase().includes(lowerTarget));
5912
+ const byTitle = pages.find((item) => item.title?.toLowerCase().includes(lowerTarget));
5530
5913
  if (byTitle) return { pageId: byTitle.id, wsUrl: byTitle.webSocketDebuggerUrl, title: byTitle.title, url: byTitle.url };
5531
- const byUrl = pages.find((t) => t.url.toLowerCase().includes(lowerTarget));
5914
+ const byUrl = pages.find((item) => item.url.toLowerCase().includes(lowerTarget));
5532
5915
  if (byUrl) return { pageId: byUrl.id, wsUrl: byUrl.webSocketDebuggerUrl, title: byUrl.title, url: byUrl.url };
5533
5916
  return null;
5534
5917
  }
5535
5918
  function resolveLaunchOpts(ctx) {
5536
- if (ctx.cdpEndpoint) {
5537
- return { cdpEndpoint: ctx.cdpEndpoint };
5538
- }
5539
- return { headless: true };
5919
+ return ctx.cdpEndpoint ? { cdpEndpoint: ctx.cdpEndpoint } : { headless: true };
5540
5920
  }
5541
5921
  var CHROMIUM_CANDIDATES = [
5542
5922
  "/Applications/Chromium.app/Contents/MacOS/Chromium",
@@ -5546,57 +5926,58 @@ var CHROMIUM_CANDIDATES = [
5546
5926
  "/usr/bin/google-chrome"
5547
5927
  ];
5548
5928
  function discoverChromiumPath() {
5549
- for (const p of CHROMIUM_CANDIDATES) {
5550
- if (existsSync(p)) return p;
5551
- }
5552
- return void 0;
5929
+ return CHROMIUM_CANDIDATES.find((path) => existsSync(path));
5930
+ }
5931
+ var browserPool = /* @__PURE__ */ new Map();
5932
+ var sharedCdpProxy = null;
5933
+ function getSharedCdpProxy() {
5934
+ return sharedCdpProxy;
5935
+ }
5936
+ function setSharedCdpProxy(proxy) {
5937
+ sharedCdpProxy = proxy;
5553
5938
  }
5554
- var _browserPool = /* @__PURE__ */ new Map();
5555
5939
  async function createBrowser(options) {
5556
5940
  if (options?.cdpEndpoint) {
5557
5941
  const realEndpoint = await resolveCDPEndpoint(options.cdpEndpoint);
5558
5942
  if (!options.intercept) {
5559
- const pooled = _browserPool.get(realEndpoint);
5560
- if (pooled && !pooled.disconnected) {
5561
- return pooled;
5562
- }
5563
- if (pooled) _browserPool.delete(realEndpoint);
5943
+ const pooled = browserPool.get(realEndpoint);
5944
+ if (pooled && !pooled.disconnected) return pooled;
5945
+ if (pooled) browserPool.delete(realEndpoint);
5564
5946
  }
5565
5947
  if (options.intercept) {
5566
5948
  const config = typeof options.intercept === "object" ? { ...options.intercept, cdpEndpoint: realEndpoint } : { cdpEndpoint: realEndpoint };
5567
- _sharedCdpProxy = new CDPInterceptorProxy(config);
5568
- const proxyPort = await _sharedCdpProxy.start();
5949
+ sharedCdpProxy = new CDPInterceptorProxy(config);
5950
+ const proxyPort = await sharedCdpProxy.start();
5569
5951
  console.error(`[CDP Interceptor] Proxy running on ws://localhost:${proxyPort}, forwarding to ${realEndpoint}`);
5570
5952
  const { browser: browser3 } = await launch({ cdpEndpoint: `ws://localhost:${proxyPort}` });
5571
5953
  return browser3;
5572
5954
  }
5573
5955
  const { browser: browser2 } = await launch({ cdpEndpoint: realEndpoint });
5574
- await browser2.discoverContexts().catch((err) => {
5575
- console.error(`[browser] discoverContexts failed: ${errMsg(err)}`);
5956
+ await browser2.discoverContexts().catch((error) => {
5957
+ console.error(`[browser] discoverContexts failed: ${errMsg(error)}`);
5576
5958
  });
5577
- if (!options.intercept) _browserPool.set(realEndpoint, browser2);
5959
+ browserPool.set(realEndpoint, browser2);
5578
5960
  return browser2;
5579
5961
  }
5580
5962
  const executablePath = options?.executablePath || process.env.XBROWSER_CHROMIUM_PATH || discoverChromiumPath();
5581
5963
  const { browser } = await launch({ executablePath, headless: options?.headless ?? true });
5582
5964
  return browser;
5583
5965
  }
5584
- async function getBrowser(options) {
5585
- if (_sharedBrowser) return _sharedBrowser;
5586
- _sharedBrowser = await createBrowser(options);
5587
- if (options?.cdpEndpoint && options.intercept) {
5588
- }
5589
- return _sharedBrowser;
5590
- }
5591
- function findSession(name) {
5592
- return sessions.find(name);
5593
- }
5594
- function getSessionById(id) {
5595
- return sessions.get(id);
5966
+
5967
+ // src/browser/state.ts
5968
+ import { randomUUID } from "crypto";
5969
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync, readdirSync, unlinkSync, writeFileSync } from "fs";
5970
+ import { join as join2 } from "path";
5971
+ import { homedir } from "os";
5972
+ import { SessionStore } from "@dyyz1993/xcli-core";
5973
+ var SESSION_DIR = join2(homedir(), ".xbrowser", "sessions");
5974
+ var sessions = new SessionStore();
5975
+ var sharedState = { browser: null, idleTimer: null };
5976
+ function sessionFile(name) {
5977
+ return join2(SESSION_DIR, `${name}.json`);
5596
5978
  }
5597
- function setActivePage(session, page) {
5598
- session.page = page;
5599
- session.lastActivityAt = Date.now();
5979
+ function ensureSessionDir() {
5980
+ mkdirSync2(SESSION_DIR, { recursive: true });
5600
5981
  }
5601
5982
  function saveSessionDiskMeta(name, data) {
5602
5983
  ensureSessionDir();
@@ -5610,20 +5991,40 @@ function saveSessionDiskMeta(name, data) {
5610
5991
  writeFileSync(file, JSON.stringify(existing, null, 2));
5611
5992
  }
5612
5993
  function readSessionDiskMeta(name) {
5613
- const file = sessionFile(name);
5614
5994
  try {
5615
- return JSON.parse(readFileSync(file, "utf8"));
5995
+ return JSON.parse(readFileSync(sessionFile(name), "utf8"));
5616
5996
  } catch {
5617
5997
  return null;
5618
5998
  }
5619
5999
  }
5620
6000
  function deleteSessionDiskMeta(name) {
5621
- const file = sessionFile(name);
5622
6001
  try {
5623
- unlinkSync(file);
6002
+ unlinkSync(sessionFile(name));
5624
6003
  } catch {
5625
6004
  }
5626
6005
  }
6006
+ function newSessionId() {
6007
+ return randomUUID();
6008
+ }
6009
+
6010
+ // src/browser/lifecycle.ts
6011
+ function registerSession(session) {
6012
+ const complete = {
6013
+ id: session.id ?? newSessionId(),
6014
+ createdAt: session.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
6015
+ lastActivityAt: session.lastActivityAt ?? Date.now(),
6016
+ ...session
6017
+ };
6018
+ sessions.set(complete);
6019
+ resetIdleTimer();
6020
+ return complete;
6021
+ }
6022
+
6023
+ // src/browser/restore.ts
6024
+ function logSessionEvent(event, details) {
6025
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
6026
+ console.error(`[SESSION] ${timestamp} [PID:${process.pid}] ${event} | ${details}`);
6027
+ }
5627
6028
  async function isSessionPageAlive(session) {
5628
6029
  const page = session.page;
5629
6030
  if (!page || typeof page.evaluate !== "function") return false;
@@ -5635,69 +6036,65 @@ async function isSessionPageAlive(session) {
5635
6036
  ]);
5636
6037
  return true;
5637
6038
  } catch {
5638
- await new Promise((r) => setTimeout(r, 400));
6039
+ await new Promise((resolve) => setTimeout(resolve, 400));
5639
6040
  }
5640
6041
  }
5641
6042
  return false;
5642
6043
  }
5643
- async function findOrRestoreSession(name, cdpEndpoint) {
5644
- const inMem = findSession(name);
5645
- if (inMem) {
5646
- if (await isSessionPageAlive(inMem)) return inMem;
5647
- logSessionEvent("stale_session", `name="${name}" \u2014 page \u63A2\u9488\u5931\u8D25\uFF08\u6D4F\u89C8\u5668\u53EF\u80FD\u5DF2\u91CD\u542F\uFF09\uFF0C\u5C31\u5730\u91CD\u5EFA`);
6044
+ async function findOrRestoreSession(name, cdpEndpoint, cleanup = async () => false, installNetworkCapture2 = async () => {
6045
+ }) {
6046
+ const inMemory = findSession(name);
6047
+ if (inMemory) {
6048
+ if (await isSessionPageAlive(inMemory)) return inMemory;
6049
+ logSessionEvent("stale_session", `name="${name}" \u2014 page probe failed; rebuilding`);
5648
6050
  try {
5649
- await closeSessionByName(name);
6051
+ await cleanup(name);
5650
6052
  } catch {
5651
6053
  }
5652
6054
  }
5653
6055
  const meta = readSessionDiskMeta(name);
5654
6056
  if (!meta) return void 0;
5655
- const ep = cdpEndpoint || meta.cdpEndpoint;
5656
- if (!ep) return void 0;
6057
+ const endpoint = cdpEndpoint || meta.cdpEndpoint;
6058
+ if (!endpoint) return void 0;
5657
6059
  try {
5658
- const b = await createBrowser({ cdpEndpoint: ep });
5659
- await new Promise((r) => setTimeout(r, 500));
5660
- let contexts = b.contexts();
6060
+ const browser = await createBrowser({ cdpEndpoint: endpoint });
6061
+ await new Promise((resolve) => setTimeout(resolve, 500));
6062
+ let contexts = browser.contexts();
5661
6063
  if (contexts.length === 0) {
5662
- await new Promise((r) => setTimeout(r, 500));
5663
- contexts = b.contexts();
6064
+ await new Promise((resolve) => setTimeout(resolve, 500));
6065
+ contexts = browser.contexts();
5664
6066
  }
5665
- const context = contexts[0] || await b.newContext();
6067
+ const context = contexts[0] || await browser.newContext();
5666
6068
  const savedUrl = meta.conversationUrl || meta.url;
5667
- const targetHostname = savedUrl ? (() => {
6069
+ let targetHostname = "";
6070
+ if (savedUrl) {
5668
6071
  try {
5669
- return new URL(savedUrl).hostname;
6072
+ targetHostname = new URL(savedUrl).hostname;
5670
6073
  } catch {
5671
- return "";
6074
+ targetHostname = "";
5672
6075
  }
5673
- })() : "";
6076
+ }
5674
6077
  let page = null;
5675
6078
  let fallbackPage = null;
5676
- for (const ctx of contexts) {
5677
- const pages = ctx.pages();
5678
- for (const p of pages) {
5679
- const pUrl = p.url();
5680
- if (pUrl && pUrl !== "about:blank" && !pUrl.startsWith("chrome://") && !pUrl.startsWith("chrome-untrusted://") && !pUrl.startsWith("chrome-error://")) {
5681
- if (targetHostname && pUrl.includes(targetHostname)) {
5682
- page = p;
5683
- break;
5684
- }
5685
- if (!fallbackPage) {
5686
- fallbackPage = p;
5687
- }
6079
+ for (const browserContext of contexts) {
6080
+ for (const candidate of browserContext.pages()) {
6081
+ const url = candidate.url();
6082
+ if (!url || url === "about:blank" || url.startsWith("chrome://") || url.startsWith("chrome-untrusted://") || url.startsWith("chrome-error://")) continue;
6083
+ if (targetHostname && url.includes(targetHostname)) {
6084
+ page = candidate;
6085
+ break;
5688
6086
  }
6087
+ fallbackPage ??= candidate;
5689
6088
  }
5690
6089
  if (page) break;
5691
6090
  }
5692
- page = page || fallbackPage;
6091
+ page ??= fallbackPage;
5693
6092
  if (!page) {
5694
- const targets = await getCDPTargets2(ep);
5695
- const matchTarget = targets.find(
5696
- (t) => t.url && t.url !== "about:blank" && !t.url.startsWith("chrome://") && !t.url.startsWith("chrome-untrusted://") && !t.url.startsWith("chrome-error://") && (targetHostname ? t.url.includes(targetHostname) : true)
5697
- );
5698
- if (matchTarget && matchTarget.url) {
6093
+ const targets = await getCDPTargets2(endpoint);
6094
+ const match = targets.find((target) => target.url && target.url !== "about:blank" && !target.url.startsWith("chrome://") && !target.url.startsWith("chrome-untrusted://") && !target.url.startsWith("chrome-error://") && (!targetHostname || target.url.includes(targetHostname)));
6095
+ if (match?.url) {
5699
6096
  page = await context.newPage();
5700
- await page.goto(matchTarget.url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
6097
+ await page.goto(match.url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
5701
6098
  });
5702
6099
  }
5703
6100
  }
@@ -5711,201 +6108,49 @@ async function findOrRestoreSession(name, cdpEndpoint) {
5711
6108
  new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 3e3))
5712
6109
  ]);
5713
6110
  } catch {
5714
- console.log(`[Session] "${name}" restored page unresponsive, creating fresh session`);
5715
6111
  deleteSessionDiskMeta(name);
5716
6112
  return void 0;
5717
6113
  }
5718
6114
  const targetUrl = meta.conversationUrl || meta.url;
5719
6115
  if (targetUrl && page.url() !== targetUrl) {
5720
- try {
5721
- if (!page.url().includes(new URL(targetUrl).hostname)) {
5722
- await page.goto(targetUrl, { waitUntil: "domcontentloaded", timeout: 3e4 }).catch(() => {
5723
- });
5724
- }
5725
- } catch {
5726
- }
5727
- }
5728
- const session = {
5729
- id: meta.id || randomUUID(),
5730
- name,
5731
- context,
5732
- page,
5733
- browser: b,
5734
- createdAt: meta.createdAt || (/* @__PURE__ */ new Date()).toISOString(),
5735
- lastActivityAt: Date.now(),
5736
- isCDP: true,
5737
- cdpEndpoint: ep
5738
- };
5739
- for (const existingSession of sessions.list()) {
5740
- if (existingSession.name === name) {
5741
- logSessionEvent("remove_stale", `Removing stale session name="${name}" id="${existingSession.id}" during restore`);
5742
- sessions.removeById(existingSession.id);
5743
- }
5744
- }
5745
- sessions.set(session);
5746
- resetIdleTimer();
5747
- await installNetworkCapture(page, name);
5748
- return session;
5749
- } catch (e) {
5750
- console.error(`[Session Restore] Failed for "${name}":`, errMsg(e));
5751
- deleteSessionDiskMeta(name);
5752
- return void 0;
5753
- }
5754
- }
5755
- async function createEphemeralContext(options) {
5756
- if (options?.cdpEndpoint) {
5757
- const endpoint = await resolveCDPEndpoint(options.cdpEndpoint);
5758
- const { browser: b2 } = await launch({ cdpEndpoint: endpoint });
5759
- const contexts = b2.contexts();
5760
- const ctx = contexts[0] || await b2.newContext();
5761
- const allPages = ctx.pages();
5762
- const existingPages = allPages.filter((p) => {
5763
- const url = p.url();
5764
- return url !== "about:blank" && !url.startsWith("chrome://") && !url.startsWith("chrome-untrusted://") && !url.startsWith("chrome-error://");
5765
- });
5766
- const page2 = existingPages.length > 0 ? existingPages[0] : allPages.length > 0 ? allPages[0] : await ctx.newPage();
5767
- resetIdleTimer();
5768
- ephemeralConnections.set(page2, b2);
5769
- return { context: ctx, page: page2 };
5770
- }
5771
- const b = await getBrowser(options);
5772
- const context = await b.newContext();
5773
- const page = await context.newPage();
5774
- resetIdleTimer();
5775
- return { context, page };
5776
- }
5777
- var ephemeralConnections = /* @__PURE__ */ new WeakMap();
5778
- async function closeEphemeralContext(context) {
5779
- try {
5780
- const pages = context.pages();
5781
- for (const p of pages) {
5782
- const conn = ephemeralConnections.get(p);
5783
- if (conn) {
5784
- ephemeralConnections.delete(p);
5785
- await conn.close();
5786
- break;
5787
- }
5788
- }
5789
- await context.close();
5790
- } catch {
5791
- }
5792
- if (sessions.size === 0 && idleTimer) {
5793
- clearTimeout(idleTimer);
5794
- idleTimer = null;
5795
- }
5796
- }
5797
- function getAllSessions() {
5798
- return sessions.list();
5799
- }
5800
- async function installNetworkCapture(page, sessionName) {
5801
- if (process.env.XBROWSER_DAEMON_WORKER !== "1") return;
5802
- const { networkStore } = await import("./network-store-YVDNUREI.js");
5803
- const requestData = /* @__PURE__ */ new Map();
5804
- const responseMeta = /* @__PURE__ */ new Map();
5805
- const xbPage = page;
5806
- xbPage.on("request", (params) => {
5807
- try {
5808
- const p = params;
5809
- requestData.set(p.requestId, {
5810
- method: p.request.method,
5811
- headers: p.request.headers,
5812
- postData: p.request.postData ?? null,
5813
- resourceType: p.type
5814
- });
5815
- } catch {
5816
- }
5817
- });
5818
- xbPage.on("response", (params) => {
5819
- try {
5820
- const p = params;
5821
- responseMeta.set(p.requestId, {
5822
- status: p.response.status,
5823
- url: p.response.url,
5824
- headers: p.response.headers,
5825
- mimeType: p.response.mimeType,
5826
- type: p.type
5827
- });
5828
- } catch {
5829
- }
5830
- });
5831
- xbPage.on("requestfinished", async (params) => {
5832
- try {
5833
- const p = params;
5834
- const meta = responseMeta.get(p.requestId);
5835
- if (!meta) return;
5836
- const req = requestData.get(p.requestId);
5837
- const method = req?.method ?? "GET";
5838
- const contentType = meta.headers["content-type"] || meta.headers["Content-Type"] || "";
5839
- const resourceType = req?.resourceType ?? meta.type;
5840
- const requestHeaders = req?.headers ?? {};
5841
- let requestBody = void 0;
5842
- const isPostLike = ["POST", "PATCH", "PUT"].includes(method);
5843
- if (isPostLike && requestHeaders["content-type"]?.includes("application/json")) {
5844
- const postData = req?.postData;
5845
- if (postData) {
5846
- try {
5847
- requestBody = JSON.parse(postData);
5848
- } catch {
5849
- requestBody = postData;
5850
- }
5851
- }
5852
- }
5853
- let responseBody = void 0;
5854
- let size = 0;
5855
- const isJsonish = contentType.includes("json") || contentType.includes("javascript") || contentType.includes("text/");
5856
- if (isJsonish) {
5857
- try {
5858
- const bodyResult = await xbPage._cdpSend(
5859
- "Network.getResponseBody",
5860
- { requestId: p.requestId }
5861
- );
5862
- const text = bodyResult.body ?? "";
5863
- size = text.length;
5864
- if (size <= 10240) {
5865
- try {
5866
- responseBody = JSON.parse(text);
5867
- } catch {
5868
- responseBody = text.slice(0, 200);
5869
- }
5870
- }
5871
- } catch {
5872
- }
5873
- } else {
5874
- try {
5875
- const bodyResult = await xbPage._cdpSend(
5876
- "Network.getResponseBody",
5877
- { requestId: p.requestId }
5878
- );
5879
- size = bodyResult.body?.length ?? 0;
5880
- } catch {
5881
- size = 0;
6116
+ try {
6117
+ if (!page.url().includes(new URL(targetUrl).hostname)) {
6118
+ await page.goto(targetUrl, { waitUntil: "domcontentloaded", timeout: 3e4 }).catch(() => {
6119
+ });
5882
6120
  }
6121
+ } catch {
5883
6122
  }
5884
- networkStore.add(sessionName, {
5885
- timestamp: Date.now(),
5886
- method,
5887
- url: meta.url,
5888
- path: new URL(meta.url).pathname,
5889
- status: meta.status,
5890
- contentType,
5891
- size,
5892
- headers: meta.headers,
5893
- body: responseBody,
5894
- requestHeaders,
5895
- requestBody,
5896
- resourceType
5897
- });
5898
- requestData.delete(p.requestId);
5899
- responseMeta.delete(p.requestId);
5900
- } catch {
5901
6123
  }
5902
- });
6124
+ const session = {
6125
+ id: meta.id,
6126
+ name,
6127
+ context,
6128
+ page,
6129
+ browser,
6130
+ createdAt: meta.createdAt,
6131
+ lastActivityAt: Date.now(),
6132
+ isCDP: true,
6133
+ cdpEndpoint: endpoint
6134
+ };
6135
+ for (const existing of sessions.list()) {
6136
+ if (existing.name === name) sessions.removeById(existing.id);
6137
+ }
6138
+ sessions.set(session);
6139
+ await installNetworkCapture2(session.page, name);
6140
+ return session;
6141
+ } catch (error) {
6142
+ console.error(`[Session Restore] Failed for "${name}":`, errMsg(error));
6143
+ deleteSessionDiskMeta(name);
6144
+ return void 0;
6145
+ }
5903
6146
  }
5904
- async function createSession(name, url, options) {
6147
+
6148
+ // src/browser/create-session.ts
6149
+ async function createSessionImpl(name, url, options, deps) {
5905
6150
  const existing = findSession(name);
5906
6151
  if (existing) {
5907
- logSessionEvent("replace_session", `name="${name}" id="${existing.id}" \u2014 closing existing session before creating new one`);
5908
- await closeSessionByName(name);
6152
+ deps.logSessionEvent("replace_session", `name="${name}" id="${existing.id}" \u2014 closing existing session before creating new one`);
6153
+ await deps.closeSessionByName(name);
5909
6154
  }
5910
6155
  const b = await createBrowser(options);
5911
6156
  const isCDP = !!options?.cdpEndpoint;
@@ -6016,7 +6261,7 @@ async function createSession(name, url, options) {
6016
6261
  }
6017
6262
  }
6018
6263
  if (!targetPage && options?.cdpEndpoint) {
6019
- const targets = await getCDPTargets2(options.cdpEndpoint);
6264
+ const targets = await deps.getCDPTargets(options.cdpEndpoint);
6020
6265
  const ownedUrlsT = /* @__PURE__ */ new Set();
6021
6266
  for (const ssn of sessions.list()) {
6022
6267
  try {
@@ -6097,27 +6342,270 @@ async function createSession(name, url, options) {
6097
6342
  await page.goto(url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
6098
6343
  });
6099
6344
  }
6100
- const session = {
6101
- id: randomUUID(),
6345
+ const session = deps.registerSession({
6102
6346
  name,
6103
6347
  context,
6104
6348
  page,
6105
6349
  browser: b,
6106
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
6107
- lastActivityAt: Date.now(),
6108
6350
  isCDP,
6109
6351
  cdpEndpoint: options?.cdpEndpoint
6110
- };
6111
- sessions.set(session);
6112
- logSessionEvent("create_session", `name="${name}" id="${session.id}" url="${url || "(no url)"}" isCDP=${isCDP} cdpEndpoint=${options?.cdpEndpoint || "(none)"}`);
6113
- resetIdleTimer();
6114
- await installNetworkCapture(page, name);
6352
+ });
6353
+ deps.logSessionEvent("create_session", `name="${name}" id="${session.id}" url="${url || "(no url)"}" isCDP=${isCDP} cdpEndpoint=${options?.cdpEndpoint || "(none)"}`);
6354
+ await deps.installNetworkCapture(page, name);
6115
6355
  return session;
6116
6356
  }
6357
+
6358
+ // src/browser.ts
6359
+ function logSessionEvent2(event, details) {
6360
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
6361
+ console.error(`[SESSION] ${timestamp} [PID:${process.pid}] ${event} | ${details}`);
6362
+ }
6363
+ var IDLE_TIMEOUT_MS = (process.env.XBROWSER_IDLE_TIMEOUT ? parseInt(process.env.XBROWSER_IDLE_TIMEOUT, 10) : 30) * 60 * 1e3;
6364
+ function resetIdleTimer() {
6365
+ if (sharedState.idleTimer) clearTimeout(sharedState.idleTimer);
6366
+ sharedState.idleTimer = setTimeout(async () => {
6367
+ const now = Date.now();
6368
+ let allIdle = true;
6369
+ const idleSessions = [];
6370
+ for (const s of sessions) {
6371
+ if (now - s.lastActivityAt < IDLE_TIMEOUT_MS) {
6372
+ allIdle = false;
6373
+ } else {
6374
+ idleSessions.push(`${s.name}(${(now - s.lastActivityAt) / 1e3}s idle)`);
6375
+ }
6376
+ }
6377
+ if (allIdle && (sessions.size > 0 || sharedState.browser)) {
6378
+ logSessionEvent2("idle_timeout", `Sessions idle for >${IDLE_TIMEOUT_MS / 6e4}min. Sessions: ${idleSessions.join(", ") || "all"}. Calling destroyBrowser()`);
6379
+ await destroyBrowser().catch(() => {
6380
+ });
6381
+ }
6382
+ }, IDLE_TIMEOUT_MS);
6383
+ if (sharedState.idleTimer && typeof sharedState.idleTimer.unref === "function") {
6384
+ sharedState.idleTimer.unref();
6385
+ }
6386
+ }
6387
+ async function findOrRestoreSession2(name, cdpEndpoint) {
6388
+ return findOrRestoreSession(
6389
+ name,
6390
+ cdpEndpoint,
6391
+ closeSessionByName,
6392
+ installNetworkCapture
6393
+ );
6394
+ }
6395
+ function touchSession(id) {
6396
+ const s = sessions.get(id);
6397
+ if (s) s.lastActivityAt = Date.now();
6398
+ resetIdleTimer();
6399
+ }
6400
+ process.on("exit", () => {
6401
+ for (const session of sessions.list()) {
6402
+ if (session.isCDP) {
6403
+ logSessionEvent2("process_exit", `Session "${session.name}": CDP connection (not closing external browser).`);
6404
+ } else {
6405
+ logSessionEvent2("process_exit", `Session "${session.name}": Closing self-launched browser.`);
6406
+ try {
6407
+ session.browser?.close();
6408
+ } catch {
6409
+ }
6410
+ }
6411
+ }
6412
+ if (sharedState.browser) {
6413
+ logSessionEvent2("process_exit", "Closing shared browser (self-launched only, external CDP is safe).");
6414
+ try {
6415
+ sharedState.browser.close();
6416
+ } catch {
6417
+ }
6418
+ sharedState.browser = null;
6419
+ }
6420
+ const cdpProxy = getSharedCdpProxy();
6421
+ if (cdpProxy) {
6422
+ try {
6423
+ cdpProxy.stop();
6424
+ } catch {
6425
+ }
6426
+ setSharedCdpProxy(null);
6427
+ }
6428
+ sessions.clear();
6429
+ });
6430
+ async function getBrowser(options) {
6431
+ if (sharedState.browser) return sharedState.browser;
6432
+ sharedState.browser = await createBrowser(options);
6433
+ if (options?.cdpEndpoint && options.intercept) {
6434
+ }
6435
+ return sharedState.browser;
6436
+ }
6437
+ function findSession(name) {
6438
+ return sessions.find(name);
6439
+ }
6440
+ function getSessionById2(id) {
6441
+ return sessions.get(id);
6442
+ }
6443
+ function setActivePage2(session, page) {
6444
+ session.page = page;
6445
+ session.lastActivityAt = Date.now();
6446
+ }
6447
+ async function createEphemeralContext(options) {
6448
+ if (options?.cdpEndpoint) {
6449
+ const endpoint = await resolveCDPEndpoint(options.cdpEndpoint);
6450
+ const { browser: b2 } = await launch({ cdpEndpoint: endpoint });
6451
+ const contexts = b2.contexts();
6452
+ const ctx = contexts[0] || await b2.newContext();
6453
+ const allPages = ctx.pages();
6454
+ const existingPages = allPages.filter((p) => {
6455
+ const url = p.url();
6456
+ return url !== "about:blank" && !url.startsWith("chrome://") && !url.startsWith("chrome-untrusted://") && !url.startsWith("chrome-error://");
6457
+ });
6458
+ const page2 = existingPages.length > 0 ? existingPages[0] : allPages.length > 0 ? allPages[0] : await ctx.newPage();
6459
+ resetIdleTimer();
6460
+ ephemeralConnections.set(page2, b2);
6461
+ return { context: ctx, page: page2 };
6462
+ }
6463
+ const b = await getBrowser(options);
6464
+ const context = await b.newContext();
6465
+ const page = await context.newPage();
6466
+ resetIdleTimer();
6467
+ return { context, page };
6468
+ }
6469
+ var ephemeralConnections = /* @__PURE__ */ new WeakMap();
6470
+ async function closeEphemeralContext(context) {
6471
+ try {
6472
+ const pages = context.pages();
6473
+ for (const p of pages) {
6474
+ const conn = ephemeralConnections.get(p);
6475
+ if (conn) {
6476
+ ephemeralConnections.delete(p);
6477
+ await conn.close();
6478
+ break;
6479
+ }
6480
+ }
6481
+ await context.close();
6482
+ } catch {
6483
+ }
6484
+ if (sessions.size === 0 && sharedState.idleTimer) {
6485
+ clearTimeout(sharedState.idleTimer);
6486
+ sharedState.idleTimer = null;
6487
+ }
6488
+ }
6489
+ function getAllSessions2() {
6490
+ return sessions.list();
6491
+ }
6492
+ async function installNetworkCapture(page, sessionName) {
6493
+ if (process.env.XBROWSER_DAEMON_WORKER !== "1") return;
6494
+ const { networkStore } = await import("./network-store-YVDNUREI.js");
6495
+ const requestData = /* @__PURE__ */ new Map();
6496
+ const responseMeta = /* @__PURE__ */ new Map();
6497
+ const xbPage = page;
6498
+ xbPage.on("request", (params) => {
6499
+ try {
6500
+ const p = params;
6501
+ requestData.set(p.requestId, {
6502
+ method: p.request.method,
6503
+ headers: p.request.headers,
6504
+ postData: p.request.postData ?? null,
6505
+ resourceType: p.type
6506
+ });
6507
+ } catch {
6508
+ }
6509
+ });
6510
+ xbPage.on("response", (params) => {
6511
+ try {
6512
+ const p = params;
6513
+ responseMeta.set(p.requestId, {
6514
+ status: p.response.status,
6515
+ url: p.response.url,
6516
+ headers: p.response.headers,
6517
+ mimeType: p.response.mimeType,
6518
+ type: p.type
6519
+ });
6520
+ } catch {
6521
+ }
6522
+ });
6523
+ xbPage.on("requestfinished", async (params) => {
6524
+ try {
6525
+ const p = params;
6526
+ const meta = responseMeta.get(p.requestId);
6527
+ if (!meta) return;
6528
+ const req = requestData.get(p.requestId);
6529
+ const method = req?.method ?? "GET";
6530
+ const contentType = meta.headers["content-type"] || meta.headers["Content-Type"] || "";
6531
+ const resourceType = req?.resourceType ?? meta.type;
6532
+ const requestHeaders = req?.headers ?? {};
6533
+ let requestBody = void 0;
6534
+ const isPostLike = ["POST", "PATCH", "PUT"].includes(method);
6535
+ if (isPostLike && requestHeaders["content-type"]?.includes("application/json")) {
6536
+ const postData = req?.postData;
6537
+ if (postData) {
6538
+ try {
6539
+ requestBody = JSON.parse(postData);
6540
+ } catch {
6541
+ requestBody = postData;
6542
+ }
6543
+ }
6544
+ }
6545
+ let responseBody = void 0;
6546
+ let size = 0;
6547
+ const isJsonish = contentType.includes("json") || contentType.includes("javascript") || contentType.includes("text/");
6548
+ if (isJsonish) {
6549
+ try {
6550
+ const bodyResult = await xbPage._cdpSend(
6551
+ "Network.getResponseBody",
6552
+ { requestId: p.requestId }
6553
+ );
6554
+ const text = bodyResult.body ?? "";
6555
+ size = text.length;
6556
+ if (size <= 10240) {
6557
+ try {
6558
+ responseBody = JSON.parse(text);
6559
+ } catch {
6560
+ responseBody = text.slice(0, 200);
6561
+ }
6562
+ }
6563
+ } catch {
6564
+ }
6565
+ } else {
6566
+ try {
6567
+ const bodyResult = await xbPage._cdpSend(
6568
+ "Network.getResponseBody",
6569
+ { requestId: p.requestId }
6570
+ );
6571
+ size = bodyResult.body?.length ?? 0;
6572
+ } catch {
6573
+ size = 0;
6574
+ }
6575
+ }
6576
+ networkStore.add(sessionName, {
6577
+ timestamp: Date.now(),
6578
+ method,
6579
+ url: meta.url,
6580
+ path: new URL(meta.url).pathname,
6581
+ status: meta.status,
6582
+ contentType,
6583
+ size,
6584
+ headers: meta.headers,
6585
+ body: responseBody,
6586
+ requestHeaders,
6587
+ requestBody,
6588
+ resourceType
6589
+ });
6590
+ requestData.delete(p.requestId);
6591
+ responseMeta.delete(p.requestId);
6592
+ } catch {
6593
+ }
6594
+ });
6595
+ }
6596
+ async function createSession(name, url, options) {
6597
+ return createSessionImpl(name, url, options, {
6598
+ closeSessionByName,
6599
+ installNetworkCapture,
6600
+ registerSession,
6601
+ logSessionEvent: logSessionEvent2,
6602
+ getCDPTargets: getCDPTargets2
6603
+ });
6604
+ }
6117
6605
  async function closeSessionByName(name) {
6118
6606
  for (const session of sessions) {
6119
6607
  if (session.name === name || session.id === name) {
6120
- logSessionEvent("close_session", `name="${session.name}" id="${session.id}" url="${session.page.url()}"`);
6608
+ logSessionEvent2("close_session", `name="${session.name}" id="${session.id}" url="${session.page.url()}"`);
6121
6609
  if (session.isCDP) {
6122
6610
  if (session.browser) {
6123
6611
  await session.browser.close().catch(() => {
@@ -6133,7 +6621,7 @@ async function closeSessionByName(name) {
6133
6621
  sessions.removeById(session.id);
6134
6622
  const file2 = sessionFile(session.name);
6135
6623
  try {
6136
- unlinkSync(file2);
6624
+ unlinkSync2(file2);
6137
6625
  } catch {
6138
6626
  }
6139
6627
  try {
@@ -6143,7 +6631,7 @@ async function closeSessionByName(name) {
6143
6631
  } catch {
6144
6632
  }
6145
6633
  try {
6146
- const { SessionRecorder } = await import("./session-recorder-563ISSJK.js");
6634
+ const { SessionRecorder } = await import("./session-recorder-R3GDGXLJ.js");
6147
6635
  SessionRecorder.cleanup(session.name);
6148
6636
  } catch {
6149
6637
  }
@@ -6152,14 +6640,14 @@ async function closeSessionByName(name) {
6152
6640
  }
6153
6641
  const file = sessionFile(name);
6154
6642
  try {
6155
- unlinkSync(file);
6643
+ unlinkSync2(file);
6156
6644
  } catch {
6157
6645
  }
6158
6646
  return false;
6159
6647
  }
6160
6648
  async function closeAllSessions() {
6161
6649
  const names = sessions.list().map((s) => `${s.name}(${s.page.url()})`).join(", ");
6162
- if (names) logSessionEvent("close_all_sessions", `Closing ${sessions.size} sessions: ${names}`);
6650
+ if (names) logSessionEvent2("close_all_sessions", `Closing ${sessions.size} sessions: ${names}`);
6163
6651
  for (const session of sessions.list()) {
6164
6652
  try {
6165
6653
  if (session.isCDP) {
@@ -6181,38 +6669,37 @@ async function closeAllSessions() {
6181
6669
  }
6182
6670
  }
6183
6671
  async function destroyBrowser() {
6184
- logSessionEvent("destroy_browser", `Sessions count: ${sessions.size}. Clearing idle timer and closing all sessions.`);
6185
- if (idleTimer) {
6186
- clearTimeout(idleTimer);
6187
- idleTimer = null;
6672
+ logSessionEvent2("destroy_browser", `Sessions count: ${sessions.size}. Clearing idle timer and closing all sessions.`);
6673
+ if (sharedState.idleTimer) {
6674
+ clearTimeout(sharedState.idleTimer);
6675
+ sharedState.idleTimer = null;
6188
6676
  }
6189
6677
  await closeAllSessions();
6190
- if (_sharedBrowser) {
6191
- await _sharedBrowser.close().catch(() => {
6678
+ if (sharedState.browser) {
6679
+ await sharedState.browser.close().catch(() => {
6192
6680
  });
6193
- _sharedBrowser = null;
6681
+ sharedState.browser = null;
6194
6682
  }
6195
- if (_sharedCdpProxy) {
6196
- await _sharedCdpProxy.stop().catch(() => {
6683
+ if (getSharedCdpProxy()) {
6684
+ await getSharedCdpProxy().stop().catch(() => {
6197
6685
  });
6198
- _sharedCdpProxy = null;
6686
+ setSharedCdpProxy(null);
6199
6687
  }
6200
6688
  }
6201
6689
  function resetForTesting() {
6202
6690
  sessions.clear();
6203
- _sharedBrowser = null;
6204
- _sharedCdpProxy = null;
6691
+ sharedState.browser = null;
6692
+ sharedState.idleTimer = null;
6693
+ setSharedCdpProxy(null);
6205
6694
  try {
6206
- for (const f of readdirSync(SESSION_DIR)) {
6207
- unlinkSync(join2(SESSION_DIR, f));
6208
- }
6695
+ for (const file of readdirSync2(SESSION_DIR)) unlinkSync2(join3(SESSION_DIR, file));
6209
6696
  } catch {
6210
6697
  }
6211
6698
  }
6212
6699
  async function ensureProcessCanExit() {
6213
- if (idleTimer) {
6214
- clearTimeout(idleTimer);
6215
- idleTimer = null;
6700
+ if (sharedState.idleTimer) {
6701
+ clearTimeout(sharedState.idleTimer);
6702
+ sharedState.idleTimer = null;
6216
6703
  }
6217
6704
  for (const session of sessions.list()) {
6218
6705
  if (session.browser) {
@@ -6224,35 +6711,36 @@ async function ensureProcessCanExit() {
6224
6711
  }
6225
6712
  }
6226
6713
  sessions.clear();
6227
- if (_sharedBrowser) {
6228
- await _sharedBrowser.close().catch(() => {
6714
+ if (sharedState.browser) {
6715
+ await sharedState.browser.close().catch(() => {
6229
6716
  });
6230
- _sharedBrowser = null;
6717
+ sharedState.browser = null;
6231
6718
  }
6232
- if (_sharedCdpProxy) {
6233
- await _sharedCdpProxy.stop().catch(() => {
6719
+ if (getSharedCdpProxy()) {
6720
+ await getSharedCdpProxy().stop().catch(() => {
6234
6721
  });
6235
- _sharedCdpProxy = null;
6722
+ setSharedCdpProxy(null);
6236
6723
  }
6237
6724
  }
6238
6725
 
6239
6726
  export {
6240
6727
  createRuleEngine,
6241
- touchSession,
6242
6728
  findTargetPage,
6243
6729
  resolveLaunchOpts,
6244
6730
  createBrowser,
6245
- getBrowser,
6246
- findSession,
6247
- getSessionById,
6248
- setActivePage,
6249
6731
  saveSessionDiskMeta,
6250
6732
  readSessionDiskMeta,
6251
6733
  deleteSessionDiskMeta,
6252
- findOrRestoreSession,
6734
+ resetIdleTimer,
6735
+ findOrRestoreSession2 as findOrRestoreSession,
6736
+ touchSession,
6737
+ getBrowser,
6738
+ findSession,
6739
+ getSessionById2 as getSessionById,
6740
+ setActivePage2 as setActivePage,
6253
6741
  createEphemeralContext,
6254
6742
  closeEphemeralContext,
6255
- getAllSessions,
6743
+ getAllSessions2 as getAllSessions,
6256
6744
  createSession,
6257
6745
  closeSessionByName,
6258
6746
  closeAllSessions,