@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
@@ -406,9 +406,81 @@ var init_site_knowledge = __esm({
406
406
  });
407
407
 
408
408
  // src/recorder/session-recorder.ts
409
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2, readFileSync as readFileSync2, rmSync } from "fs";
410
- import { join as join2 } from "path";
411
- import { homedir as homedir2 } from "os";
409
+ init_site_knowledge();
410
+ import { existsSync as existsSync2, mkdirSync as mkdirSync3, writeFileSync as writeFileSync3, readFileSync as readFileSync3, rmSync } from "fs";
411
+ import { join as join4 } from "path";
412
+ import { homedir as homedir3 } from "os";
413
+
414
+ // src/recorder/network-capture.ts
415
+ function createNetworkCaptureState() {
416
+ return { entries: [], counter: { value: 0 }, lastRequestKey: "", lastRequestTs: 0 };
417
+ }
418
+ function handleNetworkRequest(request, state) {
419
+ const resourceType = request.resourceType();
420
+ if (["image", "stylesheet", "font", "manifest", "other"].includes(resourceType)) return;
421
+ const url = request.url();
422
+ if (url.startsWith("data:") || url.startsWith("chrome-extension://") || url.startsWith("blob:")) return;
423
+ const dedupKey = request.method() + " " + url;
424
+ const now = Date.now();
425
+ if (state.lastRequestKey === dedupKey && now - state.lastRequestTs < 100) return;
426
+ state.lastRequestKey = dedupKey;
427
+ state.lastRequestTs = now;
428
+ state.counter.value++;
429
+ const entry = {
430
+ id: state.counter.value,
431
+ timestamp: Date.now(),
432
+ method: request.method(),
433
+ url,
434
+ path: new URL(url).pathname,
435
+ status: 0,
436
+ resourceType,
437
+ contentType: "",
438
+ responseSize: 0
439
+ };
440
+ if (["POST", "PATCH", "PUT"].includes(request.method())) {
441
+ try {
442
+ const postData = request.postData();
443
+ if (postData) {
444
+ try {
445
+ entry.requestBody = JSON.parse(postData);
446
+ } catch {
447
+ entry.requestBody = postData.substring(0, 500);
448
+ }
449
+ }
450
+ } catch {
451
+ }
452
+ }
453
+ state.entries.push(entry);
454
+ }
455
+ async function handleNetworkResponse(response, state) {
456
+ const url = response.url();
457
+ if (url.startsWith("data:") || url.startsWith("chrome-extension://") || url.startsWith("blob:")) return;
458
+ const entry = [...state.entries].reverse().find((e) => e.url === url && e.status === 0);
459
+ if (!entry) return;
460
+ entry.status = response.status();
461
+ entry.contentType = response.headers()["content-type"] || "";
462
+ const resourceType = response.request().resourceType();
463
+ const isApi = ["fetch", "xhr"].includes(resourceType) || entry.contentType.includes("json") || entry.contentType.includes("text/");
464
+ if (isApi) {
465
+ try {
466
+ const text = await response.text();
467
+ entry.responseSize = text.length;
468
+ if (text.length <= 20480) {
469
+ try {
470
+ entry.responseBody = JSON.parse(text);
471
+ } catch {
472
+ entry.responseBody = text.substring(0, 500);
473
+ }
474
+ }
475
+ } catch {
476
+ }
477
+ } else {
478
+ try {
479
+ entry.responseSize = parseInt(response.headers()["content-length"] || "0", 10);
480
+ } catch {
481
+ }
482
+ }
483
+ }
412
484
 
413
485
  // src/recorder/selector-utils.ts
414
486
  function getSelectorGeneratorScript() {
@@ -672,8 +744,7 @@ function getSelectorGeneratorScript() {
672
744
  `;
673
745
  }
674
746
 
675
- // src/recorder/session-recorder.ts
676
- init_site_knowledge();
747
+ // src/recorder/injection-scripts.ts
677
748
  var ACTION_SIGNAL_SCRIPT = `
678
749
  (function() {
679
750
  if (window.__xb_action_signal) return;
@@ -2461,166 +2532,926 @@ var CHECKPOINT_OVERLAY_SCRIPT = `
2461
2532
  }, true);
2462
2533
  })();
2463
2534
  `;
2464
- var SessionRecorder = class _SessionRecorder {
2465
- context;
2466
- page;
2467
- sessionName;
2468
- startUrl = "";
2469
- startedAt = 0;
2470
- actions = [];
2471
- network = [];
2472
- contextChanges = [];
2473
- checkpoints = [];
2474
- /** Proactive baseline scan of filter/sort/tab/menu regions. Keyed by
2475
- * containerSelector so re-scans after navigation replace rather than dup. */
2476
- discoveredFilters = /* @__PURE__ */ new Map();
2477
- actionCounter = 0;
2478
- networkCounter = 0;
2479
- contextCounter = 0;
2480
- checkpointCounter = 0;
2481
- pollTimer = null;
2482
- flushTimer = null;
2483
- lastActionTs = 0;
2484
- activePages = /* @__PURE__ */ new Set();
2485
- lastKnownUrl = "";
2486
- // Track URL to detect real navigation changes
2487
- /** Dedup map: key = normalizedType|tag|value → expiration timestamp.
2488
- * Replaces old single-entry cdpActionDedup for bidirectional dedup. */
2489
- dedupMap = /* @__PURE__ */ new Map();
2490
- dedupActionCount = 0;
2491
- // counter for periodic cleanup
2492
- /** Network dedup: last request key for short-window dedup */
2493
- _lastRequestKey = "";
2494
- _lastRequestTs = 0;
2495
- _isRecording = false;
2496
- streamMode = "clean";
2497
- /** Snapshot throttle: prevents too many screenshots during rapid inputs.
2498
- * Keyed by 'type|elementSelector', value = last snapshot timestamp. */
2499
- snapshotThrottle = /* @__PURE__ */ new Map();
2500
- /** Ambient action types: filtered out in clean mode */
2501
- static AMBIENT_TYPES = /* @__PURE__ */ new Set([
2502
- "hover",
2503
- "focus",
2504
- "scroll",
2505
- "visibility",
2506
- "resize",
2507
- "clipboard",
2508
- "touch",
2509
- "contextmenu"
2510
- ]);
2511
- constructor(context, page, sessionName) {
2512
- this.context = context;
2513
- this.page = page;
2514
- this.sessionName = sessionName;
2515
- }
2516
- get isRecording() {
2517
- return this._isRecording;
2518
- }
2519
- get actionCount() {
2520
- return this.actions.length;
2521
- }
2522
- /** Record an action triggered by a CDP command (e.g. xbrowser fill/click/goto) */
2523
- async recordCommandAction(action) {
2524
- const dedupFromAction = this.dedupKey(action.type, action.selector, action.element?.tag, action.value);
2525
- if (dedupFromAction) {
2526
- const entry = this.dedupMap.get(dedupFromAction);
2527
- if (entry && entry.origin === "signal" && Date.now() < entry.expires) {
2528
- return;
2529
- }
2530
- }
2531
- this.actionCounter++;
2532
- const ts = Date.now();
2533
- const actionUrl = action.url && action.url !== "about:blank" ? action.url : this.lastKnownUrl || this.page.url();
2534
- const actionToPush = {
2535
- id: this.actionCounter,
2536
- type: action.type,
2537
- timestamp: ts,
2538
- url: actionUrl,
2539
- pageTitle: "",
2540
- element: action.element || (action.selector ? { tag: "", selector: action.selector, text: "" } : void 0),
2541
- value: action.value
2542
- };
2543
- this.actions.push(actionToPush);
2544
- actionToPush.elementScreenshot = await Promise.race([
2545
- this.captureElementScreenshot(this.page, {
2546
- type: action.type,
2547
- element: actionToPush.element
2548
- }).catch(() => void 0),
2549
- new Promise((r) => setTimeout(r, 3e3))
2550
- ]);
2551
- await Promise.race([
2552
- this.captureAutoSnapshot(this.page, actionToPush, "after").catch(() => {
2553
- }),
2554
- new Promise((r) => setTimeout(r, 6e3))
2555
- ]);
2556
- this.lastActionTs = ts;
2557
- this.dedupMap.set(dedupFromAction, { expires: Date.now() + 4e3, origin: "command" });
2558
- this.dedupActionCount++;
2559
- if (this.dedupActionCount % 200 === 0) {
2560
- const now = Date.now();
2561
- for (const [k, v] of this.dedupMap) {
2562
- if (now >= v.expires) this.dedupMap.delete(k);
2535
+
2536
+ // src/recorder/script-injector.ts
2537
+ async function injectActionScript(page) {
2538
+ let success = false;
2539
+ const maxAttempts = 3;
2540
+ let lastError = "";
2541
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
2542
+ try {
2543
+ await page.evaluate(getSelectorGeneratorScript());
2544
+ await page.evaluate(ACTION_SIGNAL_SCRIPT);
2545
+ await page.evaluate(`window.__xb_action_script_src = ${JSON.stringify(ACTION_SIGNAL_SCRIPT)};`);
2546
+ const injected = await page.evaluate(`(function() {
2547
+ try { return !!window.__xb_action_signal; } catch(e) { return false; }
2548
+ })()`).catch(() => false);
2549
+ if (injected) {
2550
+ success = true;
2551
+ break;
2563
2552
  }
2553
+ lastError = "verification failed (script did not set __xb_action_signal flag)";
2554
+ console.error(`[recorder] Action signal injection verification failed (attempt ${attempt}/${maxAttempts})`);
2555
+ } catch (e) {
2556
+ const err = e instanceof Error ? e : new Error(typeof e === "string" ? e : "unknown error");
2557
+ lastError = err.message;
2558
+ console.error(`[recorder] Action signal injection error (attempt ${attempt}/${maxAttempts}): ${err.message}`);
2564
2559
  }
2565
- if (action.url && action.url !== "about:blank") {
2566
- this.lastKnownUrl = action.url;
2567
- } else if (action.type === "goto" && action.value && action.value !== "about:blank") {
2568
- this.lastKnownUrl = action.value;
2560
+ if (attempt < maxAttempts) {
2561
+ await new Promise((r) => setTimeout(r, 1e3));
2569
2562
  }
2570
2563
  }
2571
- /** Generate dedup key for an action (normalized type + selector/tag + value). */
2572
- dedupKey(type, selector, tag, value) {
2573
- const normType = type === "cdp-click" ? "click" : type === "cdp-fill" ? "input" : type === "cdp-eval" ? "eval" : type;
2574
- const selOrTag = selector || tag || "";
2575
- return `${normType}|${selOrTag}|${value || ""}`;
2576
- }
2577
- get networkCount() {
2578
- return this.network.length;
2564
+ if (!success) {
2565
+ console.error(`[recorder] WARNING: Action signal injection FAILED after ${maxAttempts} attempts. User actions will NOT be recorded. Last error: ${lastError}`);
2579
2566
  }
2580
- getLiveData() {
2581
- return this.buildData();
2567
+ try {
2568
+ await page.evaluate(CHECKPOINT_OVERLAY_SCRIPT);
2569
+ } catch (e) {
2570
+ const msg = e instanceof Error ? e.message : String(e);
2571
+ console.error(`[recorder] Checkpoint overlay injection failed (non-fatal): ${msg}`);
2582
2572
  }
2583
- addManualCheckpoint(type, hint, selector) {
2584
- this.checkpointCounter++;
2585
- const cp = {
2586
- id: this.checkpointCounter,
2587
- type,
2588
- timestamp: Date.now(),
2589
- url: this.page.url(),
2590
- pageTitle: "",
2591
- hint,
2592
- selector,
2593
- source: "manual"
2594
- };
2595
- this.checkpoints.push(cp);
2596
- return cp;
2573
+ if (success) {
2574
+ try {
2575
+ await page.evaluate(`(function() {
2576
+ if (typeof window.__xb_scanFilters === 'function') {
2577
+ setTimeout(window.__xb_scanFilters, 100);
2578
+ }
2579
+ })()`);
2580
+ } catch {
2581
+ }
2597
2582
  }
2598
- /** Directory for this session's recordings. */
2599
- get recordingsDir() {
2600
- return _SessionRecorder.getRecordingsDir(this.sessionName);
2583
+ try {
2584
+ await page.evaluate(`
2585
+ (function() {
2586
+ var _scriptSrc = ${JSON.stringify(ACTION_SIGNAL_SCRIPT)};
2587
+ function injectIframe(iframe) {
2588
+ try {
2589
+ var w = iframe.contentWindow;
2590
+ if (!w) return;
2591
+ // Force re-injection: clear old flag
2592
+ try { delete w.__xb_action_signal; } catch(e) {}
2593
+ w.eval(_scriptSrc);
2594
+ // Tag iframe so flushIframes knows it's injected
2595
+ iframe.__xb_injected = true;
2596
+ } catch(e) {}
2597
+ }
2598
+ function watchIframe(iframe) {
2599
+ if (iframe.__xb_watched) return;
2600
+ iframe.__xb_watched = true;
2601
+ injectIframe(iframe);
2602
+ iframe.addEventListener('load', function() { injectIframe(iframe); });
2603
+ }
2604
+ // Inject into existing iframes
2605
+ try {
2606
+ var iframes = document.querySelectorAll('iframe');
2607
+ for (var i = 0; i < iframes.length; i++) watchIframe(iframes[i]);
2608
+ } catch(e) {}
2609
+ // Watch for dynamically inserted iframes
2610
+ if (!window.__xb_iframe_observer) {
2611
+ window.__xb_iframe_observer = new MutationObserver(function(mutations) {
2612
+ for (var m = 0; m < mutations.length; m++) {
2613
+ for (var n = 0; n < mutations[m].addedNodes.length; n++) {
2614
+ var node = mutations[m].addedNodes[n];
2615
+ if (node.tagName === 'IFRAME') {
2616
+ watchIframe(node);
2617
+ } else if (node.querySelectorAll) {
2618
+ var sub = node.querySelectorAll('iframe');
2619
+ for (var k = 0; k < sub.length; k++) watchIframe(sub[k]);
2620
+ }
2621
+ }
2622
+ }
2623
+ });
2624
+ window.__xb_iframe_observer.observe(document.documentElement, { childList: true, subtree: true });
2625
+ }
2626
+ // Periodic re-injection for iframes that load late or navigate internally
2627
+ if (!window.__xb_iframe_timer) {
2628
+ window.__xb_iframe_timer = setInterval(function() {
2629
+ try {
2630
+ var iframes = document.querySelectorAll('iframe');
2631
+ for (var i = 0; i < iframes.length; i++) {
2632
+ if (!iframes[i].__xb_injected) {
2633
+ watchIframe(iframes[i]);
2634
+ }
2635
+ }
2636
+ } catch(e) {}
2637
+ }, 3000);
2638
+ }
2639
+ })();
2640
+ `);
2641
+ } catch {
2601
2642
  }
2602
- /** Directory for auto-captured snapshots (PNG screenshots, stored in .tmp for easy cleanup). */
2603
- get snapshotsDir() {
2604
- return join2(this.recordingsDir, ".tmp", "snapshots");
2643
+ return success;
2644
+ }
2645
+
2646
+ // src/recorder/summary-builder.ts
2647
+ var POST_WINDOW = 5e3;
2648
+ var MERGE_WINDOW = 2e3;
2649
+ var COMPACT_MAX_FLOW_ITEMS = 100;
2650
+ var COMPACT_MAX_API_ITEMS = 20;
2651
+ function buildCompactSummary(data, startedAt) {
2652
+ const flow = [];
2653
+ let lastInputKey = "";
2654
+ const events = [
2655
+ ...data.actions.map((action) => ({ timestamp: action.timestamp, action })),
2656
+ ...data.contextChanges.map((contextChange) => ({ timestamp: contextChange.timestamp, contextChange }))
2657
+ ].sort((a, b) => a.timestamp - b.timestamp);
2658
+ for (const event of events) {
2659
+ if (flow.length >= COMPACT_MAX_FLOW_ITEMS) break;
2660
+ if (event.contextChange) {
2661
+ if (event.contextChange.type !== "navigate" || !event.contextChange.url) continue;
2662
+ lastInputKey = "";
2663
+ flow.push({
2664
+ step: flow.length + 1,
2665
+ action: `navigate ${event.contextChange.url}`
2666
+ });
2667
+ continue;
2668
+ }
2669
+ const action = event.action;
2670
+ if (!action) continue;
2671
+ const selector = action.element?.selector || action.element?.ariaLabel || action.element?.placeholder || action.element?.tag || "";
2672
+ const text = (action.element?.text || "").trim();
2673
+ const target = selector || text || action.url || "unknown";
2674
+ let description = "";
2675
+ if (action.type === "input" || action.type === "cdp-fill") {
2676
+ const inputKey = `${action.type}|${target}`;
2677
+ if (inputKey === lastInputKey) continue;
2678
+ lastInputKey = inputKey;
2679
+ description = `fill ${target} value=${truncate(action.value || "", 60)}`;
2680
+ } else if (action.type === "click" || action.type === "cdp-click") {
2681
+ lastInputKey = "";
2682
+ description = `click ${target}${text ? ` text=${truncate(text, 60)}` : ""}`;
2683
+ } else if (action.type === "change") {
2684
+ lastInputKey = "";
2685
+ description = `change ${target} value=${truncate(action.value || "", 60)}`;
2686
+ } else if (action.type === "submit") {
2687
+ lastInputKey = "";
2688
+ description = `submit ${target}`;
2689
+ } else if (action.type === "hover") {
2690
+ lastInputKey = "";
2691
+ description = `hover ${target}`;
2692
+ } else if (action.type === "drag") {
2693
+ lastInputKey = "";
2694
+ description = `drag from (${action.drag?.fromX ?? 0},${action.drag?.fromY ?? 0}) to (${action.drag?.toX ?? 0},${action.drag?.toY ?? 0})`;
2695
+ } else if (action.type === "drop") {
2696
+ lastInputKey = "";
2697
+ description = `drop ${action.files?.count ?? 1} file(s) on ${target}`;
2698
+ } else {
2699
+ continue;
2700
+ }
2701
+ flow.push({ step: flow.length + 1, action: description });
2702
+ }
2703
+ const keyApis = data.network.filter((entry) => (entry.resourceType === "fetch" || entry.resourceType === "xhr") && entry.contentType.toLowerCase().includes("json")).sort((a, b) => b.responseSize - a.responseSize).slice(0, COMPACT_MAX_API_ITEMS).map((entry) => ({
2704
+ method: entry.method,
2705
+ url: entry.url,
2706
+ path: entry.path,
2707
+ status: entry.status,
2708
+ contentType: entry.contentType,
2709
+ responseSize: entry.responseSize,
2710
+ ...entry.requestBody === void 0 ? {} : { requestBody: entry.requestBody }
2711
+ }));
2712
+ return {
2713
+ startUrl: data.startUrl,
2714
+ recordedAt: new Date(startedAt).toISOString(),
2715
+ durationMs: Math.max(0, Date.now() - startedAt),
2716
+ totalActions: data.actions.length,
2717
+ totalNetworkRequests: data.network.length,
2718
+ flow,
2719
+ keyApis
2720
+ };
2721
+ }
2722
+ function truncate(value, maxLength) {
2723
+ return value.length > maxLength ? `${value.slice(0, Math.max(0, maxLength - 3))}...` : value;
2724
+ }
2725
+ function buildSummary(data, startedAt) {
2726
+ const steps = [];
2727
+ const selectorToRef = /* @__PURE__ */ new Map();
2728
+ const elements = {};
2729
+ let refCounter = 0;
2730
+ function getRef(action) {
2731
+ const sel = action.element?.selector || action.element?.tag || "_none";
2732
+ if (selectorToRef.has(sel)) return selectorToRef.get(sel);
2733
+ refCounter++;
2734
+ const ref = "e" + refCounter;
2735
+ selectorToRef.set(sel, ref);
2736
+ if (action.element) {
2737
+ elements[ref] = {
2738
+ selector: action.element.selector || action.element.tag,
2739
+ tag: action.element.tag,
2740
+ text: action.element.text,
2741
+ role: action.element.role,
2742
+ type: action.element.type,
2743
+ placeholder: action.element.placeholder,
2744
+ ariaLabel: action.element.ariaLabel,
2745
+ href: action.element.href
2746
+ };
2747
+ } else {
2748
+ elements[ref] = { selector: "_none", tag: "_", text: "" };
2749
+ }
2750
+ return ref;
2751
+ }
2752
+ const isNoiseNetwork = (n) => {
2753
+ const url = n.url || "";
2754
+ const path = n.path || "";
2755
+ const rt = n.resourceType || "";
2756
+ if (["image", "stylesheet", "font", "manifest", "other"].includes(rt)) return true;
2757
+ if (n.status === 0) return true;
2758
+ if (/\/ztbox|\/mwb2\.gif|\/hmslog|\/log\.gif|\/tongji|hm\.baidu|clickstream|\/actionlog|\/collect\?|\/track|\/beacon/i.test(url)) return true;
2759
+ if (/\/favicon\.ico|\/robots\.txt/i.test(path)) return true;
2760
+ return false;
2761
+ };
2762
+ const meaningfulNetwork = data.network.filter((n) => !isNoiseNetwork(n));
2763
+ const filtered = data.actions;
2764
+ const groups = [];
2765
+ let current = null;
2766
+ for (const action of filtered) {
2767
+ const sameElement = current && current.primary.element?.selector && current.primary.element.selector === action.element?.selector && action.timestamp - current.primary.timestamp < MERGE_WINDOW;
2768
+ const isInputLike = action.type === "input" || action.type === "keydown" || action.type === "change";
2769
+ if (current && (sameElement || isInputLike && current.actions.some((a) => a.type === "input" || a.type === "click") && action.timestamp - current.primary.timestamp < MERGE_WINDOW)) {
2770
+ current.actions.push(action);
2771
+ if (action.type === "input") current.primary = action;
2772
+ } else {
2773
+ current = { actions: [action], primary: action };
2774
+ groups.push(current);
2775
+ }
2605
2776
  }
2606
- static getRecordingsDir(sessionName) {
2607
- return join2(homedir2(), ".xbrowser", "sessions", sessionName, "recordings");
2777
+ for (const group of groups) {
2778
+ const primary = group.primary;
2779
+ const tsStart = Math.min(...group.actions.map((a) => a.timestamp));
2780
+ const tsEnd = Math.max(...group.actions.map((a) => a.timestamp));
2781
+ const inputAction = group.actions.find((a) => a.type === "input");
2782
+ const nearbyNetwork = meaningfulNetwork.filter(
2783
+ (n) => n.timestamp >= tsStart - 500 && n.timestamp <= tsEnd + POST_WINDOW
2784
+ );
2785
+ const nearbyContext = data.contextChanges.filter(
2786
+ (c) => c.timestamp >= tsStart - 500 && c.timestamp <= tsEnd + POST_WINDOW
2787
+ );
2788
+ const matchedInputs = inputAction ? matchActionToNetwork(inputAction, nearbyNetwork) : [];
2789
+ const clickMatches = primary.type === "click" && primary.element?.text ? matchActionToNetwork(primary, nearbyNetwork) : [];
2790
+ const signals = primary.__signals || [];
2791
+ steps.push({
2792
+ step: steps.length + 1,
2793
+ ref: getRef(primary),
2794
+ action: primary,
2795
+ network: nearbyNetwork.map((n) => ({
2796
+ ...n,
2797
+ responseBody: n.responseBody && JSON.stringify(n.responseBody).length > 1e3 ? "[truncated, " + JSON.stringify(n.responseBody).length + " bytes]" : n.responseBody
2798
+ })),
2799
+ contextChanges: nearbyContext,
2800
+ matchedInputs: [...matchedInputs, ...clickMatches],
2801
+ signals
2802
+ });
2608
2803
  }
2609
- /** Path to the control file (used by record stop to signal this process). */
2610
- get controlFilePath() {
2611
- return join2(this.recordingsDir, ".control.json");
2804
+ return {
2805
+ startUrl: data.startUrl,
2806
+ recordedAt: new Date(startedAt).toISOString(),
2807
+ durationMs: Date.now() - startedAt,
2808
+ totalActions: data.actions.length,
2809
+ totalNetworkRequests: meaningfulNetwork.length,
2810
+ steps,
2811
+ elements,
2812
+ checkpoints: data.checkpoints
2813
+ };
2814
+ }
2815
+ function matchActionToNetwork(action, nearbyNetwork) {
2816
+ const matches = [];
2817
+ const searchValue = (action.value || action.element?.text || "").trim();
2818
+ if (!searchValue || searchValue.length < 2) return matches;
2819
+ for (const netEntry of nearbyNetwork) {
2820
+ if (netEntry.url.includes(encodeURIComponent(searchValue)) || netEntry.url.includes(searchValue)) {
2821
+ matches.push({ inputValue: searchValue, networkId: netEntry.id, paramName: "url" });
2822
+ }
2823
+ if (netEntry.requestBody && typeof netEntry.requestBody === "object") {
2824
+ searchObjectForValue(
2825
+ netEntry.requestBody,
2826
+ searchValue,
2827
+ netEntry.id,
2828
+ "",
2829
+ matches
2830
+ );
2831
+ }
2612
2832
  }
2613
- /** Path to the stop signal file (written by `record stop`). */
2614
- get stopSignalPath() {
2615
- return join2(this.recordingsDir, ".stop");
2833
+ return matches;
2834
+ }
2835
+ function searchObjectForValue(obj, targetValue, networkId, prefix, results) {
2836
+ for (const [key, value] of Object.entries(obj)) {
2837
+ const fullKey = prefix ? `${prefix}.${key}` : key;
2838
+ if (typeof value === "string" && value.includes(targetValue)) {
2839
+ results.push({ inputValue: targetValue, networkId, paramName: fullKey });
2840
+ } else if (typeof value === "object" && value !== null) {
2841
+ searchObjectForValue(value, targetValue, networkId, fullKey, results);
2842
+ }
2616
2843
  }
2617
- // ─── Start ──────────────────────────────────────────────────────
2618
- async start(url, options) {
2619
- if (this._isRecording) throw new Error("Already recording");
2620
- this._isRecording = true;
2621
- this.startedAt = Date.now();
2622
- this.actions = [];
2623
- this.network = [];
2844
+ }
2845
+
2846
+ // src/recorder/markdown-summary.ts
2847
+ import { readFileSync as readFileSync2 } from "fs";
2848
+ import { join as join2 } from "path";
2849
+ import { homedir as homedir2 } from "os";
2850
+ function buildMarkdownSummary(_data, summary) {
2851
+ const lines = [];
2852
+ const durSec = Math.round(summary.durationMs / 1e3);
2853
+ lines.push("# Recording Summary");
2854
+ lines.push("");
2855
+ lines.push(`- **URL**: ${summary.startUrl}`);
2856
+ lines.push(`- **Recorded**: ${summary.recordedAt}`);
2857
+ lines.push(`- **Duration**: ${durSec}s`);
2858
+ lines.push(`- **Steps**: ${summary.totalActions} actions, ${summary.totalNetworkRequests} network requests`);
2859
+ if (summary.checkpoints.length > 0) {
2860
+ const cpTypes = summary.checkpoints.map((c) => c.type);
2861
+ lines.push(`- **Checkpoints**: ${summary.checkpoints.length} (${[...new Set(cpTypes)].join(", ")})`);
2862
+ } else {
2863
+ lines.push("- **Checkpoints**: 0");
2864
+ }
2865
+ const checkpointSteps = /* @__PURE__ */ new Map();
2866
+ for (const cp of summary.checkpoints) {
2867
+ if (cp.relatedActionId != null) {
2868
+ for (const step of summary.steps) {
2869
+ if (step.action.id === cp.relatedActionId) {
2870
+ checkpointSteps.set(step.step, cp);
2871
+ break;
2872
+ }
2873
+ }
2874
+ }
2875
+ }
2876
+ lines.push("");
2877
+ lines.push("## Steps");
2878
+ lines.push("");
2879
+ for (const step of summary.steps) {
2880
+ const a = step.action;
2881
+ const el = a.element;
2882
+ const cp = checkpointSteps.get(step.step);
2883
+ if (cp) {
2884
+ lines.push(`### Step ${step.step}: \u26A0\uFE0F CHECKPOINT \u2014 ${cp.hint}`);
2885
+ lines.push(`- **Type**: ${cp.type} (${cp.source})`);
2886
+ lines.push(`- **Hint**: ${cp.hint}`);
2887
+ if (cp.selector) lines.push(`- **Selector**: \`${cp.selector}\``);
2888
+ lines.push(`- **Action needed**: Human intervention required before continuing`);
2889
+ } else {
2890
+ const title = describeActionTitle(a);
2891
+ lines.push(`### Step ${step.step}: ${title}`);
2892
+ }
2893
+ if (el) {
2894
+ const parts = [`\`${el.selector || el.tag}\``];
2895
+ if (el.text) parts.push(`"${el.text.substring(0, 60)}"`);
2896
+ parts.push(`(${el.tag})`);
2897
+ if (el.type) parts.push(`type=${el.type}`);
2898
+ lines.push(`- **Element**: ${parts.join(" ")}`);
2899
+ }
2900
+ if (a.value != null && a.type === "input") {
2901
+ lines.push(`- **Value**: "${a.value.substring(0, 100)}"`);
2902
+ }
2903
+ if (step.network.length > 0) {
2904
+ const netDescs = step.network.map((n) => {
2905
+ let desc = `${n.method} ${n.path}`;
2906
+ if (n.status) desc += ` \u2192 ${n.status}`;
2907
+ if (n.responseSize > 0) desc += ` (${formatBytes(n.responseSize)})`;
2908
+ return desc;
2909
+ });
2910
+ lines.push(`- **Network**: ${netDescs.join(", ")}`);
2911
+ for (const n of step.network) {
2912
+ if (n.requestBody && typeof n.requestBody === "object") {
2913
+ const bodyStr = JSON.stringify(n.requestBody);
2914
+ if (bodyStr.length <= 300) {
2915
+ lines.push(` - \`${n.method} ${n.path}\` body: \`${bodyStr}\``);
2916
+ } else {
2917
+ lines.push(` - \`${n.method} ${n.path}\` body: \`${bodyStr.substring(0, 300)}...\` (${bodyStr.length} bytes)`);
2918
+ }
2919
+ }
2920
+ }
2921
+ } else {
2922
+ lines.push("- **Network**: none");
2923
+ }
2924
+ if (step.matchedInputs.length > 0) {
2925
+ for (const m of step.matchedInputs) {
2926
+ lines.push(`- **Input matched**: "${m.inputValue}" \u2192 ${m.paramName} (network #${m.networkId})`);
2927
+ }
2928
+ }
2929
+ for (const ctx of step.contextChanges) {
2930
+ if (ctx.type === "navigate") {
2931
+ lines.push(`- **Navigate**: \u2192 ${ctx.url}`);
2932
+ } else if (ctx.type === "new_tab") {
2933
+ lines.push(`- **New tab**: ${ctx.url}`);
2934
+ }
2935
+ }
2936
+ if (a.clickContext) {
2937
+ if (a.clickContext.appeared?.length > 0) {
2938
+ for (const popup of a.clickContext.appeared) {
2939
+ const roleStr = popup.role ? ` [${popup.role}]` : "";
2940
+ lines.push(`- **Popup**: <${popup.tag}${roleStr}> "${(popup.text || "").substring(0, 60)}"`);
2941
+ if (popup.items?.length > 0) {
2942
+ const itemStrs = popup.items.slice(0, 8).map((i) => {
2943
+ const dis = i.disabled ? " [disabled]" : "";
2944
+ return `"${i.text}"${dis}`;
2945
+ });
2946
+ let itemLine = ` - Items: ${itemStrs.join(", ")}`;
2947
+ if (popup.items.length > 8) itemLine += ` ... +${popup.items.length - 8} more`;
2948
+ lines.push(itemLine);
2949
+ }
2950
+ }
2951
+ }
2952
+ if (a.clickContext.stateChanges?.length > 0) {
2953
+ for (const sc of a.clickContext.stateChanges) {
2954
+ const parts = [];
2955
+ if (sc.ariaExpanded !== void 0) parts.push(`expanded=${sc.ariaExpanded}`);
2956
+ if (sc.disabled) parts.push("disabled");
2957
+ if (sc.ariaSelected !== void 0) parts.push(`selected=${sc.ariaSelected}`);
2958
+ if (sc.dataState) parts.push(`state=${sc.dataState}`);
2959
+ if (parts.length > 0) {
2960
+ lines.push(`- **State**: <${sc.tag}> "${(sc.text || "").substring(0, 30)}" ${parts.join(", ")}`);
2961
+ }
2962
+ }
2963
+ }
2964
+ }
2965
+ lines.push("");
2966
+ }
2967
+ const allNetwork = summary.steps.flatMap((s) => s.network);
2968
+ if (allNetwork.length > 0) {
2969
+ lines.push("## Network Timeline");
2970
+ lines.push("");
2971
+ allNetwork.forEach((n, i) => {
2972
+ let line = `${i + 1}. ${n.method} ${n.path}`;
2973
+ if (n.status) line += ` \u2192 ${n.status}`;
2974
+ if (n.requestBody && typeof n.requestBody === "object") {
2975
+ const bodyStr = JSON.stringify(n.requestBody);
2976
+ if (bodyStr.length <= 150) {
2977
+ line += ` ${bodyStr}`;
2978
+ }
2979
+ }
2980
+ if (n.responseSize > 0) line += ` (${formatBytes(n.responseSize)})`;
2981
+ lines.push(line);
2982
+ });
2983
+ lines.push("");
2984
+ }
2985
+ const orphanCheckpoints = summary.checkpoints.filter(
2986
+ (cp) => cp.relatedActionId == null || !checkpointSteps.has(
2987
+ summary.steps.find((s) => s.action.id === cp.relatedActionId)?.step ?? -1
2988
+ )
2989
+ );
2990
+ if (orphanCheckpoints.length > 0) {
2991
+ lines.push("## Unresolved Checkpoints");
2992
+ lines.push("");
2993
+ for (const cp of orphanCheckpoints) {
2994
+ const src = cp.source === "auto" ? "[auto]" : "[manual]";
2995
+ lines.push(`- ${src} **${cp.type}**: ${cp.hint}`);
2996
+ if (cp.selector) lines.push(` - Selector: \`${cp.selector}\``);
2997
+ }
2998
+ lines.push("");
2999
+ }
3000
+ return lines.join("\n");
3001
+ }
3002
+ function describeActionTitle(a) {
3003
+ const el = a.element;
3004
+ const elText = el?.text ? `"${el.text.substring(0, 40)}"` : "";
3005
+ const elTag = el?.tag ? `<${el.tag}>` : "";
3006
+ switch (a.type) {
3007
+ case "click":
3008
+ return `Click ${elText || elTag} button`.replace(/ +/g, " ").trim();
3009
+ case "input":
3010
+ return `Input "${(a.value || "").substring(0, 50)}" in ${elText || elTag || "field"}`.replace(/ +/g, " ").trim();
3011
+ case "change":
3012
+ return `Change ${elText || elTag} to "${(a.value || "").substring(0, 30)}"`;
3013
+ case "keydown":
3014
+ return `Press ${a.key || "key"} on ${elText || elTag || "element"}`;
3015
+ case "submit":
3016
+ return `Submit ${elText || elTag || "form"}`;
3017
+ default:
3018
+ return `${a.type} ${elText || elTag}`.trim() || a.type;
3019
+ }
3020
+ }
3021
+ function formatBytes(bytes) {
3022
+ if (bytes < 1024) return `${bytes}B`;
3023
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
3024
+ return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
3025
+ }
3026
+
3027
+ // src/recorder/observation-insights.ts
3028
+ async function detectCheckpoints(page, allocateCheckpointId) {
3029
+ const CHECKPOINT_RULES = [
3030
+ { type: "captcha", selectors: ['img[src*="captcha"]', 'img[src*="verify"]', '[class*="captcha"]', '[id*="captcha"]', "#captcha", ".captcha"] },
3031
+ { type: "slider", selectors: ['[class*="slider"]', '[class*="drag-verify"]', '[class*="slide-verify"]'] },
3032
+ { type: "login", selectors: ['input[type="password"]'] },
3033
+ { type: "iframe", selectors: ['iframe[src*="captcha"]', 'iframe[src*="verify"]', 'iframe[src*="recaptcha"]', 'iframe[title*="captcha"]'] }
3034
+ ];
3035
+ try {
3036
+ const found = await page.evaluate((rules) => {
3037
+ const results = [];
3038
+ for (const rule of rules) {
3039
+ for (const sel of rule.selectors) {
3040
+ try {
3041
+ const el = document.querySelector(sel);
3042
+ if (el) {
3043
+ const rect = el.getBoundingClientRect();
3044
+ if (rect.width > 0 && rect.height > 0) {
3045
+ results.push({
3046
+ type: rule.type,
3047
+ selector: sel,
3048
+ text: (el.textContent || "").substring(0, 60)
3049
+ });
3050
+ }
3051
+ }
3052
+ } catch {
3053
+ }
3054
+ }
3055
+ }
3056
+ return results;
3057
+ }, CHECKPOINT_RULES);
3058
+ const entries = [];
3059
+ for (const item of found) {
3060
+ const id = allocateCheckpointId();
3061
+ ;
3062
+ const hints = {
3063
+ captcha: "Captcha verification detected",
3064
+ slider: "Slider verification detected",
3065
+ login: "Login form detected (password field)",
3066
+ iframe: "Verification iframe detected"
3067
+ };
3068
+ entries.push({
3069
+ id,
3070
+ type: item.type,
3071
+ timestamp: Date.now(),
3072
+ url: page.url(),
3073
+ pageTitle: await page.title().catch(() => ""),
3074
+ hint: hints[item.type] || item.type,
3075
+ selector: item.selector,
3076
+ source: "auto",
3077
+ context: { matchedSelector: item.selector, elementText: item.text }
3078
+ });
3079
+ }
3080
+ return entries;
3081
+ } catch {
3082
+ return [];
3083
+ }
3084
+ }
3085
+ async function verifyAction(page, action, network, checkpoints) {
3086
+ const signals = [];
3087
+ try {
3088
+ const currentUrl = page.url();
3089
+ if (currentUrl && currentUrl !== "about:blank" && currentUrl !== action.url) {
3090
+ signals.push({ type: "url_change", value: currentUrl, label: `URL changed to ${currentUrl}` });
3091
+ }
3092
+ } catch {
3093
+ }
3094
+ try {
3095
+ const recentNetwork = network.filter(
3096
+ (n) => n.timestamp > action.timestamp - 100 && n.timestamp < action.timestamp + 5e3 && n.status >= 200 && n.status < 400
3097
+ );
3098
+ for (const net of recentNetwork.slice(0, 3)) {
3099
+ signals.push({
3100
+ type: "network_success",
3101
+ value: `${net.status}`,
3102
+ label: `${net.method} ${net.path} \u2192 ${net.status}`
3103
+ });
3104
+ }
3105
+ } catch {
3106
+ }
3107
+ try {
3108
+ const recentDialog = [...checkpoints].reverse().find(
3109
+ (cp) => cp.type === "dialog" && Math.abs(cp.timestamp - action.timestamp) < 3e3
3110
+ );
3111
+ if (recentDialog) {
3112
+ signals.push({ type: "dialog", value: recentDialog.type, label: recentDialog.hint });
3113
+ }
3114
+ } catch {
3115
+ }
3116
+ return signals;
3117
+ }
3118
+
3119
+ // src/recorder/page-context.ts
3120
+ import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
3121
+ import { join as join3 } from "path";
3122
+ var SNAPSHOT_TYPES = /* @__PURE__ */ new Set([
3123
+ "click",
3124
+ "dblclick",
3125
+ "navigation",
3126
+ "goto",
3127
+ "submit",
3128
+ "cdp-click",
3129
+ "cdp-fill",
3130
+ "input",
3131
+ "change",
3132
+ "filechooser",
3133
+ "popup_appear"
3134
+ ]);
3135
+ async function captureElementScreenshot(page, action) {
3136
+ const keyTypes = ["click", "input", "change", "dblclick", "cdp-click", "cdp-fill", "filechooser"];
3137
+ if (!keyTypes.includes(action.type)) return;
3138
+ if (!action.element?.selector) return;
3139
+ const selector = action.element.selector;
3140
+ try {
3141
+ const buffer = await page.locator(selector).first().screenshot({
3142
+ type: "png",
3143
+ timeout: 3e3
3144
+ });
3145
+ return buffer.toString("base64");
3146
+ } catch {
3147
+ }
3148
+ try {
3149
+ await page.waitForSelector(selector, { state: "visible", timeout: 2e3 });
3150
+ const buffer = await page.locator(selector).first().screenshot({
3151
+ type: "png",
3152
+ timeout: 3e3
3153
+ });
3154
+ return buffer.toString("base64");
3155
+ } catch {
3156
+ }
3157
+ try {
3158
+ const buffer = await page.screenshot({ type: "png", timeout: 3e3 });
3159
+ return buffer.toString("base64");
3160
+ } catch {
3161
+ return;
3162
+ }
3163
+ }
3164
+ function isSnapshotThrottled(type, selector, snapshotThrottle) {
3165
+ if (type === "input" || type === "change" || type === "cdp-fill") {
3166
+ const key = `${type}|${selector || ""}`;
3167
+ const last = snapshotThrottle.get(key);
3168
+ const now = Date.now();
3169
+ if (last && now - last < 2e3) return true;
3170
+ snapshotThrottle.set(key, now);
3171
+ }
3172
+ return false;
3173
+ }
3174
+ async function captureAutoSnapshot(page, action, suffix = "after", snapshotsDir, snapshotThrottle) {
3175
+ if (!SNAPSHOT_TYPES.has(action.type)) return;
3176
+ if (isSnapshotThrottled(action.type, action.element?.selector, snapshotThrottle)) return;
3177
+ const snapDir = snapshotsDir;
3178
+ mkdirSync2(snapDir, { recursive: true });
3179
+ const stepId = String(action.id).padStart(3, "0");
3180
+ const snapshot = {};
3181
+ try {
3182
+ const pngPath = join3(snapDir, `step-${stepId}-${suffix}.png`);
3183
+ const buffer = await page.screenshot({ type: "png", timeout: 5e3 });
3184
+ writeFileSync2(pngPath, buffer);
3185
+ snapshot.png = `.tmp/snapshots/step-${stepId}-${suffix}.png`;
3186
+ } catch {
3187
+ }
3188
+ try {
3189
+ snapshot.aria = await page.evaluate(`
3190
+ (function() {
3191
+ try {
3192
+ var parts = [];
3193
+ var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT, null, false);
3194
+ var node;
3195
+ while (node = walker.nextNode()) {
3196
+ var tag = node.tagName.toLowerCase();
3197
+ var role = node.getAttribute('role') || '';
3198
+ var text = (node.textContent || '').trim().substring(0, 60);
3199
+ var ariaLabel = node.getAttribute('aria-label') || '';
3200
+ if (role || tag === 'button' || tag === 'a' || tag === 'input' || tag === 'select' || tag === 'textarea') {
3201
+ parts.push((role || tag) + ': ' + (ariaLabel || text).substring(0, 40));
3202
+ }
3203
+ }
3204
+ return parts.slice(0, 100).join(' | ');
3205
+ } catch(e) { return ''; }
3206
+ })()
3207
+ `);
3208
+ } catch {
3209
+ }
3210
+ if (snapshot.png || snapshot.aria) {
3211
+ action.snapshots = snapshot;
3212
+ }
3213
+ }
3214
+ async function captureClickContext(page, cx, cy) {
3215
+ await new Promise((r) => setTimeout(r, 300));
3216
+ try {
3217
+ const ctx = await page.evaluate(`
3218
+ (function() {
3219
+ var cx = ${cx}, cy = ${cy};
3220
+ var POPOVER_SELECTORS = [
3221
+ '[role="menu"]','[role="listbox"]','[role="dialog"]','[role="tooltip"]','[role="popover"]',
3222
+ '[role="combobox"]','[role="tree"]','[role="grid"]',
3223
+ '.popover','.popup','.dropdown','.menu','.modal','.tooltip','.panel',
3224
+ '[class*="popover"]','[class*="popup"]','[class*="dropdown"]','[class*="menu"]',
3225
+ '[class*="tooltip"]','[class*="modal"]','[class*="panel"]','[class*="overlay"]','[class*="sheet"]',
3226
+ '[data-popup]','[data-dropdown]','[data-menu]','[data-popover"]',
3227
+ '.semi-dropdown','.semi-popover','.semi-modal',
3228
+ '.ant-dropdown','.ant-popover','.ant-modal',
3229
+ '.el-dropdown','.el-popover','.el-dialog',
3230
+ '.t-dropdown','.t-popup','.t-dialog'
3231
+ ];
3232
+
3233
+ function isNear(el, x, y, range) {
3234
+ try {
3235
+ var r = el.getBoundingClientRect();
3236
+ if (!r || r.width === 0 || r.height === 0) return false;
3237
+ return !(r.left > x + range || r.right < x - range || r.top > y + range || r.bottom < y - range);
3238
+ } catch(e) { return false; }
3239
+ }
3240
+
3241
+ var result = { appeared: [], disappeared: [], stateChanges: [] };
3242
+ var seenElements = new Set();
3243
+
3244
+ for (var si = 0; si < POPOVER_SELECTORS.length; si++) {
3245
+ try {
3246
+ var els = document.querySelectorAll(POPOVER_SELECTORS[si]);
3247
+ for (var j = 0; j < els.length; j++) {
3248
+ var el = els[j];
3249
+ if (seenElements.has(el)) continue;
3250
+ if (!isNear(el, cx, cy, 300)) continue;
3251
+ var rect = el.getBoundingClientRect();
3252
+ if (rect.width === 0 || rect.height === 0) continue;
3253
+ seenElements.add(el);
3254
+
3255
+ var items = [];
3256
+ var children = el.querySelectorAll('a,button,[role="menuitem"],[role="option"],[role="treeitem"],li,div[class*="item"]');
3257
+ var seenItemTexts = new Set();
3258
+ for (var k = 0; k < Math.min(children.length, 30); k++) {
3259
+ var child = children[k];
3260
+ var childText = (child.textContent || '').trim().substring(0, 60);
3261
+ if (!childText || seenItemTexts.has(childText)) continue;
3262
+ seenItemTexts.add(childText);
3263
+ var ci = { text: childText };
3264
+ try { if (child.disabled || child.getAttribute('aria-disabled') === 'true') ci.disabled = true; } catch(e) {}
3265
+ try { if (child.tagName) ci.tag = child.tagName.toLowerCase(); } catch(e) {}
3266
+ try { if (child.href) ci.href = child.href.substring(0, 80); } catch(e) {}
3267
+ items.push(ci);
3268
+ }
3269
+
3270
+ result.appeared.push({
3271
+ tag: el.tagName.toLowerCase(),
3272
+ selector: el.id ? '#' + el.id : undefined,
3273
+ role: el.getAttribute('role'),
3274
+ text: (el.textContent || '').trim().substring(0, 100),
3275
+ rect: { x: Math.round(rect.x), y: Math.round(rect.y), w: Math.round(rect.width), h: Math.round(rect.height) },
3276
+ items: items
3277
+ });
3278
+ }
3279
+ } catch(e) { /* skip invalid selectors */ }
3280
+ }
3281
+
3282
+ var allInteractive = document.querySelectorAll('[aria-expanded],[disabled],[aria-disabled],[aria-selected],[data-state]');
3283
+ for (var i = 0; i < allInteractive.length; i++) {
3284
+ var el2 = allInteractive[i];
3285
+ if (!isNear(el2, cx, cy, 200)) continue;
3286
+ var info = { tag: el2.tagName.toLowerCase(), text: (el2.textContent || '').trim().substring(0, 60) };
3287
+ try { if (el2.id) info.id = el2.id; } catch(e) {}
3288
+ try { if (el2.getAttribute('aria-expanded')) info.ariaExpanded = el2.getAttribute('aria-expanded'); } catch(e) {}
3289
+ try { if (el2.disabled || el2.getAttribute('aria-disabled') === 'true') info.disabled = true; } catch(e) {}
3290
+ try { if (el2.getAttribute('aria-selected')) info.ariaSelected = el2.getAttribute('aria-selected'); } catch(e) {}
3291
+ try { if (el2.getAttribute('data-state')) info.dataState = el2.getAttribute('data-state'); } catch(e) {}
3292
+ result.stateChanges.push(info);
3293
+ }
3294
+
3295
+ return result;
3296
+ })()
3297
+ `);
3298
+ if (ctx.appeared.length > 0 || ctx.stateChanges.length > 0) {
3299
+ return ctx;
3300
+ }
3301
+ } catch {
3302
+ }
3303
+ return void 0;
3304
+ }
3305
+
3306
+ // src/recorder/session-recorder.ts
3307
+ var SessionRecorder = class _SessionRecorder {
3308
+ context;
3309
+ page;
3310
+ sessionName;
3311
+ startUrl = "";
3312
+ startedAt = 0;
3313
+ actions = [];
3314
+ networkCapture = createNetworkCaptureState();
3315
+ contextChanges = [];
3316
+ checkpoints = [];
3317
+ /** Proactive baseline scan of filter/sort/tab/menu regions. Keyed by
3318
+ * containerSelector so re-scans after navigation replace rather than dup. */
3319
+ discoveredFilters = /* @__PURE__ */ new Map();
3320
+ actionCounter = 0;
3321
+ contextCounter = 0;
3322
+ checkpointCounter = 0;
3323
+ pollTimer = null;
3324
+ flushTimer = null;
3325
+ lastActionTs = 0;
3326
+ activePages = /* @__PURE__ */ new Set();
3327
+ lastKnownUrl = "";
3328
+ dedupMap = /* @__PURE__ */ new Map();
3329
+ dedupActionCount = 0;
3330
+ _isRecording = false;
3331
+ streamMode = "clean";
3332
+ snapshotThrottle = /* @__PURE__ */ new Map();
3333
+ static AMBIENT_TYPES = /* @__PURE__ */ new Set([
3334
+ "hover",
3335
+ "focus",
3336
+ "scroll",
3337
+ "visibility",
3338
+ "resize",
3339
+ "clipboard",
3340
+ "touch",
3341
+ "contextmenu"
3342
+ ]);
3343
+ constructor(context, page, sessionName) {
3344
+ this.context = context;
3345
+ this.page = page;
3346
+ this.sessionName = sessionName;
3347
+ }
3348
+ get isRecording() {
3349
+ return this._isRecording;
3350
+ }
3351
+ get actionCount() {
3352
+ return this.actions.length;
3353
+ }
3354
+ /** Record an action triggered by a CDP command (e.g. xbrowser fill/click/goto) */
3355
+ async recordCommandAction(action) {
3356
+ const dedupFromAction = this.dedupKey(action.type, action.selector, action.element?.tag, action.value);
3357
+ if (dedupFromAction) {
3358
+ const entry = this.dedupMap.get(dedupFromAction);
3359
+ if (entry && entry.origin === "signal" && Date.now() < entry.expires) {
3360
+ return;
3361
+ }
3362
+ }
3363
+ this.actionCounter++;
3364
+ const ts = Date.now();
3365
+ const actionUrl = action.url && action.url !== "about:blank" ? action.url : this.lastKnownUrl || this.page.url();
3366
+ const actionToPush = {
3367
+ id: this.actionCounter,
3368
+ type: action.type,
3369
+ timestamp: ts,
3370
+ url: actionUrl,
3371
+ pageTitle: "",
3372
+ element: action.element || (action.selector ? { tag: "", selector: action.selector, text: "" } : void 0),
3373
+ value: action.value
3374
+ };
3375
+ this.actions.push(actionToPush);
3376
+ actionToPush.elementScreenshot = await Promise.race([
3377
+ captureElementScreenshot(this.page, {
3378
+ type: action.type,
3379
+ element: actionToPush.element
3380
+ }).catch(() => void 0),
3381
+ new Promise((r) => setTimeout(r, 3e3))
3382
+ ]);
3383
+ await Promise.race([
3384
+ captureAutoSnapshot(this.page, actionToPush, "after", this.snapshotsDir, this.snapshotThrottle).catch(() => {
3385
+ }),
3386
+ new Promise((r) => setTimeout(r, 6e3))
3387
+ ]);
3388
+ this.lastActionTs = ts;
3389
+ this.dedupMap.set(dedupFromAction, { expires: Date.now() + 4e3, origin: "command" });
3390
+ this.dedupActionCount++;
3391
+ if (this.dedupActionCount % 200 === 0) {
3392
+ const now = Date.now();
3393
+ for (const [k, v] of this.dedupMap) {
3394
+ if (now >= v.expires) this.dedupMap.delete(k);
3395
+ }
3396
+ }
3397
+ if (action.url && action.url !== "about:blank") {
3398
+ this.lastKnownUrl = action.url;
3399
+ } else if (action.type === "goto" && action.value && action.value !== "about:blank") {
3400
+ this.lastKnownUrl = action.value;
3401
+ }
3402
+ }
3403
+ /** Generate dedup key for an action (normalized type + selector/tag + value). */
3404
+ dedupKey(type, selector, tag, value) {
3405
+ const normType = type === "cdp-click" ? "click" : type === "cdp-fill" ? "input" : type === "cdp-eval" ? "eval" : type;
3406
+ const selOrTag = selector || tag || "";
3407
+ return `${normType}|${selOrTag}|${value || ""}`;
3408
+ }
3409
+ get networkCount() {
3410
+ return this.networkCapture.entries.length;
3411
+ }
3412
+ getLiveData() {
3413
+ return this.buildData();
3414
+ }
3415
+ addManualCheckpoint(type, hint, selector) {
3416
+ this.checkpointCounter++;
3417
+ const cp = {
3418
+ id: this.checkpointCounter,
3419
+ type,
3420
+ timestamp: Date.now(),
3421
+ url: this.page.url(),
3422
+ pageTitle: "",
3423
+ hint,
3424
+ selector,
3425
+ source: "manual"
3426
+ };
3427
+ this.checkpoints.push(cp);
3428
+ return cp;
3429
+ }
3430
+ /** Directory for this session's recordings. */
3431
+ get recordingsDir() {
3432
+ return _SessionRecorder.getRecordingsDir(this.sessionName);
3433
+ }
3434
+ /** Directory for auto-captured snapshots (PNG screenshots, stored in .tmp for easy cleanup). */
3435
+ get snapshotsDir() {
3436
+ return join4(this.recordingsDir, ".tmp", "snapshots");
3437
+ }
3438
+ static getRecordingsDir(sessionName) {
3439
+ return join4(homedir3(), ".xbrowser", "sessions", sessionName, "recordings");
3440
+ }
3441
+ /** Path to the control file (used by record stop to signal this process). */
3442
+ get controlFilePath() {
3443
+ return join4(this.recordingsDir, ".control.json");
3444
+ }
3445
+ /** Path to the stop signal file (written by `record stop`). */
3446
+ get stopSignalPath() {
3447
+ return join4(this.recordingsDir, ".stop");
3448
+ }
3449
+ // ─── Start ──────────────────────────────────────────────────────
3450
+ async start(url, options) {
3451
+ if (this._isRecording) throw new Error("Already recording");
3452
+ this._isRecording = true;
3453
+ this.startedAt = Date.now();
3454
+ this.actions = [];
2624
3455
  this.contextChanges = [];
2625
3456
  this.checkpoints = [];
2626
3457
  this.checkpointCounter = 0;
@@ -2645,14 +3476,14 @@ var SessionRecorder = class _SessionRecorder {
2645
3476
  } else {
2646
3477
  this.startUrl = this.page.url();
2647
3478
  }
2648
- mkdirSync2(this.recordingsDir, { recursive: true });
3479
+ mkdirSync3(this.recordingsDir, { recursive: true });
2649
3480
  const control = {
2650
3481
  pid: process.pid,
2651
3482
  startedAt: new Date(this.startedAt).toISOString(),
2652
3483
  startUrl: this.startUrl,
2653
3484
  sessionName: this.sessionName
2654
3485
  };
2655
- writeFileSync2(this.controlFilePath, JSON.stringify(control, null, 2), "utf-8");
3486
+ writeFileSync3(this.controlFilePath, JSON.stringify(control, null, 2), "utf-8");
2656
3487
  await this.injectActionScript(this.page);
2657
3488
  this.context.on("page", this.handleNewPage);
2658
3489
  this.pollTimer = setInterval(() => void this.pollActions(), 200);
@@ -2687,21 +3518,21 @@ var SessionRecorder = class _SessionRecorder {
2687
3518
  });
2688
3519
  }
2689
3520
  const data = this.buildData();
2690
- const summary = this.buildSummary(data);
3521
+ const summary = buildSummary(data, this.startedAt);
2691
3522
  this.writeFinalOutput(data, summary);
2692
3523
  try {
2693
3524
  const knowledge = updateSiteKnowledge(data);
2694
- const knowledgeDir = join2(this.recordingsDir, "site-knowledge.md");
2695
- const knowledgeJson = join2(this.recordingsDir, "site-knowledge.json");
3525
+ const knowledgeDir = join4(this.recordingsDir, "site-knowledge.md");
3526
+ const knowledgeJson = join4(this.recordingsDir, "site-knowledge.json");
2696
3527
  const { readFileSync: rf } = __require("fs");
2697
3528
  const { getKnowledgePath: getKnowledgePath2 } = (init_site_knowledge(), __toCommonJS(site_knowledge_exports));
2698
3529
  const mdPath = getKnowledgePath2(knowledge.domain, "md");
2699
3530
  try {
2700
3531
  const md = rf(mdPath, "utf-8");
2701
- writeFileSync2(knowledgeDir, md, "utf-8");
3532
+ writeFileSync3(knowledgeDir, md, "utf-8");
2702
3533
  } catch {
2703
3534
  }
2704
- writeFileSync2(knowledgeJson, JSON.stringify(knowledge, null, 2), "utf-8");
3535
+ writeFileSync3(knowledgeJson, JSON.stringify(knowledge, null, 2), "utf-8");
2705
3536
  } catch {
2706
3537
  }
2707
3538
  try {
@@ -2721,261 +3552,96 @@ var SessionRecorder = class _SessionRecorder {
2721
3552
  rmSync(dir, { recursive: true, force: true });
2722
3553
  }
2723
3554
  }
2724
- // ─── Wait for stop signal (blocks the process) ──────────────────
2725
- waitForStopSignal() {
2726
- return new Promise((resolve) => {
2727
- const check = () => {
2728
- if (existsSync2(this.stopSignalPath)) {
2729
- resolve();
2730
- } else {
2731
- setTimeout(check, 300);
2732
- }
2733
- };
2734
- check();
2735
- });
2736
- }
2737
- // ─── Static: send stop signal to a running recorder ─────────────
2738
- static async sendStopSignal(sessionName) {
2739
- const dir = _SessionRecorder.getRecordingsDir(sessionName);
2740
- const controlPath = join2(dir, ".control.json");
2741
- const stopPath = join2(dir, ".stop");
2742
- if (!existsSync2(controlPath)) return null;
2743
- const control = JSON.parse(readFileSync2(controlPath, "utf-8"));
2744
- let alive = false;
2745
- try {
2746
- process.kill(control.pid, 0);
2747
- alive = true;
2748
- } catch {
2749
- alive = false;
2750
- }
2751
- if (!alive) {
2752
- try {
2753
- rmSync(controlPath);
2754
- } catch {
2755
- }
2756
- return control;
2757
- }
2758
- mkdirSync2(dir, { recursive: true });
2759
- writeFileSync2(stopPath, JSON.stringify({ stoppedAt: (/* @__PURE__ */ new Date()).toISOString() }), "utf-8");
2760
- for (let i = 0; i < 50; i++) {
2761
- await new Promise((r) => setTimeout(r, 200));
2762
- if (!existsSync2(controlPath)) return control;
2763
- try {
2764
- process.kill(control.pid, 0);
2765
- } catch {
2766
- try {
2767
- rmSync(controlPath);
2768
- } catch {
2769
- }
2770
- return control;
2771
- }
2772
- }
2773
- try {
2774
- rmSync(controlPath);
2775
- } catch {
2776
- }
2777
- return control;
2778
- }
2779
- // ─── Static: read recording from disk ───────────────────────────
2780
- static readSummary(sessionName) {
2781
- const path = join2(_SessionRecorder.getRecordingsDir(sessionName), "summary.json");
2782
- try {
2783
- return JSON.parse(readFileSync2(path, "utf-8"));
2784
- } catch {
2785
- return null;
2786
- }
2787
- }
2788
- static readData(sessionName) {
2789
- const path = join2(_SessionRecorder.getRecordingsDir(sessionName), "recording.json");
2790
- try {
2791
- return JSON.parse(readFileSync2(path, "utf-8"));
2792
- } catch {
2793
- return null;
2794
- }
2795
- }
2796
- // ==================== Private ====================
2797
- /** Whether the initial action-signal script injection succeeded. Check this
2798
- * after start() returns — if false, user actions will NOT be recorded and
2799
- * the caller should surface a clear error to the user instead of silently
2800
- * pretending recording is working. */
2801
- _injectionFailed = false;
2802
- get injectionFailed() {
2803
- return this._injectionFailed;
2804
- }
2805
- async injectActionScript(page) {
2806
- let success = false;
2807
- const maxAttempts = 3;
2808
- let lastError = "";
2809
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
2810
- try {
2811
- await page.evaluate(getSelectorGeneratorScript());
2812
- await page.evaluate(ACTION_SIGNAL_SCRIPT);
2813
- await page.evaluate(`window.__xb_action_script_src = ${JSON.stringify(ACTION_SIGNAL_SCRIPT)};`);
2814
- const injected = await page.evaluate(`(function() {
2815
- try { return !!window.__xb_action_signal; } catch(e) { return false; }
2816
- })()`).catch(() => false);
2817
- if (injected) {
2818
- success = true;
2819
- break;
2820
- }
2821
- lastError = "verification failed (script did not set __xb_action_signal flag)";
2822
- console.error(`[recorder] Action signal injection verification failed (attempt ${attempt}/${maxAttempts})`);
2823
- } catch (e) {
2824
- const err = e instanceof Error ? e : new Error(typeof e === "string" ? e : "unknown error");
2825
- lastError = err.message;
2826
- console.error(`[recorder] Action signal injection error (attempt ${attempt}/${maxAttempts}): ${err.message}`);
2827
- }
2828
- if (attempt < maxAttempts) {
2829
- await new Promise((r) => setTimeout(r, 1e3));
2830
- }
2831
- }
2832
- if (!success) {
2833
- this._injectionFailed = true;
2834
- console.error(`[recorder] WARNING: Action signal injection FAILED after ${maxAttempts} attempts. User actions will NOT be recorded. Last error: ${lastError}`);
2835
- }
2836
- try {
2837
- await page.evaluate(CHECKPOINT_OVERLAY_SCRIPT);
2838
- } catch (e) {
2839
- const msg = e instanceof Error ? e.message : String(e);
2840
- console.error(`[recorder] Checkpoint overlay injection failed (non-fatal): ${msg}`);
2841
- }
2842
- if (success) {
2843
- try {
2844
- await page.evaluate(`(function() {
2845
- if (typeof window.__xb_scanFilters === 'function') {
2846
- setTimeout(window.__xb_scanFilters, 100);
2847
- }
2848
- })()`);
2849
- } catch {
2850
- }
2851
- }
2852
- try {
2853
- await page.evaluate(`
2854
- (function() {
2855
- var _scriptSrc = ${JSON.stringify(ACTION_SIGNAL_SCRIPT)};
2856
- function injectIframe(iframe) {
2857
- try {
2858
- var w = iframe.contentWindow;
2859
- if (!w) return;
2860
- // Force re-injection: clear old flag
2861
- try { delete w.__xb_action_signal; } catch(e) {}
2862
- w.eval(_scriptSrc);
2863
- // Tag iframe so flushIframes knows it's injected
2864
- iframe.__xb_injected = true;
2865
- } catch(e) {}
2866
- }
2867
- function watchIframe(iframe) {
2868
- if (iframe.__xb_watched) return;
2869
- iframe.__xb_watched = true;
2870
- injectIframe(iframe);
2871
- iframe.addEventListener('load', function() { injectIframe(iframe); });
2872
- }
2873
- // Inject into existing iframes
2874
- try {
2875
- var iframes = document.querySelectorAll('iframe');
2876
- for (var i = 0; i < iframes.length; i++) watchIframe(iframes[i]);
2877
- } catch(e) {}
2878
- // Watch for dynamically inserted iframes
2879
- if (!window.__xb_iframe_observer) {
2880
- window.__xb_iframe_observer = new MutationObserver(function(mutations) {
2881
- for (var m = 0; m < mutations.length; m++) {
2882
- for (var n = 0; n < mutations[m].addedNodes.length; n++) {
2883
- var node = mutations[m].addedNodes[n];
2884
- if (node.tagName === 'IFRAME') {
2885
- watchIframe(node);
2886
- } else if (node.querySelectorAll) {
2887
- var sub = node.querySelectorAll('iframe');
2888
- for (var k = 0; k < sub.length; k++) watchIframe(sub[k]);
2889
- }
2890
- }
2891
- }
2892
- });
2893
- window.__xb_iframe_observer.observe(document.documentElement, { childList: true, subtree: true });
2894
- }
2895
- // Periodic re-injection for iframes that load late or navigate internally
2896
- if (!window.__xb_iframe_timer) {
2897
- window.__xb_iframe_timer = setInterval(function() {
2898
- try {
2899
- var iframes = document.querySelectorAll('iframe');
2900
- for (var i = 0; i < iframes.length; i++) {
2901
- if (!iframes[i].__xb_injected) {
2902
- watchIframe(iframes[i]);
2903
- }
2904
- }
2905
- } catch(e) {}
2906
- }, 3000);
2907
- }
2908
- })();
2909
- `);
2910
- } catch {
2911
- }
2912
- }
2913
- // ─── Network capture ────────────────────────────────────────────
2914
- handleRequest = (request) => {
2915
- const resourceType = request.resourceType();
2916
- if (["image", "stylesheet", "font", "manifest", "other"].includes(resourceType)) return;
2917
- const url = request.url();
2918
- if (url.startsWith("data:") || url.startsWith("chrome-extension://") || url.startsWith("blob:")) return;
2919
- const dedupKey = request.method() + " " + url;
2920
- const now = Date.now();
2921
- if (this._lastRequestKey === dedupKey && now - this._lastRequestTs < 100) return;
2922
- this._lastRequestKey = dedupKey;
2923
- this._lastRequestTs = now;
2924
- this.networkCounter++;
2925
- const entry = {
2926
- id: this.networkCounter,
2927
- timestamp: Date.now(),
2928
- method: request.method(),
2929
- url,
2930
- path: new URL(url).pathname,
2931
- status: 0,
2932
- resourceType,
2933
- contentType: "",
2934
- responseSize: 0
2935
- };
2936
- if (["POST", "PATCH", "PUT"].includes(request.method())) {
2937
- try {
2938
- const postData = request.postData();
2939
- if (postData) {
2940
- try {
2941
- entry.requestBody = JSON.parse(postData);
2942
- } catch {
2943
- entry.requestBody = postData.substring(0, 500);
2944
- }
3555
+ // ─── Wait for stop signal (blocks the process) ──────────────────
3556
+ waitForStopSignal() {
3557
+ return new Promise((resolve) => {
3558
+ const check = () => {
3559
+ if (existsSync2(this.stopSignalPath)) {
3560
+ resolve();
3561
+ } else {
3562
+ setTimeout(check, 300);
2945
3563
  }
2946
- } catch {
2947
- }
3564
+ };
3565
+ check();
3566
+ });
3567
+ }
3568
+ // ─── Static: send stop signal to a running recorder ─────────────
3569
+ static async sendStopSignal(sessionName) {
3570
+ const dir = _SessionRecorder.getRecordingsDir(sessionName);
3571
+ const controlPath = join4(dir, ".control.json");
3572
+ const stopPath = join4(dir, ".stop");
3573
+ if (!existsSync2(controlPath)) return null;
3574
+ const control = JSON.parse(readFileSync3(controlPath, "utf-8"));
3575
+ let alive = false;
3576
+ try {
3577
+ process.kill(control.pid, 0);
3578
+ alive = true;
3579
+ } catch {
3580
+ alive = false;
2948
3581
  }
2949
- this.network.push(entry);
2950
- };
2951
- handleResponse = async (response) => {
2952
- const url = response.url();
2953
- if (url.startsWith("data:") || url.startsWith("chrome-extension://") || url.startsWith("blob:")) return;
2954
- const entry = [...this.network].reverse().find((e) => e.url === url && e.status === 0);
2955
- if (!entry) return;
2956
- entry.status = response.status();
2957
- entry.contentType = response.headers()["content-type"] || "";
2958
- const resourceType = response.request().resourceType();
2959
- const isApi = ["fetch", "xhr"].includes(resourceType) || entry.contentType.includes("json") || entry.contentType.includes("text/");
2960
- if (isApi) {
3582
+ if (!alive) {
2961
3583
  try {
2962
- const text = await response.text();
2963
- entry.responseSize = text.length;
2964
- if (text.length <= 20480) {
2965
- try {
2966
- entry.responseBody = JSON.parse(text);
2967
- } catch {
2968
- entry.responseBody = text.substring(0, 500);
2969
- }
2970
- }
3584
+ rmSync(controlPath);
2971
3585
  } catch {
2972
3586
  }
2973
- } else {
3587
+ return control;
3588
+ }
3589
+ mkdirSync3(dir, { recursive: true });
3590
+ writeFileSync3(stopPath, JSON.stringify({ stoppedAt: (/* @__PURE__ */ new Date()).toISOString() }), "utf-8");
3591
+ for (let i = 0; i < 50; i++) {
3592
+ await new Promise((r) => setTimeout(r, 200));
3593
+ if (!existsSync2(controlPath)) return control;
2974
3594
  try {
2975
- entry.responseSize = parseInt(response.headers()["content-length"] || "0", 10);
3595
+ process.kill(control.pid, 0);
2976
3596
  } catch {
3597
+ try {
3598
+ rmSync(controlPath);
3599
+ } catch {
3600
+ }
3601
+ return control;
2977
3602
  }
2978
3603
  }
3604
+ try {
3605
+ rmSync(controlPath);
3606
+ } catch {
3607
+ }
3608
+ return control;
3609
+ }
3610
+ // ─── Static: read recording from disk ───────────────────────────
3611
+ static readSummary(sessionName) {
3612
+ const path = join4(_SessionRecorder.getRecordingsDir(sessionName), "summary.json");
3613
+ try {
3614
+ return JSON.parse(readFileSync3(path, "utf-8"));
3615
+ } catch {
3616
+ return null;
3617
+ }
3618
+ }
3619
+ static readData(sessionName) {
3620
+ const path = join4(_SessionRecorder.getRecordingsDir(sessionName), "recording.json");
3621
+ try {
3622
+ return JSON.parse(readFileSync3(path, "utf-8"));
3623
+ } catch {
3624
+ return null;
3625
+ }
3626
+ }
3627
+ // ==================== Private ====================
3628
+ /** Whether the initial action-signal script injection succeeded. Check this
3629
+ * after start() returns — if false, user actions will NOT be recorded and
3630
+ * the caller should surface a clear error to the user instead of silently
3631
+ * pretending recording is working. */
3632
+ _injectionFailed = false;
3633
+ get injectionFailed() {
3634
+ return this._injectionFailed;
3635
+ }
3636
+ async injectActionScript(page) {
3637
+ this._injectionFailed = !await injectActionScript(page);
3638
+ }
3639
+ // ─── Network capture ────────────────────────────────────────────
3640
+ handleRequest = (request) => {
3641
+ handleNetworkRequest(request, this.networkCapture);
3642
+ };
3643
+ handleResponse = async (response) => {
3644
+ await handleNetworkResponse(response, this.networkCapture);
2979
3645
  };
2980
3646
  // ─── Page tracking ──────────────────────────────────────────────
2981
3647
  handleNewPage = async (page) => {
@@ -3265,7 +3931,7 @@ var SessionRecorder = class _SessionRecorder {
3265
3931
  popupAppear: raw.popupAppear
3266
3932
  };
3267
3933
  this.actions.push(pushed2);
3268
- await this.captureAutoSnapshot(page, pushed2, "after").catch(() => {
3934
+ await captureAutoSnapshot(page, pushed2, "after", this.snapshotsDir, this.snapshotThrottle).catch(() => {
3269
3935
  });
3270
3936
  this.lastActionTs = raw.ts;
3271
3937
  continue;
@@ -3295,7 +3961,7 @@ var SessionRecorder = class _SessionRecorder {
3295
3961
  this.actionCounter++;
3296
3962
  let clickContext;
3297
3963
  if (raw.type === "click" && raw.x !== void 0 && raw.y !== void 0) {
3298
- clickContext = await this.captureClickContext(page, raw.x, raw.y);
3964
+ clickContext = await captureClickContext(page, raw.x, raw.y);
3299
3965
  }
3300
3966
  this.actions.push({
3301
3967
  id: this.actionCounter,
@@ -3322,8 +3988,8 @@ var SessionRecorder = class _SessionRecorder {
3322
3988
  drag: raw.drag
3323
3989
  });
3324
3990
  const pushed = this.actions[this.actions.length - 1];
3325
- pushed.elementScreenshot = await this.captureElementScreenshot(page, raw);
3326
- await this.captureAutoSnapshot(page, pushed, "after").catch(() => {
3991
+ pushed.elementScreenshot = await captureElementScreenshot(page, raw);
3992
+ await captureAutoSnapshot(page, pushed, "after", this.snapshotsDir, this.snapshotThrottle).catch(() => {
3327
3993
  });
3328
3994
  this.lastActionTs = raw.ts;
3329
3995
  const dedupKey = this.dedupKey(raw.type, raw.element?.selector, raw.element?.tag, raw.value);
@@ -3333,13 +3999,13 @@ var SessionRecorder = class _SessionRecorder {
3333
3999
  }
3334
4000
  const verifyTypes = /* @__PURE__ */ new Set(["click", "submit", "input", "change", "cdp-click", "cdp-fill"]);
3335
4001
  if (verifyTypes.has(raw.type)) {
3336
- const signals = await this.verifyAction(page, pushed).catch(() => []);
4002
+ const signals = await verifyAction(page, pushed, this.networkCapture.entries, this.checkpoints).catch(() => []);
3337
4003
  if (signals.length > 0) {
3338
4004
  pushed.__signals = signals;
3339
4005
  }
3340
4006
  }
3341
4007
  if (raw.type === "click" || raw.type === "navigate" || raw.type === "submit") {
3342
- const detected = await this.detectCheckpoints(page);
4008
+ const detected = await detectCheckpoints(page, () => ++this.checkpointCounter);
3343
4009
  for (const cp of detected) {
3344
4010
  cp.relatedActionId = this.actionCounter;
3345
4011
  this.checkpoints.push(cp);
@@ -3347,339 +4013,31 @@ var SessionRecorder = class _SessionRecorder {
3347
4013
  }
3348
4014
  }
3349
4015
  }
3350
- /**
3351
- * Capture a screenshot of the target element for key action types.
3352
- * Returns a base64-encoded PNG string, or undefined if the element has no
3353
- * selector or the screenshot fails (non-critical — never blocks recording).
3354
- *
3355
- * Only captures for: click, input, change, dblclick, and their CDP counterparts.
3356
- *
3357
- * Retry strategy (3 attempts, 3s each):
3358
- * 1. element screenshot via locator
3359
- * 2. retry element screenshot (element may have been animating/detached)
3360
- * 3. fallback to viewport screenshot (so we always get *something*)
3361
- */
3362
- async captureElementScreenshot(page, action) {
3363
- const keyTypes = ["click", "input", "change", "dblclick", "cdp-click", "cdp-fill", "filechooser"];
3364
- if (!keyTypes.includes(action.type)) return;
3365
- if (!action.element?.selector) return;
3366
- const selector = action.element.selector;
3367
- try {
3368
- const buffer = await page.locator(selector).first().screenshot({
3369
- type: "png",
3370
- timeout: 3e3
3371
- });
3372
- return buffer.toString("base64");
3373
- } catch {
3374
- }
3375
- try {
3376
- await page.waitForSelector(selector, { state: "visible", timeout: 2e3 });
3377
- const buffer = await page.locator(selector).first().screenshot({
3378
- type: "png",
3379
- timeout: 3e3
3380
- });
3381
- return buffer.toString("base64");
3382
- } catch {
3383
- }
3384
- try {
3385
- const buffer = await page.screenshot({ type: "png", timeout: 3e3 });
3386
- return buffer.toString("base64");
3387
- } catch {
3388
- return;
3389
- }
3390
- }
3391
- /**
3392
- * Action types that trigger auto-snapshot capture.
3393
- * Hover is excluded — it's too noisy and rarely changes the page visually.
3394
- * Popup_appear captures the popup state (after only).
3395
- */
3396
- static SNAPSHOT_TYPES = /* @__PURE__ */ new Set([
3397
- "click",
3398
- "dblclick",
3399
- "navigation",
3400
- "goto",
3401
- "submit",
3402
- "cdp-click",
3403
- "cdp-fill",
3404
- "input",
3405
- "change",
3406
- "filechooser",
3407
- "popup_appear"
3408
- ]);
3409
- /**
3410
- * Throttle key for snapshot capture to avoid too many during rapid inputs.
3411
- * Returns true if this action should be throttled (skip snapshot).
3412
- */
3413
- isSnapshotThrottled(type, selector) {
3414
- if (type === "input" || type === "change" || type === "cdp-fill") {
3415
- const key = `${type}|${selector || ""}`;
3416
- const last = this.snapshotThrottle.get(key);
3417
- const now = Date.now();
3418
- if (last && now - last < 2e3) return true;
3419
- this.snapshotThrottle.set(key, now);
3420
- }
3421
- return false;
3422
- }
3423
- /**
3424
- * Capture a viewport screenshot + compact accessibility tree for a key action.
3425
- * - PNG stored in .tmp/snapshots/ (temporary, easy to clean up)
3426
- * - aria tree stored inline as compact text on the action (searchable via grep)
3427
- *
3428
- * Non-blocking (errors silently caught). Throttled for rapid inputs.
3429
- */
3430
- async captureAutoSnapshot(page, action, suffix = "after") {
3431
- if (!_SessionRecorder.SNAPSHOT_TYPES.has(action.type)) return;
3432
- if (this.isSnapshotThrottled(action.type, action.element?.selector)) return;
3433
- const snapDir = this.snapshotsDir;
3434
- mkdirSync2(snapDir, { recursive: true });
3435
- const stepId = String(action.id).padStart(3, "0");
3436
- const snapshot = {};
3437
- try {
3438
- const pngPath = join2(snapDir, `step-${stepId}-${suffix}.png`);
3439
- const buffer = await page.screenshot({ type: "png", timeout: 5e3 });
3440
- writeFileSync2(pngPath, buffer);
3441
- snapshot.png = `.tmp/snapshots/step-${stepId}-${suffix}.png`;
3442
- } catch {
3443
- }
3444
- try {
3445
- snapshot.aria = await page.evaluate(`
3446
- (function() {
3447
- try {
3448
- var parts = [];
3449
- var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT, null, false);
3450
- var node;
3451
- while (node = walker.nextNode()) {
3452
- var tag = node.tagName.toLowerCase();
3453
- var role = node.getAttribute('role') || '';
3454
- var text = (node.textContent || '').trim().substring(0, 60);
3455
- var ariaLabel = node.getAttribute('aria-label') || '';
3456
- if (role || tag === 'button' || tag === 'a' || tag === 'input' || tag === 'select' || tag === 'textarea') {
3457
- parts.push((role || tag) + ': ' + (ariaLabel || text).substring(0, 40));
3458
- }
3459
- }
3460
- return parts.slice(0, 100).join(' | ');
3461
- } catch(e) { return ''; }
3462
- })()
3463
- `);
3464
- } catch {
3465
- }
3466
- if (snapshot.png || snapshot.aria) {
3467
- action.snapshots = snapshot;
3468
- }
3469
- }
3470
- /**
3471
- * After a click, wait 300ms then scan for popover/dropdown/menu elements
3472
- * near the click position. This runs server-side to avoid race conditions
3473
- * with the client-side poll interval.
3474
- */
3475
- async captureClickContext(page, cx, cy) {
3476
- await new Promise((r) => setTimeout(r, 300));
3477
- try {
3478
- const ctx = await page.evaluate(`
3479
- (function() {
3480
- var cx = ${cx}, cy = ${cy};
3481
- var POPOVER_SELECTORS = [
3482
- '[role="menu"]','[role="listbox"]','[role="dialog"]','[role="tooltip"]','[role="popover"]',
3483
- '[role="combobox"]','[role="tree"]','[role="grid"]',
3484
- '.popover','.popup','.dropdown','.menu','.modal','.tooltip','.panel',
3485
- '[class*="popover"]','[class*="popup"]','[class*="dropdown"]','[class*="menu"]',
3486
- '[class*="tooltip"]','[class*="modal"]','[class*="panel"]','[class*="overlay"]','[class*="sheet"]',
3487
- '[data-popup]','[data-dropdown]','[data-menu]','[data-popover"]',
3488
- '.semi-dropdown','.semi-popover','.semi-modal',
3489
- '.ant-dropdown','.ant-popover','.ant-modal',
3490
- '.el-dropdown','.el-popover','.el-dialog',
3491
- '.t-dropdown','.t-popup','.t-dialog'
3492
- ];
3493
-
3494
- function isNear(el, x, y, range) {
3495
- try {
3496
- var r = el.getBoundingClientRect();
3497
- if (!r || r.width === 0 || r.height === 0) return false;
3498
- return !(r.left > x + range || r.right < x - range || r.top > y + range || r.bottom < y - range);
3499
- } catch(e) { return false; }
3500
- }
3501
-
3502
- var result = { appeared: [], disappeared: [], stateChanges: [] };
3503
- var seenElements = new Set();
3504
-
3505
- for (var si = 0; si < POPOVER_SELECTORS.length; si++) {
3506
- try {
3507
- var els = document.querySelectorAll(POPOVER_SELECTORS[si]);
3508
- for (var j = 0; j < els.length; j++) {
3509
- var el = els[j];
3510
- if (seenElements.has(el)) continue;
3511
- if (!isNear(el, cx, cy, 300)) continue;
3512
- var rect = el.getBoundingClientRect();
3513
- if (rect.width === 0 || rect.height === 0) continue;
3514
- seenElements.add(el);
3515
-
3516
- var items = [];
3517
- var children = el.querySelectorAll('a,button,[role="menuitem"],[role="option"],[role="treeitem"],li,div[class*="item"]');
3518
- var seenItemTexts = new Set();
3519
- for (var k = 0; k < Math.min(children.length, 30); k++) {
3520
- var child = children[k];
3521
- var childText = (child.textContent || '').trim().substring(0, 60);
3522
- if (!childText || seenItemTexts.has(childText)) continue;
3523
- seenItemTexts.add(childText);
3524
- var ci = { text: childText };
3525
- try { if (child.disabled || child.getAttribute('aria-disabled') === 'true') ci.disabled = true; } catch(e) {}
3526
- try { if (child.tagName) ci.tag = child.tagName.toLowerCase(); } catch(e) {}
3527
- try { if (child.href) ci.href = child.href.substring(0, 80); } catch(e) {}
3528
- items.push(ci);
3529
- }
3530
-
3531
- result.appeared.push({
3532
- tag: el.tagName.toLowerCase(),
3533
- selector: el.id ? '#' + el.id : undefined,
3534
- role: el.getAttribute('role'),
3535
- text: (el.textContent || '').trim().substring(0, 100),
3536
- rect: { x: Math.round(rect.x), y: Math.round(rect.y), w: Math.round(rect.width), h: Math.round(rect.height) },
3537
- items: items
3538
- });
3539
- }
3540
- } catch(e) { /* skip invalid selectors */ }
3541
- }
3542
-
3543
- var allInteractive = document.querySelectorAll('[aria-expanded],[disabled],[aria-disabled],[aria-selected],[data-state]');
3544
- for (var i = 0; i < allInteractive.length; i++) {
3545
- var el2 = allInteractive[i];
3546
- if (!isNear(el2, cx, cy, 200)) continue;
3547
- var info = { tag: el2.tagName.toLowerCase(), text: (el2.textContent || '').trim().substring(0, 60) };
3548
- try { if (el2.id) info.id = el2.id; } catch(e) {}
3549
- try { if (el2.getAttribute('aria-expanded')) info.ariaExpanded = el2.getAttribute('aria-expanded'); } catch(e) {}
3550
- try { if (el2.disabled || el2.getAttribute('aria-disabled') === 'true') info.disabled = true; } catch(e) {}
3551
- try { if (el2.getAttribute('aria-selected')) info.ariaSelected = el2.getAttribute('aria-selected'); } catch(e) {}
3552
- try { if (el2.getAttribute('data-state')) info.dataState = el2.getAttribute('data-state'); } catch(e) {}
3553
- result.stateChanges.push(info);
3554
- }
3555
-
3556
- return result;
3557
- })()
3558
- `);
3559
- if (ctx.appeared.length > 0 || ctx.stateChanges.length > 0) {
3560
- return ctx;
3561
- }
3562
- } catch {
3563
- }
3564
- return void 0;
3565
- }
3566
- async detectCheckpoints(page) {
3567
- const CHECKPOINT_RULES = [
3568
- { type: "captcha", selectors: ['img[src*="captcha"]', 'img[src*="verify"]', '[class*="captcha"]', '[id*="captcha"]', "#captcha", ".captcha"] },
3569
- { type: "slider", selectors: ['[class*="slider"]', '[class*="drag-verify"]', '[class*="slide-verify"]'] },
3570
- { type: "login", selectors: ['input[type="password"]'] },
3571
- { type: "iframe", selectors: ['iframe[src*="captcha"]', 'iframe[src*="verify"]', 'iframe[src*="recaptcha"]', 'iframe[title*="captcha"]'] }
3572
- ];
3573
- try {
3574
- const found = await page.evaluate((rules) => {
3575
- const results = [];
3576
- for (const rule of rules) {
3577
- for (const sel of rule.selectors) {
3578
- try {
3579
- const el = document.querySelector(sel);
3580
- if (el) {
3581
- const rect = el.getBoundingClientRect();
3582
- if (rect.width > 0 && rect.height > 0) {
3583
- results.push({
3584
- type: rule.type,
3585
- selector: sel,
3586
- text: (el.textContent || "").substring(0, 60)
3587
- });
3588
- }
3589
- }
3590
- } catch {
3591
- }
3592
- }
3593
- }
3594
- return results;
3595
- }, CHECKPOINT_RULES);
3596
- const entries = [];
3597
- for (const item of found) {
3598
- this.checkpointCounter++;
3599
- const hints = {
3600
- captcha: "Captcha verification detected",
3601
- slider: "Slider verification detected",
3602
- login: "Login form detected (password field)",
3603
- iframe: "Verification iframe detected"
3604
- };
3605
- entries.push({
3606
- id: this.checkpointCounter,
3607
- type: item.type,
3608
- timestamp: Date.now(),
3609
- url: page.url(),
3610
- pageTitle: await page.title().catch(() => ""),
3611
- hint: hints[item.type] || item.type,
3612
- selector: item.selector,
3613
- source: "auto",
3614
- context: { matchedSelector: item.selector, elementText: item.text }
3615
- });
3616
- }
3617
- return entries;
3618
- } catch {
3619
- return [];
3620
- }
3621
- }
3622
- // ─── Verification: collect success signals after key actions ──────
3623
- /**
3624
- * After a key action (click/submit/input), check for success signals:
3625
- * URL changes, recent successful network responses, dialog appearances.
3626
- */
3627
- async verifyAction(page, action) {
3628
- const signals = [];
3629
- try {
3630
- const currentUrl = page.url();
3631
- if (currentUrl && currentUrl !== "about:blank" && currentUrl !== action.url) {
3632
- signals.push({ type: "url_change", value: currentUrl, label: `URL changed to ${currentUrl}` });
3633
- }
3634
- } catch {
3635
- }
3636
- try {
3637
- const recentNetwork = this.network.filter(
3638
- (n) => n.timestamp > action.timestamp - 100 && n.timestamp < action.timestamp + 5e3 && n.status >= 200 && n.status < 400
3639
- );
3640
- for (const net of recentNetwork.slice(0, 3)) {
3641
- signals.push({
3642
- type: "network_success",
3643
- value: `${net.status}`,
3644
- label: `${net.method} ${net.path} \u2192 ${net.status}`
3645
- });
3646
- }
3647
- } catch {
3648
- }
3649
- try {
3650
- const recentDialog = [...this.checkpoints].reverse().find(
3651
- (cp) => cp.type === "dialog" && Math.abs(cp.timestamp - action.timestamp) < 3e3
3652
- );
3653
- if (recentDialog) {
3654
- signals.push({ type: "dialog", value: recentDialog.type, label: recentDialog.hint });
3655
- }
3656
- } catch {
3657
- }
3658
- return signals;
3659
- }
3660
4016
  // ─── Periodic disk flush ────────────────────────────────────────
3661
4017
  flushToDisk() {
3662
4018
  const data = this.buildData();
3663
4019
  try {
3664
- writeFileSync2(
3665
- join2(this.recordingsDir, "recording.json"),
4020
+ writeFileSync3(
4021
+ join4(this.recordingsDir, "recording.json"),
3666
4022
  JSON.stringify(data, null, 2),
3667
4023
  "utf-8"
3668
4024
  );
3669
- const jsonlPath = join2(this.recordingsDir, "recording.jsonl");
4025
+ const jsonlPath = join4(this.recordingsDir, "recording.jsonl");
3670
4026
  const lines = data.actions.map((a) => JSON.stringify(a)).join("\n") + "\n";
3671
- writeFileSync2(jsonlPath, lines, "utf-8");
4027
+ writeFileSync3(jsonlPath, lines, "utf-8");
3672
4028
  } catch {
3673
4029
  }
3674
4030
  }
3675
4031
  writeFinalOutput(data, summary) {
3676
- mkdirSync2(this.recordingsDir, { recursive: true });
3677
- writeFileSync2(join2(this.recordingsDir, "recording.json"), JSON.stringify(data, null, 2), "utf-8");
3678
- const jsonlPath = join2(this.recordingsDir, "recording.jsonl");
4032
+ mkdirSync3(this.recordingsDir, { recursive: true });
4033
+ writeFileSync3(join4(this.recordingsDir, "recording.json"), JSON.stringify(data, null, 2), "utf-8");
4034
+ const jsonlPath = join4(this.recordingsDir, "recording.jsonl");
3679
4035
  const lines = data.actions.map((a) => JSON.stringify(a)).join("\n") + "\n";
3680
- writeFileSync2(jsonlPath, lines, "utf-8");
3681
- writeFileSync2(join2(this.recordingsDir, "summary.json"), JSON.stringify(summary, null, 2), "utf-8");
3682
- writeFileSync2(join2(this.recordingsDir, "summary.md"), this.buildMarkdownSummary(data, summary), "utf-8");
4036
+ writeFileSync3(jsonlPath, lines, "utf-8");
4037
+ writeFileSync3(join4(this.recordingsDir, "summary.json"), JSON.stringify(summary, null, 2), "utf-8");
4038
+ const compactSummary = buildCompactSummary(data, this.startedAt);
4039
+ writeFileSync3(join4(this.recordingsDir, "summary-compact.json"), JSON.stringify(compactSummary, null, 2), "utf-8");
4040
+ writeFileSync3(join4(this.recordingsDir, "summary.md"), buildMarkdownSummary(data, summary), "utf-8");
3683
4041
  }
3684
4042
  buildData() {
3685
4043
  return {
@@ -3687,320 +4045,13 @@ var SessionRecorder = class _SessionRecorder {
3687
4045
  sessionName: this.sessionName,
3688
4046
  startedAt: new Date(this.startedAt).toISOString(),
3689
4047
  actions: [...this.actions],
3690
- network: [...this.network],
4048
+ network: [...this.networkCapture.entries],
3691
4049
  contextChanges: [...this.contextChanges],
3692
4050
  checkpoints: [...this.checkpoints],
3693
4051
  discoveredFilters: [...this.discoveredFilters.values()]
3694
4052
  };
3695
4053
  }
3696
- // ─── Summary builder with ref compression + input→network matching ──
3697
- buildSummary(data) {
3698
- const POST_WINDOW = 5e3;
3699
- const MERGE_WINDOW = 2e3;
3700
- const steps = [];
3701
- const selectorToRef = /* @__PURE__ */ new Map();
3702
- const elements = {};
3703
- let refCounter = 0;
3704
- function getRef(action) {
3705
- const sel = action.element?.selector || action.element?.tag || "_none";
3706
- if (selectorToRef.has(sel)) return selectorToRef.get(sel);
3707
- refCounter++;
3708
- const ref = "e" + refCounter;
3709
- selectorToRef.set(sel, ref);
3710
- if (action.element) {
3711
- elements[ref] = {
3712
- selector: action.element.selector || action.element.tag,
3713
- tag: action.element.tag,
3714
- text: action.element.text,
3715
- role: action.element.role,
3716
- type: action.element.type,
3717
- placeholder: action.element.placeholder,
3718
- ariaLabel: action.element.ariaLabel,
3719
- href: action.element.href
3720
- };
3721
- } else {
3722
- elements[ref] = { selector: "_none", tag: "_", text: "" };
3723
- }
3724
- return ref;
3725
- }
3726
- const isNoiseNetwork = (n) => {
3727
- const url = n.url || "";
3728
- const path = n.path || "";
3729
- const rt = n.resourceType || "";
3730
- if (["image", "stylesheet", "font", "manifest", "other"].includes(rt)) return true;
3731
- if (n.status === 0) return true;
3732
- if (/\/ztbox|\/mwb2\.gif|\/hmslog|\/log\.gif|\/tongji|hm\.baidu|clickstream|\/actionlog|\/collect\?|\/track|\/beacon/i.test(url)) return true;
3733
- if (/\/favicon\.ico|\/robots\.txt/i.test(path)) return true;
3734
- return false;
3735
- };
3736
- const meaningfulNetwork = data.network.filter((n) => !isNoiseNetwork(n));
3737
- const filtered = data.actions;
3738
- const groups = [];
3739
- let current = null;
3740
- for (const action of filtered) {
3741
- const sameElement = current && current.primary.element?.selector && current.primary.element.selector === action.element?.selector && action.timestamp - current.primary.timestamp < MERGE_WINDOW;
3742
- const isInputLike = action.type === "input" || action.type === "keydown" || action.type === "change";
3743
- if (current && (sameElement || isInputLike && current.actions.some((a) => a.type === "input" || a.type === "click") && action.timestamp - current.primary.timestamp < MERGE_WINDOW)) {
3744
- current.actions.push(action);
3745
- if (action.type === "input") current.primary = action;
3746
- } else {
3747
- current = { actions: [action], primary: action };
3748
- groups.push(current);
3749
- }
3750
- }
3751
- for (const group of groups) {
3752
- const primary = group.primary;
3753
- const tsStart = Math.min(...group.actions.map((a) => a.timestamp));
3754
- const tsEnd = Math.max(...group.actions.map((a) => a.timestamp));
3755
- const inputAction = group.actions.find((a) => a.type === "input");
3756
- const nearbyNetwork = meaningfulNetwork.filter(
3757
- (n) => n.timestamp >= tsStart - 500 && n.timestamp <= tsEnd + POST_WINDOW
3758
- );
3759
- const nearbyContext = data.contextChanges.filter(
3760
- (c) => c.timestamp >= tsStart - 500 && c.timestamp <= tsEnd + POST_WINDOW
3761
- );
3762
- const matchedInputs = inputAction ? this.matchActionToNetwork(inputAction, nearbyNetwork) : [];
3763
- const clickMatches = primary.type === "click" && primary.element?.text ? this.matchActionToNetwork(primary, nearbyNetwork) : [];
3764
- const signals = primary.__signals || [];
3765
- steps.push({
3766
- step: steps.length + 1,
3767
- ref: getRef(primary),
3768
- action: primary,
3769
- network: nearbyNetwork.map((n) => ({
3770
- ...n,
3771
- responseBody: n.responseBody && JSON.stringify(n.responseBody).length > 1e3 ? "[truncated, " + JSON.stringify(n.responseBody).length + " bytes]" : n.responseBody
3772
- })),
3773
- contextChanges: nearbyContext,
3774
- matchedInputs: [...matchedInputs, ...clickMatches],
3775
- signals
3776
- });
3777
- }
3778
- return {
3779
- startUrl: data.startUrl,
3780
- recordedAt: new Date(this.startedAt).toISOString(),
3781
- durationMs: Date.now() - this.startedAt,
3782
- totalActions: data.actions.length,
3783
- totalNetworkRequests: meaningfulNetwork.length,
3784
- steps,
3785
- elements,
3786
- checkpoints: data.checkpoints
3787
- };
3788
- }
3789
- matchActionToNetwork(action, nearbyNetwork) {
3790
- const matches = [];
3791
- const searchValue = (action.value || action.element?.text || "").trim();
3792
- if (!searchValue || searchValue.length < 2) return matches;
3793
- for (const netEntry of nearbyNetwork) {
3794
- if (netEntry.url.includes(encodeURIComponent(searchValue)) || netEntry.url.includes(searchValue)) {
3795
- matches.push({ inputValue: searchValue, networkId: netEntry.id, paramName: "url" });
3796
- }
3797
- if (netEntry.requestBody && typeof netEntry.requestBody === "object") {
3798
- this.searchObjectForValue(
3799
- netEntry.requestBody,
3800
- searchValue,
3801
- netEntry.id,
3802
- "",
3803
- matches
3804
- );
3805
- }
3806
- }
3807
- return matches;
3808
- }
3809
- searchObjectForValue(obj, targetValue, networkId, prefix, results) {
3810
- for (const [key, value] of Object.entries(obj)) {
3811
- const fullKey = prefix ? `${prefix}.${key}` : key;
3812
- if (typeof value === "string" && value.includes(targetValue)) {
3813
- results.push({ inputValue: targetValue, networkId, paramName: fullKey });
3814
- } else if (typeof value === "object" && value !== null) {
3815
- this.searchObjectForValue(value, targetValue, networkId, fullKey, results);
3816
- }
3817
- }
3818
- }
3819
- buildMarkdownSummary(_data, summary) {
3820
- const lines = [];
3821
- const durSec = Math.round(summary.durationMs / 1e3);
3822
- lines.push("# Recording Summary");
3823
- lines.push("");
3824
- lines.push(`- **URL**: ${summary.startUrl}`);
3825
- lines.push(`- **Recorded**: ${summary.recordedAt}`);
3826
- lines.push(`- **Duration**: ${durSec}s`);
3827
- lines.push(`- **Steps**: ${summary.totalActions} actions, ${summary.totalNetworkRequests} network requests`);
3828
- if (summary.checkpoints.length > 0) {
3829
- const cpTypes = summary.checkpoints.map((c) => c.type);
3830
- lines.push(`- **Checkpoints**: ${summary.checkpoints.length} (${[...new Set(cpTypes)].join(", ")})`);
3831
- } else {
3832
- lines.push("- **Checkpoints**: 0");
3833
- }
3834
- const checkpointSteps = /* @__PURE__ */ new Map();
3835
- for (const cp of summary.checkpoints) {
3836
- if (cp.relatedActionId != null) {
3837
- for (const step of summary.steps) {
3838
- if (step.action.id === cp.relatedActionId) {
3839
- checkpointSteps.set(step.step, cp);
3840
- break;
3841
- }
3842
- }
3843
- }
3844
- }
3845
- lines.push("");
3846
- lines.push("## Steps");
3847
- lines.push("");
3848
- for (const step of summary.steps) {
3849
- const a = step.action;
3850
- const el = a.element;
3851
- const cp = checkpointSteps.get(step.step);
3852
- if (cp) {
3853
- lines.push(`### Step ${step.step}: \u26A0\uFE0F CHECKPOINT \u2014 ${cp.hint}`);
3854
- lines.push(`- **Type**: ${cp.type} (${cp.source})`);
3855
- lines.push(`- **Hint**: ${cp.hint}`);
3856
- if (cp.selector) lines.push(`- **Selector**: \`${cp.selector}\``);
3857
- lines.push(`- **Action needed**: Human intervention required before continuing`);
3858
- } else {
3859
- const title = describeActionTitle(a);
3860
- lines.push(`### Step ${step.step}: ${title}`);
3861
- }
3862
- if (el) {
3863
- const parts = [`\`${el.selector || el.tag}\``];
3864
- if (el.text) parts.push(`"${el.text.substring(0, 60)}"`);
3865
- parts.push(`(${el.tag})`);
3866
- if (el.type) parts.push(`type=${el.type}`);
3867
- lines.push(`- **Element**: ${parts.join(" ")}`);
3868
- }
3869
- if (a.value != null && a.type === "input") {
3870
- lines.push(`- **Value**: "${a.value.substring(0, 100)}"`);
3871
- }
3872
- if (step.network.length > 0) {
3873
- const netDescs = step.network.map((n) => {
3874
- let desc = `${n.method} ${n.path}`;
3875
- if (n.status) desc += ` \u2192 ${n.status}`;
3876
- if (n.responseSize > 0) desc += ` (${formatBytes(n.responseSize)})`;
3877
- return desc;
3878
- });
3879
- lines.push(`- **Network**: ${netDescs.join(", ")}`);
3880
- for (const n of step.network) {
3881
- if (n.requestBody && typeof n.requestBody === "object") {
3882
- const bodyStr = JSON.stringify(n.requestBody);
3883
- if (bodyStr.length <= 300) {
3884
- lines.push(` - \`${n.method} ${n.path}\` body: \`${bodyStr}\``);
3885
- } else {
3886
- lines.push(` - \`${n.method} ${n.path}\` body: \`${bodyStr.substring(0, 300)}...\` (${bodyStr.length} bytes)`);
3887
- }
3888
- }
3889
- }
3890
- } else {
3891
- lines.push("- **Network**: none");
3892
- }
3893
- if (step.matchedInputs.length > 0) {
3894
- for (const m of step.matchedInputs) {
3895
- lines.push(`- **Input matched**: "${m.inputValue}" \u2192 ${m.paramName} (network #${m.networkId})`);
3896
- }
3897
- }
3898
- for (const ctx of step.contextChanges) {
3899
- if (ctx.type === "navigate") {
3900
- lines.push(`- **Navigate**: \u2192 ${ctx.url}`);
3901
- } else if (ctx.type === "new_tab") {
3902
- lines.push(`- **New tab**: ${ctx.url}`);
3903
- }
3904
- }
3905
- if (a.clickContext) {
3906
- if (a.clickContext.appeared?.length > 0) {
3907
- for (const popup of a.clickContext.appeared) {
3908
- const roleStr = popup.role ? ` [${popup.role}]` : "";
3909
- lines.push(`- **Popup**: <${popup.tag}${roleStr}> "${(popup.text || "").substring(0, 60)}"`);
3910
- if (popup.items?.length > 0) {
3911
- const itemStrs = popup.items.slice(0, 8).map((i) => {
3912
- const dis = i.disabled ? " [disabled]" : "";
3913
- return `"${i.text}"${dis}`;
3914
- });
3915
- let itemLine = ` - Items: ${itemStrs.join(", ")}`;
3916
- if (popup.items.length > 8) itemLine += ` ... +${popup.items.length - 8} more`;
3917
- lines.push(itemLine);
3918
- }
3919
- }
3920
- }
3921
- if (a.clickContext.stateChanges?.length > 0) {
3922
- for (const sc of a.clickContext.stateChanges) {
3923
- const parts = [];
3924
- if (sc.ariaExpanded !== void 0) parts.push(`expanded=${sc.ariaExpanded}`);
3925
- if (sc.disabled) parts.push("disabled");
3926
- if (sc.ariaSelected !== void 0) parts.push(`selected=${sc.ariaSelected}`);
3927
- if (sc.dataState) parts.push(`state=${sc.dataState}`);
3928
- if (parts.length > 0) {
3929
- lines.push(`- **State**: <${sc.tag}> "${(sc.text || "").substring(0, 30)}" ${parts.join(", ")}`);
3930
- }
3931
- }
3932
- }
3933
- }
3934
- lines.push("");
3935
- }
3936
- const allNetwork = summary.steps.flatMap((s) => s.network);
3937
- if (allNetwork.length > 0) {
3938
- lines.push("## Network Timeline");
3939
- lines.push("");
3940
- allNetwork.forEach((n, i) => {
3941
- let line = `${i + 1}. ${n.method} ${n.path}`;
3942
- if (n.status) line += ` \u2192 ${n.status}`;
3943
- if (n.requestBody && typeof n.requestBody === "object") {
3944
- const bodyStr = JSON.stringify(n.requestBody);
3945
- if (bodyStr.length <= 150) {
3946
- line += ` ${bodyStr}`;
3947
- }
3948
- }
3949
- if (n.responseSize > 0) line += ` (${formatBytes(n.responseSize)})`;
3950
- lines.push(line);
3951
- });
3952
- lines.push("");
3953
- }
3954
- const orphanCheckpoints = summary.checkpoints.filter(
3955
- (cp) => cp.relatedActionId == null || !checkpointSteps.has(
3956
- summary.steps.find((s) => s.action.id === cp.relatedActionId)?.step ?? -1
3957
- )
3958
- );
3959
- if (orphanCheckpoints.length > 0) {
3960
- lines.push("## Unresolved Checkpoints");
3961
- lines.push("");
3962
- for (const cp of orphanCheckpoints) {
3963
- const src = cp.source === "auto" ? "[auto]" : "[manual]";
3964
- lines.push(`- ${src} **${cp.type}**: ${cp.hint}`);
3965
- if (cp.selector) lines.push(` - Selector: \`${cp.selector}\``);
3966
- }
3967
- lines.push("");
3968
- }
3969
- return lines.join("\n");
3970
- }
3971
- static readMarkdownSummary(sessionName) {
3972
- const path = join2(_SessionRecorder.getRecordingsDir(sessionName), "summary.md");
3973
- try {
3974
- return readFileSync2(path, "utf-8");
3975
- } catch {
3976
- return null;
3977
- }
3978
- }
3979
4054
  };
3980
- function describeActionTitle(a) {
3981
- const el = a.element;
3982
- const elText = el?.text ? `"${el.text.substring(0, 40)}"` : "";
3983
- const elTag = el?.tag ? `<${el.tag}>` : "";
3984
- switch (a.type) {
3985
- case "click":
3986
- return `Click ${elText || elTag} button`.replace(/ +/g, " ").trim();
3987
- case "input":
3988
- return `Input "${(a.value || "").substring(0, 50)}" in ${elText || elTag || "field"}`.replace(/ +/g, " ").trim();
3989
- case "change":
3990
- return `Change ${elText || elTag} to "${(a.value || "").substring(0, 30)}"`;
3991
- case "keydown":
3992
- return `Press ${a.key || "key"} on ${elText || elTag || "element"}`;
3993
- case "submit":
3994
- return `Submit ${elText || elTag || "form"}`;
3995
- default:
3996
- return `${a.type} ${elText || elTag}`.trim() || a.type;
3997
- }
3998
- }
3999
- function formatBytes(bytes) {
4000
- if (bytes < 1024) return `${bytes}B`;
4001
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
4002
- return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
4003
- }
4004
4055
 
4005
4056
  export {
4006
4057
  SessionRecorder