@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
@@ -2970,6 +2970,7 @@ var SessionRecorder = class _SessionRecorder {
2970
2970
  if (entry && entry.origin === "signal" && Date.now() < entry.expires) {
2971
2971
  return;
2972
2972
  }
2973
+ this.dedupMap.set(dedupFromAction, { expires: Date.now() + 4e3, origin: "command" });
2973
2974
  }
2974
2975
  this.actionCounter++;
2975
2976
  const ts = Date.now();
@@ -3011,6 +3012,28 @@ var SessionRecorder = class _SessionRecorder {
3011
3012
  this.lastKnownUrl = action.value;
3012
3013
  }
3013
3014
  }
3015
+ /**
3016
+ * Reserve the dedup entry for a command BEFORE it executes. Both sides used
3017
+ * to write their entry only after their awaited captures (element screenshot,
3018
+ * auto-snapshot, click context): a fast click's signal was flushed while the
3019
+ * command was still in flight, found no 'command' entry and recorded itself,
3020
+ * and the command then found no 'signal' entry and recorded again.
3021
+ * Returns an undo for commands that end up recording nothing (failed or
3022
+ * thrown) — a reservation left behind would swallow a later real action on
3023
+ * the same element. A live 'signal' entry is kept: the real action was
3024
+ * already recorded and must still suppress the duplicate command action.
3025
+ */
3026
+ reserveCommandAction(action) {
3027
+ const key = this.dedupKey(action.type, action.selector, void 0, action.value);
3028
+ const entry = this.dedupMap.get(key);
3029
+ if (entry && entry.origin === "signal" && Date.now() < entry.expires) return () => {
3030
+ };
3031
+ const reservation = { expires: Date.now() + 4e3, origin: "command" };
3032
+ this.dedupMap.set(key, reservation);
3033
+ return () => {
3034
+ if (this.dedupMap.get(key) === reservation) this.dedupMap.delete(key);
3035
+ };
3036
+ }
3014
3037
  /** Generate dedup key for an action (normalized type + selector/tag + value). */
3015
3038
  dedupKey(type, selector, tag, value) {
3016
3039
  const normType = type === "cdp-click" ? "click" : type === "cdp-fill" ? "input" : type === "cdp-eval" ? "eval" : type;
@@ -3605,8 +3628,11 @@ var SessionRecorder = class _SessionRecorder {
3605
3628
  this.lastActionTs = raw.ts;
3606
3629
  const dedupKey = this.dedupKey(raw.type, raw.element?.selector, raw.element?.tag, raw.value);
3607
3630
  if (dedupKey) {
3608
- this.dedupMap.set(dedupKey, { expires: Date.now() + 4e3, origin: "signal" });
3609
- this.dedupActionCount++;
3631
+ const current = this.dedupMap.get(dedupKey);
3632
+ if (!current || current.origin !== "command" || Date.now() >= current.expires) {
3633
+ this.dedupMap.set(dedupKey, { expires: Date.now() + 4e3, origin: "signal" });
3634
+ this.dedupActionCount++;
3635
+ }
3610
3636
  }
3611
3637
  const verifyTypes = /* @__PURE__ */ new Set(["click", "submit", "input", "change", "cdp-click", "cdp-fill"]);
3612
3638
  if (verifyTypes.has(raw.type)) {
@@ -1,7 +1,6 @@
1
1
  import {
2
- ScreencastCapturer,
3
2
  getCaptchaConfig
4
- } from "./chunk-QCV2PI7U.js";
3
+ } from "./chunk-ZTHE5RBZ.js";
5
4
 
6
5
  // src/human-interaction.ts
7
6
  import { execFile } from "child_process";
@@ -177,27 +176,52 @@ var WebhookNotifier = class {
177
176
  };
178
177
 
179
178
  // src/human-interaction.ts
179
+ var DEFAULT_HUMAN_INTERACTION_SESSION = "default";
180
+ var activeWaitsByServer = /* @__PURE__ */ new WeakMap();
181
+ function acquireWaitSlot(server, sessionName) {
182
+ let sessions = activeWaitsByServer.get(server);
183
+ if (!sessions) {
184
+ sessions = /* @__PURE__ */ new Map();
185
+ activeWaitsByServer.set(server, sessions);
186
+ }
187
+ if (sessions.has(sessionName)) return false;
188
+ sessions.set(sessionName, "starting");
189
+ return true;
190
+ }
191
+ function releaseWaitSlot(server, sessionName) {
192
+ activeWaitsByServer.get(server)?.delete(sessionName);
193
+ }
194
+ function isHumanWaitActive(server, sessionName) {
195
+ return activeWaitsByServer.get(server)?.get(sessionName) === "waiting";
196
+ }
180
197
  var HumanInteractionManager = class {
181
198
  wsServer;
182
199
  page;
183
- capturer;
200
+ sessionName;
184
201
  webhook;
185
202
  autoOpen;
186
- constructor(wsServer, page) {
203
+ constructor(wsServer, page, sessionName) {
187
204
  this.wsServer = wsServer;
188
205
  this.page = page;
189
- this.capturer = new ScreencastCapturer();
206
+ this.sessionName = sessionName && sessionName.trim() ? sessionName.trim() : DEFAULT_HUMAN_INTERACTION_SESSION;
190
207
  const cfg = getCaptchaConfig();
191
208
  this.webhook = new WebhookNotifier(cfg.notifyUrl);
192
209
  this.autoOpen = cfg.autoOpen;
193
- this.wsServer.registerSession("default", page);
210
+ this.wsServer.registerSession(this.sessionName, page);
211
+ }
212
+ /** The named session this manager interacts with. */
213
+ get session() {
214
+ return this.sessionName;
215
+ }
216
+ buildPreviewUrl() {
217
+ return `http://localhost:${this.wsServer.getPort()}/preview/${encodeURIComponent(this.sessionName)}`;
194
218
  }
195
219
  async sendWebhook(event, overrides = {}) {
196
220
  await this.webhook.notify({
197
221
  event,
198
222
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
199
223
  url: this.page.url(),
200
- previewUrl: `http://localhost:${this.wsServer.getPort()}`,
224
+ previewUrl: this.buildPreviewUrl(),
201
225
  ...overrides
202
226
  });
203
227
  }
@@ -214,11 +238,16 @@ var HumanInteractionManager = class {
214
238
  /**
215
239
  * Wait for a human to solve a CAPTCHA or complete an interaction.
216
240
  *
217
- * Starts screencast streaming, sends webhook and broadcast notifications,
218
- * then polls for CAPTCHA resolution or waits for a manual solve signal.
241
+ * Sends session-scoped notifications and waits for CAPTCHA resolution
242
+ * or a manual solve signal from a viewer bound to this session.
243
+ *
244
+ * Only one wait may be in flight per session per WSServer. The wait
245
+ * slot, listener, and timers are cleaned
246
+ * up on every exit path (auto-detected / preview / timeout / error).
219
247
  *
220
248
  * @param options - Configuration for timeout, auto-detection, and reason text.
221
249
  * @returns Result indicating whether the CAPTCHA was solved and by what method.
250
+ * @throws If a wait is already in progress for this session.
222
251
  */
223
252
  async waitForHuman(options = {}) {
224
253
  const {
@@ -227,102 +256,117 @@ var HumanInteractionManager = class {
227
256
  autoDetect = true,
228
257
  detectInterval = 2e3
229
258
  } = options;
230
- const captcha = await CaptchaDetector.detect(this.page);
231
- const captchaInfo = captcha.detected ? captcha : void 0;
232
- await this.capturer.startCapture(this.page, "default", (frame) => {
233
- this.wsServer.broadcast({
234
- type: "screenshot",
235
- data: {
236
- sessionId: frame.sessionId,
237
- id: frame.id,
238
- timestamp: frame.timestamp,
239
- data: frame.data,
240
- url: frame.url,
241
- viewport: frame.viewport
242
- }
243
- });
244
- });
245
- const previewUrl = `http://localhost:${this.wsServer.getPort()}`;
246
- await this.sendWebhook("captcha-detected", {
247
- reason: captchaInfo ? `${captchaInfo.type ?? "unknown"} CAPTCHA detected` : reason,
248
- timeout,
249
- targetUrl: this.page.url()
250
- });
251
- this.wsServer.broadcast({
252
- type: "captcha-detected",
253
- sessionId: "default",
254
- url: this.page.url(),
255
- reason: captchaInfo ? `${captchaInfo.type ?? "unknown"} CAPTCHA detected` : reason,
256
- timeout
257
- });
258
- this.tryAutoOpen(previewUrl);
259
- console.log("");
260
- console.log("\u26A0\uFE0F \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");
261
- console.log(`\u26A0\uFE0F ${captchaInfo ? (captchaInfo.type ?? "UNKNOWN").toUpperCase() + " CAPTCHA" : "INTERACTION"} REQUIRED`);
262
- console.log(`\u26A0\uFE0F URL: ${this.page.url()}`);
263
- console.log(`\u26A0\uFE0F `);
264
- console.log(`\u26A0\uFE0F Solve via:`);
265
- console.log(`\u26A0\uFE0F \u{1F4FA} Preview: ${previewUrl}`);
266
- console.log(`\u26A0\uFE0F \u{1F310} Direct: ${this.page.url()}`);
267
- console.log(`\u26A0\uFE0F \u23ED\uFE0F Skip`);
268
- console.log(`\u26A0\uFE0F \u274C Abort`);
269
- console.log(`\u26A0\uFE0F `);
270
- console.log(`\u26A0\uFE0F \u23F3 Waiting... (${timeout}s timeout)`);
271
- console.log("\u26A0\uFE0F \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");
272
- console.log("");
273
- return new Promise((resolve) => {
274
- let resolved = false;
275
- let pollTimer = null;
276
- let timeoutTimer = null;
277
- const cleanup = () => {
278
- if (pollTimer) clearInterval(pollTimer);
279
- if (timeoutTimer) clearTimeout(timeoutTimer);
280
- this.wsServer.removeListener("human-solved", onHumanSolved);
281
- this.capturer.stopCapture();
282
- };
283
- if (autoDetect && captchaInfo) {
284
- pollTimer = setInterval(async () => {
285
- if (resolved) return;
286
- try {
287
- const solved = await CaptchaDetector.isSolved(this.page, captchaInfo.selector);
288
- if (solved) {
289
- resolved = true;
290
- cleanup();
291
- this.wsServer.broadcast({ type: "resolved", sessionId: "default" });
292
- console.log("\u2705 CAPTCHA auto-detected as solved!");
293
- this.sendWebhook("captcha-resolved", { reason: "auto-detected" });
294
- resolve({ solved: true, method: "auto-detected" });
295
- }
296
- } catch {
297
- }
298
- }, detectInterval);
259
+ if (!acquireWaitSlot(this.wsServer, this.sessionName)) {
260
+ throw new Error(
261
+ `waitForHuman already in progress for session "${this.sessionName}" \u2014 only one human-interaction wait per session is allowed`
262
+ );
263
+ }
264
+ let slotReleased = false;
265
+ const releaseSlot = () => {
266
+ if (!slotReleased) {
267
+ slotReleased = true;
268
+ releaseWaitSlot(this.wsServer, this.sessionName);
299
269
  }
300
- const onHumanSolved = () => {
301
- if (!resolved) {
302
- resolved = true;
303
- cleanup();
304
- this.wsServer.broadcast({ type: "resolved", sessionId: "default" });
305
- console.log("\u2705 CAPTCHA solved via preview!");
306
- this.sendWebhook("captcha-resolved", { reason: "preview" });
307
- resolve({ solved: true, method: "preview" });
270
+ };
271
+ try {
272
+ const captcha = await CaptchaDetector.detect(this.page);
273
+ const captchaInfo = captcha.detected ? captcha : void 0;
274
+ const previewUrl = this.buildPreviewUrl();
275
+ const waitReason = captchaInfo ? `${captchaInfo.type ?? "unknown"} CAPTCHA detected` : reason;
276
+ console.log("");
277
+ console.log("\u26A0\uFE0F \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");
278
+ console.log(`\u26A0\uFE0F ${captchaInfo ? (captchaInfo.type ?? "UNKNOWN").toUpperCase() + " CAPTCHA" : "INTERACTION"} REQUIRED (session: ${this.sessionName})`);
279
+ console.log(`\u26A0\uFE0F URL: ${this.page.url()}`);
280
+ console.log(`\u26A0\uFE0F `);
281
+ console.log(`\u26A0\uFE0F Solve via:`);
282
+ console.log(`\u26A0\uFE0F \u{1F4FA} Preview: ${previewUrl}`);
283
+ console.log(`\u26A0\uFE0F \u{1F310} Direct: ${this.page.url()}`);
284
+ console.log(`\u26A0\uFE0F \u23ED\uFE0F Skip`);
285
+ console.log(`\u26A0\uFE0F \u274C Abort`);
286
+ console.log(`\u26A0\uFE0F `);
287
+ console.log(`\u26A0\uFE0F \u23F3 Waiting... (${timeout}s timeout)`);
288
+ console.log("\u26A0\uFE0F \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");
289
+ console.log("");
290
+ return await new Promise((resolve) => {
291
+ let resolved = false;
292
+ let pollTimer = null;
293
+ let timeoutTimer = null;
294
+ const cleanup = () => {
295
+ if (pollTimer) clearInterval(pollTimer);
296
+ if (timeoutTimer) clearTimeout(timeoutTimer);
297
+ this.wsServer.removeListener("human-solved", onHumanSolved);
298
+ releaseSlot();
299
+ };
300
+ if (autoDetect && captchaInfo) {
301
+ pollTimer = setInterval(async () => {
302
+ if (resolved) return;
303
+ try {
304
+ const solved = await CaptchaDetector.isSolved(this.page, captchaInfo.selector);
305
+ if (solved && !resolved) {
306
+ resolved = true;
307
+ cleanup();
308
+ this.wsServer.broadcastToSession(this.sessionName, {
309
+ type: "resolved",
310
+ sessionId: this.sessionName
311
+ });
312
+ console.log("\u2705 CAPTCHA auto-detected as solved!");
313
+ this.sendWebhook("captcha-resolved", { reason: "auto-detected" });
314
+ resolve({ solved: true, method: "auto-detected" });
315
+ }
316
+ } catch {
317
+ }
318
+ }, detectInterval);
308
319
  }
309
- };
310
- this.wsServer.on("human-solved", onHumanSolved);
311
- if (timeout > 0) {
312
- timeoutTimer = setTimeout(() => {
320
+ const onHumanSolved = (payload) => {
321
+ if (!payload || payload.sessionId !== this.sessionName) return;
313
322
  if (!resolved) {
314
323
  resolved = true;
315
324
  cleanup();
316
- console.log("\u23F0 Timeout - skipping");
317
- this.sendWebhook("captcha-resolved", { reason: "timeout" });
318
- resolve({ solved: false, method: "timeout" });
325
+ this.wsServer.broadcastToSession(this.sessionName, {
326
+ type: "resolved",
327
+ sessionId: this.sessionName
328
+ });
329
+ console.log("\u2705 CAPTCHA solved via preview!");
330
+ this.sendWebhook("captcha-resolved", { reason: "preview" });
331
+ resolve({ solved: true, method: "preview" });
319
332
  }
320
- }, timeout * 1e3);
321
- }
322
- });
333
+ };
334
+ this.wsServer.on("human-solved", onHumanSolved);
335
+ if (timeout > 0) {
336
+ timeoutTimer = setTimeout(() => {
337
+ if (!resolved) {
338
+ resolved = true;
339
+ cleanup();
340
+ this.wsServer.broadcastToSession(this.sessionName, {
341
+ type: "handoff-timeout",
342
+ sessionId: this.sessionName
343
+ });
344
+ console.log("\u23F0 Timeout - skipping");
345
+ this.sendWebhook("captcha-resolved", { reason: "timeout" });
346
+ resolve({ solved: false, method: "timeout" });
347
+ }
348
+ }, timeout * 1e3);
349
+ }
350
+ activeWaitsByServer.get(this.wsServer)?.set(this.sessionName, "waiting");
351
+ this.wsServer.broadcastToSession(this.sessionName, {
352
+ type: "captcha-detected",
353
+ sessionId: this.sessionName,
354
+ url: this.page.url(),
355
+ reason: waitReason,
356
+ timeout
357
+ });
358
+ void this.sendWebhook("captcha-detected", { reason: waitReason, timeout, targetUrl: this.page.url() });
359
+ this.tryAutoOpen(previewUrl);
360
+ });
361
+ } catch (err) {
362
+ releaseSlot();
363
+ throw err;
364
+ }
323
365
  }
324
366
  };
325
367
 
326
368
  export {
369
+ DEFAULT_HUMAN_INTERACTION_SESSION,
370
+ isHumanWaitActive,
327
371
  HumanInteractionManager
328
372
  };
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  createRuleEngine,
3
3
  launch
4
- } from "./chunk-R7AG7ONI.js";
4
+ } from "./chunk-ZCZELQCS.js";
5
5
  import {
6
6
  errMsg
7
7
  } from "./chunk-GDKLH7ZY.js";
@@ -1225,7 +1225,10 @@ async function closeSessionByName(name) {
1225
1225
  for (const session of sessions) {
1226
1226
  if (session.name === name || session.id === name) {
1227
1227
  logSessionEvent2("close_session", `name="${session.name}" id="${session.id}" url="${session.page.url()}"`);
1228
- if (session.isCDP) {
1228
+ if (session.bridge) {
1229
+ await session.page.close().catch(() => {
1230
+ });
1231
+ } else if (session.isCDP) {
1229
1232
  if (session.reusedExistingPage) {
1230
1233
  logSessionEvent2("close_session", `name="${session.name}" \u2014 reused existing tab, disconnecting only`);
1231
1234
  await session.browser.disconnect().catch(() => {
@@ -1256,7 +1259,7 @@ async function closeSessionByName(name) {
1256
1259
  } catch {
1257
1260
  }
1258
1261
  try {
1259
- const { SessionRecorder } = await import("./session-recorder-N7VEKJVW.js");
1262
+ const { SessionRecorder } = await import("./session-recorder-KMKSQWEP.js");
1260
1263
  SessionRecorder.cleanup(session.name);
1261
1264
  } catch {
1262
1265
  }
@@ -1353,9 +1356,12 @@ export {
1353
1356
  findTargetPage,
1354
1357
  resolveLaunchOpts,
1355
1358
  createBrowser,
1359
+ sessions,
1356
1360
  saveSessionDiskMeta,
1357
1361
  readSessionDiskMeta,
1358
1362
  deleteSessionDiskMeta,
1363
+ newSessionId,
1364
+ registerSession,
1359
1365
  resetIdleTimer,
1360
1366
  findOrRestoreSession2 as findOrRestoreSession,
1361
1367
  touchSession,
@@ -0,0 +1,64 @@
1
+ // src/cli/output.ts
2
+ import { outputFormatter, OutputFormatter } from "@dyyz1993/xcli-core";
3
+ var formatter = new OutputFormatter();
4
+ function outputResult(result, mode = "text") {
5
+ if (mode !== "json" && mode !== "yaml" && typeof result === "object" && result !== null) {
6
+ const r = result;
7
+ if (r.success === false) {
8
+ outputError(r.message ? String(r.message) : "Unknown error");
9
+ }
10
+ if (r.ok === false) {
11
+ outputError(r.error ? String(r.error) : "Unknown error");
12
+ }
13
+ }
14
+ const output = outputFormatter.format(result, {
15
+ mode,
16
+ color: mode === "text",
17
+ emoji: false
18
+ });
19
+ console.log(output);
20
+ }
21
+ function outputError(message) {
22
+ const formatted = formatter.formatError(message, { color: true, emoji: false });
23
+ console.error(formatted);
24
+ process.exitCode = 1;
25
+ }
26
+ function outputEnvelope(result, meta, mode) {
27
+ if (mode !== "json" && mode !== "yaml") {
28
+ if (!result.success) {
29
+ outputError(result.message || "Unknown error");
30
+ return;
31
+ }
32
+ outputResult(result.data, mode);
33
+ return;
34
+ }
35
+ const { command, ...extraMeta } = meta;
36
+ const commandResult = {
37
+ success: result.success,
38
+ data: result.data,
39
+ message: result.message,
40
+ tips: [],
41
+ meta: {
42
+ duration: result.duration ?? 0,
43
+ ...extraMeta
44
+ }
45
+ };
46
+ const formatted = outputFormatter.formatEnvelope(commandResult, {
47
+ command,
48
+ extraMeta,
49
+ mode
50
+ });
51
+ console.log(formatted);
52
+ if (result.tips?.length) {
53
+ for (const tip of result.tips) {
54
+ const text = typeof tip === "string" ? tip : tip.message;
55
+ if (text) console.error(` \u{1F4A1} ${text}`);
56
+ }
57
+ }
58
+ }
59
+
60
+ export {
61
+ outputResult,
62
+ outputError,
63
+ outputEnvelope
64
+ };
@@ -0,0 +1,150 @@
1
+ import {
2
+ outputEnvelope,
3
+ outputError
4
+ } from "./chunk-RGL2YTWQ.js";
5
+ import {
6
+ executeChain
7
+ } from "./chunk-GVJ2UY65.js";
8
+ import {
9
+ forwardManagedRun
10
+ } from "./chunk-WGWPWNIA.js";
11
+ import {
12
+ errMsg
13
+ } from "./chunk-GDKLH7ZY.js";
14
+
15
+ // src/stdin.ts
16
+ import { readStdin, readCommandFile, splitFileLine } from "@dyyz1993/xcli-core";
17
+
18
+ // src/cli/run-routes.ts
19
+ import { readFileSync as readFileSync2 } from "fs";
20
+ import { z } from "zod/v4";
21
+
22
+ // src/browser/session-persistence.ts
23
+ import {
24
+ lstatSync,
25
+ existsSync,
26
+ mkdirSync,
27
+ readdirSync,
28
+ readFileSync,
29
+ renameSync,
30
+ unlinkSync,
31
+ writeFileSync
32
+ } from "fs";
33
+ import { homedir } from "os";
34
+ import { join } from "path";
35
+ import { randomUUID } from "crypto";
36
+ function sanitizeSessionName(name) {
37
+ if (!name || name === "." || name === "..") {
38
+ throw new Error(`Invalid session name "${name}": must be a non-empty file-safe name`);
39
+ }
40
+ if (name.length > 64) {
41
+ throw new Error(`Invalid session name: too long (max 64 chars, got ${name.length})`);
42
+ }
43
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)) {
44
+ throw new Error(
45
+ `Invalid session name "${name}": only [A-Za-z0-9._-] allowed and it must start with an alphanumeric character`
46
+ );
47
+ }
48
+ return name;
49
+ }
50
+
51
+ // src/cli/run-routes.ts
52
+ var manifest = z.object({
53
+ jobs: z.array(z.object({
54
+ session: z.string(),
55
+ chain: z.string().trim().min(1)
56
+ })).min(1).max(100)
57
+ });
58
+ async function runNamedJobs(jobs, limit, run = forwardManagedRun) {
59
+ if (!Number.isInteger(limit) || limit < 1 || limit > 8) throw new Error("--parallel must be an integer from 1 to 8");
60
+ const names = jobs.map((job) => sanitizeSessionName(job.session));
61
+ if (new Set(names).size !== names.length) throw new Error("Each job must use a different session name");
62
+ const results = [];
63
+ let next = 0;
64
+ await Promise.all(Array.from({ length: Math.min(limit, jobs.length) }, async () => {
65
+ while (next < jobs.length) {
66
+ const index = next++;
67
+ const { session, chain } = jobs[index];
68
+ try {
69
+ const result = await run(chain, session);
70
+ results[index] = { session, success: result.success, result };
71
+ } catch (error) {
72
+ results[index] = { session, success: false, error: errMsg(error) };
73
+ }
74
+ }
75
+ }));
76
+ return results;
77
+ }
78
+ async function handleManagedRunFile(filePath, options) {
79
+ try {
80
+ if (filePath.endsWith(".json")) {
81
+ const { jobs } = manifest.parse(JSON.parse(readFileSync2(filePath, "utf8")));
82
+ const results = await runNamedJobs(jobs, options.parallel === void 0 ? 2 : Number(options.parallel));
83
+ const success = results.every((job) => job.success);
84
+ const failures = results.filter((job) => !job.success);
85
+ const message2 = failures.length ? `Jobs failed: ${failures.map((job) => job.session).join(", ")}` : void 0;
86
+ outputEnvelope({ success, data: { jobs: results }, message: message2 }, { command: "run" }, options.mode);
87
+ if (!success) process.exitCode = 1;
88
+ return;
89
+ }
90
+ if (options.parallel !== void 0) throw new Error("--parallel requires a JSON job manifest");
91
+ const commands = readCommandFile(filePath);
92
+ if (commands.length === 0) throw new Error("No commands found in file");
93
+ const session = sanitizeSessionName(options.sessionName);
94
+ const result = await forwardManagedRun(commands.join(" ; "), session, true);
95
+ const failed = result.steps.find((step) => !step.success);
96
+ const message = result.success ? void 0 : result.stoppedReason ?? failed?.message ?? "Run failed";
97
+ outputEnvelope({ success: result.success, data: result, message }, { command: "run", session }, options.mode);
98
+ if (!result.success) process.exitCode = 1;
99
+ } catch (error) {
100
+ outputEnvelope({ success: false, data: null, message: errMsg(error) }, { command: "run" }, options.mode);
101
+ process.exitCode = 1;
102
+ }
103
+ }
104
+ async function handleRun(filePath, options) {
105
+ let commands;
106
+ try {
107
+ commands = readCommandFile(filePath);
108
+ } catch (e) {
109
+ outputError(`Failed to read file '${filePath}': ${errMsg(e)}`);
110
+ return;
111
+ }
112
+ if (commands.length === 0) {
113
+ outputError("No commands found in file");
114
+ return;
115
+ }
116
+ const chain = commands.join(" ; ");
117
+ const chainResult = await executeChain(chain, {
118
+ cdpEndpoint: options?.cdpEndpoint,
119
+ sessionName: options?.sessionName,
120
+ fileMode: true
121
+ });
122
+ for (const step of chainResult.steps) {
123
+ if (step.success) {
124
+ process.stdout.write(`[OK] ${step.raw}
125
+ `);
126
+ if (step.data && typeof step.data === "object") {
127
+ const d = step.data;
128
+ for (const [k, v] of Object.entries(d)) {
129
+ if (k !== "ok")
130
+ process.stdout.write(` ${k}: ${typeof v === "string" ? v : JSON.stringify(v)}
131
+ `);
132
+ }
133
+ }
134
+ } else {
135
+ outputError(`[FAIL] ${step.raw}: ${step.message}`);
136
+ }
137
+ }
138
+ if (chainResult.stoppedReason) {
139
+ outputError(`Stopped: ${chainResult.stoppedReason}`);
140
+ }
141
+ if (!chainResult.success) process.exit(1);
142
+ }
143
+
144
+ export {
145
+ readStdin,
146
+ readCommandFile,
147
+ runNamedJobs,
148
+ handleManagedRunFile,
149
+ handleRun
150
+ };
@@ -3,7 +3,9 @@ import { createRequire } from "module";
3
3
  var require2 = createRequire(import.meta.url);
4
4
  var pkg = require2("../package.json");
5
5
  var version = pkg.version;
6
+ var buildId = true ? "mwuaecno" : "dev";
6
7
 
7
8
  export {
8
- version
9
+ version,
10
+ buildId
9
11
  };