@xbrowser/cli 1.34.0 → 1.36.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 (63) hide show
  1. package/README.md +137 -80
  2. package/dist/{browser-ZWEJ663M.js → browser-IEZOLTHA.js} +3 -3
  3. package/dist/{browser-GXL6V2JW.js → browser-NHQDQRXB.js} +3 -2
  4. package/dist/{browser-X7LO42UI.js → browser-XELRNYBL.js} +3 -3
  5. package/dist/cdp-driver-CCG3OJUQ.js +49 -0
  6. package/dist/{cdp-driver-GCFEMRFJ.js → cdp-driver-HBMCD7NU.js} +2 -2
  7. package/dist/{cdp-driver-QOUSRPR2.js → cdp-driver-MJD7YIQI.js} +2 -2
  8. package/dist/{cdp-driver-4MNHDU2J.js → cdp-driver-YJU4GRSV.js} +196 -95
  9. package/dist/chunk-2IOFJ6A3.js +149 -0
  10. package/dist/chunk-3SZTCI33.js +147 -0
  11. package/dist/{chunk-VYTQLZAX.js → chunk-5UXRFNXG.js} +28 -2
  12. package/dist/{chunk-NAIHOVDZ.js → chunk-63526WET.js} +2 -8
  13. package/dist/{chunk-YIL44YDX.js → chunk-6DS3T6UK.js} +196 -95
  14. package/dist/{chunk-J4NOL5XX.js → chunk-7KVH6MQG.js} +1099 -204
  15. package/dist/{chunk-N7DFS4V7.js → chunk-ENTENDF5.js} +9 -3
  16. package/dist/{chunk-R57Z5KZX.js → chunk-GVJ2UY65.js} +1078 -185
  17. package/dist/{chunk-3E6VVMK2.js → chunk-GYGVHWG3.js} +272 -1460
  18. package/dist/{chunk-2KPI5GKP.js → chunk-IYCB2KJL.js} +2 -8
  19. package/dist/chunk-KSB4PMCY.js +1380 -0
  20. package/dist/{chunk-RMYKVZIZ.js → chunk-L6QJUB33.js} +28 -2
  21. package/dist/{chunk-TBJUSUKF.js → chunk-NBT2CE3H.js} +140 -96
  22. package/dist/{chunk-DZ6XEPAH.js → chunk-PGEZJ6V3.js} +9 -3
  23. package/dist/chunk-RGL2YTWQ.js +64 -0
  24. package/dist/chunk-RL5FFY2Q.js +150 -0
  25. package/dist/{chunk-43TEMG4U.js → chunk-SBMVECDS.js} +3 -1
  26. package/dist/{chunk-BND5O5KC.js → chunk-SQLICOPZ.js} +177 -240
  27. package/dist/{chunk-O5PASNI7.js → chunk-UUW5EGES.js} +139 -237
  28. package/dist/{chunk-SH6OTPXN.js → chunk-WGWPWNIA.js} +78 -17
  29. package/dist/chunk-YW4BIJQL.js +489 -0
  30. package/dist/{chunk-R7AG7ONI.js → chunk-ZCZELQCS.js} +196 -95
  31. package/dist/chunk-ZR4NHTUV.js +39 -0
  32. package/dist/cli.js +2284 -307
  33. package/dist/convert-JNOM6H6A.js +490 -0
  34. package/dist/{convert-R3XXYKC6.js → convert-K6TLQEPX.js} +5 -3
  35. package/dist/{daemon-client-7D6EZNOE.js → daemon-client-AKQK5IIB.js} +79 -18
  36. package/dist/{daemon-client-HEGAXWGK.js → daemon-client-BBPQWLUX.js} +7 -1
  37. package/dist/daemon-main.js +2305 -164
  38. package/dist/human-interaction-BGAZC3JR.js +12 -0
  39. package/dist/human-interaction-TPKPEE7A.js +11 -0
  40. package/dist/human-interaction-ZSD3IX6Q.js +12 -0
  41. package/dist/index.d.ts +251 -97
  42. package/dist/index.js +2929 -298
  43. package/dist/{launcher-TOLF23ET.js → launcher-AUJK5QQM.js} +1 -1
  44. package/dist/{launcher-ZYB32LSZ.js → launcher-QBAZ6F5L.js} +1 -1
  45. package/dist/mistake-ledger-2B4N54CO.js +29 -0
  46. package/dist/{recovery-ORHJSBDN.js → recovery-5AGY7CV3.js} +4 -5
  47. package/dist/{recovery-XDKN63O5.js → recovery-7NRRHLS4.js} +2 -2
  48. package/dist/{recovery-JFGV3DBX.js → recovery-TIBRFGRP.js} +2 -2
  49. package/dist/run-routes-64IBBVOX.js +24 -0
  50. package/dist/run-routes-FG4LIACU.js +26 -0
  51. package/dist/{server-5U56MQD2.js → server-K22LJBO2.js} +5 -4
  52. package/dist/{server-R4OYD7ZC.js → server-ZHZDJJMG.js} +5 -3
  53. package/dist/{session-recorder-RUNQOJ7T.js → session-recorder-CNTY5KXF.js} +1 -1
  54. package/dist/{session-recorder-N7VEKJVW.js → session-recorder-KMKSQWEP.js} +1 -1
  55. package/dist/{session-replayer-GHEFFNGV.js → session-replayer-4TCLQI76.js} +1 -1
  56. package/dist/viewer-routes-CEO7HWCB.js +11 -0
  57. package/package.json +3 -2
  58. package/dist/chunk-ETCO4SNK.js +0 -206
  59. package/dist/chunk-QCV2PI7U.js +0 -184
  60. package/dist/convert-LB3GJTLR.js +0 -207
  61. package/dist/human-interaction-ISMMOJOK.js +0 -8
  62. package/dist/human-interaction-STTZZZ5N.js +0 -8
  63. package/dist/human-interaction-UXFYV7DU.js +0 -8
@@ -0,0 +1,1380 @@
1
+ import {
2
+ createRuleEngine,
3
+ launch
4
+ } from "./chunk-GYGVHWG3.js";
5
+ import {
6
+ errMsg
7
+ } from "./chunk-GDKLH7ZY.js";
8
+
9
+ // src/browser.ts
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";
85
+
86
+ // src/cdp-interceptor/proxy.ts
87
+ import { WebSocketServer, WebSocket } from "ws";
88
+
89
+ // src/cdp-interceptor/logger.ts
90
+ function createLogger(config) {
91
+ const buffer = [];
92
+ const MAX_BUFFER = 2e3;
93
+ return {
94
+ info(message, meta) {
95
+ if (!config.enableLogging) return;
96
+ const ts = (/* @__PURE__ */ new Date()).toISOString();
97
+ if (meta) {
98
+ console.log(`[CDPInterceptor ${ts}] ${message}`, JSON.stringify(meta));
99
+ } else {
100
+ console.log(`[CDPInterceptor ${ts}] ${message}`);
101
+ }
102
+ },
103
+ log(method, direction, sessionId, payload, decision) {
104
+ const entry = {
105
+ timestamp: Date.now(),
106
+ direction,
107
+ sessionId,
108
+ method,
109
+ payload: sanitizePayload(payload),
110
+ decision: decision ?? void 0
111
+ };
112
+ if (config.enableLogging) {
113
+ buffer.push(entry);
114
+ if (buffer.length > MAX_BUFFER) buffer.shift();
115
+ const tag = decision ? decision.action === "block" ? "\u{1F6AB}BLOCK" : decision.action === "transform" ? "\u{1F504}XFMR" : "\u2705" : " ";
116
+ const reason = decision ? ` [${decision.severity}] ${decision.reason}` : "";
117
+ console.log(`[CDP] ${tag} ${direction} ${method}${reason}`);
118
+ }
119
+ return entry;
120
+ },
121
+ getRecent(count) {
122
+ return buffer.slice(-count);
123
+ },
124
+ flush() {
125
+ buffer.length = 0;
126
+ }
127
+ };
128
+ }
129
+ function sanitizePayload(payload) {
130
+ if (typeof payload !== "object" || payload === null) return { raw: String(payload) };
131
+ const obj = payload;
132
+ const cleaned = {};
133
+ for (const [key, value] of Object.entries(obj)) {
134
+ if (key === "data" && typeof value === "string" && value.length > 200) {
135
+ cleaned[key] = `<binary: ${value.length} chars>`;
136
+ } else if (key === "expression" && typeof value === "string" && value.length > 500) {
137
+ cleaned[key] = value.substring(0, 500) + "...";
138
+ } else {
139
+ cleaned[key] = value;
140
+ }
141
+ }
142
+ return cleaned;
143
+ }
144
+
145
+ // src/cdp-interceptor/advisor.ts
146
+ function formatBlockMessage(decision, method) {
147
+ const adv = advise(decision, method);
148
+ const lines = [
149
+ `[CDP-FIREWALL-BLOCK] rule=${decision.ruleId}`,
150
+ `method=${method}`,
151
+ `reason=${decision.reason}`,
152
+ `suggestion=${decision.suggestion ?? adv.detail}`
153
+ ];
154
+ if (adv.codeExample) {
155
+ lines.push(`code-example=`);
156
+ lines.push(adv.codeExample);
157
+ }
158
+ return lines.join("\n");
159
+ }
160
+ function advise(decision, originalMethod) {
161
+ const baseAdvice = getBaseAdvice(decision, originalMethod);
162
+ return {
163
+ ruleId: decision.ruleId,
164
+ title: baseAdvice.title,
165
+ detail: decision.suggestion ?? baseAdvice.detail,
166
+ codeExample: baseAdvice.codeExample
167
+ };
168
+ }
169
+ function getBaseAdvice(decision, method) {
170
+ switch (decision.ruleId) {
171
+ case "dom-mutation":
172
+ return {
173
+ title: "Direct DOM property mutation blocked",
174
+ detail: `Your ${method} call tried to set a DOM property directly. In React/Vue/Angular, this bypasses the framework's virtual DOM completely meaning onChange/onInput never fires. The website CAN detect this mismatch as automation.`,
175
+ codeExample: [
176
+ "# \u274C BLOCKED \u2014 what you tried to do:",
177
+ `page.evaluate(\`el.value = 'hello'\`) # triggers isTrusted=false`,
178
+ "",
179
+ "# \u2705 USE INSTEAD \u2014 proper CDP input dispatch:",
180
+ "page.fill('#selector', 'hello') # Playwright: dispatches input+change events",
181
+ "page.type('#selector', 'hello', {delay}) # Playwright: real keystrokes",
182
+ "page.locator('#selector').fill('hello') # Playwright: recommended API"
183
+ ].join("\n")
184
+ };
185
+ case "mouse-trajectory":
186
+ return {
187
+ title: "Unnatural mouse trajectory blocked",
188
+ detail: `Your ${method} sequence formed a perfectly linear path. Human hands have micro-tremors (1-3px variation at any point along the arc), acceleration curves, and never draw straight lines between distant points.`,
189
+ codeExample: [
190
+ "# \u274C BLOCKED \u2014 linear interpolation:",
191
+ "for i in range(20):",
192
+ " page.mouse.move(x0 + (x1-x0)*(i/20), y0 + (y1-y0)*(i/20))",
193
+ "",
194
+ "# \u2705 USE INSTEAD \u2014 Bezier curves with overshoot:",
195
+ '# Use "ghost-cursor" or similar library',
196
+ "from ghost_cursor import path_to",
197
+ "path_to(page, (x1, y1))"
198
+ ].join("\n")
199
+ };
200
+ case "input-keystroke":
201
+ if (method === "Input.insertText") {
202
+ return {
203
+ title: "Input.insertText detected (logged, not blocked)",
204
+ detail: "Input.insertText bypasses native keyDown\u2192keyPress\u2192input\u2192keyUp events. Playwright uses this internally for page.fill(). Logged for observability."
205
+ };
206
+ }
207
+ return {
208
+ title: "Unnatural keystroke timing blocked",
209
+ detail: `Your ${method} calls have unnaturally constant timing (e.g., exact 50ms intervals). Human typing always has variation (CV > 0.2).`,
210
+ codeExample: [
211
+ "# \u274C BLOCKED \u2014 exact constant delay:",
212
+ "page.type('#input', 'hello', {delay: 50}) # every keystroke exactly 50ms apart",
213
+ "",
214
+ "# \u2705 USE INSTEAD \u2014 variable delay (human-like):",
215
+ "page.fill('#input', 'hello') # recommended, dispatches events properly",
216
+ "# OR: type with randomized delay",
217
+ "page.type('#input', 'hello', {delay: 50 + Math.floor(Math.random() * 80)})"
218
+ ].join("\n")
219
+ };
220
+ case "automation-signals":
221
+ return {
222
+ title: "Browser automation marker detected",
223
+ detail: `Your ${method} call accessed a property/marker that anti-crawler systems check to detect automation. These markers (navigator.webdriver, window.__playwright, etc.) are the #1 detection vector.`,
224
+ codeExample: [
225
+ "# \u274C BLOCKED \u2014 don't check for automation markers:",
226
+ "navigator.webdriver # NEVER check this",
227
+ "window.__playwright # NEVER check this",
228
+ "chrome.runtime # NEVER check this",
229
+ "",
230
+ "# \u2705 Just go about your business normally.",
231
+ "# Anti-detection is handled by the CDP firewall automatically."
232
+ ].join("\n")
233
+ };
234
+ case "fingerprinting":
235
+ return {
236
+ title: "Browser fingerprinting API access blocked",
237
+ detail: `Your ${method} call accessed a known fingerprinting API. These APIs (canvas.toDataURL, WebGL getParameter, AudioContext, etc.) are used by anti-crawler systems to build a unique device fingerprint.`,
238
+ codeExample: [
239
+ "# \u274C BLOCKED \u2014 fingerprinting vector:",
240
+ "canvas.toDataURL() # returns unique browser hash",
241
+ 'gl.getParameter(gl.VENDOR) # returns "SwiftShader" in headless',
242
+ "screen.availWidth - screen.availHeight # no OS chrome in headless",
243
+ "",
244
+ "# \u2705 Avoid accessing these APIs. They are only used for fingerprinting."
245
+ ].join("\n")
246
+ };
247
+ case "event-simulation":
248
+ return {
249
+ title: "Synthetic event simulation blocked",
250
+ detail: `Your ${method} call simulated user interaction via el.click() or dispatchEvent(new Event(...)). These produce isTrusted=false events, which are 100% detectable by any anti-crawler that checks isTrusted on critical events.`,
251
+ codeExample: [
252
+ "# \u274C BLOCKED \u2014 synthetic events (isTrusted=false):",
253
+ "el.click() # isTrusted=false",
254
+ 'el.dispatchEvent(new Event("click")) # isTrusted=false',
255
+ "el.focus() # isTrusted=false",
256
+ "",
257
+ "# \u2705 USE INSTEAD \u2014 CDP-level input dispatch (isTrusted=true):",
258
+ "page.click(selector) # uses Input.dispatchMouseEvent",
259
+ "page.fill(selector, value) # dispatches real input events"
260
+ ].join("\n")
261
+ };
262
+ case "emulation-override":
263
+ return {
264
+ title: "CDP emulation override blocked",
265
+ detail: `Your ${method} call overrides browser behavior in a way that creates detectable inconsistencies. Anti-crawler systems cross-check multiple sources (e.g., navigator.userAgent vs HTTP User-Agent header) to catch these mismatches.`,
266
+ codeExample: [
267
+ "# \u274C BLOCKED \u2014 detectable emulation override:",
268
+ "Emulation.setUserAgentOverride(...) # JS vs HTTP header mismatch",
269
+ "Emulation.setGeolocationOverride(...) # IP geo vs overridden geo mismatch",
270
+ "Emulation.setDeviceMetricsOverride(...) # matchMedia vs actual viewport",
271
+ "",
272
+ "# \u2705 These are handled automatically by the CDP firewall.",
273
+ "# Do NOT call them manually."
274
+ ].join("\n")
275
+ };
276
+ case "network-anomaly":
277
+ return {
278
+ title: "Network anomaly detected",
279
+ detail: `Your ${method} call triggered a network pattern that is characteristic of scrapers: blocking URLs, clearing caches, or intercepting requests.`,
280
+ codeExample: [
281
+ "# \u274C BLOCKED \u2014 scraper optimization:",
282
+ "Network.clearBrowserCache() # natural users never do this",
283
+ 'Network.setBlockedURLs(["*fonts*"]) # blocking resources is detectable',
284
+ "Fetch.enable() # MITM-style interception",
285
+ "",
286
+ "# \u2705 Let the browser manage its own cache and network normally."
287
+ ].join("\n")
288
+ };
289
+ case "page-lifecycle":
290
+ return {
291
+ title: "Suspicious page lifecycle pattern blocked",
292
+ detail: `Your ${method} call reveals an unnatural page interaction sequence: navigating too fast, taking screenshots before the page renders, or generating PDFs (a telltale scraper giveaway).`,
293
+ codeExample: [
294
+ "# \u274C BLOCKED \u2014 unnatural lifecycle:",
295
+ "page.goto(url); page.pdf() # PDF = scraper giveaway",
296
+ "page.goto(url); page.screenshot() <500ms # screenshot before render",
297
+ "page.goto(url) 3x in <100ms # rapid navigation barrage",
298
+ "",
299
+ "# \u2705 Add proper waits between actions:",
300
+ 'page.goto(url, {waitUntil: "networkidle"})',
301
+ 'page.waitForSelector("body")',
302
+ "page.screenshot() # after rendering"
303
+ ].join("\n")
304
+ };
305
+ default:
306
+ return {
307
+ title: decision.reason,
308
+ detail: decision.suggestion ?? `The CDP call "${method}" was blocked by rule "${decision.ruleId}".`
309
+ };
310
+ }
311
+ }
312
+
313
+ // src/cdp-interceptor/proxy.ts
314
+ function makeCompoundId(cdpSessionId, rawSessionId) {
315
+ return `${cdpSessionId ?? "nil"}::${rawSessionId ?? "nil"}`;
316
+ }
317
+ var CDPInterceptorProxy = class {
318
+ wss = null;
319
+ engine;
320
+ config;
321
+ logger;
322
+ started = false;
323
+ stats = {
324
+ totalMessages: 0,
325
+ blockedMessages: 0,
326
+ transformedMessages: 0,
327
+ passedMessages: 0,
328
+ byRule: {}
329
+ };
330
+ constructor(config) {
331
+ this.config = config;
332
+ this.engine = createRuleEngine(config.rules);
333
+ this.logger = createLogger({
334
+ enableLogging: config.enableLogging ?? true,
335
+ logDir: config.logDir
336
+ });
337
+ }
338
+ /** The port the proxy is listening on (only valid after start()) */
339
+ get port() {
340
+ const addr = this.wss?.address();
341
+ if (addr && typeof addr === "object") return addr.port;
342
+ return 0;
343
+ }
344
+ /** Start the proxy server */
345
+ async start() {
346
+ if (this.started) return this.port;
347
+ return new Promise((resolve, reject) => {
348
+ this.wss = new WebSocketServer({ port: this.config.listenPort ?? 0 }, () => {
349
+ const port = this.port;
350
+ this.engine.start();
351
+ this.started = true;
352
+ this.logger.info("CDP interceptor proxy started", { port, endpoint: this.config.cdpEndpoint });
353
+ resolve(port);
354
+ });
355
+ this.wss.on("error", reject);
356
+ this.wss.on("connection", (clientWs, _req) => {
357
+ this.handleConnection(clientWs);
358
+ });
359
+ });
360
+ }
361
+ /** Stop the proxy server */
362
+ async stop() {
363
+ this.engine.stop();
364
+ this.logger.flush();
365
+ this.started = false;
366
+ return new Promise((resolve) => {
367
+ if (!this.wss) return resolve();
368
+ this.wss.close(() => resolve());
369
+ this.wss = null;
370
+ });
371
+ }
372
+ /** Get accumulated statistics */
373
+ getStats() {
374
+ return { ...this.stats };
375
+ }
376
+ /** Get recent log entries (for inspection) */
377
+ getRecentLogs(count = 50) {
378
+ return this.logger.getRecent(count);
379
+ }
380
+ // ── Connection handling ──────────────────────────────────────
381
+ handleConnection(clientWs) {
382
+ let browserWs = null;
383
+ let isAlive = true;
384
+ const pendingMessages = [];
385
+ browserWs = new WebSocket(this.config.cdpEndpoint);
386
+ clientWs.on("message", (raw) => {
387
+ if (browserWs && browserWs.readyState === WebSocket.OPEN) {
388
+ this.handleClientMessage(clientWs, browserWs, raw);
389
+ } else {
390
+ pendingMessages.push(raw);
391
+ }
392
+ });
393
+ browserWs.on("open", () => {
394
+ for (const buf of pendingMessages) {
395
+ this.handleClientMessage(clientWs, browserWs, buf);
396
+ }
397
+ pendingMessages.length = 0;
398
+ });
399
+ browserWs.on("error", (err) => {
400
+ this.logger.info("Browser WebSocket error", { error: String(err) });
401
+ });
402
+ browserWs.on("close", (code, reason) => {
403
+ if (isAlive && clientWs.readyState === WebSocket.OPEN) {
404
+ this.logger.info("Browser WS closed, closing client", { code, reason: String(reason) });
405
+ clientWs.close();
406
+ }
407
+ });
408
+ browserWs.on("message", (raw) => {
409
+ this.handleBrowserMessage(clientWs, browserWs, raw);
410
+ });
411
+ const cleanup = () => {
412
+ isAlive = false;
413
+ if (browserWs && browserWs.readyState === WebSocket.OPEN) {
414
+ browserWs.close();
415
+ }
416
+ };
417
+ clientWs.on("close", cleanup);
418
+ clientWs.on("error", cleanup);
419
+ browserWs.on("close", () => {
420
+ if (isAlive && clientWs.readyState === WebSocket.OPEN) {
421
+ clientWs.close();
422
+ }
423
+ });
424
+ browserWs.on("error", cleanup);
425
+ }
426
+ // ── Message processing ───────────────────────────────────────
427
+ handleClientMessage(clientWs, browserWs, raw) {
428
+ const msg = this.parseMessage(raw);
429
+ if (!msg) return;
430
+ this.stats.totalMessages++;
431
+ if (!("method" in msg)) {
432
+ browserWs.send(raw.toString());
433
+ return;
434
+ }
435
+ const request = msg;
436
+ const ctx = {
437
+ method: request.method,
438
+ params: request.params ?? {},
439
+ sessionId: makeCompoundId("_cdpSession" in browserWs ? browserWs._cdpSession : void 0, request.sessionId),
440
+ direction: "client\u2192browser"
441
+ };
442
+ const decision = this.engine.evaluate(ctx);
443
+ this.logger.log(ctx.method, "client\u2192browser", ctx.sessionId, { method: ctx.method, params: ctx.params }, decision);
444
+ if (decision) {
445
+ this.recordDecision(decision);
446
+ }
447
+ if (decision?.action === "block") {
448
+ const blockMsg = formatBlockMessage(decision, ctx.method);
449
+ const errorResponse = {
450
+ id: request.id,
451
+ error: {
452
+ code: decision.errorCode ?? -32e3,
453
+ message: blockMsg
454
+ },
455
+ sessionId: request.sessionId
456
+ };
457
+ this.stats.blockedMessages++;
458
+ console.error(`
459
+ ${blockMsg}
460
+ `);
461
+ clientWs.send(JSON.stringify(errorResponse));
462
+ return;
463
+ }
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
+ }
478
+ const transformed = { ...request, params: decision.transformedParams };
479
+ this.stats.transformedMessages++;
480
+ browserWs.send(JSON.stringify(transformed));
481
+ return;
482
+ }
483
+ this.stats.passedMessages++;
484
+ browserWs.send(raw.toString());
485
+ }
486
+ handleBrowserMessage(clientWs, _browserWs, raw) {
487
+ const msg = this.parseMessage(raw);
488
+ if (!msg) {
489
+ clientWs.send(raw.toString());
490
+ return;
491
+ }
492
+ if ("method" in msg) {
493
+ const event = msg;
494
+ const ctx = {
495
+ method: event.method,
496
+ params: event.params ?? {},
497
+ sessionId: event.sessionId ?? "browser",
498
+ direction: "browser\u2192client"
499
+ };
500
+ const decision = this.engine.evaluate(ctx);
501
+ if (decision?.action === "block") {
502
+ return;
503
+ }
504
+ }
505
+ clientWs.send(raw.toString());
506
+ }
507
+ // ── Utilities ────────────────────────────────────────────────
508
+ parseMessage(raw) {
509
+ try {
510
+ return JSON.parse(raw.toString());
511
+ } catch {
512
+ return null;
513
+ }
514
+ }
515
+ recordDecision(decision) {
516
+ if (!this.stats.byRule[decision.ruleId]) {
517
+ this.stats.byRule[decision.ruleId] = { matched: 0, blocked: 0, transformed: 0 };
518
+ }
519
+ this.stats.byRule[decision.ruleId].matched++;
520
+ if (decision.action === "block") {
521
+ this.stats.byRule[decision.ruleId].blocked++;
522
+ } else if (decision.action === "transform") {
523
+ this.stats.byRule[decision.ruleId].transformed++;
524
+ }
525
+ }
526
+ };
527
+
528
+ // src/browser/connection.ts
529
+ async function getCDPTargets(cdpEndpoint) {
530
+ try {
531
+ const endpoint = String(cdpEndpoint);
532
+ let url = "http://localhost:9222/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`;
539
+ }
540
+ const response = await fetch(url);
541
+ return await response.json();
542
+ } catch {
543
+ return [];
544
+ }
545
+ }
546
+ async function findTargetPage(cdpEndpoint, target) {
547
+ const targets = await getCDPTargets(cdpEndpoint);
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);
550
+ if (byId) return { pageId: byId.id, wsUrl: byId.webSocketDebuggerUrl, title: byId.title, url: byId.url };
551
+ const lowerTarget = target.toLowerCase();
552
+ const byTitle = pages.find((item) => item.title?.toLowerCase().includes(lowerTarget));
553
+ if (byTitle) return { pageId: byTitle.id, wsUrl: byTitle.webSocketDebuggerUrl, title: byTitle.title, url: byTitle.url };
554
+ const byUrl = pages.find((item) => item.url.toLowerCase().includes(lowerTarget));
555
+ if (byUrl) return { pageId: byUrl.id, wsUrl: byUrl.webSocketDebuggerUrl, title: byUrl.title, url: byUrl.url };
556
+ return null;
557
+ }
558
+ function resolveLaunchOpts(ctx) {
559
+ return ctx.cdpEndpoint ? { cdpEndpoint: ctx.cdpEndpoint } : { headless: true };
560
+ }
561
+ var CHROMIUM_CANDIDATES = [
562
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
563
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
564
+ "/usr/bin/chromium-browser",
565
+ "/usr/bin/chromium",
566
+ "/usr/bin/google-chrome"
567
+ ];
568
+ function discoverChromiumPath() {
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;
578
+ }
579
+ async function createBrowser(options) {
580
+ if (options?.cdpEndpoint) {
581
+ const realEndpoint = await resolveCDPEndpoint(options.cdpEndpoint);
582
+ if (!options.intercept) {
583
+ const pooled = browserPool.get(realEndpoint);
584
+ if (pooled && !pooled.disconnected) return pooled;
585
+ if (pooled) browserPool.delete(realEndpoint);
586
+ }
587
+ if (options.intercept) {
588
+ const config = typeof options.intercept === "object" ? { ...options.intercept, cdpEndpoint: realEndpoint } : { cdpEndpoint: realEndpoint };
589
+ sharedCdpProxy = new CDPInterceptorProxy(config);
590
+ const proxyPort = await sharedCdpProxy.start();
591
+ console.error(`[CDP Interceptor] Proxy running on ws://localhost:${proxyPort}, forwarding to ${realEndpoint}`);
592
+ const { browser: browser3 } = await launch({ cdpEndpoint: `ws://localhost:${proxyPort}` });
593
+ return browser3;
594
+ }
595
+ const { browser: browser2 } = await launch({ cdpEndpoint: realEndpoint });
596
+ await browser2.discoverContexts().catch((error) => {
597
+ console.error(`[browser] discoverContexts failed: ${errMsg(error)}`);
598
+ });
599
+ browserPool.set(realEndpoint, browser2);
600
+ return browser2;
601
+ }
602
+ const executablePath = options?.executablePath || process.env.XBROWSER_CHROMIUM_PATH || discoverChromiumPath();
603
+ const { browser } = await launch({ executablePath, headless: options?.headless ?? true });
604
+ return browser;
605
+ }
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`);
618
+ }
619
+ function ensureSessionDir() {
620
+ mkdirSync(SESSION_DIR, { recursive: true });
621
+ }
622
+ function saveSessionDiskMeta(name, data) {
623
+ ensureSessionDir();
624
+ const file = sessionFile(name);
625
+ let existing = {};
626
+ try {
627
+ existing = JSON.parse(readFileSync(file, "utf8"));
628
+ } catch {
629
+ }
630
+ Object.assign(existing, data, { name });
631
+ writeFileSync(file, JSON.stringify(existing, null, 2));
632
+ }
633
+ function readSessionDiskMeta(name) {
634
+ try {
635
+ return JSON.parse(readFileSync(sessionFile(name), "utf8"));
636
+ } catch {
637
+ return null;
638
+ }
639
+ }
640
+ function deleteSessionDiskMeta(name) {
641
+ try {
642
+ unlinkSync(sessionFile(name));
643
+ } catch {
644
+ }
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
+ }
668
+ async function isSessionPageAlive(session) {
669
+ const page = session.page;
670
+ if (!page || typeof page.evaluate !== "function") return false;
671
+ for (let attempt = 0; attempt < 3; attempt++) {
672
+ try {
673
+ await Promise.race([
674
+ page.evaluate("1"),
675
+ new Promise((_, reject) => setTimeout(() => reject(new Error("liveness probe timeout")), 1500))
676
+ ]);
677
+ return true;
678
+ } catch {
679
+ await new Promise((resolve) => setTimeout(resolve, 400));
680
+ }
681
+ }
682
+ return false;
683
+ }
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`);
690
+ try {
691
+ await cleanup(name);
692
+ } catch {
693
+ }
694
+ }
695
+ const meta = readSessionDiskMeta(name);
696
+ if (!meta) return void 0;
697
+ const endpoint = cdpEndpoint || meta.cdpEndpoint;
698
+ if (!endpoint) return void 0;
699
+ try {
700
+ const browser = await createBrowser({ cdpEndpoint: endpoint });
701
+ await new Promise((resolve) => setTimeout(resolve, 500));
702
+ let contexts = browser.contexts();
703
+ if (contexts.length === 0) {
704
+ await new Promise((resolve) => setTimeout(resolve, 500));
705
+ contexts = browser.contexts();
706
+ }
707
+ const context = contexts[0] || await browser.newContext();
708
+ const savedUrl = meta.conversationUrl || meta.url;
709
+ let targetHostname = "";
710
+ if (savedUrl) {
711
+ try {
712
+ targetHostname = new URL(savedUrl).hostname;
713
+ } catch {
714
+ targetHostname = "";
715
+ }
716
+ }
717
+ let page = null;
718
+ let fallbackPage = null;
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;
726
+ }
727
+ fallbackPage ??= candidate;
728
+ }
729
+ if (page) break;
730
+ }
731
+ page ??= fallbackPage;
732
+ if (!page) {
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) {
736
+ page = await context.newPage();
737
+ await page.goto(match.url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
738
+ });
739
+ }
740
+ }
741
+ if (!page) {
742
+ const pages = context.pages();
743
+ page = pages.length > 0 ? pages[0] : await context.newPage();
744
+ }
745
+ try {
746
+ await Promise.race([
747
+ page.evaluate(() => true),
748
+ new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 3e3))
749
+ ]);
750
+ } catch {
751
+ deleteSessionDiskMeta(name);
752
+ return void 0;
753
+ }
754
+ const targetUrl = meta.conversationUrl || meta.url;
755
+ if (targetUrl && page.url() !== targetUrl) {
756
+ try {
757
+ if (!page.url().includes(new URL(targetUrl).hostname)) {
758
+ await page.goto(targetUrl, { waitUntil: "domcontentloaded", timeout: 3e4 }).catch(() => {
759
+ });
760
+ }
761
+ } catch {
762
+ }
763
+ }
764
+ const session = {
765
+ id: meta.id,
766
+ name,
767
+ context,
768
+ page,
769
+ browser,
770
+ createdAt: meta.createdAt,
771
+ lastActivityAt: Date.now(),
772
+ isCDP: true,
773
+ cdpEndpoint: endpoint
774
+ };
775
+ for (const existing of sessions.list()) {
776
+ if (existing.name === name) sessions.removeById(existing.id);
777
+ }
778
+ sessions.set(session);
779
+ await installNetworkCapture2(session.page, name);
780
+ return session;
781
+ } catch (error) {
782
+ console.error(`[Session Restore] Failed for "${name}":`, errMsg(error));
783
+ deleteSessionDiskMeta(name);
784
+ return void 0;
785
+ }
786
+ }
787
+
788
+ // src/browser/create-session.ts
789
+ async function createSessionImpl(name, url, options, deps) {
790
+ const existing = findSession(name);
791
+ if (existing) {
792
+ deps.logSessionEvent("replace_session", `name="${name}" id="${existing.id}" \u2014 closing existing session before creating new one`);
793
+ await deps.closeSessionByName(name);
794
+ }
795
+ const b = await createBrowser(options);
796
+ const isCDP = !!options?.cdpEndpoint;
797
+ let context;
798
+ let page;
799
+ let reusedExistingPage = false;
800
+ if (isCDP) {
801
+ const targetHostname = url ? (() => {
802
+ try {
803
+ return new URL(url).hostname;
804
+ } catch {
805
+ return "";
806
+ }
807
+ })() : "";
808
+ const isRealPageUrl = (u) => !!u && u !== "about:blank" && !u.startsWith("chrome://") && !u.startsWith("chrome-untrusted://") && !u.startsWith("chrome-error://");
809
+ const resolvePageUrl = async (p) => {
810
+ const u = p.url();
811
+ if (u && u !== "about:blank") return u;
812
+ try {
813
+ return await p.evaluate("location.href");
814
+ } catch {
815
+ return u ?? "";
816
+ }
817
+ };
818
+ const pollStart = Date.now();
819
+ for (; ; ) {
820
+ const ctxs = b.contexts();
821
+ let hostHit = false;
822
+ let anyHit = false;
823
+ for (const ctx of ctxs) {
824
+ for (const p of ctx.pages()) {
825
+ const u = await resolvePageUrl(p);
826
+ if (!isRealPageUrl(u)) continue;
827
+ anyHit = true;
828
+ if (targetHostname && u.includes(targetHostname)) {
829
+ hostHit = true;
830
+ break;
831
+ }
832
+ }
833
+ if (hostHit) break;
834
+ }
835
+ if (process.env.XB_DEBUG_SESSION_POLL) {
836
+ console.error(`[poll] t=${Date.now() - pollStart}ms ctxs=${ctxs.length} hostHit=${hostHit} anyHit=${anyHit}`);
837
+ }
838
+ if (hostHit) break;
839
+ if (anyHit && Date.now() - pollStart >= 2e3) break;
840
+ if (Date.now() - pollStart >= 5e3) break;
841
+ await new Promise((r) => setTimeout(r, 200));
842
+ }
843
+ let contexts = b.contexts();
844
+ if (contexts.length === 0) {
845
+ await new Promise((r) => setTimeout(r, 500));
846
+ contexts = b.contexts();
847
+ }
848
+ context = contexts[0] || await b.newContext();
849
+ let targetPage = null;
850
+ const ownedUrls = /* @__PURE__ */ new Set();
851
+ for (const ssn of sessions.list()) {
852
+ try {
853
+ const u = ssn.page?.url();
854
+ if (u && u !== "about:blank") ownedUrls.add(u);
855
+ } catch {
856
+ }
857
+ }
858
+ if (url) {
859
+ for (const ctx of contexts) {
860
+ for (const p of ctx.pages()) {
861
+ try {
862
+ const pUrl = await resolvePageUrl(p);
863
+ if (ownedUrls.has(pUrl)) continue;
864
+ if (pUrl === url) {
865
+ targetPage = p;
866
+ break;
867
+ }
868
+ } catch {
869
+ }
870
+ }
871
+ if (targetPage) break;
872
+ }
873
+ }
874
+ if (!targetPage && targetHostname) {
875
+ for (const ctx of contexts) {
876
+ const pages = ctx.pages();
877
+ for (const p of pages) {
878
+ const pUrl0 = await resolvePageUrl(p);
879
+ if (ownedUrls.has(pUrl0)) continue;
880
+ const pUrl = pUrl0;
881
+ let hostnameMatches = false;
882
+ try {
883
+ hostnameMatches = new URL(pUrl).hostname === targetHostname;
884
+ } catch {
885
+ }
886
+ if (isRealPageUrl(pUrl) && hostnameMatches) {
887
+ targetPage = p;
888
+ break;
889
+ }
890
+ }
891
+ if (targetPage) break;
892
+ }
893
+ }
894
+ if (!targetPage && options?.cdpEndpoint) {
895
+ const targets = await deps.getCDPTargets(options.cdpEndpoint);
896
+ const ownedUrlsT = /* @__PURE__ */ new Set();
897
+ for (const ssn of sessions.list()) {
898
+ try {
899
+ const u = ssn.page?.url();
900
+ if (u && u !== "about:blank") ownedUrlsT.add(u);
901
+ } catch {
902
+ }
903
+ }
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
+ });
913
+ if (matchTarget && matchTarget.url) {
914
+ const ownedUrls2 = /* @__PURE__ */ new Set();
915
+ for (const ssn of sessions.list()) {
916
+ try {
917
+ const u = ssn.page?.url();
918
+ if (u && u !== "about:blank") ownedUrls2.add(u);
919
+ } catch {
920
+ }
921
+ }
922
+ const isOwned = (p) => {
923
+ try {
924
+ return ownedUrls2.has(p.url());
925
+ } catch {
926
+ return false;
927
+ }
928
+ };
929
+ const existing2 = context.pages().find((p) => {
930
+ try {
931
+ return p.url() === matchTarget.url && !isOwned(p);
932
+ } catch {
933
+ return false;
934
+ }
935
+ });
936
+ if (existing2) {
937
+ targetPage = existing2;
938
+ } else {
939
+ targetPage = await context.newPage();
940
+ await targetPage.goto(matchTarget.url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
941
+ });
942
+ }
943
+ }
944
+ }
945
+ const targetPageExisted = !!targetPage;
946
+ if (!targetPage) {
947
+ targetPage = await context.newPage();
948
+ }
949
+ page = targetPage;
950
+ reusedExistingPage = targetPageExisted;
951
+ if (isCDP) {
952
+ await Promise.resolve(targetPage.bringToFront?.()).catch(() => {
953
+ });
954
+ }
955
+ } else {
956
+ context = await b.newContext({ viewport: { width: 1920, height: 1080 } });
957
+ page = await context.newPage();
958
+ }
959
+ if (url && page.url() !== url) {
960
+ await page.goto(url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
961
+ });
962
+ }
963
+ const session = deps.registerSession({
964
+ name,
965
+ context,
966
+ page,
967
+ browser: b,
968
+ isCDP,
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);
974
+ return session;
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-YVDNUREI.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
+ }
1224
+ async function closeSessionByName(name) {
1225
+ for (const session of sessions) {
1226
+ if (session.name === name || session.id === name) {
1227
+ logSessionEvent2("close_session", `name="${session.name}" id="${session.id}" url="${session.page.url()}"`);
1228
+ if (session.bridge) {
1229
+ await session.page.close().catch(() => {
1230
+ });
1231
+ } else if (session.isCDP) {
1232
+ if (session.reusedExistingPage) {
1233
+ logSessionEvent2("close_session", `name="${session.name}" \u2014 reused existing tab, disconnecting only`);
1234
+ await session.browser.disconnect().catch(() => {
1235
+ });
1236
+ } else {
1237
+ await session.page.close().catch(() => {
1238
+ });
1239
+ await session.browser.disconnect().catch(() => {
1240
+ });
1241
+ }
1242
+ } else {
1243
+ await session.context.close();
1244
+ if (session.browser) {
1245
+ await session.browser.close().catch(() => {
1246
+ });
1247
+ }
1248
+ }
1249
+ sessions.removeById(session.id);
1250
+ const file2 = sessionFile(session.name);
1251
+ try {
1252
+ unlinkSync2(file2);
1253
+ } catch {
1254
+ }
1255
+ try {
1256
+ const { networkStore, commandLogStore } = await import("./network-store-YVDNUREI.js");
1257
+ networkStore.clear(session.name);
1258
+ commandLogStore.clear(session.name);
1259
+ } catch {
1260
+ }
1261
+ try {
1262
+ const { SessionRecorder } = await import("./session-recorder-CNTY5KXF.js");
1263
+ SessionRecorder.cleanup(session.name);
1264
+ } catch {
1265
+ }
1266
+ return true;
1267
+ }
1268
+ }
1269
+ const file = sessionFile(name);
1270
+ try {
1271
+ unlinkSync2(file);
1272
+ } catch {
1273
+ }
1274
+ return false;
1275
+ }
1276
+ async function closeAllSessions() {
1277
+ const names = sessions.list().map((s) => `${s.name}(${s.page.url()})`).join(", ");
1278
+ if (names) logSessionEvent2("close_all_sessions", `Closing ${sessions.size} sessions: ${names}`);
1279
+ for (const session of sessions.list()) {
1280
+ try {
1281
+ if (session.isCDP) {
1282
+ if (session.browser) {
1283
+ await session.browser.close().catch(() => {
1284
+ });
1285
+ }
1286
+ } else {
1287
+ await session.context.close();
1288
+ if (session.browser) {
1289
+ await session.browser.close().catch(() => {
1290
+ });
1291
+ }
1292
+ }
1293
+ sessions.removeById(session.id);
1294
+ } catch {
1295
+ sessions.removeById(session.id);
1296
+ }
1297
+ }
1298
+ }
1299
+ async function destroyBrowser() {
1300
+ logSessionEvent2("destroy_browser", `Sessions count: ${sessions.size}. Clearing idle timer and closing all sessions.`);
1301
+ if (sharedState.idleTimer) {
1302
+ clearTimeout(sharedState.idleTimer);
1303
+ sharedState.idleTimer = null;
1304
+ }
1305
+ await closeAllSessions();
1306
+ if (sharedState.browser) {
1307
+ await sharedState.browser.close().catch(() => {
1308
+ });
1309
+ sharedState.browser = null;
1310
+ }
1311
+ if (getSharedCdpProxy()) {
1312
+ await getSharedCdpProxy().stop().catch(() => {
1313
+ });
1314
+ setSharedCdpProxy(null);
1315
+ }
1316
+ }
1317
+ function resetForTesting() {
1318
+ sessions.clear();
1319
+ sharedState.browser = null;
1320
+ sharedState.idleTimer = null;
1321
+ setSharedCdpProxy(null);
1322
+ try {
1323
+ for (const file of readdirSync2(SESSION_DIR)) unlinkSync2(join2(SESSION_DIR, file));
1324
+ } catch {
1325
+ }
1326
+ }
1327
+ async function ensureProcessCanExit() {
1328
+ if (sharedState.idleTimer) {
1329
+ clearTimeout(sharedState.idleTimer);
1330
+ sharedState.idleTimer = null;
1331
+ }
1332
+ for (const session of sessions.list()) {
1333
+ if (session.browser) {
1334
+ if (session.isCDP) {
1335
+ } else {
1336
+ await session.browser.close().catch(() => {
1337
+ });
1338
+ }
1339
+ }
1340
+ }
1341
+ sessions.clear();
1342
+ if (sharedState.browser) {
1343
+ await sharedState.browser.close().catch(() => {
1344
+ });
1345
+ sharedState.browser = null;
1346
+ }
1347
+ if (getSharedCdpProxy()) {
1348
+ await getSharedCdpProxy().stop().catch(() => {
1349
+ });
1350
+ setSharedCdpProxy(null);
1351
+ }
1352
+ }
1353
+
1354
+ export {
1355
+ findTargetPage,
1356
+ resolveLaunchOpts,
1357
+ createBrowser,
1358
+ sessions,
1359
+ saveSessionDiskMeta,
1360
+ readSessionDiskMeta,
1361
+ deleteSessionDiskMeta,
1362
+ newSessionId,
1363
+ registerSession,
1364
+ resetIdleTimer,
1365
+ findOrRestoreSession2 as findOrRestoreSession,
1366
+ touchSession,
1367
+ getBrowser,
1368
+ findSession,
1369
+ getSessionById2 as getSessionById,
1370
+ setActivePage2 as setActivePage,
1371
+ createEphemeralContext,
1372
+ closeEphemeralContext,
1373
+ getAllSessions2 as getAllSessions,
1374
+ createSession,
1375
+ closeSessionByName,
1376
+ closeAllSessions,
1377
+ destroyBrowser,
1378
+ resetForTesting,
1379
+ ensureProcessCanExit
1380
+ };