@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,18 +1,16 @@
1
1
  import {
2
2
  launch
3
- } from "./chunk-J3HXZVSN.js";
3
+ } from "./chunk-SPNWUUHA.js";
4
4
  import {
5
5
  errMsg
6
6
  } from "./chunk-GDKLH7ZY.js";
7
7
  import {
8
8
  CDPInterceptorProxy
9
- } from "./chunk-WYETQ5C7.js";
9
+ } from "./chunk-NEE6EMYA.js";
10
10
 
11
11
  // src/browser.ts
12
- import { randomUUID } from "crypto";
13
- import { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "fs";
14
- import { join } from "path";
15
- import { homedir } from "os";
12
+ import { readdirSync as readdirSync2, unlinkSync as unlinkSync2 } from "fs";
13
+ import { join as join2 } from "path";
16
14
 
17
15
  // src/utils/cdp.ts
18
16
  async function fetchNoProxy(url) {
@@ -84,116 +82,39 @@ async function resolveCDPEndpoint(raw) {
84
82
  return raw;
85
83
  }
86
84
 
87
- // src/browser.ts
88
- import { SessionStore } from "@dyyz1993/xcli-core";
89
- function logSessionEvent(event, details) {
90
- const ts = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
91
- const pid = process.pid;
92
- console.error(`[SESSION] ${ts} [PID:${pid}] ${event} | ${details}`);
93
- }
94
- var SESSION_DIR = join(homedir(), ".xbrowser", "sessions");
95
- function sessionFile(name) {
96
- return join(SESSION_DIR, `${name}.json`);
97
- }
98
- function ensureSessionDir() {
99
- mkdirSync(SESSION_DIR, { recursive: true });
100
- }
101
- var sessions = new SessionStore();
102
- var _sharedBrowser = null;
103
- var _sharedCdpProxy = null;
104
- var IDLE_TIMEOUT_MS = (process.env.XBROWSER_IDLE_TIMEOUT ? parseInt(process.env.XBROWSER_IDLE_TIMEOUT, 10) : 30) * 60 * 1e3;
105
- var idleTimer = null;
106
- function resetIdleTimer() {
107
- if (idleTimer) clearTimeout(idleTimer);
108
- idleTimer = setTimeout(async () => {
109
- const now = Date.now();
110
- let allIdle = true;
111
- const idleSessions = [];
112
- for (const s of sessions) {
113
- if (now - s.lastActivityAt < IDLE_TIMEOUT_MS) {
114
- allIdle = false;
115
- } else {
116
- idleSessions.push(`${s.name}(${(now - s.lastActivityAt) / 1e3}s idle)`);
117
- }
118
- }
119
- if (allIdle && (sessions.size > 0 || _sharedBrowser)) {
120
- logSessionEvent("idle_timeout", `Sessions idle for >${IDLE_TIMEOUT_MS / 6e4}min. Sessions: ${idleSessions.join(", ") || "all"}. Calling destroyBrowser()`);
121
- await destroyBrowser().catch(() => {
122
- });
123
- }
124
- }, IDLE_TIMEOUT_MS);
125
- if (idleTimer && typeof idleTimer.unref === "function") {
126
- idleTimer.unref();
127
- }
128
- }
129
- function touchSession(id) {
130
- const s = sessions.get(id);
131
- if (s) s.lastActivityAt = Date.now();
132
- resetIdleTimer();
133
- }
134
- process.on("exit", () => {
135
- for (const session of sessions.list()) {
136
- if (session.isCDP) {
137
- logSessionEvent("process_exit", `Session "${session.name}": CDP connection (not closing external browser).`);
138
- } else {
139
- logSessionEvent("process_exit", `Session "${session.name}": Closing self-launched browser.`);
140
- try {
141
- session.browser?.close();
142
- } catch {
143
- }
144
- }
145
- }
146
- if (_sharedBrowser) {
147
- logSessionEvent("process_exit", "Closing shared browser (self-launched only, external CDP is safe).");
148
- try {
149
- _sharedBrowser.close();
150
- } catch {
151
- }
152
- _sharedBrowser = null;
153
- }
154
- if (_sharedCdpProxy) {
155
- try {
156
- _sharedCdpProxy.stop();
157
- } catch {
158
- }
159
- _sharedCdpProxy = null;
160
- }
161
- sessions.clear();
162
- });
85
+ // src/browser/connection.ts
86
+ import { existsSync } from "fs";
163
87
  async function getCDPTargets(cdpEndpoint) {
164
88
  try {
165
- const ep = String(cdpEndpoint);
89
+ const endpoint = String(cdpEndpoint);
166
90
  let url = "http://localhost:9222/json/list";
167
- if (ep.startsWith("http://") || ep.startsWith("https://")) {
168
- const u = new URL(ep);
169
- u.pathname = (u.pathname.replace(/\/+$/, "") || "") + "/json/list";
170
- url = u.toString();
171
- } else if (/^\d+$/.test(ep)) {
172
- url = `http://localhost:${ep}/json/list`;
173
- }
174
- const resp = await fetch(url);
175
- return await resp.json();
91
+ if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) {
92
+ const parsed = new URL(endpoint);
93
+ parsed.pathname = (parsed.pathname.replace(/\/+$/, "") || "") + "/json/list";
94
+ url = parsed.toString();
95
+ } else if (/^\d+$/.test(endpoint)) {
96
+ url = `http://localhost:${endpoint}/json/list`;
97
+ }
98
+ const response = await fetch(url);
99
+ return await response.json();
176
100
  } catch {
177
101
  return [];
178
102
  }
179
103
  }
180
104
  async function findTargetPage(cdpEndpoint, target) {
181
105
  const targets = await getCDPTargets(cdpEndpoint);
182
- 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://"));
183
- const byId = pages.find((t) => t.id === target);
106
+ 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://"));
107
+ const byId = pages.find((item) => item.id === target);
184
108
  if (byId) return { pageId: byId.id, wsUrl: byId.webSocketDebuggerUrl, title: byId.title, url: byId.url };
185
109
  const lowerTarget = target.toLowerCase();
186
- const byTitle = pages.find((t) => t.title && t.title.toLowerCase().includes(lowerTarget));
110
+ const byTitle = pages.find((item) => item.title?.toLowerCase().includes(lowerTarget));
187
111
  if (byTitle) return { pageId: byTitle.id, wsUrl: byTitle.webSocketDebuggerUrl, title: byTitle.title, url: byTitle.url };
188
- const byUrl = pages.find((t) => t.url.toLowerCase().includes(lowerTarget));
112
+ const byUrl = pages.find((item) => item.url.toLowerCase().includes(lowerTarget));
189
113
  if (byUrl) return { pageId: byUrl.id, wsUrl: byUrl.webSocketDebuggerUrl, title: byUrl.title, url: byUrl.url };
190
114
  return null;
191
115
  }
192
116
  function resolveLaunchOpts(ctx) {
193
- if (ctx.cdpEndpoint) {
194
- return { cdpEndpoint: ctx.cdpEndpoint };
195
- }
196
- return { headless: true };
117
+ return ctx.cdpEndpoint ? { cdpEndpoint: ctx.cdpEndpoint } : { headless: true };
197
118
  }
198
119
  var CHROMIUM_CANDIDATES = [
199
120
  "/Applications/Chromium.app/Contents/MacOS/Chromium",
@@ -203,57 +124,58 @@ var CHROMIUM_CANDIDATES = [
203
124
  "/usr/bin/google-chrome"
204
125
  ];
205
126
  function discoverChromiumPath() {
206
- for (const p of CHROMIUM_CANDIDATES) {
207
- if (existsSync(p)) return p;
208
- }
209
- return void 0;
127
+ return CHROMIUM_CANDIDATES.find((path) => existsSync(path));
128
+ }
129
+ var browserPool = /* @__PURE__ */ new Map();
130
+ var sharedCdpProxy = null;
131
+ function getSharedCdpProxy() {
132
+ return sharedCdpProxy;
133
+ }
134
+ function setSharedCdpProxy(proxy) {
135
+ sharedCdpProxy = proxy;
210
136
  }
211
- var _browserPool = /* @__PURE__ */ new Map();
212
137
  async function createBrowser(options) {
213
138
  if (options?.cdpEndpoint) {
214
139
  const realEndpoint = await resolveCDPEndpoint(options.cdpEndpoint);
215
140
  if (!options.intercept) {
216
- const pooled = _browserPool.get(realEndpoint);
217
- if (pooled && !pooled.disconnected) {
218
- return pooled;
219
- }
220
- if (pooled) _browserPool.delete(realEndpoint);
141
+ const pooled = browserPool.get(realEndpoint);
142
+ if (pooled && !pooled.disconnected) return pooled;
143
+ if (pooled) browserPool.delete(realEndpoint);
221
144
  }
222
145
  if (options.intercept) {
223
146
  const config = typeof options.intercept === "object" ? { ...options.intercept, cdpEndpoint: realEndpoint } : { cdpEndpoint: realEndpoint };
224
- _sharedCdpProxy = new CDPInterceptorProxy(config);
225
- const proxyPort = await _sharedCdpProxy.start();
147
+ sharedCdpProxy = new CDPInterceptorProxy(config);
148
+ const proxyPort = await sharedCdpProxy.start();
226
149
  console.error(`[CDP Interceptor] Proxy running on ws://localhost:${proxyPort}, forwarding to ${realEndpoint}`);
227
150
  const { browser: browser3 } = await launch({ cdpEndpoint: `ws://localhost:${proxyPort}` });
228
151
  return browser3;
229
152
  }
230
153
  const { browser: browser2 } = await launch({ cdpEndpoint: realEndpoint });
231
- await browser2.discoverContexts().catch((err) => {
232
- console.error(`[browser] discoverContexts failed: ${errMsg(err)}`);
154
+ await browser2.discoverContexts().catch((error) => {
155
+ console.error(`[browser] discoverContexts failed: ${errMsg(error)}`);
233
156
  });
234
- if (!options.intercept) _browserPool.set(realEndpoint, browser2);
157
+ browserPool.set(realEndpoint, browser2);
235
158
  return browser2;
236
159
  }
237
160
  const executablePath = options?.executablePath || process.env.XBROWSER_CHROMIUM_PATH || discoverChromiumPath();
238
161
  const { browser } = await launch({ executablePath, headless: options?.headless ?? true });
239
162
  return browser;
240
163
  }
241
- async function getBrowser(options) {
242
- if (_sharedBrowser) return _sharedBrowser;
243
- _sharedBrowser = await createBrowser(options);
244
- if (options?.cdpEndpoint && options.intercept) {
245
- }
246
- return _sharedBrowser;
247
- }
248
- function findSession(name) {
249
- return sessions.find(name);
250
- }
251
- function getSessionById(id) {
252
- return sessions.get(id);
164
+
165
+ // src/browser/state.ts
166
+ import { randomUUID } from "crypto";
167
+ import { existsSync as existsSync2, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "fs";
168
+ import { join } from "path";
169
+ import { homedir } from "os";
170
+ import { SessionStore } from "@dyyz1993/xcli-core";
171
+ var SESSION_DIR = join(homedir(), ".xbrowser", "sessions");
172
+ var sessions = new SessionStore();
173
+ var sharedState = { browser: null, idleTimer: null };
174
+ function sessionFile(name) {
175
+ return join(SESSION_DIR, `${name}.json`);
253
176
  }
254
- function setActivePage(session, page) {
255
- session.page = page;
256
- session.lastActivityAt = Date.now();
177
+ function ensureSessionDir() {
178
+ mkdirSync(SESSION_DIR, { recursive: true });
257
179
  }
258
180
  function saveSessionDiskMeta(name, data) {
259
181
  ensureSessionDir();
@@ -267,20 +189,40 @@ function saveSessionDiskMeta(name, data) {
267
189
  writeFileSync(file, JSON.stringify(existing, null, 2));
268
190
  }
269
191
  function readSessionDiskMeta(name) {
270
- const file = sessionFile(name);
271
192
  try {
272
- return JSON.parse(readFileSync(file, "utf8"));
193
+ return JSON.parse(readFileSync(sessionFile(name), "utf8"));
273
194
  } catch {
274
195
  return null;
275
196
  }
276
197
  }
277
198
  function deleteSessionDiskMeta(name) {
278
- const file = sessionFile(name);
279
199
  try {
280
- unlinkSync(file);
200
+ unlinkSync(sessionFile(name));
281
201
  } catch {
282
202
  }
283
203
  }
204
+ function newSessionId() {
205
+ return randomUUID();
206
+ }
207
+
208
+ // src/browser/lifecycle.ts
209
+ function registerSession(session) {
210
+ const complete = {
211
+ id: session.id ?? newSessionId(),
212
+ createdAt: session.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
213
+ lastActivityAt: session.lastActivityAt ?? Date.now(),
214
+ ...session
215
+ };
216
+ sessions.set(complete);
217
+ resetIdleTimer();
218
+ return complete;
219
+ }
220
+
221
+ // src/browser/restore.ts
222
+ function logSessionEvent(event, details) {
223
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
224
+ console.error(`[SESSION] ${timestamp} [PID:${process.pid}] ${event} | ${details}`);
225
+ }
284
226
  async function isSessionPageAlive(session) {
285
227
  const page = session.page;
286
228
  if (!page || typeof page.evaluate !== "function") return false;
@@ -292,69 +234,65 @@ async function isSessionPageAlive(session) {
292
234
  ]);
293
235
  return true;
294
236
  } catch {
295
- await new Promise((r) => setTimeout(r, 400));
237
+ await new Promise((resolve) => setTimeout(resolve, 400));
296
238
  }
297
239
  }
298
240
  return false;
299
241
  }
300
- async function findOrRestoreSession(name, cdpEndpoint) {
301
- const inMem = findSession(name);
302
- if (inMem) {
303
- if (await isSessionPageAlive(inMem)) return inMem;
304
- 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`);
242
+ async function findOrRestoreSession(name, cdpEndpoint, cleanup = async () => false, installNetworkCapture2 = async () => {
243
+ }) {
244
+ const inMemory = findSession(name);
245
+ if (inMemory) {
246
+ if (await isSessionPageAlive(inMemory)) return inMemory;
247
+ logSessionEvent("stale_session", `name="${name}" \u2014 page probe failed; rebuilding`);
305
248
  try {
306
- await closeSessionByName(name);
249
+ await cleanup(name);
307
250
  } catch {
308
251
  }
309
252
  }
310
253
  const meta = readSessionDiskMeta(name);
311
254
  if (!meta) return void 0;
312
- const ep = cdpEndpoint || meta.cdpEndpoint;
313
- if (!ep) return void 0;
255
+ const endpoint = cdpEndpoint || meta.cdpEndpoint;
256
+ if (!endpoint) return void 0;
314
257
  try {
315
- const b = await createBrowser({ cdpEndpoint: ep });
316
- await new Promise((r) => setTimeout(r, 500));
317
- let contexts = b.contexts();
258
+ const browser = await createBrowser({ cdpEndpoint: endpoint });
259
+ await new Promise((resolve) => setTimeout(resolve, 500));
260
+ let contexts = browser.contexts();
318
261
  if (contexts.length === 0) {
319
- await new Promise((r) => setTimeout(r, 500));
320
- contexts = b.contexts();
262
+ await new Promise((resolve) => setTimeout(resolve, 500));
263
+ contexts = browser.contexts();
321
264
  }
322
- const context = contexts[0] || await b.newContext();
265
+ const context = contexts[0] || await browser.newContext();
323
266
  const savedUrl = meta.conversationUrl || meta.url;
324
- const targetHostname = savedUrl ? (() => {
267
+ let targetHostname = "";
268
+ if (savedUrl) {
325
269
  try {
326
- return new URL(savedUrl).hostname;
270
+ targetHostname = new URL(savedUrl).hostname;
327
271
  } catch {
328
- return "";
272
+ targetHostname = "";
329
273
  }
330
- })() : "";
274
+ }
331
275
  let page = null;
332
276
  let fallbackPage = null;
333
- for (const ctx of contexts) {
334
- const pages = ctx.pages();
335
- for (const p of pages) {
336
- const pUrl = p.url();
337
- if (pUrl && pUrl !== "about:blank" && !pUrl.startsWith("chrome://") && !pUrl.startsWith("chrome-untrusted://") && !pUrl.startsWith("chrome-error://")) {
338
- if (targetHostname && pUrl.includes(targetHostname)) {
339
- page = p;
340
- break;
341
- }
342
- if (!fallbackPage) {
343
- fallbackPage = p;
344
- }
277
+ for (const browserContext of contexts) {
278
+ for (const candidate of browserContext.pages()) {
279
+ const url = candidate.url();
280
+ if (!url || url === "about:blank" || url.startsWith("chrome://") || url.startsWith("chrome-untrusted://") || url.startsWith("chrome-error://")) continue;
281
+ if (targetHostname && url.includes(targetHostname)) {
282
+ page = candidate;
283
+ break;
345
284
  }
285
+ fallbackPage ??= candidate;
346
286
  }
347
287
  if (page) break;
348
288
  }
349
- page = page || fallbackPage;
289
+ page ??= fallbackPage;
350
290
  if (!page) {
351
- const targets = await getCDPTargets(ep);
352
- const matchTarget = targets.find(
353
- (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)
354
- );
355
- if (matchTarget && matchTarget.url) {
291
+ const targets = await getCDPTargets(endpoint);
292
+ 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)));
293
+ if (match?.url) {
356
294
  page = await context.newPage();
357
- await page.goto(matchTarget.url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
295
+ await page.goto(match.url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
358
296
  });
359
297
  }
360
298
  }
@@ -368,7 +306,6 @@ async function findOrRestoreSession(name, cdpEndpoint) {
368
306
  new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 3e3))
369
307
  ]);
370
308
  } catch {
371
- console.log(`[Session] "${name}" restored page unresponsive, creating fresh session`);
372
309
  deleteSessionDiskMeta(name);
373
310
  return void 0;
374
311
  }
@@ -383,191 +320,41 @@ async function findOrRestoreSession(name, cdpEndpoint) {
383
320
  }
384
321
  }
385
322
  const session = {
386
- id: meta.id || randomUUID(),
323
+ id: meta.id,
387
324
  name,
388
325
  context,
389
326
  page,
390
- browser: b,
391
- createdAt: meta.createdAt || (/* @__PURE__ */ new Date()).toISOString(),
327
+ browser,
328
+ createdAt: meta.createdAt,
392
329
  lastActivityAt: Date.now(),
393
330
  isCDP: true,
394
- cdpEndpoint: ep
331
+ cdpEndpoint: endpoint
395
332
  };
396
- for (const existingSession of sessions.list()) {
397
- if (existingSession.name === name) {
398
- logSessionEvent("remove_stale", `Removing stale session name="${name}" id="${existingSession.id}" during restore`);
399
- sessions.removeById(existingSession.id);
400
- }
333
+ for (const existing of sessions.list()) {
334
+ if (existing.name === name) sessions.removeById(existing.id);
401
335
  }
402
336
  sessions.set(session);
403
- resetIdleTimer();
404
- await installNetworkCapture(page, name);
337
+ await installNetworkCapture2(session.page, name);
405
338
  return session;
406
- } catch (e) {
407
- console.error(`[Session Restore] Failed for "${name}":`, errMsg(e));
339
+ } catch (error) {
340
+ console.error(`[Session Restore] Failed for "${name}":`, errMsg(error));
408
341
  deleteSessionDiskMeta(name);
409
342
  return void 0;
410
343
  }
411
344
  }
412
- async function createEphemeralContext(options) {
413
- if (options?.cdpEndpoint) {
414
- const endpoint = await resolveCDPEndpoint(options.cdpEndpoint);
415
- const { browser: b2 } = await launch({ cdpEndpoint: endpoint });
416
- const contexts = b2.contexts();
417
- const ctx = contexts[0] || await b2.newContext();
418
- const allPages = ctx.pages();
419
- const existingPages = allPages.filter((p) => {
420
- const url = p.url();
421
- return url !== "about:blank" && !url.startsWith("chrome://") && !url.startsWith("chrome-untrusted://") && !url.startsWith("chrome-error://");
422
- });
423
- const page2 = existingPages.length > 0 ? existingPages[0] : allPages.length > 0 ? allPages[0] : await ctx.newPage();
424
- resetIdleTimer();
425
- ephemeralConnections.set(page2, b2);
426
- return { context: ctx, page: page2 };
427
- }
428
- const b = await getBrowser(options);
429
- const context = await b.newContext();
430
- const page = await context.newPage();
431
- resetIdleTimer();
432
- return { context, page };
433
- }
434
- var ephemeralConnections = /* @__PURE__ */ new WeakMap();
435
- async function closeEphemeralContext(context) {
436
- try {
437
- const pages = context.pages();
438
- for (const p of pages) {
439
- const conn = ephemeralConnections.get(p);
440
- if (conn) {
441
- ephemeralConnections.delete(p);
442
- await conn.close();
443
- break;
444
- }
445
- }
446
- await context.close();
447
- } catch {
448
- }
449
- if (sessions.size === 0 && idleTimer) {
450
- clearTimeout(idleTimer);
451
- idleTimer = null;
452
- }
453
- }
454
- function getAllSessions() {
455
- return sessions.list();
456
- }
457
- async function installNetworkCapture(page, sessionName) {
458
- if (process.env.XBROWSER_DAEMON_WORKER !== "1") return;
459
- const { networkStore } = await import("./network-store-YVDNUREI.js");
460
- const requestData = /* @__PURE__ */ new Map();
461
- const responseMeta = /* @__PURE__ */ new Map();
462
- const xbPage = page;
463
- xbPage.on("request", (params) => {
464
- try {
465
- const p = params;
466
- requestData.set(p.requestId, {
467
- method: p.request.method,
468
- headers: p.request.headers,
469
- postData: p.request.postData ?? null,
470
- resourceType: p.type
471
- });
472
- } catch {
473
- }
474
- });
475
- xbPage.on("response", (params) => {
476
- try {
477
- const p = params;
478
- responseMeta.set(p.requestId, {
479
- status: p.response.status,
480
- url: p.response.url,
481
- headers: p.response.headers,
482
- mimeType: p.response.mimeType,
483
- type: p.type
484
- });
485
- } catch {
486
- }
487
- });
488
- xbPage.on("requestfinished", async (params) => {
489
- try {
490
- const p = params;
491
- const meta = responseMeta.get(p.requestId);
492
- if (!meta) return;
493
- const req = requestData.get(p.requestId);
494
- const method = req?.method ?? "GET";
495
- const contentType = meta.headers["content-type"] || meta.headers["Content-Type"] || "";
496
- const resourceType = req?.resourceType ?? meta.type;
497
- const requestHeaders = req?.headers ?? {};
498
- let requestBody = void 0;
499
- const isPostLike = ["POST", "PATCH", "PUT"].includes(method);
500
- if (isPostLike && requestHeaders["content-type"]?.includes("application/json")) {
501
- const postData = req?.postData;
502
- if (postData) {
503
- try {
504
- requestBody = JSON.parse(postData);
505
- } catch {
506
- requestBody = postData;
507
- }
508
- }
509
- }
510
- let responseBody = void 0;
511
- let size = 0;
512
- const isJsonish = contentType.includes("json") || contentType.includes("javascript") || contentType.includes("text/");
513
- if (isJsonish) {
514
- try {
515
- const bodyResult = await xbPage._cdpSend(
516
- "Network.getResponseBody",
517
- { requestId: p.requestId }
518
- );
519
- const text = bodyResult.body ?? "";
520
- size = text.length;
521
- if (size <= 10240) {
522
- try {
523
- responseBody = JSON.parse(text);
524
- } catch {
525
- responseBody = text.slice(0, 200);
526
- }
527
- }
528
- } catch {
529
- }
530
- } else {
531
- try {
532
- const bodyResult = await xbPage._cdpSend(
533
- "Network.getResponseBody",
534
- { requestId: p.requestId }
535
- );
536
- size = bodyResult.body?.length ?? 0;
537
- } catch {
538
- size = 0;
539
- }
540
- }
541
- networkStore.add(sessionName, {
542
- timestamp: Date.now(),
543
- method,
544
- url: meta.url,
545
- path: new URL(meta.url).pathname,
546
- status: meta.status,
547
- contentType,
548
- size,
549
- headers: meta.headers,
550
- body: responseBody,
551
- requestHeaders,
552
- requestBody,
553
- resourceType
554
- });
555
- requestData.delete(p.requestId);
556
- responseMeta.delete(p.requestId);
557
- } catch {
558
- }
559
- });
560
- }
561
- async function createSession(name, url, options) {
345
+
346
+ // src/browser/create-session.ts
347
+ async function createSessionImpl(name, url, options, deps) {
562
348
  const existing = findSession(name);
563
349
  if (existing) {
564
- logSessionEvent("replace_session", `name="${name}" id="${existing.id}" \u2014 closing existing session before creating new one`);
565
- await closeSessionByName(name);
350
+ deps.logSessionEvent("replace_session", `name="${name}" id="${existing.id}" \u2014 closing existing session before creating new one`);
351
+ await deps.closeSessionByName(name);
566
352
  }
567
353
  const b = await createBrowser(options);
568
354
  const isCDP = !!options?.cdpEndpoint;
569
355
  let context;
570
356
  let page;
357
+ let reusedExistingPage = false;
571
358
  if (isCDP) {
572
359
  const targetHostname = url ? (() => {
573
360
  try {
@@ -649,22 +436,12 @@ async function createSession(name, url, options) {
649
436
  const pUrl0 = await resolvePageUrl(p);
650
437
  if (ownedUrls.has(pUrl0)) continue;
651
438
  const pUrl = pUrl0;
652
- if (isRealPageUrl(pUrl) && pUrl.includes(targetHostname)) {
653
- targetPage = p;
654
- break;
439
+ let hostnameMatches = false;
440
+ try {
441
+ hostnameMatches = new URL(pUrl).hostname === targetHostname;
442
+ } catch {
655
443
  }
656
- }
657
- if (targetPage) break;
658
- }
659
- }
660
- if (!targetPage) {
661
- for (const ctx of contexts) {
662
- const pages = ctx.pages();
663
- for (const p of pages) {
664
- const pUrl0 = await resolvePageUrl(p);
665
- if (ownedUrls.has(pUrl0)) continue;
666
- const pUrl = pUrl0;
667
- if (isRealPageUrl(pUrl)) {
444
+ if (isRealPageUrl(pUrl) && hostnameMatches) {
668
445
  targetPage = p;
669
446
  break;
670
447
  }
@@ -673,7 +450,7 @@ async function createSession(name, url, options) {
673
450
  }
674
451
  }
675
452
  if (!targetPage && options?.cdpEndpoint) {
676
- const targets = await getCDPTargets(options.cdpEndpoint);
453
+ const targets = await deps.getCDPTargets(options.cdpEndpoint);
677
454
  const ownedUrlsT = /* @__PURE__ */ new Set();
678
455
  for (const ssn of sessions.list()) {
679
456
  try {
@@ -682,9 +459,15 @@ async function createSession(name, url, options) {
682
459
  } catch {
683
460
  }
684
461
  }
685
- const matchTarget = targets.find(
686
- (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)
687
- );
462
+ const matchTarget = targets.find((t) => {
463
+ if (!t.url || !isRealPageUrl(t.url) || ownedUrlsT.has(t.url)) return false;
464
+ if (!url) return false;
465
+ try {
466
+ return new URL(t.url).hostname === targetHostname;
467
+ } catch {
468
+ return false;
469
+ }
470
+ });
688
471
  if (matchTarget && matchTarget.url) {
689
472
  const ownedUrls2 = /* @__PURE__ */ new Set();
690
473
  for (const ssn of sessions.list()) {
@@ -717,31 +500,12 @@ async function createSession(name, url, options) {
717
500
  }
718
501
  }
719
502
  }
503
+ const targetPageExisted = !!targetPage;
720
504
  if (!targetPage) {
721
- const pages = context.pages();
722
- if (pages.length > 1) {
723
- try {
724
- const owned = /* @__PURE__ */ new Set();
725
- for (const ssn of sessions.list()) owned.add(ssn.page);
726
- for (const p of pages) {
727
- if (owned.has(p)) continue;
728
- const vis = await p.evaluate("document.visibilityState").catch(() => "hidden");
729
- if (vis === "visible") {
730
- targetPage = p;
731
- break;
732
- }
733
- }
734
- } catch {
735
- }
736
- }
737
- if (!targetPage && pages.length > 0) {
738
- targetPage = pages[0];
739
- }
740
- if (!targetPage) {
741
- targetPage = await context.newPage();
742
- }
505
+ targetPage = await context.newPage();
743
506
  }
744
507
  page = targetPage;
508
+ reusedExistingPage = targetPageExisted;
745
509
  if (isCDP) {
746
510
  await Promise.resolve(targetPage.bringToFront?.()).catch(() => {
747
511
  });
@@ -754,30 +518,280 @@ async function createSession(name, url, options) {
754
518
  await page.goto(url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
755
519
  });
756
520
  }
757
- const session = {
758
- id: randomUUID(),
521
+ const session = deps.registerSession({
759
522
  name,
760
523
  context,
761
524
  page,
762
525
  browser: b,
763
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
764
- lastActivityAt: Date.now(),
765
526
  isCDP,
766
- cdpEndpoint: options?.cdpEndpoint
767
- };
768
- sessions.set(session);
769
- logSessionEvent("create_session", `name="${name}" id="${session.id}" url="${url || "(no url)"}" isCDP=${isCDP} cdpEndpoint=${options?.cdpEndpoint || "(none)"}`);
770
- resetIdleTimer();
771
- await installNetworkCapture(page, name);
527
+ cdpEndpoint: options?.cdpEndpoint,
528
+ ...isCDP ? { reusedExistingPage } : {}
529
+ });
530
+ deps.logSessionEvent("create_session", `name="${name}" id="${session.id}" url="${url || "(no url)"}" isCDP=${isCDP} cdpEndpoint=${options?.cdpEndpoint || "(none)"}`);
531
+ await deps.installNetworkCapture(page, name);
772
532
  return session;
773
533
  }
534
+
535
+ // src/browser.ts
536
+ function logSessionEvent2(event, details) {
537
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
538
+ console.error(`[SESSION] ${timestamp} [PID:${process.pid}] ${event} | ${details}`);
539
+ }
540
+ var IDLE_TIMEOUT_MS = (process.env.XBROWSER_IDLE_TIMEOUT ? parseInt(process.env.XBROWSER_IDLE_TIMEOUT, 10) : 30) * 60 * 1e3;
541
+ function resetIdleTimer() {
542
+ if (sharedState.idleTimer) clearTimeout(sharedState.idleTimer);
543
+ sharedState.idleTimer = setTimeout(async () => {
544
+ const now = Date.now();
545
+ let allIdle = true;
546
+ const idleSessions = [];
547
+ for (const s of sessions) {
548
+ if (now - s.lastActivityAt < IDLE_TIMEOUT_MS) {
549
+ allIdle = false;
550
+ } else {
551
+ idleSessions.push(`${s.name}(${(now - s.lastActivityAt) / 1e3}s idle)`);
552
+ }
553
+ }
554
+ if (allIdle && (sessions.size > 0 || sharedState.browser)) {
555
+ logSessionEvent2("idle_timeout", `Sessions idle for >${IDLE_TIMEOUT_MS / 6e4}min. Sessions: ${idleSessions.join(", ") || "all"}. Calling destroyBrowser()`);
556
+ await destroyBrowser().catch(() => {
557
+ });
558
+ }
559
+ }, IDLE_TIMEOUT_MS);
560
+ if (sharedState.idleTimer && typeof sharedState.idleTimer.unref === "function") {
561
+ sharedState.idleTimer.unref();
562
+ }
563
+ }
564
+ async function findOrRestoreSession2(name, cdpEndpoint) {
565
+ return findOrRestoreSession(
566
+ name,
567
+ cdpEndpoint,
568
+ closeSessionByName,
569
+ installNetworkCapture
570
+ );
571
+ }
572
+ function touchSession(id) {
573
+ const s = sessions.get(id);
574
+ if (s) s.lastActivityAt = Date.now();
575
+ resetIdleTimer();
576
+ }
577
+ process.on("exit", () => {
578
+ for (const session of sessions.list()) {
579
+ if (session.isCDP) {
580
+ logSessionEvent2("process_exit", `Session "${session.name}": CDP connection (not closing external browser).`);
581
+ } else {
582
+ logSessionEvent2("process_exit", `Session "${session.name}": Closing self-launched browser.`);
583
+ try {
584
+ session.browser?.close();
585
+ } catch {
586
+ }
587
+ }
588
+ }
589
+ if (sharedState.browser) {
590
+ logSessionEvent2("process_exit", "Closing shared browser (self-launched only, external CDP is safe).");
591
+ try {
592
+ sharedState.browser.close();
593
+ } catch {
594
+ }
595
+ sharedState.browser = null;
596
+ }
597
+ const cdpProxy = getSharedCdpProxy();
598
+ if (cdpProxy) {
599
+ try {
600
+ cdpProxy.stop();
601
+ } catch {
602
+ }
603
+ setSharedCdpProxy(null);
604
+ }
605
+ sessions.clear();
606
+ });
607
+ async function getBrowser(options) {
608
+ if (sharedState.browser) return sharedState.browser;
609
+ sharedState.browser = await createBrowser(options);
610
+ if (options?.cdpEndpoint && options.intercept) {
611
+ }
612
+ return sharedState.browser;
613
+ }
614
+ function findSession(name) {
615
+ return sessions.find(name);
616
+ }
617
+ function getSessionById2(id) {
618
+ return sessions.get(id);
619
+ }
620
+ function setActivePage2(session, page) {
621
+ session.page = page;
622
+ session.lastActivityAt = Date.now();
623
+ }
624
+ async function createEphemeralContext(options) {
625
+ if (options?.cdpEndpoint) {
626
+ const endpoint = await resolveCDPEndpoint(options.cdpEndpoint);
627
+ const { browser: b2 } = await launch({ cdpEndpoint: endpoint });
628
+ const contexts = b2.contexts();
629
+ const ctx = contexts[0] || await b2.newContext();
630
+ const allPages = ctx.pages();
631
+ const existingPages = allPages.filter((p) => {
632
+ const url = p.url();
633
+ return url !== "about:blank" && !url.startsWith("chrome://") && !url.startsWith("chrome-untrusted://") && !url.startsWith("chrome-error://");
634
+ });
635
+ const page2 = existingPages.length > 0 ? existingPages[0] : allPages.length > 0 ? allPages[0] : await ctx.newPage();
636
+ resetIdleTimer();
637
+ ephemeralConnections.set(page2, b2);
638
+ return { context: ctx, page: page2 };
639
+ }
640
+ const b = await getBrowser(options);
641
+ const context = await b.newContext();
642
+ const page = await context.newPage();
643
+ resetIdleTimer();
644
+ return { context, page };
645
+ }
646
+ var ephemeralConnections = /* @__PURE__ */ new WeakMap();
647
+ async function closeEphemeralContext(context) {
648
+ try {
649
+ const pages = context.pages();
650
+ for (const p of pages) {
651
+ const conn = ephemeralConnections.get(p);
652
+ if (conn) {
653
+ ephemeralConnections.delete(p);
654
+ await conn.close();
655
+ break;
656
+ }
657
+ }
658
+ await context.close();
659
+ } catch {
660
+ }
661
+ if (sessions.size === 0 && sharedState.idleTimer) {
662
+ clearTimeout(sharedState.idleTimer);
663
+ sharedState.idleTimer = null;
664
+ }
665
+ }
666
+ function getAllSessions2() {
667
+ return sessions.list();
668
+ }
669
+ async function installNetworkCapture(page, sessionName) {
670
+ if (process.env.XBROWSER_DAEMON_WORKER !== "1") return;
671
+ const { networkStore } = await import("./network-store-YVDNUREI.js");
672
+ const requestData = /* @__PURE__ */ new Map();
673
+ const responseMeta = /* @__PURE__ */ new Map();
674
+ const xbPage = page;
675
+ xbPage.on("request", (params) => {
676
+ try {
677
+ const p = params;
678
+ requestData.set(p.requestId, {
679
+ method: p.request.method,
680
+ headers: p.request.headers,
681
+ postData: p.request.postData ?? null,
682
+ resourceType: p.type
683
+ });
684
+ } catch {
685
+ }
686
+ });
687
+ xbPage.on("response", (params) => {
688
+ try {
689
+ const p = params;
690
+ responseMeta.set(p.requestId, {
691
+ status: p.response.status,
692
+ url: p.response.url,
693
+ headers: p.response.headers,
694
+ mimeType: p.response.mimeType,
695
+ type: p.type
696
+ });
697
+ } catch {
698
+ }
699
+ });
700
+ xbPage.on("requestfinished", async (params) => {
701
+ try {
702
+ const p = params;
703
+ const meta = responseMeta.get(p.requestId);
704
+ if (!meta) return;
705
+ const req = requestData.get(p.requestId);
706
+ const method = req?.method ?? "GET";
707
+ const contentType = meta.headers["content-type"] || meta.headers["Content-Type"] || "";
708
+ const resourceType = req?.resourceType ?? meta.type;
709
+ const requestHeaders = req?.headers ?? {};
710
+ let requestBody = void 0;
711
+ const isPostLike = ["POST", "PATCH", "PUT"].includes(method);
712
+ if (isPostLike && requestHeaders["content-type"]?.includes("application/json")) {
713
+ const postData = req?.postData;
714
+ if (postData) {
715
+ try {
716
+ requestBody = JSON.parse(postData);
717
+ } catch {
718
+ requestBody = postData;
719
+ }
720
+ }
721
+ }
722
+ let responseBody = void 0;
723
+ let size = 0;
724
+ const isJsonish = contentType.includes("json") || contentType.includes("javascript") || contentType.includes("text/");
725
+ if (isJsonish) {
726
+ try {
727
+ const bodyResult = await xbPage._cdpSend(
728
+ "Network.getResponseBody",
729
+ { requestId: p.requestId }
730
+ );
731
+ const text = bodyResult.body ?? "";
732
+ size = text.length;
733
+ if (size <= 10240) {
734
+ try {
735
+ responseBody = JSON.parse(text);
736
+ } catch {
737
+ responseBody = text.slice(0, 200);
738
+ }
739
+ }
740
+ } catch {
741
+ }
742
+ } else {
743
+ try {
744
+ const bodyResult = await xbPage._cdpSend(
745
+ "Network.getResponseBody",
746
+ { requestId: p.requestId }
747
+ );
748
+ size = bodyResult.body?.length ?? 0;
749
+ } catch {
750
+ size = 0;
751
+ }
752
+ }
753
+ networkStore.add(sessionName, {
754
+ timestamp: Date.now(),
755
+ method,
756
+ url: meta.url,
757
+ path: new URL(meta.url).pathname,
758
+ status: meta.status,
759
+ contentType,
760
+ size,
761
+ headers: meta.headers,
762
+ body: responseBody,
763
+ requestHeaders,
764
+ requestBody,
765
+ resourceType
766
+ });
767
+ requestData.delete(p.requestId);
768
+ responseMeta.delete(p.requestId);
769
+ } catch {
770
+ }
771
+ });
772
+ }
773
+ async function createSession(name, url, options) {
774
+ return createSessionImpl(name, url, options, {
775
+ closeSessionByName,
776
+ installNetworkCapture,
777
+ registerSession,
778
+ logSessionEvent: logSessionEvent2,
779
+ getCDPTargets
780
+ });
781
+ }
774
782
  async function closeSessionByName(name) {
775
783
  for (const session of sessions) {
776
784
  if (session.name === name || session.id === name) {
777
- logSessionEvent("close_session", `name="${session.name}" id="${session.id}" url="${session.page.url()}"`);
785
+ logSessionEvent2("close_session", `name="${session.name}" id="${session.id}" url="${session.page.url()}"`);
778
786
  if (session.isCDP) {
779
- if (session.browser) {
780
- await session.browser.close().catch(() => {
787
+ if (session.reusedExistingPage) {
788
+ logSessionEvent2("close_session", `name="${session.name}" \u2014 reused existing tab, disconnecting only`);
789
+ await session.browser.disconnect().catch(() => {
790
+ });
791
+ } else {
792
+ await session.page.close().catch(() => {
793
+ });
794
+ await session.browser.disconnect().catch(() => {
781
795
  });
782
796
  }
783
797
  } else {
@@ -790,7 +804,7 @@ async function closeSessionByName(name) {
790
804
  sessions.removeById(session.id);
791
805
  const file2 = sessionFile(session.name);
792
806
  try {
793
- unlinkSync(file2);
807
+ unlinkSync2(file2);
794
808
  } catch {
795
809
  }
796
810
  try {
@@ -800,7 +814,7 @@ async function closeSessionByName(name) {
800
814
  } catch {
801
815
  }
802
816
  try {
803
- const { SessionRecorder } = await import("./session-recorder-563ISSJK.js");
817
+ const { SessionRecorder } = await import("./session-recorder-RUNQOJ7T.js");
804
818
  SessionRecorder.cleanup(session.name);
805
819
  } catch {
806
820
  }
@@ -809,14 +823,14 @@ async function closeSessionByName(name) {
809
823
  }
810
824
  const file = sessionFile(name);
811
825
  try {
812
- unlinkSync(file);
826
+ unlinkSync2(file);
813
827
  } catch {
814
828
  }
815
829
  return false;
816
830
  }
817
831
  async function closeAllSessions() {
818
832
  const names = sessions.list().map((s) => `${s.name}(${s.page.url()})`).join(", ");
819
- if (names) logSessionEvent("close_all_sessions", `Closing ${sessions.size} sessions: ${names}`);
833
+ if (names) logSessionEvent2("close_all_sessions", `Closing ${sessions.size} sessions: ${names}`);
820
834
  for (const session of sessions.list()) {
821
835
  try {
822
836
  if (session.isCDP) {
@@ -838,38 +852,37 @@ async function closeAllSessions() {
838
852
  }
839
853
  }
840
854
  async function destroyBrowser() {
841
- logSessionEvent("destroy_browser", `Sessions count: ${sessions.size}. Clearing idle timer and closing all sessions.`);
842
- if (idleTimer) {
843
- clearTimeout(idleTimer);
844
- idleTimer = null;
855
+ logSessionEvent2("destroy_browser", `Sessions count: ${sessions.size}. Clearing idle timer and closing all sessions.`);
856
+ if (sharedState.idleTimer) {
857
+ clearTimeout(sharedState.idleTimer);
858
+ sharedState.idleTimer = null;
845
859
  }
846
860
  await closeAllSessions();
847
- if (_sharedBrowser) {
848
- await _sharedBrowser.close().catch(() => {
861
+ if (sharedState.browser) {
862
+ await sharedState.browser.close().catch(() => {
849
863
  });
850
- _sharedBrowser = null;
864
+ sharedState.browser = null;
851
865
  }
852
- if (_sharedCdpProxy) {
853
- await _sharedCdpProxy.stop().catch(() => {
866
+ if (getSharedCdpProxy()) {
867
+ await getSharedCdpProxy().stop().catch(() => {
854
868
  });
855
- _sharedCdpProxy = null;
869
+ setSharedCdpProxy(null);
856
870
  }
857
871
  }
858
872
  function resetForTesting() {
859
873
  sessions.clear();
860
- _sharedBrowser = null;
861
- _sharedCdpProxy = null;
874
+ sharedState.browser = null;
875
+ sharedState.idleTimer = null;
876
+ setSharedCdpProxy(null);
862
877
  try {
863
- for (const f of readdirSync(SESSION_DIR)) {
864
- unlinkSync(join(SESSION_DIR, f));
865
- }
878
+ for (const file of readdirSync2(SESSION_DIR)) unlinkSync2(join2(SESSION_DIR, file));
866
879
  } catch {
867
880
  }
868
881
  }
869
882
  async function ensureProcessCanExit() {
870
- if (idleTimer) {
871
- clearTimeout(idleTimer);
872
- idleTimer = null;
883
+ if (sharedState.idleTimer) {
884
+ clearTimeout(sharedState.idleTimer);
885
+ sharedState.idleTimer = null;
873
886
  }
874
887
  for (const session of sessions.list()) {
875
888
  if (session.browser) {
@@ -881,34 +894,35 @@ async function ensureProcessCanExit() {
881
894
  }
882
895
  }
883
896
  sessions.clear();
884
- if (_sharedBrowser) {
885
- await _sharedBrowser.close().catch(() => {
897
+ if (sharedState.browser) {
898
+ await sharedState.browser.close().catch(() => {
886
899
  });
887
- _sharedBrowser = null;
900
+ sharedState.browser = null;
888
901
  }
889
- if (_sharedCdpProxy) {
890
- await _sharedCdpProxy.stop().catch(() => {
902
+ if (getSharedCdpProxy()) {
903
+ await getSharedCdpProxy().stop().catch(() => {
891
904
  });
892
- _sharedCdpProxy = null;
905
+ setSharedCdpProxy(null);
893
906
  }
894
907
  }
895
908
 
896
909
  export {
897
- touchSession,
898
910
  findTargetPage,
899
911
  resolveLaunchOpts,
900
912
  createBrowser,
901
- getBrowser,
902
- findSession,
903
- getSessionById,
904
- setActivePage,
905
913
  saveSessionDiskMeta,
906
914
  readSessionDiskMeta,
907
915
  deleteSessionDiskMeta,
908
- findOrRestoreSession,
916
+ resetIdleTimer,
917
+ findOrRestoreSession2 as findOrRestoreSession,
918
+ touchSession,
919
+ getBrowser,
920
+ findSession,
921
+ getSessionById2 as getSessionById,
922
+ setActivePage2 as setActivePage,
909
923
  createEphemeralContext,
910
924
  closeEphemeralContext,
911
- getAllSessions,
925
+ getAllSessions2 as getAllSessions,
912
926
  createSession,
913
927
  closeSessionByName,
914
928
  closeAllSessions,