@xbrowser/cli 1.28.0 → 1.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +2 -2
  2. package/dist/{browser-4IYIHZ6R.js → browser-6PFTHZI3.js} +8 -6
  3. package/dist/{browser-NYYCR4O7.js → browser-I2NLJN2A.js} +5 -3
  4. package/dist/{browser-ZD53IMUJ.js → browser-KOUA4ZDA.js} +6 -4
  5. package/dist/{cdp-driver-EFEW4ZEN.js → cdp-driver-3ETNFQA4.js} +4 -4
  6. package/dist/{cdp-driver-HB744QB4.js → cdp-driver-U7HDQMQ5.js} +1578 -896
  7. package/dist/{cdp-driver-4X6Q62WI.js → cdp-driver-WBFJNOLD.js} +3 -3
  8. package/dist/{chunk-SEEWE5SJ.js → chunk-2KPI5GKP.js} +3 -0
  9. package/dist/{chunk-OEC7ZSFW.js → chunk-3K57RYVC.js} +1942 -1580
  10. package/dist/{chunk-75DNUI6M.js → chunk-6UJU2FJK.js} +146 -0
  11. package/dist/{chunk-FNXA6FDM.js → chunk-BND5O5KC.js} +2 -1
  12. package/dist/{chunk-KECYFWJO.js → chunk-BOZTIIBT.js} +441 -427
  13. package/dist/{chunk-WK3INZLA.js → chunk-KPTD3SNJ.js} +1121 -759
  14. package/dist/{chunk-OSZNJT4U.js → chunk-LM32MNBB.js} +79 -8
  15. package/dist/{chunk-T2AI24A5.js → chunk-NAIHOVDZ.js} +3 -0
  16. package/dist/{chunk-WYETQ5C7.js → chunk-NEE6EMYA.js} +14 -1
  17. package/dist/{chunk-3PUOISKE.js → chunk-NINETOM4.js} +524 -495
  18. package/dist/{chunk-SOPN4XDK.js → chunk-O5PASNI7.js} +2 -1
  19. package/dist/{chunk-ME5FO5YV.js → chunk-OCECE22C.js} +1578 -896
  20. package/dist/{chunk-HSYRAV3H.js → chunk-OSIDUT4H.js} +2151 -1440
  21. package/dist/{chunk-HBMEFSTB.js → chunk-QCV2PI7U.js} +2 -1
  22. package/dist/{chunk-IR6C24P7.js → chunk-RMYKVZIZ.js} +1103 -1043
  23. package/dist/{chunk-R3F4K2SB.js → chunk-SMYSNO4M.js} +10 -0
  24. package/dist/{chunk-J3HXZVSN.js → chunk-SPNWUUHA.js} +1452 -916
  25. package/dist/{chunk-PGKV24QN.js → chunk-TBJUSUKF.js} +1 -1
  26. package/dist/{chunk-V6KGBU5J.js → chunk-VYTQLZAX.js} +1091 -1040
  27. package/dist/cli.js +3447 -3377
  28. package/dist/daemon-main.js +1240 -786
  29. package/dist/{human-interaction-CTZ4IWXJ.js → human-interaction-ISMMOJOK.js} +2 -2
  30. package/dist/{human-interaction-HJCK45SL.js → human-interaction-STTZZZ5N.js} +1 -1
  31. package/dist/{human-interaction-V3VDGHHI.js → human-interaction-UXFYV7DU.js} +1 -1
  32. package/dist/index.d.ts +458 -476
  33. package/dist/index.js +3766 -3576
  34. package/dist/{launcher-SJ44X25U.js → launcher-TOLF23ET.js} +1 -1
  35. package/dist/{launcher-XHKIC4GP.js → launcher-ZYB32LSZ.js} +1 -1
  36. package/dist/{plugin-singleton-GGSBI3EG.js → plugin-singleton-A6RNITJW.js} +1 -1
  37. package/dist/{proxy-NKCYE76M.js → proxy-H3RIUOCN.js} +2 -2
  38. package/dist/{recovery-EBKORYEU.js → recovery-JFGV3DBX.js} +1 -1
  39. package/dist/{recovery-5C4FBA5O.js → recovery-ORHJSBDN.js} +2 -2
  40. package/dist/{recovery-IMZUGWSS.js → recovery-XDKN63O5.js} +1 -1
  41. package/dist/{server-26SE6YZR.js → server-TG47W7MV.js} +7 -7
  42. package/dist/{server-JXF3JOAM.js → server-U3YAX5MJ.js} +4 -4
  43. package/dist/{session-recorder-GEZVQBKW.js → session-recorder-N7VEKJVW.js} +1 -1
  44. package/dist/{session-recorder-563ISSJK.js → session-recorder-RUNQOJ7T.js} +1 -1
  45. package/dist/{session-replayer-TXTNTG33.js → session-replayer-XLWQ47BB.js} +1 -1
  46. package/dist/{stealth-QNSMIHQK.js → stealth-FMPZO2OB.js} +1 -1
  47. package/dist/{stealth-MHJNBJY7.js → stealth-MCKFKPZ6.js} +1 -1
  48. package/package.json +9 -3
@@ -1,16 +1,87 @@
1
1
  import {
2
2
  createRuleEngine,
3
3
  launch
4
- } from "./chunk-ME5FO5YV.js";
4
+ } from "./chunk-OCECE22C.js";
5
5
  import {
6
6
  errMsg
7
7
  } from "./chunk-GDKLH7ZY.js";
8
8
 
9
9
  // src/browser.ts
10
- import { randomUUID } from "crypto";
11
- import { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "fs";
12
- import { join } from "path";
13
- import { homedir } from "os";
10
+ import { readdirSync as readdirSync2, unlinkSync as unlinkSync2 } from "fs";
11
+ import { join as join2 } from "path";
12
+
13
+ // src/utils/cdp.ts
14
+ async function fetchNoProxy(url) {
15
+ const savedProxy = {
16
+ http_proxy: process.env.http_proxy,
17
+ https_proxy: process.env.https_proxy,
18
+ HTTP_PROXY: process.env.HTTP_PROXY,
19
+ HTTPS_PROXY: process.env.HTTPS_PROXY,
20
+ all_proxy: process.env.all_proxy,
21
+ ALL_PROXY: process.env.ALL_PROXY
22
+ };
23
+ for (const key of Object.keys(savedProxy)) delete process.env[key];
24
+ try {
25
+ return await fetch(url);
26
+ } finally {
27
+ for (const [key, val] of Object.entries(savedProxy)) {
28
+ if (val !== void 0) process.env[key] = val;
29
+ }
30
+ }
31
+ }
32
+ async function resolveCDPEndpoint(raw) {
33
+ if (raw === "auto") {
34
+ const ports = [9222, 9221, 9223, 9224];
35
+ for (const port of ports) {
36
+ try {
37
+ const httpResp = await fetchNoProxy(`http://localhost:${port}/json/version`);
38
+ if (httpResp.ok) {
39
+ const data = await httpResp.json();
40
+ if (data.webSocketDebuggerUrl) {
41
+ return data.webSocketDebuggerUrl;
42
+ }
43
+ }
44
+ } catch {
45
+ }
46
+ }
47
+ throw new Error(
48
+ `Could not auto-discover CDP endpoint. Tried ports: ${ports.join(", ")}.
49
+ \u53EF\u80FD\u539F\u56E0\uFF1A\u6CA1\u6709 Chrome \u4EE5 --remote-debugging-port \u542F\u52A8\u3002
50
+ \u89E3\u51B3\u65B9\u6CD5\uFF1A
51
+ 1. \u542F\u52A8 Chrome: google-chrome --remote-debugging-port=9222
52
+ 2. \u6216\u7528 cdp-tunnel: npx cdp-tunnel setup
53
+ 3. \u6216\u6307\u5B9A\u7AEF\u53E3: --cdp <port>`
54
+ );
55
+ }
56
+ if (/^\d+$/.test(raw)) {
57
+ const port = raw;
58
+ const httpResp = await fetchNoProxy(`http://localhost:${port}/json/version`);
59
+ const data = await httpResp.json();
60
+ if (!data.webSocketDebuggerUrl) {
61
+ throw new Error(`Could not discover CDP endpoint from localhost:${port}`);
62
+ }
63
+ return data.webSocketDebuggerUrl;
64
+ }
65
+ if (raw.startsWith("http://") || raw.startsWith("https://")) {
66
+ try {
67
+ const u = new URL(raw);
68
+ u.pathname = (u.pathname.replace(/\/+$/, "") || "") + "/json/version";
69
+ const httpResp = await fetchNoProxy(u.toString());
70
+ const data = await httpResp.json();
71
+ if (!data.webSocketDebuggerUrl) {
72
+ throw new Error(`Could not discover CDP endpoint from ${raw}`);
73
+ }
74
+ return data.webSocketDebuggerUrl;
75
+ } catch (error) {
76
+ console.warn(`Failed to fetch WebSocket URL from ${raw}, using endpoint directly: ${error instanceof Error ? error.message : String(error)}`);
77
+ return raw;
78
+ }
79
+ }
80
+ return raw;
81
+ }
82
+
83
+ // src/browser/connection.ts
84
+ import { existsSync } from "fs";
14
85
 
15
86
  // src/cdp-interceptor/proxy.ts
16
87
  import { WebSocketServer, WebSocket } from "ws";
@@ -391,6 +462,19 @@ ${blockMsg}
391
462
  return;
392
463
  }
393
464
  if (decision?.action === "transform" && decision.transformedParams) {
465
+ const sequence = decision.transformedParams.__sequence;
466
+ if (Array.isArray(sequence)) {
467
+ this.stats.transformedMessages++;
468
+ const dispatch = async () => {
469
+ for (const step of sequence) {
470
+ if (step.delayMs) await new Promise((resolve) => setTimeout(resolve, step.delayMs));
471
+ const transformed2 = { id: request.id, method: step.method, params: step.params, sessionId: request.sessionId };
472
+ browserWs.send(JSON.stringify(transformed2));
473
+ }
474
+ };
475
+ void dispatch();
476
+ return;
477
+ }
394
478
  const transformed = { ...request, params: decision.transformedParams };
395
479
  this.stats.transformedMessages++;
396
480
  browserWs.send(JSON.stringify(transformed));
@@ -441,186 +525,38 @@ ${blockMsg}
441
525
  }
442
526
  };
443
527
 
444
- // src/utils/cdp.ts
445
- async function fetchNoProxy(url) {
446
- const savedProxy = {
447
- http_proxy: process.env.http_proxy,
448
- https_proxy: process.env.https_proxy,
449
- HTTP_PROXY: process.env.HTTP_PROXY,
450
- HTTPS_PROXY: process.env.HTTPS_PROXY,
451
- all_proxy: process.env.all_proxy,
452
- ALL_PROXY: process.env.ALL_PROXY
453
- };
454
- for (const key of Object.keys(savedProxy)) delete process.env[key];
455
- try {
456
- return await fetch(url);
457
- } finally {
458
- for (const [key, val] of Object.entries(savedProxy)) {
459
- if (val !== void 0) process.env[key] = val;
460
- }
461
- }
462
- }
463
- async function resolveCDPEndpoint(raw) {
464
- if (raw === "auto") {
465
- const ports = [9222, 9221, 9223, 9224];
466
- for (const port of ports) {
467
- try {
468
- const httpResp = await fetchNoProxy(`http://localhost:${port}/json/version`);
469
- if (httpResp.ok) {
470
- const data = await httpResp.json();
471
- if (data.webSocketDebuggerUrl) {
472
- return data.webSocketDebuggerUrl;
473
- }
474
- }
475
- } catch {
476
- }
477
- }
478
- throw new Error(
479
- `Could not auto-discover CDP endpoint. Tried ports: ${ports.join(", ")}.
480
- \u53EF\u80FD\u539F\u56E0\uFF1A\u6CA1\u6709 Chrome \u4EE5 --remote-debugging-port \u542F\u52A8\u3002
481
- \u89E3\u51B3\u65B9\u6CD5\uFF1A
482
- 1. \u542F\u52A8 Chrome: google-chrome --remote-debugging-port=9222
483
- 2. \u6216\u7528 cdp-tunnel: npx cdp-tunnel setup
484
- 3. \u6216\u6307\u5B9A\u7AEF\u53E3: --cdp <port>`
485
- );
486
- }
487
- if (/^\d+$/.test(raw)) {
488
- const port = raw;
489
- const httpResp = await fetchNoProxy(`http://localhost:${port}/json/version`);
490
- const data = await httpResp.json();
491
- if (!data.webSocketDebuggerUrl) {
492
- throw new Error(`Could not discover CDP endpoint from localhost:${port}`);
493
- }
494
- return data.webSocketDebuggerUrl;
495
- }
496
- if (raw.startsWith("http://") || raw.startsWith("https://")) {
497
- try {
498
- const u = new URL(raw);
499
- u.pathname = (u.pathname.replace(/\/+$/, "") || "") + "/json/version";
500
- const httpResp = await fetchNoProxy(u.toString());
501
- const data = await httpResp.json();
502
- if (!data.webSocketDebuggerUrl) {
503
- throw new Error(`Could not discover CDP endpoint from ${raw}`);
504
- }
505
- return data.webSocketDebuggerUrl;
506
- } catch (error) {
507
- console.warn(`Failed to fetch WebSocket URL from ${raw}, using endpoint directly: ${error instanceof Error ? error.message : String(error)}`);
508
- return raw;
509
- }
510
- }
511
- return raw;
512
- }
513
-
514
- // src/browser.ts
515
- import { SessionStore } from "@dyyz1993/xcli-core";
516
- function logSessionEvent(event, details) {
517
- const ts = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
518
- const pid = process.pid;
519
- console.error(`[SESSION] ${ts} [PID:${pid}] ${event} | ${details}`);
520
- }
521
- var SESSION_DIR = join(homedir(), ".xbrowser", "sessions");
522
- function sessionFile(name) {
523
- return join(SESSION_DIR, `${name}.json`);
524
- }
525
- function ensureSessionDir() {
526
- mkdirSync(SESSION_DIR, { recursive: true });
527
- }
528
- var sessions = new SessionStore();
529
- var _sharedBrowser = null;
530
- var _sharedCdpProxy = null;
531
- var IDLE_TIMEOUT_MS = (process.env.XBROWSER_IDLE_TIMEOUT ? parseInt(process.env.XBROWSER_IDLE_TIMEOUT, 10) : 30) * 60 * 1e3;
532
- var idleTimer = null;
533
- function resetIdleTimer() {
534
- if (idleTimer) clearTimeout(idleTimer);
535
- idleTimer = setTimeout(async () => {
536
- const now = Date.now();
537
- let allIdle = true;
538
- const idleSessions = [];
539
- for (const s of sessions) {
540
- if (now - s.lastActivityAt < IDLE_TIMEOUT_MS) {
541
- allIdle = false;
542
- } else {
543
- idleSessions.push(`${s.name}(${(now - s.lastActivityAt) / 1e3}s idle)`);
544
- }
545
- }
546
- if (allIdle && (sessions.size > 0 || _sharedBrowser)) {
547
- logSessionEvent("idle_timeout", `Sessions idle for >${IDLE_TIMEOUT_MS / 6e4}min. Sessions: ${idleSessions.join(", ") || "all"}. Calling destroyBrowser()`);
548
- await destroyBrowser().catch(() => {
549
- });
550
- }
551
- }, IDLE_TIMEOUT_MS);
552
- if (idleTimer && typeof idleTimer.unref === "function") {
553
- idleTimer.unref();
554
- }
555
- }
556
- function touchSession(id) {
557
- const s = sessions.get(id);
558
- if (s) s.lastActivityAt = Date.now();
559
- resetIdleTimer();
560
- }
561
- process.on("exit", () => {
562
- for (const session of sessions.list()) {
563
- if (session.isCDP) {
564
- logSessionEvent("process_exit", `Session "${session.name}": CDP connection (not closing external browser).`);
565
- } else {
566
- logSessionEvent("process_exit", `Session "${session.name}": Closing self-launched browser.`);
567
- try {
568
- session.browser?.close();
569
- } catch {
570
- }
571
- }
572
- }
573
- if (_sharedBrowser) {
574
- logSessionEvent("process_exit", "Closing shared browser (self-launched only, external CDP is safe).");
575
- try {
576
- _sharedBrowser.close();
577
- } catch {
578
- }
579
- _sharedBrowser = null;
580
- }
581
- if (_sharedCdpProxy) {
582
- try {
583
- _sharedCdpProxy.stop();
584
- } catch {
585
- }
586
- _sharedCdpProxy = null;
587
- }
588
- sessions.clear();
589
- });
528
+ // src/browser/connection.ts
590
529
  async function getCDPTargets(cdpEndpoint) {
591
530
  try {
592
- const ep = String(cdpEndpoint);
531
+ const endpoint = String(cdpEndpoint);
593
532
  let url = "http://localhost:9222/json/list";
594
- if (ep.startsWith("http://") || ep.startsWith("https://")) {
595
- const u = new URL(ep);
596
- u.pathname = (u.pathname.replace(/\/+$/, "") || "") + "/json/list";
597
- url = u.toString();
598
- } else if (/^\d+$/.test(ep)) {
599
- url = `http://localhost:${ep}/json/list`;
533
+ if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) {
534
+ const parsed = new URL(endpoint);
535
+ parsed.pathname = (parsed.pathname.replace(/\/+$/, "") || "") + "/json/list";
536
+ url = parsed.toString();
537
+ } else if (/^\d+$/.test(endpoint)) {
538
+ url = `http://localhost:${endpoint}/json/list`;
600
539
  }
601
- const resp = await fetch(url);
602
- return await resp.json();
540
+ const response = await fetch(url);
541
+ return await response.json();
603
542
  } catch {
604
543
  return [];
605
544
  }
606
545
  }
607
546
  async function findTargetPage(cdpEndpoint, target) {
608
547
  const targets = await getCDPTargets(cdpEndpoint);
609
- 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://"));
610
- const byId = pages.find((t) => t.id === target);
548
+ 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://"));
549
+ const byId = pages.find((item) => item.id === target);
611
550
  if (byId) return { pageId: byId.id, wsUrl: byId.webSocketDebuggerUrl, title: byId.title, url: byId.url };
612
551
  const lowerTarget = target.toLowerCase();
613
- const byTitle = pages.find((t) => t.title && t.title.toLowerCase().includes(lowerTarget));
552
+ const byTitle = pages.find((item) => item.title?.toLowerCase().includes(lowerTarget));
614
553
  if (byTitle) return { pageId: byTitle.id, wsUrl: byTitle.webSocketDebuggerUrl, title: byTitle.title, url: byTitle.url };
615
- const byUrl = pages.find((t) => t.url.toLowerCase().includes(lowerTarget));
554
+ const byUrl = pages.find((item) => item.url.toLowerCase().includes(lowerTarget));
616
555
  if (byUrl) return { pageId: byUrl.id, wsUrl: byUrl.webSocketDebuggerUrl, title: byUrl.title, url: byUrl.url };
617
556
  return null;
618
557
  }
619
558
  function resolveLaunchOpts(ctx) {
620
- if (ctx.cdpEndpoint) {
621
- return { cdpEndpoint: ctx.cdpEndpoint };
622
- }
623
- return { headless: true };
559
+ return ctx.cdpEndpoint ? { cdpEndpoint: ctx.cdpEndpoint } : { headless: true };
624
560
  }
625
561
  var CHROMIUM_CANDIDATES = [
626
562
  "/Applications/Chromium.app/Contents/MacOS/Chromium",
@@ -630,57 +566,58 @@ var CHROMIUM_CANDIDATES = [
630
566
  "/usr/bin/google-chrome"
631
567
  ];
632
568
  function discoverChromiumPath() {
633
- for (const p of CHROMIUM_CANDIDATES) {
634
- if (existsSync(p)) return p;
635
- }
636
- return void 0;
569
+ return CHROMIUM_CANDIDATES.find((path) => existsSync(path));
570
+ }
571
+ var browserPool = /* @__PURE__ */ new Map();
572
+ var sharedCdpProxy = null;
573
+ function getSharedCdpProxy() {
574
+ return sharedCdpProxy;
575
+ }
576
+ function setSharedCdpProxy(proxy) {
577
+ sharedCdpProxy = proxy;
637
578
  }
638
- var _browserPool = /* @__PURE__ */ new Map();
639
579
  async function createBrowser(options) {
640
580
  if (options?.cdpEndpoint) {
641
581
  const realEndpoint = await resolveCDPEndpoint(options.cdpEndpoint);
642
582
  if (!options.intercept) {
643
- const pooled = _browserPool.get(realEndpoint);
644
- if (pooled && !pooled.disconnected) {
645
- return pooled;
646
- }
647
- if (pooled) _browserPool.delete(realEndpoint);
583
+ const pooled = browserPool.get(realEndpoint);
584
+ if (pooled && !pooled.disconnected) return pooled;
585
+ if (pooled) browserPool.delete(realEndpoint);
648
586
  }
649
587
  if (options.intercept) {
650
588
  const config = typeof options.intercept === "object" ? { ...options.intercept, cdpEndpoint: realEndpoint } : { cdpEndpoint: realEndpoint };
651
- _sharedCdpProxy = new CDPInterceptorProxy(config);
652
- const proxyPort = await _sharedCdpProxy.start();
589
+ sharedCdpProxy = new CDPInterceptorProxy(config);
590
+ const proxyPort = await sharedCdpProxy.start();
653
591
  console.error(`[CDP Interceptor] Proxy running on ws://localhost:${proxyPort}, forwarding to ${realEndpoint}`);
654
592
  const { browser: browser3 } = await launch({ cdpEndpoint: `ws://localhost:${proxyPort}` });
655
593
  return browser3;
656
594
  }
657
595
  const { browser: browser2 } = await launch({ cdpEndpoint: realEndpoint });
658
- await browser2.discoverContexts().catch((err) => {
659
- console.error(`[browser] discoverContexts failed: ${errMsg(err)}`);
596
+ await browser2.discoverContexts().catch((error) => {
597
+ console.error(`[browser] discoverContexts failed: ${errMsg(error)}`);
660
598
  });
661
- if (!options.intercept) _browserPool.set(realEndpoint, browser2);
599
+ browserPool.set(realEndpoint, browser2);
662
600
  return browser2;
663
601
  }
664
602
  const executablePath = options?.executablePath || process.env.XBROWSER_CHROMIUM_PATH || discoverChromiumPath();
665
603
  const { browser } = await launch({ executablePath, headless: options?.headless ?? true });
666
604
  return browser;
667
605
  }
668
- async function getBrowser(options) {
669
- if (_sharedBrowser) return _sharedBrowser;
670
- _sharedBrowser = await createBrowser(options);
671
- if (options?.cdpEndpoint && options.intercept) {
672
- }
673
- return _sharedBrowser;
674
- }
675
- function findSession(name) {
676
- return sessions.find(name);
677
- }
678
- function getSessionById(id) {
679
- return sessions.get(id);
606
+
607
+ // src/browser/state.ts
608
+ import { randomUUID } from "crypto";
609
+ import { existsSync as existsSync2, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "fs";
610
+ import { join } from "path";
611
+ import { homedir } from "os";
612
+ import { SessionStore } from "@dyyz1993/xcli-core";
613
+ var SESSION_DIR = join(homedir(), ".xbrowser", "sessions");
614
+ var sessions = new SessionStore();
615
+ var sharedState = { browser: null, idleTimer: null };
616
+ function sessionFile(name) {
617
+ return join(SESSION_DIR, `${name}.json`);
680
618
  }
681
- function setActivePage(session, page) {
682
- session.page = page;
683
- session.lastActivityAt = Date.now();
619
+ function ensureSessionDir() {
620
+ mkdirSync(SESSION_DIR, { recursive: true });
684
621
  }
685
622
  function saveSessionDiskMeta(name, data) {
686
623
  ensureSessionDir();
@@ -694,20 +631,40 @@ function saveSessionDiskMeta(name, data) {
694
631
  writeFileSync(file, JSON.stringify(existing, null, 2));
695
632
  }
696
633
  function readSessionDiskMeta(name) {
697
- const file = sessionFile(name);
698
634
  try {
699
- return JSON.parse(readFileSync(file, "utf8"));
635
+ return JSON.parse(readFileSync(sessionFile(name), "utf8"));
700
636
  } catch {
701
637
  return null;
702
638
  }
703
639
  }
704
640
  function deleteSessionDiskMeta(name) {
705
- const file = sessionFile(name);
706
641
  try {
707
- unlinkSync(file);
642
+ unlinkSync(sessionFile(name));
708
643
  } catch {
709
644
  }
710
645
  }
646
+ function newSessionId() {
647
+ return randomUUID();
648
+ }
649
+
650
+ // src/browser/lifecycle.ts
651
+ function registerSession(session) {
652
+ const complete = {
653
+ id: session.id ?? newSessionId(),
654
+ createdAt: session.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
655
+ lastActivityAt: session.lastActivityAt ?? Date.now(),
656
+ ...session
657
+ };
658
+ sessions.set(complete);
659
+ resetIdleTimer();
660
+ return complete;
661
+ }
662
+
663
+ // src/browser/restore.ts
664
+ function logSessionEvent(event, details) {
665
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
666
+ console.error(`[SESSION] ${timestamp} [PID:${process.pid}] ${event} | ${details}`);
667
+ }
711
668
  async function isSessionPageAlive(session) {
712
669
  const page = session.page;
713
670
  if (!page || typeof page.evaluate !== "function") return false;
@@ -719,69 +676,65 @@ async function isSessionPageAlive(session) {
719
676
  ]);
720
677
  return true;
721
678
  } catch {
722
- await new Promise((r) => setTimeout(r, 400));
679
+ await new Promise((resolve) => setTimeout(resolve, 400));
723
680
  }
724
681
  }
725
682
  return false;
726
683
  }
727
- async function findOrRestoreSession(name, cdpEndpoint) {
728
- const inMem = findSession(name);
729
- if (inMem) {
730
- if (await isSessionPageAlive(inMem)) return inMem;
731
- 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`);
684
+ async function findOrRestoreSession(name, cdpEndpoint, cleanup = async () => false, installNetworkCapture2 = async () => {
685
+ }) {
686
+ const inMemory = findSession(name);
687
+ if (inMemory) {
688
+ if (await isSessionPageAlive(inMemory)) return inMemory;
689
+ logSessionEvent("stale_session", `name="${name}" \u2014 page probe failed; rebuilding`);
732
690
  try {
733
- await closeSessionByName(name);
691
+ await cleanup(name);
734
692
  } catch {
735
693
  }
736
694
  }
737
695
  const meta = readSessionDiskMeta(name);
738
696
  if (!meta) return void 0;
739
- const ep = cdpEndpoint || meta.cdpEndpoint;
740
- if (!ep) return void 0;
697
+ const endpoint = cdpEndpoint || meta.cdpEndpoint;
698
+ if (!endpoint) return void 0;
741
699
  try {
742
- const b = await createBrowser({ cdpEndpoint: ep });
743
- await new Promise((r) => setTimeout(r, 500));
744
- let contexts = b.contexts();
700
+ const browser = await createBrowser({ cdpEndpoint: endpoint });
701
+ await new Promise((resolve) => setTimeout(resolve, 500));
702
+ let contexts = browser.contexts();
745
703
  if (contexts.length === 0) {
746
- await new Promise((r) => setTimeout(r, 500));
747
- contexts = b.contexts();
704
+ await new Promise((resolve) => setTimeout(resolve, 500));
705
+ contexts = browser.contexts();
748
706
  }
749
- const context = contexts[0] || await b.newContext();
707
+ const context = contexts[0] || await browser.newContext();
750
708
  const savedUrl = meta.conversationUrl || meta.url;
751
- const targetHostname = savedUrl ? (() => {
709
+ let targetHostname = "";
710
+ if (savedUrl) {
752
711
  try {
753
- return new URL(savedUrl).hostname;
712
+ targetHostname = new URL(savedUrl).hostname;
754
713
  } catch {
755
- return "";
714
+ targetHostname = "";
756
715
  }
757
- })() : "";
716
+ }
758
717
  let page = null;
759
718
  let fallbackPage = null;
760
- for (const ctx of contexts) {
761
- const pages = ctx.pages();
762
- for (const p of pages) {
763
- const pUrl = p.url();
764
- if (pUrl && pUrl !== "about:blank" && !pUrl.startsWith("chrome://") && !pUrl.startsWith("chrome-untrusted://") && !pUrl.startsWith("chrome-error://")) {
765
- if (targetHostname && pUrl.includes(targetHostname)) {
766
- page = p;
767
- break;
768
- }
769
- if (!fallbackPage) {
770
- fallbackPage = p;
771
- }
719
+ for (const browserContext of contexts) {
720
+ for (const candidate of browserContext.pages()) {
721
+ const url = candidate.url();
722
+ if (!url || url === "about:blank" || url.startsWith("chrome://") || url.startsWith("chrome-untrusted://") || url.startsWith("chrome-error://")) continue;
723
+ if (targetHostname && url.includes(targetHostname)) {
724
+ page = candidate;
725
+ break;
772
726
  }
727
+ fallbackPage ??= candidate;
773
728
  }
774
729
  if (page) break;
775
730
  }
776
- page = page || fallbackPage;
731
+ page ??= fallbackPage;
777
732
  if (!page) {
778
- const targets = await getCDPTargets(ep);
779
- const matchTarget = targets.find(
780
- (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)
781
- );
782
- if (matchTarget && matchTarget.url) {
733
+ const targets = await getCDPTargets(endpoint);
734
+ 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)));
735
+ if (match?.url) {
783
736
  page = await context.newPage();
784
- await page.goto(matchTarget.url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
737
+ await page.goto(match.url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
785
738
  });
786
739
  }
787
740
  }
@@ -795,7 +748,6 @@ async function findOrRestoreSession(name, cdpEndpoint) {
795
748
  new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 3e3))
796
749
  ]);
797
750
  } catch {
798
- console.log(`[Session] "${name}" restored page unresponsive, creating fresh session`);
799
751
  deleteSessionDiskMeta(name);
800
752
  return void 0;
801
753
  }
@@ -810,191 +762,41 @@ async function findOrRestoreSession(name, cdpEndpoint) {
810
762
  }
811
763
  }
812
764
  const session = {
813
- id: meta.id || randomUUID(),
765
+ id: meta.id,
814
766
  name,
815
767
  context,
816
768
  page,
817
- browser: b,
818
- createdAt: meta.createdAt || (/* @__PURE__ */ new Date()).toISOString(),
769
+ browser,
770
+ createdAt: meta.createdAt,
819
771
  lastActivityAt: Date.now(),
820
772
  isCDP: true,
821
- cdpEndpoint: ep
773
+ cdpEndpoint: endpoint
822
774
  };
823
- for (const existingSession of sessions.list()) {
824
- if (existingSession.name === name) {
825
- logSessionEvent("remove_stale", `Removing stale session name="${name}" id="${existingSession.id}" during restore`);
826
- sessions.removeById(existingSession.id);
827
- }
775
+ for (const existing of sessions.list()) {
776
+ if (existing.name === name) sessions.removeById(existing.id);
828
777
  }
829
778
  sessions.set(session);
830
- resetIdleTimer();
831
- await installNetworkCapture(page, name);
779
+ await installNetworkCapture2(session.page, name);
832
780
  return session;
833
- } catch (e) {
834
- console.error(`[Session Restore] Failed for "${name}":`, errMsg(e));
781
+ } catch (error) {
782
+ console.error(`[Session Restore] Failed for "${name}":`, errMsg(error));
835
783
  deleteSessionDiskMeta(name);
836
784
  return void 0;
837
785
  }
838
786
  }
839
- async function createEphemeralContext(options) {
840
- if (options?.cdpEndpoint) {
841
- const endpoint = await resolveCDPEndpoint(options.cdpEndpoint);
842
- const { browser: b2 } = await launch({ cdpEndpoint: endpoint });
843
- const contexts = b2.contexts();
844
- const ctx = contexts[0] || await b2.newContext();
845
- const allPages = ctx.pages();
846
- const existingPages = allPages.filter((p) => {
847
- const url = p.url();
848
- return url !== "about:blank" && !url.startsWith("chrome://") && !url.startsWith("chrome-untrusted://") && !url.startsWith("chrome-error://");
849
- });
850
- const page2 = existingPages.length > 0 ? existingPages[0] : allPages.length > 0 ? allPages[0] : await ctx.newPage();
851
- resetIdleTimer();
852
- ephemeralConnections.set(page2, b2);
853
- return { context: ctx, page: page2 };
854
- }
855
- const b = await getBrowser(options);
856
- const context = await b.newContext();
857
- const page = await context.newPage();
858
- resetIdleTimer();
859
- return { context, page };
860
- }
861
- var ephemeralConnections = /* @__PURE__ */ new WeakMap();
862
- async function closeEphemeralContext(context) {
863
- try {
864
- const pages = context.pages();
865
- for (const p of pages) {
866
- const conn = ephemeralConnections.get(p);
867
- if (conn) {
868
- ephemeralConnections.delete(p);
869
- await conn.close();
870
- break;
871
- }
872
- }
873
- await context.close();
874
- } catch {
875
- }
876
- if (sessions.size === 0 && idleTimer) {
877
- clearTimeout(idleTimer);
878
- idleTimer = null;
879
- }
880
- }
881
- function getAllSessions() {
882
- return sessions.list();
883
- }
884
- async function installNetworkCapture(page, sessionName) {
885
- if (process.env.XBROWSER_DAEMON_WORKER !== "1") return;
886
- const { networkStore } = await import("./network-store-XGZ25FFC.js");
887
- const requestData = /* @__PURE__ */ new Map();
888
- const responseMeta = /* @__PURE__ */ new Map();
889
- const xbPage = page;
890
- xbPage.on("request", (params) => {
891
- try {
892
- const p = params;
893
- requestData.set(p.requestId, {
894
- method: p.request.method,
895
- headers: p.request.headers,
896
- postData: p.request.postData ?? null,
897
- resourceType: p.type
898
- });
899
- } catch {
900
- }
901
- });
902
- xbPage.on("response", (params) => {
903
- try {
904
- const p = params;
905
- responseMeta.set(p.requestId, {
906
- status: p.response.status,
907
- url: p.response.url,
908
- headers: p.response.headers,
909
- mimeType: p.response.mimeType,
910
- type: p.type
911
- });
912
- } catch {
913
- }
914
- });
915
- xbPage.on("requestfinished", async (params) => {
916
- try {
917
- const p = params;
918
- const meta = responseMeta.get(p.requestId);
919
- if (!meta) return;
920
- const req = requestData.get(p.requestId);
921
- const method = req?.method ?? "GET";
922
- const contentType = meta.headers["content-type"] || meta.headers["Content-Type"] || "";
923
- const resourceType = req?.resourceType ?? meta.type;
924
- const requestHeaders = req?.headers ?? {};
925
- let requestBody = void 0;
926
- const isPostLike = ["POST", "PATCH", "PUT"].includes(method);
927
- if (isPostLike && requestHeaders["content-type"]?.includes("application/json")) {
928
- const postData = req?.postData;
929
- if (postData) {
930
- try {
931
- requestBody = JSON.parse(postData);
932
- } catch {
933
- requestBody = postData;
934
- }
935
- }
936
- }
937
- let responseBody = void 0;
938
- let size = 0;
939
- const isJsonish = contentType.includes("json") || contentType.includes("javascript") || contentType.includes("text/");
940
- if (isJsonish) {
941
- try {
942
- const bodyResult = await xbPage._cdpSend(
943
- "Network.getResponseBody",
944
- { requestId: p.requestId }
945
- );
946
- const text = bodyResult.body ?? "";
947
- size = text.length;
948
- if (size <= 10240) {
949
- try {
950
- responseBody = JSON.parse(text);
951
- } catch {
952
- responseBody = text.slice(0, 200);
953
- }
954
- }
955
- } catch {
956
- }
957
- } else {
958
- try {
959
- const bodyResult = await xbPage._cdpSend(
960
- "Network.getResponseBody",
961
- { requestId: p.requestId }
962
- );
963
- size = bodyResult.body?.length ?? 0;
964
- } catch {
965
- size = 0;
966
- }
967
- }
968
- networkStore.add(sessionName, {
969
- timestamp: Date.now(),
970
- method,
971
- url: meta.url,
972
- path: new URL(meta.url).pathname,
973
- status: meta.status,
974
- contentType,
975
- size,
976
- headers: meta.headers,
977
- body: responseBody,
978
- requestHeaders,
979
- requestBody,
980
- resourceType
981
- });
982
- requestData.delete(p.requestId);
983
- responseMeta.delete(p.requestId);
984
- } catch {
985
- }
986
- });
987
- }
988
- async function createSession(name, url, options) {
787
+
788
+ // src/browser/create-session.ts
789
+ async function createSessionImpl(name, url, options, deps) {
989
790
  const existing = findSession(name);
990
791
  if (existing) {
991
- logSessionEvent("replace_session", `name="${name}" id="${existing.id}" \u2014 closing existing session before creating new one`);
992
- await closeSessionByName(name);
792
+ deps.logSessionEvent("replace_session", `name="${name}" id="${existing.id}" \u2014 closing existing session before creating new one`);
793
+ await deps.closeSessionByName(name);
993
794
  }
994
795
  const b = await createBrowser(options);
995
796
  const isCDP = !!options?.cdpEndpoint;
996
797
  let context;
997
798
  let page;
799
+ let reusedExistingPage = false;
998
800
  if (isCDP) {
999
801
  const targetHostname = url ? (() => {
1000
802
  try {
@@ -1076,22 +878,12 @@ async function createSession(name, url, options) {
1076
878
  const pUrl0 = await resolvePageUrl(p);
1077
879
  if (ownedUrls.has(pUrl0)) continue;
1078
880
  const pUrl = pUrl0;
1079
- if (isRealPageUrl(pUrl) && pUrl.includes(targetHostname)) {
1080
- targetPage = p;
1081
- break;
881
+ let hostnameMatches = false;
882
+ try {
883
+ hostnameMatches = new URL(pUrl).hostname === targetHostname;
884
+ } catch {
1082
885
  }
1083
- }
1084
- if (targetPage) break;
1085
- }
1086
- }
1087
- if (!targetPage) {
1088
- for (const ctx of contexts) {
1089
- const pages = ctx.pages();
1090
- for (const p of pages) {
1091
- const pUrl0 = await resolvePageUrl(p);
1092
- if (ownedUrls.has(pUrl0)) continue;
1093
- const pUrl = pUrl0;
1094
- if (isRealPageUrl(pUrl)) {
886
+ if (isRealPageUrl(pUrl) && hostnameMatches) {
1095
887
  targetPage = p;
1096
888
  break;
1097
889
  }
@@ -1100,7 +892,7 @@ async function createSession(name, url, options) {
1100
892
  }
1101
893
  }
1102
894
  if (!targetPage && options?.cdpEndpoint) {
1103
- const targets = await getCDPTargets(options.cdpEndpoint);
895
+ const targets = await deps.getCDPTargets(options.cdpEndpoint);
1104
896
  const ownedUrlsT = /* @__PURE__ */ new Set();
1105
897
  for (const ssn of sessions.list()) {
1106
898
  try {
@@ -1109,9 +901,15 @@ async function createSession(name, url, options) {
1109
901
  } catch {
1110
902
  }
1111
903
  }
1112
- const matchTarget = targets.find(
1113
- (t) => t.url && t.url !== "about:blank" && !t.url.startsWith("chrome://") && !t.url.startsWith("chrome-untrusted://") && !t.url.startsWith("chrome-error://") && !ownedUrlsT.has(t.url) && (url ? t.url === url || t.url.includes(new URL(url).hostname) : true)
1114
- );
904
+ const matchTarget = targets.find((t) => {
905
+ if (!t.url || !isRealPageUrl(t.url) || ownedUrlsT.has(t.url)) return false;
906
+ if (!url) return false;
907
+ try {
908
+ return new URL(t.url).hostname === targetHostname;
909
+ } catch {
910
+ return false;
911
+ }
912
+ });
1115
913
  if (matchTarget && matchTarget.url) {
1116
914
  const ownedUrls2 = /* @__PURE__ */ new Set();
1117
915
  for (const ssn of sessions.list()) {
@@ -1144,31 +942,12 @@ async function createSession(name, url, options) {
1144
942
  }
1145
943
  }
1146
944
  }
945
+ const targetPageExisted = !!targetPage;
1147
946
  if (!targetPage) {
1148
- const pages = context.pages();
1149
- if (pages.length > 1) {
1150
- try {
1151
- const owned = /* @__PURE__ */ new Set();
1152
- for (const ssn of sessions.list()) owned.add(ssn.page);
1153
- for (const p of pages) {
1154
- if (owned.has(p)) continue;
1155
- const vis = await p.evaluate("document.visibilityState").catch(() => "hidden");
1156
- if (vis === "visible") {
1157
- targetPage = p;
1158
- break;
1159
- }
1160
- }
1161
- } catch {
1162
- }
1163
- }
1164
- if (!targetPage && pages.length > 0) {
1165
- targetPage = pages[0];
1166
- }
1167
- if (!targetPage) {
1168
- targetPage = await context.newPage();
1169
- }
947
+ targetPage = await context.newPage();
1170
948
  }
1171
949
  page = targetPage;
950
+ reusedExistingPage = targetPageExisted;
1172
951
  if (isCDP) {
1173
952
  await Promise.resolve(targetPage.bringToFront?.()).catch(() => {
1174
953
  });
@@ -1181,30 +960,280 @@ async function createSession(name, url, options) {
1181
960
  await page.goto(url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
1182
961
  });
1183
962
  }
1184
- const session = {
1185
- id: randomUUID(),
963
+ const session = deps.registerSession({
1186
964
  name,
1187
965
  context,
1188
966
  page,
1189
967
  browser: b,
1190
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1191
- lastActivityAt: Date.now(),
1192
968
  isCDP,
1193
- cdpEndpoint: options?.cdpEndpoint
1194
- };
1195
- sessions.set(session);
1196
- logSessionEvent("create_session", `name="${name}" id="${session.id}" url="${url || "(no url)"}" isCDP=${isCDP} cdpEndpoint=${options?.cdpEndpoint || "(none)"}`);
1197
- resetIdleTimer();
1198
- await installNetworkCapture(page, name);
969
+ cdpEndpoint: options?.cdpEndpoint,
970
+ ...isCDP ? { reusedExistingPage } : {}
971
+ });
972
+ deps.logSessionEvent("create_session", `name="${name}" id="${session.id}" url="${url || "(no url)"}" isCDP=${isCDP} cdpEndpoint=${options?.cdpEndpoint || "(none)"}`);
973
+ await deps.installNetworkCapture(page, name);
1199
974
  return session;
1200
975
  }
976
+
977
+ // src/browser.ts
978
+ function logSessionEvent2(event, details) {
979
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
980
+ console.error(`[SESSION] ${timestamp} [PID:${process.pid}] ${event} | ${details}`);
981
+ }
982
+ var IDLE_TIMEOUT_MS = (process.env.XBROWSER_IDLE_TIMEOUT ? parseInt(process.env.XBROWSER_IDLE_TIMEOUT, 10) : 30) * 60 * 1e3;
983
+ function resetIdleTimer() {
984
+ if (sharedState.idleTimer) clearTimeout(sharedState.idleTimer);
985
+ sharedState.idleTimer = setTimeout(async () => {
986
+ const now = Date.now();
987
+ let allIdle = true;
988
+ const idleSessions = [];
989
+ for (const s of sessions) {
990
+ if (now - s.lastActivityAt < IDLE_TIMEOUT_MS) {
991
+ allIdle = false;
992
+ } else {
993
+ idleSessions.push(`${s.name}(${(now - s.lastActivityAt) / 1e3}s idle)`);
994
+ }
995
+ }
996
+ if (allIdle && (sessions.size > 0 || sharedState.browser)) {
997
+ logSessionEvent2("idle_timeout", `Sessions idle for >${IDLE_TIMEOUT_MS / 6e4}min. Sessions: ${idleSessions.join(", ") || "all"}. Calling destroyBrowser()`);
998
+ await destroyBrowser().catch(() => {
999
+ });
1000
+ }
1001
+ }, IDLE_TIMEOUT_MS);
1002
+ if (sharedState.idleTimer && typeof sharedState.idleTimer.unref === "function") {
1003
+ sharedState.idleTimer.unref();
1004
+ }
1005
+ }
1006
+ async function findOrRestoreSession2(name, cdpEndpoint) {
1007
+ return findOrRestoreSession(
1008
+ name,
1009
+ cdpEndpoint,
1010
+ closeSessionByName,
1011
+ installNetworkCapture
1012
+ );
1013
+ }
1014
+ function touchSession(id) {
1015
+ const s = sessions.get(id);
1016
+ if (s) s.lastActivityAt = Date.now();
1017
+ resetIdleTimer();
1018
+ }
1019
+ process.on("exit", () => {
1020
+ for (const session of sessions.list()) {
1021
+ if (session.isCDP) {
1022
+ logSessionEvent2("process_exit", `Session "${session.name}": CDP connection (not closing external browser).`);
1023
+ } else {
1024
+ logSessionEvent2("process_exit", `Session "${session.name}": Closing self-launched browser.`);
1025
+ try {
1026
+ session.browser?.close();
1027
+ } catch {
1028
+ }
1029
+ }
1030
+ }
1031
+ if (sharedState.browser) {
1032
+ logSessionEvent2("process_exit", "Closing shared browser (self-launched only, external CDP is safe).");
1033
+ try {
1034
+ sharedState.browser.close();
1035
+ } catch {
1036
+ }
1037
+ sharedState.browser = null;
1038
+ }
1039
+ const cdpProxy = getSharedCdpProxy();
1040
+ if (cdpProxy) {
1041
+ try {
1042
+ cdpProxy.stop();
1043
+ } catch {
1044
+ }
1045
+ setSharedCdpProxy(null);
1046
+ }
1047
+ sessions.clear();
1048
+ });
1049
+ async function getBrowser(options) {
1050
+ if (sharedState.browser) return sharedState.browser;
1051
+ sharedState.browser = await createBrowser(options);
1052
+ if (options?.cdpEndpoint && options.intercept) {
1053
+ }
1054
+ return sharedState.browser;
1055
+ }
1056
+ function findSession(name) {
1057
+ return sessions.find(name);
1058
+ }
1059
+ function getSessionById2(id) {
1060
+ return sessions.get(id);
1061
+ }
1062
+ function setActivePage2(session, page) {
1063
+ session.page = page;
1064
+ session.lastActivityAt = Date.now();
1065
+ }
1066
+ async function createEphemeralContext(options) {
1067
+ if (options?.cdpEndpoint) {
1068
+ const endpoint = await resolveCDPEndpoint(options.cdpEndpoint);
1069
+ const { browser: b2 } = await launch({ cdpEndpoint: endpoint });
1070
+ const contexts = b2.contexts();
1071
+ const ctx = contexts[0] || await b2.newContext();
1072
+ const allPages = ctx.pages();
1073
+ const existingPages = allPages.filter((p) => {
1074
+ const url = p.url();
1075
+ return url !== "about:blank" && !url.startsWith("chrome://") && !url.startsWith("chrome-untrusted://") && !url.startsWith("chrome-error://");
1076
+ });
1077
+ const page2 = existingPages.length > 0 ? existingPages[0] : allPages.length > 0 ? allPages[0] : await ctx.newPage();
1078
+ resetIdleTimer();
1079
+ ephemeralConnections.set(page2, b2);
1080
+ return { context: ctx, page: page2 };
1081
+ }
1082
+ const b = await getBrowser(options);
1083
+ const context = await b.newContext();
1084
+ const page = await context.newPage();
1085
+ resetIdleTimer();
1086
+ return { context, page };
1087
+ }
1088
+ var ephemeralConnections = /* @__PURE__ */ new WeakMap();
1089
+ async function closeEphemeralContext(context) {
1090
+ try {
1091
+ const pages = context.pages();
1092
+ for (const p of pages) {
1093
+ const conn = ephemeralConnections.get(p);
1094
+ if (conn) {
1095
+ ephemeralConnections.delete(p);
1096
+ await conn.close();
1097
+ break;
1098
+ }
1099
+ }
1100
+ await context.close();
1101
+ } catch {
1102
+ }
1103
+ if (sessions.size === 0 && sharedState.idleTimer) {
1104
+ clearTimeout(sharedState.idleTimer);
1105
+ sharedState.idleTimer = null;
1106
+ }
1107
+ }
1108
+ function getAllSessions2() {
1109
+ return sessions.list();
1110
+ }
1111
+ async function installNetworkCapture(page, sessionName) {
1112
+ if (process.env.XBROWSER_DAEMON_WORKER !== "1") return;
1113
+ const { networkStore } = await import("./network-store-XGZ25FFC.js");
1114
+ const requestData = /* @__PURE__ */ new Map();
1115
+ const responseMeta = /* @__PURE__ */ new Map();
1116
+ const xbPage = page;
1117
+ xbPage.on("request", (params) => {
1118
+ try {
1119
+ const p = params;
1120
+ requestData.set(p.requestId, {
1121
+ method: p.request.method,
1122
+ headers: p.request.headers,
1123
+ postData: p.request.postData ?? null,
1124
+ resourceType: p.type
1125
+ });
1126
+ } catch {
1127
+ }
1128
+ });
1129
+ xbPage.on("response", (params) => {
1130
+ try {
1131
+ const p = params;
1132
+ responseMeta.set(p.requestId, {
1133
+ status: p.response.status,
1134
+ url: p.response.url,
1135
+ headers: p.response.headers,
1136
+ mimeType: p.response.mimeType,
1137
+ type: p.type
1138
+ });
1139
+ } catch {
1140
+ }
1141
+ });
1142
+ xbPage.on("requestfinished", async (params) => {
1143
+ try {
1144
+ const p = params;
1145
+ const meta = responseMeta.get(p.requestId);
1146
+ if (!meta) return;
1147
+ const req = requestData.get(p.requestId);
1148
+ const method = req?.method ?? "GET";
1149
+ const contentType = meta.headers["content-type"] || meta.headers["Content-Type"] || "";
1150
+ const resourceType = req?.resourceType ?? meta.type;
1151
+ const requestHeaders = req?.headers ?? {};
1152
+ let requestBody = void 0;
1153
+ const isPostLike = ["POST", "PATCH", "PUT"].includes(method);
1154
+ if (isPostLike && requestHeaders["content-type"]?.includes("application/json")) {
1155
+ const postData = req?.postData;
1156
+ if (postData) {
1157
+ try {
1158
+ requestBody = JSON.parse(postData);
1159
+ } catch {
1160
+ requestBody = postData;
1161
+ }
1162
+ }
1163
+ }
1164
+ let responseBody = void 0;
1165
+ let size = 0;
1166
+ const isJsonish = contentType.includes("json") || contentType.includes("javascript") || contentType.includes("text/");
1167
+ if (isJsonish) {
1168
+ try {
1169
+ const bodyResult = await xbPage._cdpSend(
1170
+ "Network.getResponseBody",
1171
+ { requestId: p.requestId }
1172
+ );
1173
+ const text = bodyResult.body ?? "";
1174
+ size = text.length;
1175
+ if (size <= 10240) {
1176
+ try {
1177
+ responseBody = JSON.parse(text);
1178
+ } catch {
1179
+ responseBody = text.slice(0, 200);
1180
+ }
1181
+ }
1182
+ } catch {
1183
+ }
1184
+ } else {
1185
+ try {
1186
+ const bodyResult = await xbPage._cdpSend(
1187
+ "Network.getResponseBody",
1188
+ { requestId: p.requestId }
1189
+ );
1190
+ size = bodyResult.body?.length ?? 0;
1191
+ } catch {
1192
+ size = 0;
1193
+ }
1194
+ }
1195
+ networkStore.add(sessionName, {
1196
+ timestamp: Date.now(),
1197
+ method,
1198
+ url: meta.url,
1199
+ path: new URL(meta.url).pathname,
1200
+ status: meta.status,
1201
+ contentType,
1202
+ size,
1203
+ headers: meta.headers,
1204
+ body: responseBody,
1205
+ requestHeaders,
1206
+ requestBody,
1207
+ resourceType
1208
+ });
1209
+ requestData.delete(p.requestId);
1210
+ responseMeta.delete(p.requestId);
1211
+ } catch {
1212
+ }
1213
+ });
1214
+ }
1215
+ async function createSession(name, url, options) {
1216
+ return createSessionImpl(name, url, options, {
1217
+ closeSessionByName,
1218
+ installNetworkCapture,
1219
+ registerSession,
1220
+ logSessionEvent: logSessionEvent2,
1221
+ getCDPTargets
1222
+ });
1223
+ }
1201
1224
  async function closeSessionByName(name) {
1202
1225
  for (const session of sessions) {
1203
1226
  if (session.name === name || session.id === name) {
1204
- logSessionEvent("close_session", `name="${session.name}" id="${session.id}" url="${session.page.url()}"`);
1227
+ logSessionEvent2("close_session", `name="${session.name}" id="${session.id}" url="${session.page.url()}"`);
1205
1228
  if (session.isCDP) {
1206
- if (session.browser) {
1207
- await session.browser.close().catch(() => {
1229
+ if (session.reusedExistingPage) {
1230
+ logSessionEvent2("close_session", `name="${session.name}" \u2014 reused existing tab, disconnecting only`);
1231
+ await session.browser.disconnect().catch(() => {
1232
+ });
1233
+ } else {
1234
+ await session.page.close().catch(() => {
1235
+ });
1236
+ await session.browser.disconnect().catch(() => {
1208
1237
  });
1209
1238
  }
1210
1239
  } else {
@@ -1217,7 +1246,7 @@ async function closeSessionByName(name) {
1217
1246
  sessions.removeById(session.id);
1218
1247
  const file2 = sessionFile(session.name);
1219
1248
  try {
1220
- unlinkSync(file2);
1249
+ unlinkSync2(file2);
1221
1250
  } catch {
1222
1251
  }
1223
1252
  try {
@@ -1227,7 +1256,7 @@ async function closeSessionByName(name) {
1227
1256
  } catch {
1228
1257
  }
1229
1258
  try {
1230
- const { SessionRecorder } = await import("./session-recorder-GEZVQBKW.js");
1259
+ const { SessionRecorder } = await import("./session-recorder-N7VEKJVW.js");
1231
1260
  SessionRecorder.cleanup(session.name);
1232
1261
  } catch {
1233
1262
  }
@@ -1236,14 +1265,14 @@ async function closeSessionByName(name) {
1236
1265
  }
1237
1266
  const file = sessionFile(name);
1238
1267
  try {
1239
- unlinkSync(file);
1268
+ unlinkSync2(file);
1240
1269
  } catch {
1241
1270
  }
1242
1271
  return false;
1243
1272
  }
1244
1273
  async function closeAllSessions() {
1245
1274
  const names = sessions.list().map((s) => `${s.name}(${s.page.url()})`).join(", ");
1246
- if (names) logSessionEvent("close_all_sessions", `Closing ${sessions.size} sessions: ${names}`);
1275
+ if (names) logSessionEvent2("close_all_sessions", `Closing ${sessions.size} sessions: ${names}`);
1247
1276
  for (const session of sessions.list()) {
1248
1277
  try {
1249
1278
  if (session.isCDP) {
@@ -1265,38 +1294,37 @@ async function closeAllSessions() {
1265
1294
  }
1266
1295
  }
1267
1296
  async function destroyBrowser() {
1268
- logSessionEvent("destroy_browser", `Sessions count: ${sessions.size}. Clearing idle timer and closing all sessions.`);
1269
- if (idleTimer) {
1270
- clearTimeout(idleTimer);
1271
- idleTimer = null;
1297
+ logSessionEvent2("destroy_browser", `Sessions count: ${sessions.size}. Clearing idle timer and closing all sessions.`);
1298
+ if (sharedState.idleTimer) {
1299
+ clearTimeout(sharedState.idleTimer);
1300
+ sharedState.idleTimer = null;
1272
1301
  }
1273
1302
  await closeAllSessions();
1274
- if (_sharedBrowser) {
1275
- await _sharedBrowser.close().catch(() => {
1303
+ if (sharedState.browser) {
1304
+ await sharedState.browser.close().catch(() => {
1276
1305
  });
1277
- _sharedBrowser = null;
1306
+ sharedState.browser = null;
1278
1307
  }
1279
- if (_sharedCdpProxy) {
1280
- await _sharedCdpProxy.stop().catch(() => {
1308
+ if (getSharedCdpProxy()) {
1309
+ await getSharedCdpProxy().stop().catch(() => {
1281
1310
  });
1282
- _sharedCdpProxy = null;
1311
+ setSharedCdpProxy(null);
1283
1312
  }
1284
1313
  }
1285
1314
  function resetForTesting() {
1286
1315
  sessions.clear();
1287
- _sharedBrowser = null;
1288
- _sharedCdpProxy = null;
1316
+ sharedState.browser = null;
1317
+ sharedState.idleTimer = null;
1318
+ setSharedCdpProxy(null);
1289
1319
  try {
1290
- for (const f of readdirSync(SESSION_DIR)) {
1291
- unlinkSync(join(SESSION_DIR, f));
1292
- }
1320
+ for (const file of readdirSync2(SESSION_DIR)) unlinkSync2(join2(SESSION_DIR, file));
1293
1321
  } catch {
1294
1322
  }
1295
1323
  }
1296
1324
  async function ensureProcessCanExit() {
1297
- if (idleTimer) {
1298
- clearTimeout(idleTimer);
1299
- idleTimer = null;
1325
+ if (sharedState.idleTimer) {
1326
+ clearTimeout(sharedState.idleTimer);
1327
+ sharedState.idleTimer = null;
1300
1328
  }
1301
1329
  for (const session of sessions.list()) {
1302
1330
  if (session.browser) {
@@ -1308,35 +1336,36 @@ async function ensureProcessCanExit() {
1308
1336
  }
1309
1337
  }
1310
1338
  sessions.clear();
1311
- if (_sharedBrowser) {
1312
- await _sharedBrowser.close().catch(() => {
1339
+ if (sharedState.browser) {
1340
+ await sharedState.browser.close().catch(() => {
1313
1341
  });
1314
- _sharedBrowser = null;
1342
+ sharedState.browser = null;
1315
1343
  }
1316
- if (_sharedCdpProxy) {
1317
- await _sharedCdpProxy.stop().catch(() => {
1344
+ if (getSharedCdpProxy()) {
1345
+ await getSharedCdpProxy().stop().catch(() => {
1318
1346
  });
1319
- _sharedCdpProxy = null;
1347
+ setSharedCdpProxy(null);
1320
1348
  }
1321
1349
  }
1322
1350
 
1323
1351
  export {
1324
1352
  resolveCDPEndpoint,
1325
- touchSession,
1326
1353
  findTargetPage,
1327
1354
  resolveLaunchOpts,
1328
1355
  createBrowser,
1329
- getBrowser,
1330
- findSession,
1331
- getSessionById,
1332
- setActivePage,
1333
1356
  saveSessionDiskMeta,
1334
1357
  readSessionDiskMeta,
1335
1358
  deleteSessionDiskMeta,
1336
- findOrRestoreSession,
1359
+ resetIdleTimer,
1360
+ findOrRestoreSession2 as findOrRestoreSession,
1361
+ touchSession,
1362
+ getBrowser,
1363
+ findSession,
1364
+ getSessionById2 as getSessionById,
1365
+ setActivePage2 as setActivePage,
1337
1366
  createEphemeralContext,
1338
1367
  closeEphemeralContext,
1339
- getAllSessions,
1368
+ getAllSessions2 as getAllSessions,
1340
1369
  createSession,
1341
1370
  closeSessionByName,
1342
1371
  closeAllSessions,