@xbrowser/cli 1.27.0 → 1.29.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 (37) hide show
  1. package/dist/{browser-NYYCR4O7.js → browser-2K3XYAKM.js} +5 -3
  2. package/dist/{browser-ZD53IMUJ.js → browser-OTEMG5NL.js} +6 -4
  3. package/dist/{browser-4IYIHZ6R.js → browser-XD3IOU5I.js} +8 -6
  4. package/dist/{cdp-driver-EFEW4ZEN.js → cdp-driver-AAS55KT2.js} +4 -4
  5. package/dist/{cdp-driver-4X6Q62WI.js → cdp-driver-O5I7SJ24.js} +3 -3
  6. package/dist/{cdp-driver-HB744QB4.js → cdp-driver-XTPY7EXP.js} +1296 -852
  7. package/dist/{chunk-SEEWE5SJ.js → chunk-2KPI5GKP.js} +3 -0
  8. package/dist/{chunk-75DNUI6M.js → chunk-6UJU2FJK.js} +146 -0
  9. package/dist/{chunk-3PUOISKE.js → chunk-CO2ZVOVT.js} +496 -452
  10. package/dist/{chunk-V6KGBU5J.js → chunk-FCPVQFTQ.js} +1011 -1038
  11. package/dist/{chunk-IDXOIXQR.js → chunk-GDKKVT2P.js} +773 -655
  12. package/dist/{chunk-HSYRAV3H.js → chunk-LFSLNHW5.js} +1846 -1358
  13. package/dist/{chunk-OSZNJT4U.js → chunk-LM32MNBB.js} +79 -8
  14. package/dist/{chunk-J3HXZVSN.js → chunk-N5XTLNKS.js} +1166 -868
  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-ME5FO5YV.js → chunk-NQPXZ74W.js} +1296 -852
  18. package/dist/{chunk-KECYFWJO.js → chunk-P33R7F2D.js} +413 -384
  19. package/dist/{chunk-YITK42HZ.js → chunk-SCYBNSOG.js} +1596 -1478
  20. package/dist/{chunk-R3F4K2SB.js → chunk-SMYSNO4M.js} +10 -0
  21. package/dist/{chunk-IR6C24P7.js → chunk-UZ6XPUBD.js} +1030 -1048
  22. package/dist/cli.js +3398 -3357
  23. package/dist/daemon-main.js +749 -700
  24. package/dist/index.d.ts +362 -474
  25. package/dist/index.js +5730 -5689
  26. package/dist/{launcher-SJ44X25U.js → launcher-TOLF23ET.js} +1 -1
  27. package/dist/{launcher-XHKIC4GP.js → launcher-ZYB32LSZ.js} +1 -1
  28. package/dist/{plugin-singleton-GGSBI3EG.js → plugin-singleton-A6RNITJW.js} +1 -1
  29. package/dist/{proxy-NKCYE76M.js → proxy-H3RIUOCN.js} +2 -2
  30. package/dist/{server-YKMRFDEM.js → server-LNZTDAKT.js} +4 -4
  31. package/dist/{server-WDDGIV3C.js → server-ZTI2K5YJ.js} +7 -7
  32. package/dist/{session-recorder-GEZVQBKW.js → session-recorder-DF2YGH2E.js} +1 -1
  33. package/dist/{session-recorder-563ISSJK.js → session-recorder-R3GDGXLJ.js} +1 -1
  34. package/dist/{session-replayer-TXTNTG33.js → session-replayer-CLTZ2URU.js} +1 -1
  35. package/dist/{stealth-QNSMIHQK.js → stealth-FMPZO2OB.js} +1 -1
  36. package/dist/{stealth-MHJNBJY7.js → stealth-MCKFKPZ6.js} +1 -1
  37. package/package.json +6 -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,850 @@ 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 || ""}`;
2564
+ if (!success) {
2565
+ console.error(`[recorder] WARNING: Action signal injection FAILED after ${maxAttempts} attempts. User actions will NOT be recorded. Last error: ${lastError}`);
2576
2566
  }
2577
- get networkCount() {
2578
- return this.network.length;
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}`);
2579
2572
  }
2580
- getLiveData() {
2581
- return this.buildData();
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
+ }
2582
2582
  }
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;
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 {
2597
2642
  }
2598
- /** Directory for this session's recordings. */
2599
- get recordingsDir() {
2600
- return _SessionRecorder.getRecordingsDir(this.sessionName);
2643
+ return success;
2644
+ }
2645
+
2646
+ // src/recorder/summary-builder.ts
2647
+ var POST_WINDOW = 5e3;
2648
+ var MERGE_WINDOW = 2e3;
2649
+ function buildSummary(data, startedAt) {
2650
+ const steps = [];
2651
+ const selectorToRef = /* @__PURE__ */ new Map();
2652
+ const elements = {};
2653
+ let refCounter = 0;
2654
+ function getRef(action) {
2655
+ const sel = action.element?.selector || action.element?.tag || "_none";
2656
+ if (selectorToRef.has(sel)) return selectorToRef.get(sel);
2657
+ refCounter++;
2658
+ const ref = "e" + refCounter;
2659
+ selectorToRef.set(sel, ref);
2660
+ if (action.element) {
2661
+ elements[ref] = {
2662
+ selector: action.element.selector || action.element.tag,
2663
+ tag: action.element.tag,
2664
+ text: action.element.text,
2665
+ role: action.element.role,
2666
+ type: action.element.type,
2667
+ placeholder: action.element.placeholder,
2668
+ ariaLabel: action.element.ariaLabel,
2669
+ href: action.element.href
2670
+ };
2671
+ } else {
2672
+ elements[ref] = { selector: "_none", tag: "_", text: "" };
2673
+ }
2674
+ return ref;
2675
+ }
2676
+ const isNoiseNetwork = (n) => {
2677
+ const url = n.url || "";
2678
+ const path = n.path || "";
2679
+ const rt = n.resourceType || "";
2680
+ if (["image", "stylesheet", "font", "manifest", "other"].includes(rt)) return true;
2681
+ if (n.status === 0) return true;
2682
+ if (/\/ztbox|\/mwb2\.gif|\/hmslog|\/log\.gif|\/tongji|hm\.baidu|clickstream|\/actionlog|\/collect\?|\/track|\/beacon/i.test(url)) return true;
2683
+ if (/\/favicon\.ico|\/robots\.txt/i.test(path)) return true;
2684
+ return false;
2685
+ };
2686
+ const meaningfulNetwork = data.network.filter((n) => !isNoiseNetwork(n));
2687
+ const filtered = data.actions;
2688
+ const groups = [];
2689
+ let current = null;
2690
+ for (const action of filtered) {
2691
+ const sameElement = current && current.primary.element?.selector && current.primary.element.selector === action.element?.selector && action.timestamp - current.primary.timestamp < MERGE_WINDOW;
2692
+ const isInputLike = action.type === "input" || action.type === "keydown" || action.type === "change";
2693
+ if (current && (sameElement || isInputLike && current.actions.some((a) => a.type === "input" || a.type === "click") && action.timestamp - current.primary.timestamp < MERGE_WINDOW)) {
2694
+ current.actions.push(action);
2695
+ if (action.type === "input") current.primary = action;
2696
+ } else {
2697
+ current = { actions: [action], primary: action };
2698
+ groups.push(current);
2699
+ }
2601
2700
  }
2602
- /** Directory for auto-captured snapshots (PNG screenshots, stored in .tmp for easy cleanup). */
2603
- get snapshotsDir() {
2604
- return join2(this.recordingsDir, ".tmp", "snapshots");
2701
+ for (const group of groups) {
2702
+ const primary = group.primary;
2703
+ const tsStart = Math.min(...group.actions.map((a) => a.timestamp));
2704
+ const tsEnd = Math.max(...group.actions.map((a) => a.timestamp));
2705
+ const inputAction = group.actions.find((a) => a.type === "input");
2706
+ const nearbyNetwork = meaningfulNetwork.filter(
2707
+ (n) => n.timestamp >= tsStart - 500 && n.timestamp <= tsEnd + POST_WINDOW
2708
+ );
2709
+ const nearbyContext = data.contextChanges.filter(
2710
+ (c) => c.timestamp >= tsStart - 500 && c.timestamp <= tsEnd + POST_WINDOW
2711
+ );
2712
+ const matchedInputs = inputAction ? matchActionToNetwork(inputAction, nearbyNetwork) : [];
2713
+ const clickMatches = primary.type === "click" && primary.element?.text ? matchActionToNetwork(primary, nearbyNetwork) : [];
2714
+ const signals = primary.__signals || [];
2715
+ steps.push({
2716
+ step: steps.length + 1,
2717
+ ref: getRef(primary),
2718
+ action: primary,
2719
+ network: nearbyNetwork.map((n) => ({
2720
+ ...n,
2721
+ responseBody: n.responseBody && JSON.stringify(n.responseBody).length > 1e3 ? "[truncated, " + JSON.stringify(n.responseBody).length + " bytes]" : n.responseBody
2722
+ })),
2723
+ contextChanges: nearbyContext,
2724
+ matchedInputs: [...matchedInputs, ...clickMatches],
2725
+ signals
2726
+ });
2605
2727
  }
2606
- static getRecordingsDir(sessionName) {
2607
- return join2(homedir2(), ".xbrowser", "sessions", sessionName, "recordings");
2728
+ return {
2729
+ startUrl: data.startUrl,
2730
+ recordedAt: new Date(startedAt).toISOString(),
2731
+ durationMs: Date.now() - startedAt,
2732
+ totalActions: data.actions.length,
2733
+ totalNetworkRequests: meaningfulNetwork.length,
2734
+ steps,
2735
+ elements,
2736
+ checkpoints: data.checkpoints
2737
+ };
2738
+ }
2739
+ function matchActionToNetwork(action, nearbyNetwork) {
2740
+ const matches = [];
2741
+ const searchValue = (action.value || action.element?.text || "").trim();
2742
+ if (!searchValue || searchValue.length < 2) return matches;
2743
+ for (const netEntry of nearbyNetwork) {
2744
+ if (netEntry.url.includes(encodeURIComponent(searchValue)) || netEntry.url.includes(searchValue)) {
2745
+ matches.push({ inputValue: searchValue, networkId: netEntry.id, paramName: "url" });
2746
+ }
2747
+ if (netEntry.requestBody && typeof netEntry.requestBody === "object") {
2748
+ searchObjectForValue(
2749
+ netEntry.requestBody,
2750
+ searchValue,
2751
+ netEntry.id,
2752
+ "",
2753
+ matches
2754
+ );
2755
+ }
2608
2756
  }
2609
- /** Path to the control file (used by record stop to signal this process). */
2610
- get controlFilePath() {
2611
- return join2(this.recordingsDir, ".control.json");
2757
+ return matches;
2758
+ }
2759
+ function searchObjectForValue(obj, targetValue, networkId, prefix, results) {
2760
+ for (const [key, value] of Object.entries(obj)) {
2761
+ const fullKey = prefix ? `${prefix}.${key}` : key;
2762
+ if (typeof value === "string" && value.includes(targetValue)) {
2763
+ results.push({ inputValue: targetValue, networkId, paramName: fullKey });
2764
+ } else if (typeof value === "object" && value !== null) {
2765
+ searchObjectForValue(value, targetValue, networkId, fullKey, results);
2766
+ }
2612
2767
  }
2613
- /** Path to the stop signal file (written by `record stop`). */
2614
- get stopSignalPath() {
2615
- return join2(this.recordingsDir, ".stop");
2768
+ }
2769
+
2770
+ // src/recorder/markdown-summary.ts
2771
+ import { readFileSync as readFileSync2 } from "fs";
2772
+ import { join as join2 } from "path";
2773
+ import { homedir as homedir2 } from "os";
2774
+ function buildMarkdownSummary(_data, summary) {
2775
+ const lines = [];
2776
+ const durSec = Math.round(summary.durationMs / 1e3);
2777
+ lines.push("# Recording Summary");
2778
+ lines.push("");
2779
+ lines.push(`- **URL**: ${summary.startUrl}`);
2780
+ lines.push(`- **Recorded**: ${summary.recordedAt}`);
2781
+ lines.push(`- **Duration**: ${durSec}s`);
2782
+ lines.push(`- **Steps**: ${summary.totalActions} actions, ${summary.totalNetworkRequests} network requests`);
2783
+ if (summary.checkpoints.length > 0) {
2784
+ const cpTypes = summary.checkpoints.map((c) => c.type);
2785
+ lines.push(`- **Checkpoints**: ${summary.checkpoints.length} (${[...new Set(cpTypes)].join(", ")})`);
2786
+ } else {
2787
+ lines.push("- **Checkpoints**: 0");
2788
+ }
2789
+ const checkpointSteps = /* @__PURE__ */ new Map();
2790
+ for (const cp of summary.checkpoints) {
2791
+ if (cp.relatedActionId != null) {
2792
+ for (const step of summary.steps) {
2793
+ if (step.action.id === cp.relatedActionId) {
2794
+ checkpointSteps.set(step.step, cp);
2795
+ break;
2796
+ }
2797
+ }
2798
+ }
2616
2799
  }
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();
2800
+ lines.push("");
2801
+ lines.push("## Steps");
2802
+ lines.push("");
2803
+ for (const step of summary.steps) {
2804
+ const a = step.action;
2805
+ const el = a.element;
2806
+ const cp = checkpointSteps.get(step.step);
2807
+ if (cp) {
2808
+ lines.push(`### Step ${step.step}: \u26A0\uFE0F CHECKPOINT \u2014 ${cp.hint}`);
2809
+ lines.push(`- **Type**: ${cp.type} (${cp.source})`);
2810
+ lines.push(`- **Hint**: ${cp.hint}`);
2811
+ if (cp.selector) lines.push(`- **Selector**: \`${cp.selector}\``);
2812
+ lines.push(`- **Action needed**: Human intervention required before continuing`);
2813
+ } else {
2814
+ const title = describeActionTitle(a);
2815
+ lines.push(`### Step ${step.step}: ${title}`);
2816
+ }
2817
+ if (el) {
2818
+ const parts = [`\`${el.selector || el.tag}\``];
2819
+ if (el.text) parts.push(`"${el.text.substring(0, 60)}"`);
2820
+ parts.push(`(${el.tag})`);
2821
+ if (el.type) parts.push(`type=${el.type}`);
2822
+ lines.push(`- **Element**: ${parts.join(" ")}`);
2823
+ }
2824
+ if (a.value != null && a.type === "input") {
2825
+ lines.push(`- **Value**: "${a.value.substring(0, 100)}"`);
2826
+ }
2827
+ if (step.network.length > 0) {
2828
+ const netDescs = step.network.map((n) => {
2829
+ let desc = `${n.method} ${n.path}`;
2830
+ if (n.status) desc += ` \u2192 ${n.status}`;
2831
+ if (n.responseSize > 0) desc += ` (${formatBytes(n.responseSize)})`;
2832
+ return desc;
2833
+ });
2834
+ lines.push(`- **Network**: ${netDescs.join(", ")}`);
2835
+ for (const n of step.network) {
2836
+ if (n.requestBody && typeof n.requestBody === "object") {
2837
+ const bodyStr = JSON.stringify(n.requestBody);
2838
+ if (bodyStr.length <= 300) {
2839
+ lines.push(` - \`${n.method} ${n.path}\` body: \`${bodyStr}\``);
2840
+ } else {
2841
+ lines.push(` - \`${n.method} ${n.path}\` body: \`${bodyStr.substring(0, 300)}...\` (${bodyStr.length} bytes)`);
2842
+ }
2843
+ }
2844
+ }
2845
+ } else {
2846
+ lines.push("- **Network**: none");
2847
+ }
2848
+ if (step.matchedInputs.length > 0) {
2849
+ for (const m of step.matchedInputs) {
2850
+ lines.push(`- **Input matched**: "${m.inputValue}" \u2192 ${m.paramName} (network #${m.networkId})`);
2851
+ }
2852
+ }
2853
+ for (const ctx of step.contextChanges) {
2854
+ if (ctx.type === "navigate") {
2855
+ lines.push(`- **Navigate**: \u2192 ${ctx.url}`);
2856
+ } else if (ctx.type === "new_tab") {
2857
+ lines.push(`- **New tab**: ${ctx.url}`);
2858
+ }
2859
+ }
2860
+ if (a.clickContext) {
2861
+ if (a.clickContext.appeared?.length > 0) {
2862
+ for (const popup of a.clickContext.appeared) {
2863
+ const roleStr = popup.role ? ` [${popup.role}]` : "";
2864
+ lines.push(`- **Popup**: <${popup.tag}${roleStr}> "${(popup.text || "").substring(0, 60)}"`);
2865
+ if (popup.items?.length > 0) {
2866
+ const itemStrs = popup.items.slice(0, 8).map((i) => {
2867
+ const dis = i.disabled ? " [disabled]" : "";
2868
+ return `"${i.text}"${dis}`;
2869
+ });
2870
+ let itemLine = ` - Items: ${itemStrs.join(", ")}`;
2871
+ if (popup.items.length > 8) itemLine += ` ... +${popup.items.length - 8} more`;
2872
+ lines.push(itemLine);
2873
+ }
2874
+ }
2875
+ }
2876
+ if (a.clickContext.stateChanges?.length > 0) {
2877
+ for (const sc of a.clickContext.stateChanges) {
2878
+ const parts = [];
2879
+ if (sc.ariaExpanded !== void 0) parts.push(`expanded=${sc.ariaExpanded}`);
2880
+ if (sc.disabled) parts.push("disabled");
2881
+ if (sc.ariaSelected !== void 0) parts.push(`selected=${sc.ariaSelected}`);
2882
+ if (sc.dataState) parts.push(`state=${sc.dataState}`);
2883
+ if (parts.length > 0) {
2884
+ lines.push(`- **State**: <${sc.tag}> "${(sc.text || "").substring(0, 30)}" ${parts.join(", ")}`);
2885
+ }
2886
+ }
2887
+ }
2888
+ }
2889
+ lines.push("");
2890
+ }
2891
+ const allNetwork = summary.steps.flatMap((s) => s.network);
2892
+ if (allNetwork.length > 0) {
2893
+ lines.push("## Network Timeline");
2894
+ lines.push("");
2895
+ allNetwork.forEach((n, i) => {
2896
+ let line = `${i + 1}. ${n.method} ${n.path}`;
2897
+ if (n.status) line += ` \u2192 ${n.status}`;
2898
+ if (n.requestBody && typeof n.requestBody === "object") {
2899
+ const bodyStr = JSON.stringify(n.requestBody);
2900
+ if (bodyStr.length <= 150) {
2901
+ line += ` ${bodyStr}`;
2902
+ }
2903
+ }
2904
+ if (n.responseSize > 0) line += ` (${formatBytes(n.responseSize)})`;
2905
+ lines.push(line);
2906
+ });
2907
+ lines.push("");
2908
+ }
2909
+ const orphanCheckpoints = summary.checkpoints.filter(
2910
+ (cp) => cp.relatedActionId == null || !checkpointSteps.has(
2911
+ summary.steps.find((s) => s.action.id === cp.relatedActionId)?.step ?? -1
2912
+ )
2913
+ );
2914
+ if (orphanCheckpoints.length > 0) {
2915
+ lines.push("## Unresolved Checkpoints");
2916
+ lines.push("");
2917
+ for (const cp of orphanCheckpoints) {
2918
+ const src = cp.source === "auto" ? "[auto]" : "[manual]";
2919
+ lines.push(`- ${src} **${cp.type}**: ${cp.hint}`);
2920
+ if (cp.selector) lines.push(` - Selector: \`${cp.selector}\``);
2921
+ }
2922
+ lines.push("");
2923
+ }
2924
+ return lines.join("\n");
2925
+ }
2926
+ function describeActionTitle(a) {
2927
+ const el = a.element;
2928
+ const elText = el?.text ? `"${el.text.substring(0, 40)}"` : "";
2929
+ const elTag = el?.tag ? `<${el.tag}>` : "";
2930
+ switch (a.type) {
2931
+ case "click":
2932
+ return `Click ${elText || elTag} button`.replace(/ +/g, " ").trim();
2933
+ case "input":
2934
+ return `Input "${(a.value || "").substring(0, 50)}" in ${elText || elTag || "field"}`.replace(/ +/g, " ").trim();
2935
+ case "change":
2936
+ return `Change ${elText || elTag} to "${(a.value || "").substring(0, 30)}"`;
2937
+ case "keydown":
2938
+ return `Press ${a.key || "key"} on ${elText || elTag || "element"}`;
2939
+ case "submit":
2940
+ return `Submit ${elText || elTag || "form"}`;
2941
+ default:
2942
+ return `${a.type} ${elText || elTag}`.trim() || a.type;
2943
+ }
2944
+ }
2945
+ function formatBytes(bytes) {
2946
+ if (bytes < 1024) return `${bytes}B`;
2947
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
2948
+ return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
2949
+ }
2950
+
2951
+ // src/recorder/observation-insights.ts
2952
+ async function detectCheckpoints(page, allocateCheckpointId) {
2953
+ const CHECKPOINT_RULES = [
2954
+ { type: "captcha", selectors: ['img[src*="captcha"]', 'img[src*="verify"]', '[class*="captcha"]', '[id*="captcha"]', "#captcha", ".captcha"] },
2955
+ { type: "slider", selectors: ['[class*="slider"]', '[class*="drag-verify"]', '[class*="slide-verify"]'] },
2956
+ { type: "login", selectors: ['input[type="password"]'] },
2957
+ { type: "iframe", selectors: ['iframe[src*="captcha"]', 'iframe[src*="verify"]', 'iframe[src*="recaptcha"]', 'iframe[title*="captcha"]'] }
2958
+ ];
2959
+ try {
2960
+ const found = await page.evaluate((rules) => {
2961
+ const results = [];
2962
+ for (const rule of rules) {
2963
+ for (const sel of rule.selectors) {
2964
+ try {
2965
+ const el = document.querySelector(sel);
2966
+ if (el) {
2967
+ const rect = el.getBoundingClientRect();
2968
+ if (rect.width > 0 && rect.height > 0) {
2969
+ results.push({
2970
+ type: rule.type,
2971
+ selector: sel,
2972
+ text: (el.textContent || "").substring(0, 60)
2973
+ });
2974
+ }
2975
+ }
2976
+ } catch {
2977
+ }
2978
+ }
2979
+ }
2980
+ return results;
2981
+ }, CHECKPOINT_RULES);
2982
+ const entries = [];
2983
+ for (const item of found) {
2984
+ const id = allocateCheckpointId();
2985
+ ;
2986
+ const hints = {
2987
+ captcha: "Captcha verification detected",
2988
+ slider: "Slider verification detected",
2989
+ login: "Login form detected (password field)",
2990
+ iframe: "Verification iframe detected"
2991
+ };
2992
+ entries.push({
2993
+ id,
2994
+ type: item.type,
2995
+ timestamp: Date.now(),
2996
+ url: page.url(),
2997
+ pageTitle: await page.title().catch(() => ""),
2998
+ hint: hints[item.type] || item.type,
2999
+ selector: item.selector,
3000
+ source: "auto",
3001
+ context: { matchedSelector: item.selector, elementText: item.text }
3002
+ });
3003
+ }
3004
+ return entries;
3005
+ } catch {
3006
+ return [];
3007
+ }
3008
+ }
3009
+ async function verifyAction(page, action, network, checkpoints) {
3010
+ const signals = [];
3011
+ try {
3012
+ const currentUrl = page.url();
3013
+ if (currentUrl && currentUrl !== "about:blank" && currentUrl !== action.url) {
3014
+ signals.push({ type: "url_change", value: currentUrl, label: `URL changed to ${currentUrl}` });
3015
+ }
3016
+ } catch {
3017
+ }
3018
+ try {
3019
+ const recentNetwork = network.filter(
3020
+ (n) => n.timestamp > action.timestamp - 100 && n.timestamp < action.timestamp + 5e3 && n.status >= 200 && n.status < 400
3021
+ );
3022
+ for (const net of recentNetwork.slice(0, 3)) {
3023
+ signals.push({
3024
+ type: "network_success",
3025
+ value: `${net.status}`,
3026
+ label: `${net.method} ${net.path} \u2192 ${net.status}`
3027
+ });
3028
+ }
3029
+ } catch {
3030
+ }
3031
+ try {
3032
+ const recentDialog = [...checkpoints].reverse().find(
3033
+ (cp) => cp.type === "dialog" && Math.abs(cp.timestamp - action.timestamp) < 3e3
3034
+ );
3035
+ if (recentDialog) {
3036
+ signals.push({ type: "dialog", value: recentDialog.type, label: recentDialog.hint });
3037
+ }
3038
+ } catch {
3039
+ }
3040
+ return signals;
3041
+ }
3042
+
3043
+ // src/recorder/page-context.ts
3044
+ import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
3045
+ import { join as join3 } from "path";
3046
+ var SNAPSHOT_TYPES = /* @__PURE__ */ new Set([
3047
+ "click",
3048
+ "dblclick",
3049
+ "navigation",
3050
+ "goto",
3051
+ "submit",
3052
+ "cdp-click",
3053
+ "cdp-fill",
3054
+ "input",
3055
+ "change",
3056
+ "filechooser",
3057
+ "popup_appear"
3058
+ ]);
3059
+ async function captureElementScreenshot(page, action) {
3060
+ const keyTypes = ["click", "input", "change", "dblclick", "cdp-click", "cdp-fill", "filechooser"];
3061
+ if (!keyTypes.includes(action.type)) return;
3062
+ if (!action.element?.selector) return;
3063
+ const selector = action.element.selector;
3064
+ try {
3065
+ const buffer = await page.locator(selector).first().screenshot({
3066
+ type: "png",
3067
+ timeout: 3e3
3068
+ });
3069
+ return buffer.toString("base64");
3070
+ } catch {
3071
+ }
3072
+ try {
3073
+ await page.waitForSelector(selector, { state: "visible", timeout: 2e3 });
3074
+ const buffer = await page.locator(selector).first().screenshot({
3075
+ type: "png",
3076
+ timeout: 3e3
3077
+ });
3078
+ return buffer.toString("base64");
3079
+ } catch {
3080
+ }
3081
+ try {
3082
+ const buffer = await page.screenshot({ type: "png", timeout: 3e3 });
3083
+ return buffer.toString("base64");
3084
+ } catch {
3085
+ return;
3086
+ }
3087
+ }
3088
+ function isSnapshotThrottled(type, selector, snapshotThrottle) {
3089
+ if (type === "input" || type === "change" || type === "cdp-fill") {
3090
+ const key = `${type}|${selector || ""}`;
3091
+ const last = snapshotThrottle.get(key);
3092
+ const now = Date.now();
3093
+ if (last && now - last < 2e3) return true;
3094
+ snapshotThrottle.set(key, now);
3095
+ }
3096
+ return false;
3097
+ }
3098
+ async function captureAutoSnapshot(page, action, suffix = "after", snapshotsDir, snapshotThrottle) {
3099
+ if (!SNAPSHOT_TYPES.has(action.type)) return;
3100
+ if (isSnapshotThrottled(action.type, action.element?.selector, snapshotThrottle)) return;
3101
+ const snapDir = snapshotsDir;
3102
+ mkdirSync2(snapDir, { recursive: true });
3103
+ const stepId = String(action.id).padStart(3, "0");
3104
+ const snapshot = {};
3105
+ try {
3106
+ const pngPath = join3(snapDir, `step-${stepId}-${suffix}.png`);
3107
+ const buffer = await page.screenshot({ type: "png", timeout: 5e3 });
3108
+ writeFileSync2(pngPath, buffer);
3109
+ snapshot.png = `.tmp/snapshots/step-${stepId}-${suffix}.png`;
3110
+ } catch {
3111
+ }
3112
+ try {
3113
+ snapshot.aria = await page.evaluate(`
3114
+ (function() {
3115
+ try {
3116
+ var parts = [];
3117
+ var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT, null, false);
3118
+ var node;
3119
+ while (node = walker.nextNode()) {
3120
+ var tag = node.tagName.toLowerCase();
3121
+ var role = node.getAttribute('role') || '';
3122
+ var text = (node.textContent || '').trim().substring(0, 60);
3123
+ var ariaLabel = node.getAttribute('aria-label') || '';
3124
+ if (role || tag === 'button' || tag === 'a' || tag === 'input' || tag === 'select' || tag === 'textarea') {
3125
+ parts.push((role || tag) + ': ' + (ariaLabel || text).substring(0, 40));
3126
+ }
3127
+ }
3128
+ return parts.slice(0, 100).join(' | ');
3129
+ } catch(e) { return ''; }
3130
+ })()
3131
+ `);
3132
+ } catch {
3133
+ }
3134
+ if (snapshot.png || snapshot.aria) {
3135
+ action.snapshots = snapshot;
3136
+ }
3137
+ }
3138
+ async function captureClickContext(page, cx, cy) {
3139
+ await new Promise((r) => setTimeout(r, 300));
3140
+ try {
3141
+ const ctx = await page.evaluate(`
3142
+ (function() {
3143
+ var cx = ${cx}, cy = ${cy};
3144
+ var POPOVER_SELECTORS = [
3145
+ '[role="menu"]','[role="listbox"]','[role="dialog"]','[role="tooltip"]','[role="popover"]',
3146
+ '[role="combobox"]','[role="tree"]','[role="grid"]',
3147
+ '.popover','.popup','.dropdown','.menu','.modal','.tooltip','.panel',
3148
+ '[class*="popover"]','[class*="popup"]','[class*="dropdown"]','[class*="menu"]',
3149
+ '[class*="tooltip"]','[class*="modal"]','[class*="panel"]','[class*="overlay"]','[class*="sheet"]',
3150
+ '[data-popup]','[data-dropdown]','[data-menu]','[data-popover"]',
3151
+ '.semi-dropdown','.semi-popover','.semi-modal',
3152
+ '.ant-dropdown','.ant-popover','.ant-modal',
3153
+ '.el-dropdown','.el-popover','.el-dialog',
3154
+ '.t-dropdown','.t-popup','.t-dialog'
3155
+ ];
3156
+
3157
+ function isNear(el, x, y, range) {
3158
+ try {
3159
+ var r = el.getBoundingClientRect();
3160
+ if (!r || r.width === 0 || r.height === 0) return false;
3161
+ return !(r.left > x + range || r.right < x - range || r.top > y + range || r.bottom < y - range);
3162
+ } catch(e) { return false; }
3163
+ }
3164
+
3165
+ var result = { appeared: [], disappeared: [], stateChanges: [] };
3166
+ var seenElements = new Set();
3167
+
3168
+ for (var si = 0; si < POPOVER_SELECTORS.length; si++) {
3169
+ try {
3170
+ var els = document.querySelectorAll(POPOVER_SELECTORS[si]);
3171
+ for (var j = 0; j < els.length; j++) {
3172
+ var el = els[j];
3173
+ if (seenElements.has(el)) continue;
3174
+ if (!isNear(el, cx, cy, 300)) continue;
3175
+ var rect = el.getBoundingClientRect();
3176
+ if (rect.width === 0 || rect.height === 0) continue;
3177
+ seenElements.add(el);
3178
+
3179
+ var items = [];
3180
+ var children = el.querySelectorAll('a,button,[role="menuitem"],[role="option"],[role="treeitem"],li,div[class*="item"]');
3181
+ var seenItemTexts = new Set();
3182
+ for (var k = 0; k < Math.min(children.length, 30); k++) {
3183
+ var child = children[k];
3184
+ var childText = (child.textContent || '').trim().substring(0, 60);
3185
+ if (!childText || seenItemTexts.has(childText)) continue;
3186
+ seenItemTexts.add(childText);
3187
+ var ci = { text: childText };
3188
+ try { if (child.disabled || child.getAttribute('aria-disabled') === 'true') ci.disabled = true; } catch(e) {}
3189
+ try { if (child.tagName) ci.tag = child.tagName.toLowerCase(); } catch(e) {}
3190
+ try { if (child.href) ci.href = child.href.substring(0, 80); } catch(e) {}
3191
+ items.push(ci);
3192
+ }
3193
+
3194
+ result.appeared.push({
3195
+ tag: el.tagName.toLowerCase(),
3196
+ selector: el.id ? '#' + el.id : undefined,
3197
+ role: el.getAttribute('role'),
3198
+ text: (el.textContent || '').trim().substring(0, 100),
3199
+ rect: { x: Math.round(rect.x), y: Math.round(rect.y), w: Math.round(rect.width), h: Math.round(rect.height) },
3200
+ items: items
3201
+ });
3202
+ }
3203
+ } catch(e) { /* skip invalid selectors */ }
3204
+ }
3205
+
3206
+ var allInteractive = document.querySelectorAll('[aria-expanded],[disabled],[aria-disabled],[aria-selected],[data-state]');
3207
+ for (var i = 0; i < allInteractive.length; i++) {
3208
+ var el2 = allInteractive[i];
3209
+ if (!isNear(el2, cx, cy, 200)) continue;
3210
+ var info = { tag: el2.tagName.toLowerCase(), text: (el2.textContent || '').trim().substring(0, 60) };
3211
+ try { if (el2.id) info.id = el2.id; } catch(e) {}
3212
+ try { if (el2.getAttribute('aria-expanded')) info.ariaExpanded = el2.getAttribute('aria-expanded'); } catch(e) {}
3213
+ try { if (el2.disabled || el2.getAttribute('aria-disabled') === 'true') info.disabled = true; } catch(e) {}
3214
+ try { if (el2.getAttribute('aria-selected')) info.ariaSelected = el2.getAttribute('aria-selected'); } catch(e) {}
3215
+ try { if (el2.getAttribute('data-state')) info.dataState = el2.getAttribute('data-state'); } catch(e) {}
3216
+ result.stateChanges.push(info);
3217
+ }
3218
+
3219
+ return result;
3220
+ })()
3221
+ `);
3222
+ if (ctx.appeared.length > 0 || ctx.stateChanges.length > 0) {
3223
+ return ctx;
3224
+ }
3225
+ } catch {
3226
+ }
3227
+ return void 0;
3228
+ }
3229
+
3230
+ // src/recorder/session-recorder.ts
3231
+ var SessionRecorder = class _SessionRecorder {
3232
+ context;
3233
+ page;
3234
+ sessionName;
3235
+ startUrl = "";
3236
+ startedAt = 0;
3237
+ actions = [];
3238
+ networkCapture = createNetworkCaptureState();
3239
+ contextChanges = [];
3240
+ checkpoints = [];
3241
+ /** Proactive baseline scan of filter/sort/tab/menu regions. Keyed by
3242
+ * containerSelector so re-scans after navigation replace rather than dup. */
3243
+ discoveredFilters = /* @__PURE__ */ new Map();
3244
+ actionCounter = 0;
3245
+ contextCounter = 0;
3246
+ checkpointCounter = 0;
3247
+ pollTimer = null;
3248
+ flushTimer = null;
3249
+ lastActionTs = 0;
3250
+ activePages = /* @__PURE__ */ new Set();
3251
+ lastKnownUrl = "";
3252
+ dedupMap = /* @__PURE__ */ new Map();
3253
+ dedupActionCount = 0;
3254
+ _isRecording = false;
3255
+ streamMode = "clean";
3256
+ snapshotThrottle = /* @__PURE__ */ new Map();
3257
+ static AMBIENT_TYPES = /* @__PURE__ */ new Set([
3258
+ "hover",
3259
+ "focus",
3260
+ "scroll",
3261
+ "visibility",
3262
+ "resize",
3263
+ "clipboard",
3264
+ "touch",
3265
+ "contextmenu"
3266
+ ]);
3267
+ constructor(context, page, sessionName) {
3268
+ this.context = context;
3269
+ this.page = page;
3270
+ this.sessionName = sessionName;
3271
+ }
3272
+ get isRecording() {
3273
+ return this._isRecording;
3274
+ }
3275
+ get actionCount() {
3276
+ return this.actions.length;
3277
+ }
3278
+ /** Record an action triggered by a CDP command (e.g. xbrowser fill/click/goto) */
3279
+ async recordCommandAction(action) {
3280
+ const dedupFromAction = this.dedupKey(action.type, action.selector, action.element?.tag, action.value);
3281
+ if (dedupFromAction) {
3282
+ const entry = this.dedupMap.get(dedupFromAction);
3283
+ if (entry && entry.origin === "signal" && Date.now() < entry.expires) {
3284
+ return;
3285
+ }
3286
+ }
3287
+ this.actionCounter++;
3288
+ const ts = Date.now();
3289
+ const actionUrl = action.url && action.url !== "about:blank" ? action.url : this.lastKnownUrl || this.page.url();
3290
+ const actionToPush = {
3291
+ id: this.actionCounter,
3292
+ type: action.type,
3293
+ timestamp: ts,
3294
+ url: actionUrl,
3295
+ pageTitle: "",
3296
+ element: action.element || (action.selector ? { tag: "", selector: action.selector, text: "" } : void 0),
3297
+ value: action.value
3298
+ };
3299
+ this.actions.push(actionToPush);
3300
+ actionToPush.elementScreenshot = await Promise.race([
3301
+ captureElementScreenshot(this.page, {
3302
+ type: action.type,
3303
+ element: actionToPush.element
3304
+ }).catch(() => void 0),
3305
+ new Promise((r) => setTimeout(r, 3e3))
3306
+ ]);
3307
+ await Promise.race([
3308
+ captureAutoSnapshot(this.page, actionToPush, "after", this.snapshotsDir, this.snapshotThrottle).catch(() => {
3309
+ }),
3310
+ new Promise((r) => setTimeout(r, 6e3))
3311
+ ]);
3312
+ this.lastActionTs = ts;
3313
+ this.dedupMap.set(dedupFromAction, { expires: Date.now() + 4e3, origin: "command" });
3314
+ this.dedupActionCount++;
3315
+ if (this.dedupActionCount % 200 === 0) {
3316
+ const now = Date.now();
3317
+ for (const [k, v] of this.dedupMap) {
3318
+ if (now >= v.expires) this.dedupMap.delete(k);
3319
+ }
3320
+ }
3321
+ if (action.url && action.url !== "about:blank") {
3322
+ this.lastKnownUrl = action.url;
3323
+ } else if (action.type === "goto" && action.value && action.value !== "about:blank") {
3324
+ this.lastKnownUrl = action.value;
3325
+ }
3326
+ }
3327
+ /** Generate dedup key for an action (normalized type + selector/tag + value). */
3328
+ dedupKey(type, selector, tag, value) {
3329
+ const normType = type === "cdp-click" ? "click" : type === "cdp-fill" ? "input" : type === "cdp-eval" ? "eval" : type;
3330
+ const selOrTag = selector || tag || "";
3331
+ return `${normType}|${selOrTag}|${value || ""}`;
3332
+ }
3333
+ get networkCount() {
3334
+ return this.networkCapture.entries.length;
3335
+ }
3336
+ getLiveData() {
3337
+ return this.buildData();
3338
+ }
3339
+ addManualCheckpoint(type, hint, selector) {
3340
+ this.checkpointCounter++;
3341
+ const cp = {
3342
+ id: this.checkpointCounter,
3343
+ type,
3344
+ timestamp: Date.now(),
3345
+ url: this.page.url(),
3346
+ pageTitle: "",
3347
+ hint,
3348
+ selector,
3349
+ source: "manual"
3350
+ };
3351
+ this.checkpoints.push(cp);
3352
+ return cp;
3353
+ }
3354
+ /** Directory for this session's recordings. */
3355
+ get recordingsDir() {
3356
+ return _SessionRecorder.getRecordingsDir(this.sessionName);
3357
+ }
3358
+ /** Directory for auto-captured snapshots (PNG screenshots, stored in .tmp for easy cleanup). */
3359
+ get snapshotsDir() {
3360
+ return join4(this.recordingsDir, ".tmp", "snapshots");
3361
+ }
3362
+ static getRecordingsDir(sessionName) {
3363
+ return join4(homedir3(), ".xbrowser", "sessions", sessionName, "recordings");
3364
+ }
3365
+ /** Path to the control file (used by record stop to signal this process). */
3366
+ get controlFilePath() {
3367
+ return join4(this.recordingsDir, ".control.json");
3368
+ }
3369
+ /** Path to the stop signal file (written by `record stop`). */
3370
+ get stopSignalPath() {
3371
+ return join4(this.recordingsDir, ".stop");
3372
+ }
3373
+ // ─── Start ──────────────────────────────────────────────────────
3374
+ async start(url, options) {
3375
+ if (this._isRecording) throw new Error("Already recording");
3376
+ this._isRecording = true;
3377
+ this.startedAt = Date.now();
2622
3378
  this.actions = [];
2623
- this.network = [];
2624
3379
  this.contextChanges = [];
2625
3380
  this.checkpoints = [];
2626
3381
  this.checkpointCounter = 0;
@@ -2645,14 +3400,14 @@ var SessionRecorder = class _SessionRecorder {
2645
3400
  } else {
2646
3401
  this.startUrl = this.page.url();
2647
3402
  }
2648
- mkdirSync2(this.recordingsDir, { recursive: true });
3403
+ mkdirSync3(this.recordingsDir, { recursive: true });
2649
3404
  const control = {
2650
3405
  pid: process.pid,
2651
3406
  startedAt: new Date(this.startedAt).toISOString(),
2652
3407
  startUrl: this.startUrl,
2653
3408
  sessionName: this.sessionName
2654
3409
  };
2655
- writeFileSync2(this.controlFilePath, JSON.stringify(control, null, 2), "utf-8");
3410
+ writeFileSync3(this.controlFilePath, JSON.stringify(control, null, 2), "utf-8");
2656
3411
  await this.injectActionScript(this.page);
2657
3412
  this.context.on("page", this.handleNewPage);
2658
3413
  this.pollTimer = setInterval(() => void this.pollActions(), 200);
@@ -2687,21 +3442,21 @@ var SessionRecorder = class _SessionRecorder {
2687
3442
  });
2688
3443
  }
2689
3444
  const data = this.buildData();
2690
- const summary = this.buildSummary(data);
3445
+ const summary = buildSummary(data, this.startedAt);
2691
3446
  this.writeFinalOutput(data, summary);
2692
3447
  try {
2693
3448
  const knowledge = updateSiteKnowledge(data);
2694
- const knowledgeDir = join2(this.recordingsDir, "site-knowledge.md");
2695
- const knowledgeJson = join2(this.recordingsDir, "site-knowledge.json");
3449
+ const knowledgeDir = join4(this.recordingsDir, "site-knowledge.md");
3450
+ const knowledgeJson = join4(this.recordingsDir, "site-knowledge.json");
2696
3451
  const { readFileSync: rf } = __require("fs");
2697
3452
  const { getKnowledgePath: getKnowledgePath2 } = (init_site_knowledge(), __toCommonJS(site_knowledge_exports));
2698
3453
  const mdPath = getKnowledgePath2(knowledge.domain, "md");
2699
3454
  try {
2700
3455
  const md = rf(mdPath, "utf-8");
2701
- writeFileSync2(knowledgeDir, md, "utf-8");
3456
+ writeFileSync3(knowledgeDir, md, "utf-8");
2702
3457
  } catch {
2703
3458
  }
2704
- writeFileSync2(knowledgeJson, JSON.stringify(knowledge, null, 2), "utf-8");
3459
+ writeFileSync3(knowledgeJson, JSON.stringify(knowledge, null, 2), "utf-8");
2705
3460
  } catch {
2706
3461
  }
2707
3462
  try {
@@ -2721,261 +3476,96 @@ var SessionRecorder = class _SessionRecorder {
2721
3476
  rmSync(dir, { recursive: true, force: true });
2722
3477
  }
2723
3478
  }
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
- }
3479
+ // ─── Wait for stop signal (blocks the process) ──────────────────
3480
+ waitForStopSignal() {
3481
+ return new Promise((resolve) => {
3482
+ const check = () => {
3483
+ if (existsSync2(this.stopSignalPath)) {
3484
+ resolve();
3485
+ } else {
3486
+ setTimeout(check, 300);
2945
3487
  }
2946
- } catch {
2947
- }
3488
+ };
3489
+ check();
3490
+ });
3491
+ }
3492
+ // ─── Static: send stop signal to a running recorder ─────────────
3493
+ static async sendStopSignal(sessionName) {
3494
+ const dir = _SessionRecorder.getRecordingsDir(sessionName);
3495
+ const controlPath = join4(dir, ".control.json");
3496
+ const stopPath = join4(dir, ".stop");
3497
+ if (!existsSync2(controlPath)) return null;
3498
+ const control = JSON.parse(readFileSync3(controlPath, "utf-8"));
3499
+ let alive = false;
3500
+ try {
3501
+ process.kill(control.pid, 0);
3502
+ alive = true;
3503
+ } catch {
3504
+ alive = false;
2948
3505
  }
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) {
3506
+ if (!alive) {
2961
3507
  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
- }
3508
+ rmSync(controlPath);
2971
3509
  } catch {
2972
3510
  }
2973
- } else {
3511
+ return control;
3512
+ }
3513
+ mkdirSync3(dir, { recursive: true });
3514
+ writeFileSync3(stopPath, JSON.stringify({ stoppedAt: (/* @__PURE__ */ new Date()).toISOString() }), "utf-8");
3515
+ for (let i = 0; i < 50; i++) {
3516
+ await new Promise((r) => setTimeout(r, 200));
3517
+ if (!existsSync2(controlPath)) return control;
2974
3518
  try {
2975
- entry.responseSize = parseInt(response.headers()["content-length"] || "0", 10);
3519
+ process.kill(control.pid, 0);
2976
3520
  } catch {
3521
+ try {
3522
+ rmSync(controlPath);
3523
+ } catch {
3524
+ }
3525
+ return control;
2977
3526
  }
2978
3527
  }
3528
+ try {
3529
+ rmSync(controlPath);
3530
+ } catch {
3531
+ }
3532
+ return control;
3533
+ }
3534
+ // ─── Static: read recording from disk ───────────────────────────
3535
+ static readSummary(sessionName) {
3536
+ const path = join4(_SessionRecorder.getRecordingsDir(sessionName), "summary.json");
3537
+ try {
3538
+ return JSON.parse(readFileSync3(path, "utf-8"));
3539
+ } catch {
3540
+ return null;
3541
+ }
3542
+ }
3543
+ static readData(sessionName) {
3544
+ const path = join4(_SessionRecorder.getRecordingsDir(sessionName), "recording.json");
3545
+ try {
3546
+ return JSON.parse(readFileSync3(path, "utf-8"));
3547
+ } catch {
3548
+ return null;
3549
+ }
3550
+ }
3551
+ // ==================== Private ====================
3552
+ /** Whether the initial action-signal script injection succeeded. Check this
3553
+ * after start() returns — if false, user actions will NOT be recorded and
3554
+ * the caller should surface a clear error to the user instead of silently
3555
+ * pretending recording is working. */
3556
+ _injectionFailed = false;
3557
+ get injectionFailed() {
3558
+ return this._injectionFailed;
3559
+ }
3560
+ async injectActionScript(page) {
3561
+ this._injectionFailed = !await injectActionScript(page);
3562
+ }
3563
+ // ─── Network capture ────────────────────────────────────────────
3564
+ handleRequest = (request) => {
3565
+ handleNetworkRequest(request, this.networkCapture);
3566
+ };
3567
+ handleResponse = async (response) => {
3568
+ await handleNetworkResponse(response, this.networkCapture);
2979
3569
  };
2980
3570
  // ─── Page tracking ──────────────────────────────────────────────
2981
3571
  handleNewPage = async (page) => {
@@ -3265,7 +3855,7 @@ var SessionRecorder = class _SessionRecorder {
3265
3855
  popupAppear: raw.popupAppear
3266
3856
  };
3267
3857
  this.actions.push(pushed2);
3268
- await this.captureAutoSnapshot(page, pushed2, "after").catch(() => {
3858
+ await captureAutoSnapshot(page, pushed2, "after", this.snapshotsDir, this.snapshotThrottle).catch(() => {
3269
3859
  });
3270
3860
  this.lastActionTs = raw.ts;
3271
3861
  continue;
@@ -3295,7 +3885,7 @@ var SessionRecorder = class _SessionRecorder {
3295
3885
  this.actionCounter++;
3296
3886
  let clickContext;
3297
3887
  if (raw.type === "click" && raw.x !== void 0 && raw.y !== void 0) {
3298
- clickContext = await this.captureClickContext(page, raw.x, raw.y);
3888
+ clickContext = await captureClickContext(page, raw.x, raw.y);
3299
3889
  }
3300
3890
  this.actions.push({
3301
3891
  id: this.actionCounter,
@@ -3322,8 +3912,8 @@ var SessionRecorder = class _SessionRecorder {
3322
3912
  drag: raw.drag
3323
3913
  });
3324
3914
  const pushed = this.actions[this.actions.length - 1];
3325
- pushed.elementScreenshot = await this.captureElementScreenshot(page, raw);
3326
- await this.captureAutoSnapshot(page, pushed, "after").catch(() => {
3915
+ pushed.elementScreenshot = await captureElementScreenshot(page, raw);
3916
+ await captureAutoSnapshot(page, pushed, "after", this.snapshotsDir, this.snapshotThrottle).catch(() => {
3327
3917
  });
3328
3918
  this.lastActionTs = raw.ts;
3329
3919
  const dedupKey = this.dedupKey(raw.type, raw.element?.selector, raw.element?.tag, raw.value);
@@ -3333,13 +3923,13 @@ var SessionRecorder = class _SessionRecorder {
3333
3923
  }
3334
3924
  const verifyTypes = /* @__PURE__ */ new Set(["click", "submit", "input", "change", "cdp-click", "cdp-fill"]);
3335
3925
  if (verifyTypes.has(raw.type)) {
3336
- const signals = await this.verifyAction(page, pushed).catch(() => []);
3926
+ const signals = await verifyAction(page, pushed, this.networkCapture.entries, this.checkpoints).catch(() => []);
3337
3927
  if (signals.length > 0) {
3338
3928
  pushed.__signals = signals;
3339
3929
  }
3340
3930
  }
3341
3931
  if (raw.type === "click" || raw.type === "navigate" || raw.type === "submit") {
3342
- const detected = await this.detectCheckpoints(page);
3932
+ const detected = await detectCheckpoints(page, () => ++this.checkpointCounter);
3343
3933
  for (const cp of detected) {
3344
3934
  cp.relatedActionId = this.actionCounter;
3345
3935
  this.checkpoints.push(cp);
@@ -3347,339 +3937,29 @@ var SessionRecorder = class _SessionRecorder {
3347
3937
  }
3348
3938
  }
3349
3939
  }
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
3940
  // ─── Periodic disk flush ────────────────────────────────────────
3661
3941
  flushToDisk() {
3662
3942
  const data = this.buildData();
3663
3943
  try {
3664
- writeFileSync2(
3665
- join2(this.recordingsDir, "recording.json"),
3944
+ writeFileSync3(
3945
+ join4(this.recordingsDir, "recording.json"),
3666
3946
  JSON.stringify(data, null, 2),
3667
3947
  "utf-8"
3668
3948
  );
3669
- const jsonlPath = join2(this.recordingsDir, "recording.jsonl");
3949
+ const jsonlPath = join4(this.recordingsDir, "recording.jsonl");
3670
3950
  const lines = data.actions.map((a) => JSON.stringify(a)).join("\n") + "\n";
3671
- writeFileSync2(jsonlPath, lines, "utf-8");
3951
+ writeFileSync3(jsonlPath, lines, "utf-8");
3672
3952
  } catch {
3673
3953
  }
3674
3954
  }
3675
3955
  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");
3956
+ mkdirSync3(this.recordingsDir, { recursive: true });
3957
+ writeFileSync3(join4(this.recordingsDir, "recording.json"), JSON.stringify(data, null, 2), "utf-8");
3958
+ const jsonlPath = join4(this.recordingsDir, "recording.jsonl");
3679
3959
  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");
3960
+ writeFileSync3(jsonlPath, lines, "utf-8");
3961
+ writeFileSync3(join4(this.recordingsDir, "summary.json"), JSON.stringify(summary, null, 2), "utf-8");
3962
+ writeFileSync3(join4(this.recordingsDir, "summary.md"), buildMarkdownSummary(data, summary), "utf-8");
3683
3963
  }
3684
3964
  buildData() {
3685
3965
  return {
@@ -3687,320 +3967,13 @@ var SessionRecorder = class _SessionRecorder {
3687
3967
  sessionName: this.sessionName,
3688
3968
  startedAt: new Date(this.startedAt).toISOString(),
3689
3969
  actions: [...this.actions],
3690
- network: [...this.network],
3970
+ network: [...this.networkCapture.entries],
3691
3971
  contextChanges: [...this.contextChanges],
3692
3972
  checkpoints: [...this.checkpoints],
3693
3973
  discoveredFilters: [...this.discoveredFilters.values()]
3694
3974
  };
3695
3975
  }
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
3976
  };
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
3977
 
4005
3978
  export {
4006
3979
  SessionRecorder