@xbrowser/cli 1.28.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-WK3INZLA.js → chunk-GDKKVT2P.js} +750 -651
  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-OEC7ZSFW.js → chunk-SCYBNSOG.js} +1560 -1461
  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 +737 -707
  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-JXF3JOAM.js → server-LNZTDAKT.js} +4 -4
  31. package/dist/{server-26SE6YZR.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
@@ -9,9 +9,81 @@ import {
9
9
  } from "./chunk-KFQGP6VL.js";
10
10
 
11
11
  // src/recorder/session-recorder.ts
12
- import { existsSync, mkdirSync, writeFileSync, readFileSync, rmSync } from "fs";
13
- import { join } from "path";
14
- import { homedir } from "os";
12
+ init_site_knowledge();
13
+ import { existsSync, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2, readFileSync as readFileSync2, rmSync } from "fs";
14
+ import { join as join3 } from "path";
15
+ import { homedir as homedir2 } from "os";
16
+
17
+ // src/recorder/network-capture.ts
18
+ function createNetworkCaptureState() {
19
+ return { entries: [], counter: { value: 0 }, lastRequestKey: "", lastRequestTs: 0 };
20
+ }
21
+ function handleNetworkRequest(request, state) {
22
+ const resourceType = request.resourceType();
23
+ if (["image", "stylesheet", "font", "manifest", "other"].includes(resourceType)) return;
24
+ const url = request.url();
25
+ if (url.startsWith("data:") || url.startsWith("chrome-extension://") || url.startsWith("blob:")) return;
26
+ const dedupKey = request.method() + " " + url;
27
+ const now = Date.now();
28
+ if (state.lastRequestKey === dedupKey && now - state.lastRequestTs < 100) return;
29
+ state.lastRequestKey = dedupKey;
30
+ state.lastRequestTs = now;
31
+ state.counter.value++;
32
+ const entry = {
33
+ id: state.counter.value,
34
+ timestamp: Date.now(),
35
+ method: request.method(),
36
+ url,
37
+ path: new URL(url).pathname,
38
+ status: 0,
39
+ resourceType,
40
+ contentType: "",
41
+ responseSize: 0
42
+ };
43
+ if (["POST", "PATCH", "PUT"].includes(request.method())) {
44
+ try {
45
+ const postData = request.postData();
46
+ if (postData) {
47
+ try {
48
+ entry.requestBody = JSON.parse(postData);
49
+ } catch {
50
+ entry.requestBody = postData.substring(0, 500);
51
+ }
52
+ }
53
+ } catch {
54
+ }
55
+ }
56
+ state.entries.push(entry);
57
+ }
58
+ async function handleNetworkResponse(response, state) {
59
+ const url = response.url();
60
+ if (url.startsWith("data:") || url.startsWith("chrome-extension://") || url.startsWith("blob:")) return;
61
+ const entry = [...state.entries].reverse().find((e) => e.url === url && e.status === 0);
62
+ if (!entry) return;
63
+ entry.status = response.status();
64
+ entry.contentType = response.headers()["content-type"] || "";
65
+ const resourceType = response.request().resourceType();
66
+ const isApi = ["fetch", "xhr"].includes(resourceType) || entry.contentType.includes("json") || entry.contentType.includes("text/");
67
+ if (isApi) {
68
+ try {
69
+ const text = await response.text();
70
+ entry.responseSize = text.length;
71
+ if (text.length <= 20480) {
72
+ try {
73
+ entry.responseBody = JSON.parse(text);
74
+ } catch {
75
+ entry.responseBody = text.substring(0, 500);
76
+ }
77
+ }
78
+ } catch {
79
+ }
80
+ } else {
81
+ try {
82
+ entry.responseSize = parseInt(response.headers()["content-length"] || "0", 10);
83
+ } catch {
84
+ }
85
+ }
86
+ }
15
87
 
16
88
  // src/recorder/selector-utils.ts
17
89
  function getSelectorGeneratorScript() {
@@ -275,8 +347,7 @@ function getSelectorGeneratorScript() {
275
347
  `;
276
348
  }
277
349
 
278
- // src/recorder/session-recorder.ts
279
- init_site_knowledge();
350
+ // src/recorder/injection-scripts.ts
280
351
  var ACTION_SIGNAL_SCRIPT = `
281
352
  (function() {
282
353
  if (window.__xb_action_signal) return;
@@ -2064,170 +2135,862 @@ var CHECKPOINT_OVERLAY_SCRIPT = `
2064
2135
  }, true);
2065
2136
  })();
2066
2137
  `;
2067
- var SessionRecorder = class _SessionRecorder {
2068
- context;
2069
- page;
2070
- sessionName;
2071
- startUrl = "";
2072
- startedAt = 0;
2073
- actions = [];
2074
- network = [];
2075
- contextChanges = [];
2076
- checkpoints = [];
2077
- /** Proactive baseline scan of filter/sort/tab/menu regions. Keyed by
2078
- * containerSelector so re-scans after navigation replace rather than dup. */
2079
- discoveredFilters = /* @__PURE__ */ new Map();
2080
- actionCounter = 0;
2081
- networkCounter = 0;
2082
- contextCounter = 0;
2083
- checkpointCounter = 0;
2084
- pollTimer = null;
2085
- flushTimer = null;
2086
- lastActionTs = 0;
2087
- activePages = /* @__PURE__ */ new Set();
2088
- lastKnownUrl = "";
2089
- // Track URL to detect real navigation changes
2090
- /** Dedup map: key = normalizedType|tag|value → expiration timestamp.
2091
- * Replaces old single-entry cdpActionDedup for bidirectional dedup. */
2092
- dedupMap = /* @__PURE__ */ new Map();
2093
- dedupActionCount = 0;
2094
- // counter for periodic cleanup
2095
- /** Network dedup: last request key for short-window dedup */
2096
- _lastRequestKey = "";
2097
- _lastRequestTs = 0;
2098
- _isRecording = false;
2099
- streamMode = "clean";
2100
- /** Snapshot throttle: prevents too many screenshots during rapid inputs.
2101
- * Keyed by 'type|elementSelector', value = last snapshot timestamp. */
2102
- snapshotThrottle = /* @__PURE__ */ new Map();
2103
- /** Ambient action types: filtered out in clean mode */
2104
- static AMBIENT_TYPES = /* @__PURE__ */ new Set([
2105
- "hover",
2106
- "focus",
2107
- "scroll",
2108
- "visibility",
2109
- "resize",
2110
- "clipboard",
2111
- "touch",
2112
- "contextmenu"
2113
- ]);
2114
- constructor(context, page, sessionName) {
2115
- this.context = context;
2116
- this.page = page;
2117
- this.sessionName = sessionName;
2118
- }
2119
- get isRecording() {
2120
- return this._isRecording;
2121
- }
2122
- get actionCount() {
2123
- return this.actions.length;
2124
- }
2125
- /** Record an action triggered by a CDP command (e.g. xbrowser fill/click/goto) */
2126
- async recordCommandAction(action) {
2127
- const dedupFromAction = this.dedupKey(action.type, action.selector, action.element?.tag, action.value);
2128
- if (dedupFromAction) {
2129
- const entry = this.dedupMap.get(dedupFromAction);
2130
- if (entry && entry.origin === "signal" && Date.now() < entry.expires) {
2131
- return;
2132
- }
2133
- }
2134
- this.actionCounter++;
2135
- const ts = Date.now();
2136
- const actionUrl = action.url && action.url !== "about:blank" ? action.url : this.lastKnownUrl || this.page.url();
2137
- const actionToPush = {
2138
- id: this.actionCounter,
2139
- type: action.type,
2140
- timestamp: ts,
2141
- url: actionUrl,
2142
- pageTitle: "",
2143
- element: action.element || (action.selector ? { tag: "", selector: action.selector, text: "" } : void 0),
2144
- value: action.value
2145
- };
2146
- this.actions.push(actionToPush);
2147
- actionToPush.elementScreenshot = await Promise.race([
2148
- this.captureElementScreenshot(this.page, {
2149
- type: action.type,
2150
- element: actionToPush.element
2151
- }).catch(() => void 0),
2152
- new Promise((r) => setTimeout(r, 3e3))
2153
- ]);
2154
- await Promise.race([
2155
- this.captureAutoSnapshot(this.page, actionToPush, "after").catch(() => {
2156
- }),
2157
- new Promise((r) => setTimeout(r, 6e3))
2158
- ]);
2159
- this.lastActionTs = ts;
2160
- this.dedupMap.set(dedupFromAction, { expires: Date.now() + 4e3, origin: "command" });
2161
- this.dedupActionCount++;
2162
- if (this.dedupActionCount % 200 === 0) {
2163
- const now = Date.now();
2164
- for (const [k, v] of this.dedupMap) {
2165
- if (now >= v.expires) this.dedupMap.delete(k);
2138
+
2139
+ // src/recorder/script-injector.ts
2140
+ async function injectActionScript(page) {
2141
+ let success = false;
2142
+ const maxAttempts = 3;
2143
+ let lastError = "";
2144
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
2145
+ try {
2146
+ await page.evaluate(getSelectorGeneratorScript());
2147
+ await page.evaluate(ACTION_SIGNAL_SCRIPT);
2148
+ await page.evaluate(`window.__xb_action_script_src = ${JSON.stringify(ACTION_SIGNAL_SCRIPT)};`);
2149
+ const injected = await page.evaluate(`(function() {
2150
+ try { return !!window.__xb_action_signal; } catch(e) { return false; }
2151
+ })()`).catch(() => false);
2152
+ if (injected) {
2153
+ success = true;
2154
+ break;
2166
2155
  }
2156
+ lastError = "verification failed (script did not set __xb_action_signal flag)";
2157
+ console.error(`[recorder] Action signal injection verification failed (attempt ${attempt}/${maxAttempts})`);
2158
+ } catch (e) {
2159
+ const err = e instanceof Error ? e : new Error(typeof e === "string" ? e : "unknown error");
2160
+ lastError = err.message;
2161
+ console.error(`[recorder] Action signal injection error (attempt ${attempt}/${maxAttempts}): ${err.message}`);
2167
2162
  }
2168
- if (action.url && action.url !== "about:blank") {
2169
- this.lastKnownUrl = action.url;
2170
- } else if (action.type === "goto" && action.value && action.value !== "about:blank") {
2171
- this.lastKnownUrl = action.value;
2163
+ if (attempt < maxAttempts) {
2164
+ await new Promise((r) => setTimeout(r, 1e3));
2172
2165
  }
2173
2166
  }
2174
- /** Generate dedup key for an action (normalized type + selector/tag + value). */
2175
- dedupKey(type, selector, tag, value) {
2176
- const normType = type === "cdp-click" ? "click" : type === "cdp-fill" ? "input" : type === "cdp-eval" ? "eval" : type;
2177
- const selOrTag = selector || tag || "";
2178
- return `${normType}|${selOrTag}|${value || ""}`;
2167
+ if (!success) {
2168
+ console.error(`[recorder] WARNING: Action signal injection FAILED after ${maxAttempts} attempts. User actions will NOT be recorded. Last error: ${lastError}`);
2179
2169
  }
2180
- get networkCount() {
2181
- return this.network.length;
2170
+ try {
2171
+ await page.evaluate(CHECKPOINT_OVERLAY_SCRIPT);
2172
+ } catch (e) {
2173
+ const msg = e instanceof Error ? e.message : String(e);
2174
+ console.error(`[recorder] Checkpoint overlay injection failed (non-fatal): ${msg}`);
2182
2175
  }
2183
- getLiveData() {
2184
- return this.buildData();
2176
+ if (success) {
2177
+ try {
2178
+ await page.evaluate(`(function() {
2179
+ if (typeof window.__xb_scanFilters === 'function') {
2180
+ setTimeout(window.__xb_scanFilters, 100);
2181
+ }
2182
+ })()`);
2183
+ } catch {
2184
+ }
2185
2185
  }
2186
- addManualCheckpoint(type, hint, selector) {
2187
- this.checkpointCounter++;
2188
- const cp = {
2189
- id: this.checkpointCounter,
2190
- type,
2191
- timestamp: Date.now(),
2192
- url: this.page.url(),
2193
- pageTitle: "",
2194
- hint,
2195
- selector,
2196
- source: "manual"
2197
- };
2198
- this.checkpoints.push(cp);
2199
- return cp;
2186
+ try {
2187
+ await page.evaluate(`
2188
+ (function() {
2189
+ var _scriptSrc = ${JSON.stringify(ACTION_SIGNAL_SCRIPT)};
2190
+ function injectIframe(iframe) {
2191
+ try {
2192
+ var w = iframe.contentWindow;
2193
+ if (!w) return;
2194
+ // Force re-injection: clear old flag
2195
+ try { delete w.__xb_action_signal; } catch(e) {}
2196
+ w.eval(_scriptSrc);
2197
+ // Tag iframe so flushIframes knows it's injected
2198
+ iframe.__xb_injected = true;
2199
+ } catch(e) {}
2200
+ }
2201
+ function watchIframe(iframe) {
2202
+ if (iframe.__xb_watched) return;
2203
+ iframe.__xb_watched = true;
2204
+ injectIframe(iframe);
2205
+ iframe.addEventListener('load', function() { injectIframe(iframe); });
2206
+ }
2207
+ // Inject into existing iframes
2208
+ try {
2209
+ var iframes = document.querySelectorAll('iframe');
2210
+ for (var i = 0; i < iframes.length; i++) watchIframe(iframes[i]);
2211
+ } catch(e) {}
2212
+ // Watch for dynamically inserted iframes
2213
+ if (!window.__xb_iframe_observer) {
2214
+ window.__xb_iframe_observer = new MutationObserver(function(mutations) {
2215
+ for (var m = 0; m < mutations.length; m++) {
2216
+ for (var n = 0; n < mutations[m].addedNodes.length; n++) {
2217
+ var node = mutations[m].addedNodes[n];
2218
+ if (node.tagName === 'IFRAME') {
2219
+ watchIframe(node);
2220
+ } else if (node.querySelectorAll) {
2221
+ var sub = node.querySelectorAll('iframe');
2222
+ for (var k = 0; k < sub.length; k++) watchIframe(sub[k]);
2223
+ }
2224
+ }
2225
+ }
2226
+ });
2227
+ window.__xb_iframe_observer.observe(document.documentElement, { childList: true, subtree: true });
2228
+ }
2229
+ // Periodic re-injection for iframes that load late or navigate internally
2230
+ if (!window.__xb_iframe_timer) {
2231
+ window.__xb_iframe_timer = setInterval(function() {
2232
+ try {
2233
+ var iframes = document.querySelectorAll('iframe');
2234
+ for (var i = 0; i < iframes.length; i++) {
2235
+ if (!iframes[i].__xb_injected) {
2236
+ watchIframe(iframes[i]);
2237
+ }
2238
+ }
2239
+ } catch(e) {}
2240
+ }, 3000);
2241
+ }
2242
+ })();
2243
+ `);
2244
+ } catch {
2200
2245
  }
2201
- /** Directory for this session's recordings. */
2202
- get recordingsDir() {
2203
- return _SessionRecorder.getRecordingsDir(this.sessionName);
2246
+ return success;
2247
+ }
2248
+
2249
+ // src/recorder/summary-builder.ts
2250
+ var POST_WINDOW = 5e3;
2251
+ var MERGE_WINDOW = 2e3;
2252
+ function buildSummary(data, startedAt) {
2253
+ const steps = [];
2254
+ const selectorToRef = /* @__PURE__ */ new Map();
2255
+ const elements = {};
2256
+ let refCounter = 0;
2257
+ function getRef(action) {
2258
+ const sel = action.element?.selector || action.element?.tag || "_none";
2259
+ if (selectorToRef.has(sel)) return selectorToRef.get(sel);
2260
+ refCounter++;
2261
+ const ref = "e" + refCounter;
2262
+ selectorToRef.set(sel, ref);
2263
+ if (action.element) {
2264
+ elements[ref] = {
2265
+ selector: action.element.selector || action.element.tag,
2266
+ tag: action.element.tag,
2267
+ text: action.element.text,
2268
+ role: action.element.role,
2269
+ type: action.element.type,
2270
+ placeholder: action.element.placeholder,
2271
+ ariaLabel: action.element.ariaLabel,
2272
+ href: action.element.href
2273
+ };
2274
+ } else {
2275
+ elements[ref] = { selector: "_none", tag: "_", text: "" };
2276
+ }
2277
+ return ref;
2278
+ }
2279
+ const isNoiseNetwork = (n) => {
2280
+ const url = n.url || "";
2281
+ const path = n.path || "";
2282
+ const rt = n.resourceType || "";
2283
+ if (["image", "stylesheet", "font", "manifest", "other"].includes(rt)) return true;
2284
+ if (n.status === 0) return true;
2285
+ if (/\/ztbox|\/mwb2\.gif|\/hmslog|\/log\.gif|\/tongji|hm\.baidu|clickstream|\/actionlog|\/collect\?|\/track|\/beacon/i.test(url)) return true;
2286
+ if (/\/favicon\.ico|\/robots\.txt/i.test(path)) return true;
2287
+ return false;
2288
+ };
2289
+ const meaningfulNetwork = data.network.filter((n) => !isNoiseNetwork(n));
2290
+ const filtered = data.actions;
2291
+ const groups = [];
2292
+ let current = null;
2293
+ for (const action of filtered) {
2294
+ const sameElement = current && current.primary.element?.selector && current.primary.element.selector === action.element?.selector && action.timestamp - current.primary.timestamp < MERGE_WINDOW;
2295
+ const isInputLike = action.type === "input" || action.type === "keydown" || action.type === "change";
2296
+ if (current && (sameElement || isInputLike && current.actions.some((a) => a.type === "input" || a.type === "click") && action.timestamp - current.primary.timestamp < MERGE_WINDOW)) {
2297
+ current.actions.push(action);
2298
+ if (action.type === "input") current.primary = action;
2299
+ } else {
2300
+ current = { actions: [action], primary: action };
2301
+ groups.push(current);
2302
+ }
2204
2303
  }
2205
- /** Directory for auto-captured snapshots (PNG screenshots, stored in .tmp for easy cleanup). */
2206
- get snapshotsDir() {
2207
- return join(this.recordingsDir, ".tmp", "snapshots");
2304
+ for (const group of groups) {
2305
+ const primary = group.primary;
2306
+ const tsStart = Math.min(...group.actions.map((a) => a.timestamp));
2307
+ const tsEnd = Math.max(...group.actions.map((a) => a.timestamp));
2308
+ const inputAction = group.actions.find((a) => a.type === "input");
2309
+ const nearbyNetwork = meaningfulNetwork.filter(
2310
+ (n) => n.timestamp >= tsStart - 500 && n.timestamp <= tsEnd + POST_WINDOW
2311
+ );
2312
+ const nearbyContext = data.contextChanges.filter(
2313
+ (c) => c.timestamp >= tsStart - 500 && c.timestamp <= tsEnd + POST_WINDOW
2314
+ );
2315
+ const matchedInputs = inputAction ? matchActionToNetwork(inputAction, nearbyNetwork) : [];
2316
+ const clickMatches = primary.type === "click" && primary.element?.text ? matchActionToNetwork(primary, nearbyNetwork) : [];
2317
+ const signals = primary.__signals || [];
2318
+ steps.push({
2319
+ step: steps.length + 1,
2320
+ ref: getRef(primary),
2321
+ action: primary,
2322
+ network: nearbyNetwork.map((n) => ({
2323
+ ...n,
2324
+ responseBody: n.responseBody && JSON.stringify(n.responseBody).length > 1e3 ? "[truncated, " + JSON.stringify(n.responseBody).length + " bytes]" : n.responseBody
2325
+ })),
2326
+ contextChanges: nearbyContext,
2327
+ matchedInputs: [...matchedInputs, ...clickMatches],
2328
+ signals
2329
+ });
2208
2330
  }
2209
- static getRecordingsDir(sessionName) {
2210
- return join(homedir(), ".xbrowser", "sessions", sessionName, "recordings");
2331
+ return {
2332
+ startUrl: data.startUrl,
2333
+ recordedAt: new Date(startedAt).toISOString(),
2334
+ durationMs: Date.now() - startedAt,
2335
+ totalActions: data.actions.length,
2336
+ totalNetworkRequests: meaningfulNetwork.length,
2337
+ steps,
2338
+ elements,
2339
+ checkpoints: data.checkpoints
2340
+ };
2341
+ }
2342
+ function matchActionToNetwork(action, nearbyNetwork) {
2343
+ const matches = [];
2344
+ const searchValue = (action.value || action.element?.text || "").trim();
2345
+ if (!searchValue || searchValue.length < 2) return matches;
2346
+ for (const netEntry of nearbyNetwork) {
2347
+ if (netEntry.url.includes(encodeURIComponent(searchValue)) || netEntry.url.includes(searchValue)) {
2348
+ matches.push({ inputValue: searchValue, networkId: netEntry.id, paramName: "url" });
2349
+ }
2350
+ if (netEntry.requestBody && typeof netEntry.requestBody === "object") {
2351
+ searchObjectForValue(
2352
+ netEntry.requestBody,
2353
+ searchValue,
2354
+ netEntry.id,
2355
+ "",
2356
+ matches
2357
+ );
2358
+ }
2211
2359
  }
2212
- /** Path to the control file (used by record stop to signal this process). */
2213
- get controlFilePath() {
2214
- return join(this.recordingsDir, ".control.json");
2360
+ return matches;
2361
+ }
2362
+ function searchObjectForValue(obj, targetValue, networkId, prefix, results) {
2363
+ for (const [key, value] of Object.entries(obj)) {
2364
+ const fullKey = prefix ? `${prefix}.${key}` : key;
2365
+ if (typeof value === "string" && value.includes(targetValue)) {
2366
+ results.push({ inputValue: targetValue, networkId, paramName: fullKey });
2367
+ } else if (typeof value === "object" && value !== null) {
2368
+ searchObjectForValue(value, targetValue, networkId, fullKey, results);
2369
+ }
2215
2370
  }
2216
- /** Path to the stop signal file (written by `record stop`). */
2217
- get stopSignalPath() {
2218
- return join(this.recordingsDir, ".stop");
2371
+ }
2372
+
2373
+ // src/recorder/markdown-summary.ts
2374
+ import { readFileSync } from "fs";
2375
+ import { join } from "path";
2376
+ import { homedir } from "os";
2377
+ function buildMarkdownSummary(_data, summary) {
2378
+ const lines = [];
2379
+ const durSec = Math.round(summary.durationMs / 1e3);
2380
+ lines.push("# Recording Summary");
2381
+ lines.push("");
2382
+ lines.push(`- **URL**: ${summary.startUrl}`);
2383
+ lines.push(`- **Recorded**: ${summary.recordedAt}`);
2384
+ lines.push(`- **Duration**: ${durSec}s`);
2385
+ lines.push(`- **Steps**: ${summary.totalActions} actions, ${summary.totalNetworkRequests} network requests`);
2386
+ if (summary.checkpoints.length > 0) {
2387
+ const cpTypes = summary.checkpoints.map((c) => c.type);
2388
+ lines.push(`- **Checkpoints**: ${summary.checkpoints.length} (${[...new Set(cpTypes)].join(", ")})`);
2389
+ } else {
2390
+ lines.push("- **Checkpoints**: 0");
2391
+ }
2392
+ const checkpointSteps = /* @__PURE__ */ new Map();
2393
+ for (const cp of summary.checkpoints) {
2394
+ if (cp.relatedActionId != null) {
2395
+ for (const step of summary.steps) {
2396
+ if (step.action.id === cp.relatedActionId) {
2397
+ checkpointSteps.set(step.step, cp);
2398
+ break;
2399
+ }
2400
+ }
2401
+ }
2219
2402
  }
2220
- // ─── Start ──────────────────────────────────────────────────────
2221
- async start(url, options) {
2222
- if (this._isRecording) throw new Error("Already recording");
2223
- this._isRecording = true;
2224
- this.startedAt = Date.now();
2225
- this.actions = [];
2226
- this.network = [];
2227
- this.contextChanges = [];
2228
- this.checkpoints = [];
2229
- this.checkpointCounter = 0;
2230
- this.streamMode = options?.stream ?? "clean";
2403
+ lines.push("");
2404
+ lines.push("## Steps");
2405
+ lines.push("");
2406
+ for (const step of summary.steps) {
2407
+ const a = step.action;
2408
+ const el = a.element;
2409
+ const cp = checkpointSteps.get(step.step);
2410
+ if (cp) {
2411
+ lines.push(`### Step ${step.step}: \u26A0\uFE0F CHECKPOINT \u2014 ${cp.hint}`);
2412
+ lines.push(`- **Type**: ${cp.type} (${cp.source})`);
2413
+ lines.push(`- **Hint**: ${cp.hint}`);
2414
+ if (cp.selector) lines.push(`- **Selector**: \`${cp.selector}\``);
2415
+ lines.push(`- **Action needed**: Human intervention required before continuing`);
2416
+ } else {
2417
+ const title = describeActionTitle(a);
2418
+ lines.push(`### Step ${step.step}: ${title}`);
2419
+ }
2420
+ if (el) {
2421
+ const parts = [`\`${el.selector || el.tag}\``];
2422
+ if (el.text) parts.push(`"${el.text.substring(0, 60)}"`);
2423
+ parts.push(`(${el.tag})`);
2424
+ if (el.type) parts.push(`type=${el.type}`);
2425
+ lines.push(`- **Element**: ${parts.join(" ")}`);
2426
+ }
2427
+ if (a.value != null && a.type === "input") {
2428
+ lines.push(`- **Value**: "${a.value.substring(0, 100)}"`);
2429
+ }
2430
+ if (step.network.length > 0) {
2431
+ const netDescs = step.network.map((n) => {
2432
+ let desc = `${n.method} ${n.path}`;
2433
+ if (n.status) desc += ` \u2192 ${n.status}`;
2434
+ if (n.responseSize > 0) desc += ` (${formatBytes(n.responseSize)})`;
2435
+ return desc;
2436
+ });
2437
+ lines.push(`- **Network**: ${netDescs.join(", ")}`);
2438
+ for (const n of step.network) {
2439
+ if (n.requestBody && typeof n.requestBody === "object") {
2440
+ const bodyStr = JSON.stringify(n.requestBody);
2441
+ if (bodyStr.length <= 300) {
2442
+ lines.push(` - \`${n.method} ${n.path}\` body: \`${bodyStr}\``);
2443
+ } else {
2444
+ lines.push(` - \`${n.method} ${n.path}\` body: \`${bodyStr.substring(0, 300)}...\` (${bodyStr.length} bytes)`);
2445
+ }
2446
+ }
2447
+ }
2448
+ } else {
2449
+ lines.push("- **Network**: none");
2450
+ }
2451
+ if (step.matchedInputs.length > 0) {
2452
+ for (const m of step.matchedInputs) {
2453
+ lines.push(`- **Input matched**: "${m.inputValue}" \u2192 ${m.paramName} (network #${m.networkId})`);
2454
+ }
2455
+ }
2456
+ for (const ctx of step.contextChanges) {
2457
+ if (ctx.type === "navigate") {
2458
+ lines.push(`- **Navigate**: \u2192 ${ctx.url}`);
2459
+ } else if (ctx.type === "new_tab") {
2460
+ lines.push(`- **New tab**: ${ctx.url}`);
2461
+ }
2462
+ }
2463
+ if (a.clickContext) {
2464
+ if (a.clickContext.appeared?.length > 0) {
2465
+ for (const popup of a.clickContext.appeared) {
2466
+ const roleStr = popup.role ? ` [${popup.role}]` : "";
2467
+ lines.push(`- **Popup**: <${popup.tag}${roleStr}> "${(popup.text || "").substring(0, 60)}"`);
2468
+ if (popup.items?.length > 0) {
2469
+ const itemStrs = popup.items.slice(0, 8).map((i) => {
2470
+ const dis = i.disabled ? " [disabled]" : "";
2471
+ return `"${i.text}"${dis}`;
2472
+ });
2473
+ let itemLine = ` - Items: ${itemStrs.join(", ")}`;
2474
+ if (popup.items.length > 8) itemLine += ` ... +${popup.items.length - 8} more`;
2475
+ lines.push(itemLine);
2476
+ }
2477
+ }
2478
+ }
2479
+ if (a.clickContext.stateChanges?.length > 0) {
2480
+ for (const sc of a.clickContext.stateChanges) {
2481
+ const parts = [];
2482
+ if (sc.ariaExpanded !== void 0) parts.push(`expanded=${sc.ariaExpanded}`);
2483
+ if (sc.disabled) parts.push("disabled");
2484
+ if (sc.ariaSelected !== void 0) parts.push(`selected=${sc.ariaSelected}`);
2485
+ if (sc.dataState) parts.push(`state=${sc.dataState}`);
2486
+ if (parts.length > 0) {
2487
+ lines.push(`- **State**: <${sc.tag}> "${(sc.text || "").substring(0, 30)}" ${parts.join(", ")}`);
2488
+ }
2489
+ }
2490
+ }
2491
+ }
2492
+ lines.push("");
2493
+ }
2494
+ const allNetwork = summary.steps.flatMap((s) => s.network);
2495
+ if (allNetwork.length > 0) {
2496
+ lines.push("## Network Timeline");
2497
+ lines.push("");
2498
+ allNetwork.forEach((n, i) => {
2499
+ let line = `${i + 1}. ${n.method} ${n.path}`;
2500
+ if (n.status) line += ` \u2192 ${n.status}`;
2501
+ if (n.requestBody && typeof n.requestBody === "object") {
2502
+ const bodyStr = JSON.stringify(n.requestBody);
2503
+ if (bodyStr.length <= 150) {
2504
+ line += ` ${bodyStr}`;
2505
+ }
2506
+ }
2507
+ if (n.responseSize > 0) line += ` (${formatBytes(n.responseSize)})`;
2508
+ lines.push(line);
2509
+ });
2510
+ lines.push("");
2511
+ }
2512
+ const orphanCheckpoints = summary.checkpoints.filter(
2513
+ (cp) => cp.relatedActionId == null || !checkpointSteps.has(
2514
+ summary.steps.find((s) => s.action.id === cp.relatedActionId)?.step ?? -1
2515
+ )
2516
+ );
2517
+ if (orphanCheckpoints.length > 0) {
2518
+ lines.push("## Unresolved Checkpoints");
2519
+ lines.push("");
2520
+ for (const cp of orphanCheckpoints) {
2521
+ const src = cp.source === "auto" ? "[auto]" : "[manual]";
2522
+ lines.push(`- ${src} **${cp.type}**: ${cp.hint}`);
2523
+ if (cp.selector) lines.push(` - Selector: \`${cp.selector}\``);
2524
+ }
2525
+ lines.push("");
2526
+ }
2527
+ return lines.join("\n");
2528
+ }
2529
+ function readMarkdownSummary(sessionName) {
2530
+ const mdPath = join(homedir(), ".xbrowser", "recordings", sessionName, "summary.md");
2531
+ try {
2532
+ return readFileSync(mdPath, "utf8");
2533
+ } catch {
2534
+ return null;
2535
+ }
2536
+ }
2537
+ function describeActionTitle(a) {
2538
+ const el = a.element;
2539
+ const elText = el?.text ? `"${el.text.substring(0, 40)}"` : "";
2540
+ const elTag = el?.tag ? `<${el.tag}>` : "";
2541
+ switch (a.type) {
2542
+ case "click":
2543
+ return `Click ${elText || elTag} button`.replace(/ +/g, " ").trim();
2544
+ case "input":
2545
+ return `Input "${(a.value || "").substring(0, 50)}" in ${elText || elTag || "field"}`.replace(/ +/g, " ").trim();
2546
+ case "change":
2547
+ return `Change ${elText || elTag} to "${(a.value || "").substring(0, 30)}"`;
2548
+ case "keydown":
2549
+ return `Press ${a.key || "key"} on ${elText || elTag || "element"}`;
2550
+ case "submit":
2551
+ return `Submit ${elText || elTag || "form"}`;
2552
+ default:
2553
+ return `${a.type} ${elText || elTag}`.trim() || a.type;
2554
+ }
2555
+ }
2556
+ function formatBytes(bytes) {
2557
+ if (bytes < 1024) return `${bytes}B`;
2558
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
2559
+ return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
2560
+ }
2561
+
2562
+ // src/recorder/observation-insights.ts
2563
+ async function detectCheckpoints(page, allocateCheckpointId) {
2564
+ const CHECKPOINT_RULES = [
2565
+ { type: "captcha", selectors: ['img[src*="captcha"]', 'img[src*="verify"]', '[class*="captcha"]', '[id*="captcha"]', "#captcha", ".captcha"] },
2566
+ { type: "slider", selectors: ['[class*="slider"]', '[class*="drag-verify"]', '[class*="slide-verify"]'] },
2567
+ { type: "login", selectors: ['input[type="password"]'] },
2568
+ { type: "iframe", selectors: ['iframe[src*="captcha"]', 'iframe[src*="verify"]', 'iframe[src*="recaptcha"]', 'iframe[title*="captcha"]'] }
2569
+ ];
2570
+ try {
2571
+ const found = await page.evaluate((rules) => {
2572
+ const results = [];
2573
+ for (const rule of rules) {
2574
+ for (const sel of rule.selectors) {
2575
+ try {
2576
+ const el = document.querySelector(sel);
2577
+ if (el) {
2578
+ const rect = el.getBoundingClientRect();
2579
+ if (rect.width > 0 && rect.height > 0) {
2580
+ results.push({
2581
+ type: rule.type,
2582
+ selector: sel,
2583
+ text: (el.textContent || "").substring(0, 60)
2584
+ });
2585
+ }
2586
+ }
2587
+ } catch {
2588
+ }
2589
+ }
2590
+ }
2591
+ return results;
2592
+ }, CHECKPOINT_RULES);
2593
+ const entries = [];
2594
+ for (const item of found) {
2595
+ const id = allocateCheckpointId();
2596
+ ;
2597
+ const hints = {
2598
+ captcha: "Captcha verification detected",
2599
+ slider: "Slider verification detected",
2600
+ login: "Login form detected (password field)",
2601
+ iframe: "Verification iframe detected"
2602
+ };
2603
+ entries.push({
2604
+ id,
2605
+ type: item.type,
2606
+ timestamp: Date.now(),
2607
+ url: page.url(),
2608
+ pageTitle: await page.title().catch(() => ""),
2609
+ hint: hints[item.type] || item.type,
2610
+ selector: item.selector,
2611
+ source: "auto",
2612
+ context: { matchedSelector: item.selector, elementText: item.text }
2613
+ });
2614
+ }
2615
+ return entries;
2616
+ } catch {
2617
+ return [];
2618
+ }
2619
+ }
2620
+ async function verifyAction(page, action, network, checkpoints) {
2621
+ const signals = [];
2622
+ try {
2623
+ const currentUrl = page.url();
2624
+ if (currentUrl && currentUrl !== "about:blank" && currentUrl !== action.url) {
2625
+ signals.push({ type: "url_change", value: currentUrl, label: `URL changed to ${currentUrl}` });
2626
+ }
2627
+ } catch {
2628
+ }
2629
+ try {
2630
+ const recentNetwork = network.filter(
2631
+ (n) => n.timestamp > action.timestamp - 100 && n.timestamp < action.timestamp + 5e3 && n.status >= 200 && n.status < 400
2632
+ );
2633
+ for (const net of recentNetwork.slice(0, 3)) {
2634
+ signals.push({
2635
+ type: "network_success",
2636
+ value: `${net.status}`,
2637
+ label: `${net.method} ${net.path} \u2192 ${net.status}`
2638
+ });
2639
+ }
2640
+ } catch {
2641
+ }
2642
+ try {
2643
+ const recentDialog = [...checkpoints].reverse().find(
2644
+ (cp) => cp.type === "dialog" && Math.abs(cp.timestamp - action.timestamp) < 3e3
2645
+ );
2646
+ if (recentDialog) {
2647
+ signals.push({ type: "dialog", value: recentDialog.type, label: recentDialog.hint });
2648
+ }
2649
+ } catch {
2650
+ }
2651
+ return signals;
2652
+ }
2653
+
2654
+ // src/recorder/page-context.ts
2655
+ import { mkdirSync, writeFileSync } from "fs";
2656
+ import { join as join2 } from "path";
2657
+ var SNAPSHOT_TYPES = /* @__PURE__ */ new Set([
2658
+ "click",
2659
+ "dblclick",
2660
+ "navigation",
2661
+ "goto",
2662
+ "submit",
2663
+ "cdp-click",
2664
+ "cdp-fill",
2665
+ "input",
2666
+ "change",
2667
+ "filechooser",
2668
+ "popup_appear"
2669
+ ]);
2670
+ async function captureElementScreenshot(page, action) {
2671
+ const keyTypes = ["click", "input", "change", "dblclick", "cdp-click", "cdp-fill", "filechooser"];
2672
+ if (!keyTypes.includes(action.type)) return;
2673
+ if (!action.element?.selector) return;
2674
+ const selector = action.element.selector;
2675
+ try {
2676
+ const buffer = await page.locator(selector).first().screenshot({
2677
+ type: "png",
2678
+ timeout: 3e3
2679
+ });
2680
+ return buffer.toString("base64");
2681
+ } catch {
2682
+ }
2683
+ try {
2684
+ await page.waitForSelector(selector, { state: "visible", timeout: 2e3 });
2685
+ const buffer = await page.locator(selector).first().screenshot({
2686
+ type: "png",
2687
+ timeout: 3e3
2688
+ });
2689
+ return buffer.toString("base64");
2690
+ } catch {
2691
+ }
2692
+ try {
2693
+ const buffer = await page.screenshot({ type: "png", timeout: 3e3 });
2694
+ return buffer.toString("base64");
2695
+ } catch {
2696
+ return;
2697
+ }
2698
+ }
2699
+ function isSnapshotThrottled(type, selector, snapshotThrottle) {
2700
+ if (type === "input" || type === "change" || type === "cdp-fill") {
2701
+ const key = `${type}|${selector || ""}`;
2702
+ const last = snapshotThrottle.get(key);
2703
+ const now = Date.now();
2704
+ if (last && now - last < 2e3) return true;
2705
+ snapshotThrottle.set(key, now);
2706
+ }
2707
+ return false;
2708
+ }
2709
+ async function captureAutoSnapshot(page, action, suffix = "after", snapshotsDir, snapshotThrottle) {
2710
+ if (!SNAPSHOT_TYPES.has(action.type)) return;
2711
+ if (isSnapshotThrottled(action.type, action.element?.selector, snapshotThrottle)) return;
2712
+ const snapDir = snapshotsDir;
2713
+ mkdirSync(snapDir, { recursive: true });
2714
+ const stepId = String(action.id).padStart(3, "0");
2715
+ const snapshot = {};
2716
+ try {
2717
+ const pngPath = join2(snapDir, `step-${stepId}-${suffix}.png`);
2718
+ const buffer = await page.screenshot({ type: "png", timeout: 5e3 });
2719
+ writeFileSync(pngPath, buffer);
2720
+ snapshot.png = `.tmp/snapshots/step-${stepId}-${suffix}.png`;
2721
+ } catch {
2722
+ }
2723
+ try {
2724
+ snapshot.aria = await page.evaluate(`
2725
+ (function() {
2726
+ try {
2727
+ var parts = [];
2728
+ var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT, null, false);
2729
+ var node;
2730
+ while (node = walker.nextNode()) {
2731
+ var tag = node.tagName.toLowerCase();
2732
+ var role = node.getAttribute('role') || '';
2733
+ var text = (node.textContent || '').trim().substring(0, 60);
2734
+ var ariaLabel = node.getAttribute('aria-label') || '';
2735
+ if (role || tag === 'button' || tag === 'a' || tag === 'input' || tag === 'select' || tag === 'textarea') {
2736
+ parts.push((role || tag) + ': ' + (ariaLabel || text).substring(0, 40));
2737
+ }
2738
+ }
2739
+ return parts.slice(0, 100).join(' | ');
2740
+ } catch(e) { return ''; }
2741
+ })()
2742
+ `);
2743
+ } catch {
2744
+ }
2745
+ if (snapshot.png || snapshot.aria) {
2746
+ action.snapshots = snapshot;
2747
+ }
2748
+ }
2749
+ async function captureClickContext(page, cx, cy) {
2750
+ await new Promise((r) => setTimeout(r, 300));
2751
+ try {
2752
+ const ctx = await page.evaluate(`
2753
+ (function() {
2754
+ var cx = ${cx}, cy = ${cy};
2755
+ var POPOVER_SELECTORS = [
2756
+ '[role="menu"]','[role="listbox"]','[role="dialog"]','[role="tooltip"]','[role="popover"]',
2757
+ '[role="combobox"]','[role="tree"]','[role="grid"]',
2758
+ '.popover','.popup','.dropdown','.menu','.modal','.tooltip','.panel',
2759
+ '[class*="popover"]','[class*="popup"]','[class*="dropdown"]','[class*="menu"]',
2760
+ '[class*="tooltip"]','[class*="modal"]','[class*="panel"]','[class*="overlay"]','[class*="sheet"]',
2761
+ '[data-popup]','[data-dropdown]','[data-menu]','[data-popover"]',
2762
+ '.semi-dropdown','.semi-popover','.semi-modal',
2763
+ '.ant-dropdown','.ant-popover','.ant-modal',
2764
+ '.el-dropdown','.el-popover','.el-dialog',
2765
+ '.t-dropdown','.t-popup','.t-dialog'
2766
+ ];
2767
+
2768
+ function isNear(el, x, y, range) {
2769
+ try {
2770
+ var r = el.getBoundingClientRect();
2771
+ if (!r || r.width === 0 || r.height === 0) return false;
2772
+ return !(r.left > x + range || r.right < x - range || r.top > y + range || r.bottom < y - range);
2773
+ } catch(e) { return false; }
2774
+ }
2775
+
2776
+ var result = { appeared: [], disappeared: [], stateChanges: [] };
2777
+ var seenElements = new Set();
2778
+
2779
+ for (var si = 0; si < POPOVER_SELECTORS.length; si++) {
2780
+ try {
2781
+ var els = document.querySelectorAll(POPOVER_SELECTORS[si]);
2782
+ for (var j = 0; j < els.length; j++) {
2783
+ var el = els[j];
2784
+ if (seenElements.has(el)) continue;
2785
+ if (!isNear(el, cx, cy, 300)) continue;
2786
+ var rect = el.getBoundingClientRect();
2787
+ if (rect.width === 0 || rect.height === 0) continue;
2788
+ seenElements.add(el);
2789
+
2790
+ var items = [];
2791
+ var children = el.querySelectorAll('a,button,[role="menuitem"],[role="option"],[role="treeitem"],li,div[class*="item"]');
2792
+ var seenItemTexts = new Set();
2793
+ for (var k = 0; k < Math.min(children.length, 30); k++) {
2794
+ var child = children[k];
2795
+ var childText = (child.textContent || '').trim().substring(0, 60);
2796
+ if (!childText || seenItemTexts.has(childText)) continue;
2797
+ seenItemTexts.add(childText);
2798
+ var ci = { text: childText };
2799
+ try { if (child.disabled || child.getAttribute('aria-disabled') === 'true') ci.disabled = true; } catch(e) {}
2800
+ try { if (child.tagName) ci.tag = child.tagName.toLowerCase(); } catch(e) {}
2801
+ try { if (child.href) ci.href = child.href.substring(0, 80); } catch(e) {}
2802
+ items.push(ci);
2803
+ }
2804
+
2805
+ result.appeared.push({
2806
+ tag: el.tagName.toLowerCase(),
2807
+ selector: el.id ? '#' + el.id : undefined,
2808
+ role: el.getAttribute('role'),
2809
+ text: (el.textContent || '').trim().substring(0, 100),
2810
+ rect: { x: Math.round(rect.x), y: Math.round(rect.y), w: Math.round(rect.width), h: Math.round(rect.height) },
2811
+ items: items
2812
+ });
2813
+ }
2814
+ } catch(e) { /* skip invalid selectors */ }
2815
+ }
2816
+
2817
+ var allInteractive = document.querySelectorAll('[aria-expanded],[disabled],[aria-disabled],[aria-selected],[data-state]');
2818
+ for (var i = 0; i < allInteractive.length; i++) {
2819
+ var el2 = allInteractive[i];
2820
+ if (!isNear(el2, cx, cy, 200)) continue;
2821
+ var info = { tag: el2.tagName.toLowerCase(), text: (el2.textContent || '').trim().substring(0, 60) };
2822
+ try { if (el2.id) info.id = el2.id; } catch(e) {}
2823
+ try { if (el2.getAttribute('aria-expanded')) info.ariaExpanded = el2.getAttribute('aria-expanded'); } catch(e) {}
2824
+ try { if (el2.disabled || el2.getAttribute('aria-disabled') === 'true') info.disabled = true; } catch(e) {}
2825
+ try { if (el2.getAttribute('aria-selected')) info.ariaSelected = el2.getAttribute('aria-selected'); } catch(e) {}
2826
+ try { if (el2.getAttribute('data-state')) info.dataState = el2.getAttribute('data-state'); } catch(e) {}
2827
+ result.stateChanges.push(info);
2828
+ }
2829
+
2830
+ return result;
2831
+ })()
2832
+ `);
2833
+ if (ctx.appeared.length > 0 || ctx.stateChanges.length > 0) {
2834
+ return ctx;
2835
+ }
2836
+ } catch {
2837
+ }
2838
+ return void 0;
2839
+ }
2840
+
2841
+ // src/recorder/session-recorder.ts
2842
+ var SessionRecorder = class _SessionRecorder {
2843
+ context;
2844
+ page;
2845
+ sessionName;
2846
+ startUrl = "";
2847
+ startedAt = 0;
2848
+ actions = [];
2849
+ networkCapture = createNetworkCaptureState();
2850
+ contextChanges = [];
2851
+ checkpoints = [];
2852
+ /** Proactive baseline scan of filter/sort/tab/menu regions. Keyed by
2853
+ * containerSelector so re-scans after navigation replace rather than dup. */
2854
+ discoveredFilters = /* @__PURE__ */ new Map();
2855
+ actionCounter = 0;
2856
+ contextCounter = 0;
2857
+ checkpointCounter = 0;
2858
+ pollTimer = null;
2859
+ flushTimer = null;
2860
+ lastActionTs = 0;
2861
+ activePages = /* @__PURE__ */ new Set();
2862
+ lastKnownUrl = "";
2863
+ dedupMap = /* @__PURE__ */ new Map();
2864
+ dedupActionCount = 0;
2865
+ _isRecording = false;
2866
+ streamMode = "clean";
2867
+ snapshotThrottle = /* @__PURE__ */ new Map();
2868
+ static AMBIENT_TYPES = /* @__PURE__ */ new Set([
2869
+ "hover",
2870
+ "focus",
2871
+ "scroll",
2872
+ "visibility",
2873
+ "resize",
2874
+ "clipboard",
2875
+ "touch",
2876
+ "contextmenu"
2877
+ ]);
2878
+ constructor(context, page, sessionName) {
2879
+ this.context = context;
2880
+ this.page = page;
2881
+ this.sessionName = sessionName;
2882
+ }
2883
+ get isRecording() {
2884
+ return this._isRecording;
2885
+ }
2886
+ get actionCount() {
2887
+ return this.actions.length;
2888
+ }
2889
+ /** Record an action triggered by a CDP command (e.g. xbrowser fill/click/goto) */
2890
+ async recordCommandAction(action) {
2891
+ const dedupFromAction = this.dedupKey(action.type, action.selector, action.element?.tag, action.value);
2892
+ if (dedupFromAction) {
2893
+ const entry = this.dedupMap.get(dedupFromAction);
2894
+ if (entry && entry.origin === "signal" && Date.now() < entry.expires) {
2895
+ return;
2896
+ }
2897
+ }
2898
+ this.actionCounter++;
2899
+ const ts = Date.now();
2900
+ const actionUrl = action.url && action.url !== "about:blank" ? action.url : this.lastKnownUrl || this.page.url();
2901
+ const actionToPush = {
2902
+ id: this.actionCounter,
2903
+ type: action.type,
2904
+ timestamp: ts,
2905
+ url: actionUrl,
2906
+ pageTitle: "",
2907
+ element: action.element || (action.selector ? { tag: "", selector: action.selector, text: "" } : void 0),
2908
+ value: action.value
2909
+ };
2910
+ this.actions.push(actionToPush);
2911
+ actionToPush.elementScreenshot = await Promise.race([
2912
+ captureElementScreenshot(this.page, {
2913
+ type: action.type,
2914
+ element: actionToPush.element
2915
+ }).catch(() => void 0),
2916
+ new Promise((r) => setTimeout(r, 3e3))
2917
+ ]);
2918
+ await Promise.race([
2919
+ captureAutoSnapshot(this.page, actionToPush, "after", this.snapshotsDir, this.snapshotThrottle).catch(() => {
2920
+ }),
2921
+ new Promise((r) => setTimeout(r, 6e3))
2922
+ ]);
2923
+ this.lastActionTs = ts;
2924
+ this.dedupMap.set(dedupFromAction, { expires: Date.now() + 4e3, origin: "command" });
2925
+ this.dedupActionCount++;
2926
+ if (this.dedupActionCount % 200 === 0) {
2927
+ const now = Date.now();
2928
+ for (const [k, v] of this.dedupMap) {
2929
+ if (now >= v.expires) this.dedupMap.delete(k);
2930
+ }
2931
+ }
2932
+ if (action.url && action.url !== "about:blank") {
2933
+ this.lastKnownUrl = action.url;
2934
+ } else if (action.type === "goto" && action.value && action.value !== "about:blank") {
2935
+ this.lastKnownUrl = action.value;
2936
+ }
2937
+ }
2938
+ /** Generate dedup key for an action (normalized type + selector/tag + value). */
2939
+ dedupKey(type, selector, tag, value) {
2940
+ const normType = type === "cdp-click" ? "click" : type === "cdp-fill" ? "input" : type === "cdp-eval" ? "eval" : type;
2941
+ const selOrTag = selector || tag || "";
2942
+ return `${normType}|${selOrTag}|${value || ""}`;
2943
+ }
2944
+ get networkCount() {
2945
+ return this.networkCapture.entries.length;
2946
+ }
2947
+ getLiveData() {
2948
+ return this.buildData();
2949
+ }
2950
+ addManualCheckpoint(type, hint, selector) {
2951
+ this.checkpointCounter++;
2952
+ const cp = {
2953
+ id: this.checkpointCounter,
2954
+ type,
2955
+ timestamp: Date.now(),
2956
+ url: this.page.url(),
2957
+ pageTitle: "",
2958
+ hint,
2959
+ selector,
2960
+ source: "manual"
2961
+ };
2962
+ this.checkpoints.push(cp);
2963
+ return cp;
2964
+ }
2965
+ /** Directory for this session's recordings. */
2966
+ get recordingsDir() {
2967
+ return _SessionRecorder.getRecordingsDir(this.sessionName);
2968
+ }
2969
+ /** Directory for auto-captured snapshots (PNG screenshots, stored in .tmp for easy cleanup). */
2970
+ get snapshotsDir() {
2971
+ return join3(this.recordingsDir, ".tmp", "snapshots");
2972
+ }
2973
+ static getRecordingsDir(sessionName) {
2974
+ return join3(homedir2(), ".xbrowser", "sessions", sessionName, "recordings");
2975
+ }
2976
+ /** Path to the control file (used by record stop to signal this process). */
2977
+ get controlFilePath() {
2978
+ return join3(this.recordingsDir, ".control.json");
2979
+ }
2980
+ /** Path to the stop signal file (written by `record stop`). */
2981
+ get stopSignalPath() {
2982
+ return join3(this.recordingsDir, ".stop");
2983
+ }
2984
+ // ─── Start ──────────────────────────────────────────────────────
2985
+ async start(url, options) {
2986
+ if (this._isRecording) throw new Error("Already recording");
2987
+ this._isRecording = true;
2988
+ this.startedAt = Date.now();
2989
+ this.actions = [];
2990
+ this.contextChanges = [];
2991
+ this.checkpoints = [];
2992
+ this.checkpointCounter = 0;
2993
+ this.streamMode = options?.stream ?? "clean";
2231
2994
  this.lastKnownUrl = this.page.url();
2232
2995
  await this.page.addInitScript(getSelectorGeneratorScript());
2233
2996
  await this.page.addInitScript(ACTION_SIGNAL_SCRIPT);
@@ -2248,14 +3011,14 @@ var SessionRecorder = class _SessionRecorder {
2248
3011
  } else {
2249
3012
  this.startUrl = this.page.url();
2250
3013
  }
2251
- mkdirSync(this.recordingsDir, { recursive: true });
3014
+ mkdirSync2(this.recordingsDir, { recursive: true });
2252
3015
  const control = {
2253
3016
  pid: process.pid,
2254
3017
  startedAt: new Date(this.startedAt).toISOString(),
2255
3018
  startUrl: this.startUrl,
2256
3019
  sessionName: this.sessionName
2257
3020
  };
2258
- writeFileSync(this.controlFilePath, JSON.stringify(control, null, 2), "utf-8");
3021
+ writeFileSync2(this.controlFilePath, JSON.stringify(control, null, 2), "utf-8");
2259
3022
  await this.injectActionScript(this.page);
2260
3023
  this.context.on("page", this.handleNewPage);
2261
3024
  this.pollTimer = setInterval(() => void this.pollActions(), 200);
@@ -2290,21 +3053,21 @@ var SessionRecorder = class _SessionRecorder {
2290
3053
  });
2291
3054
  }
2292
3055
  const data = this.buildData();
2293
- const summary = this.buildSummary(data);
3056
+ const summary = buildSummary(data, this.startedAt);
2294
3057
  this.writeFinalOutput(data, summary);
2295
3058
  try {
2296
3059
  const knowledge = updateSiteKnowledge(data);
2297
- const knowledgeDir = join(this.recordingsDir, "site-knowledge.md");
2298
- const knowledgeJson = join(this.recordingsDir, "site-knowledge.json");
3060
+ const knowledgeDir = join3(this.recordingsDir, "site-knowledge.md");
3061
+ const knowledgeJson = join3(this.recordingsDir, "site-knowledge.json");
2299
3062
  const { readFileSync: rf } = __require("fs");
2300
3063
  const { getKnowledgePath } = (init_site_knowledge(), __toCommonJS(site_knowledge_exports));
2301
3064
  const mdPath = getKnowledgePath(knowledge.domain, "md");
2302
3065
  try {
2303
3066
  const md = rf(mdPath, "utf-8");
2304
- writeFileSync(knowledgeDir, md, "utf-8");
3067
+ writeFileSync2(knowledgeDir, md, "utf-8");
2305
3068
  } catch {
2306
3069
  }
2307
- writeFileSync(knowledgeJson, JSON.stringify(knowledge, null, 2), "utf-8");
3070
+ writeFileSync2(knowledgeJson, JSON.stringify(knowledge, null, 2), "utf-8");
2308
3071
  } catch {
2309
3072
  }
2310
3073
  try {
@@ -2317,268 +3080,103 @@ var SessionRecorder = class _SessionRecorder {
2317
3080
  }
2318
3081
  return { data, summary };
2319
3082
  }
2320
- // ─── Cleanup (called on session close) ──────────────────────────
2321
- static cleanup(sessionName) {
2322
- const dir = _SessionRecorder.getRecordingsDir(sessionName);
2323
- if (existsSync(dir)) {
2324
- rmSync(dir, { recursive: true, force: true });
2325
- }
2326
- }
2327
- // ─── Wait for stop signal (blocks the process) ──────────────────
2328
- waitForStopSignal() {
2329
- return new Promise((resolve) => {
2330
- const check = () => {
2331
- if (existsSync(this.stopSignalPath)) {
2332
- resolve();
2333
- } else {
2334
- setTimeout(check, 300);
2335
- }
2336
- };
2337
- check();
2338
- });
2339
- }
2340
- // ─── Static: send stop signal to a running recorder ─────────────
2341
- static async sendStopSignal(sessionName) {
2342
- const dir = _SessionRecorder.getRecordingsDir(sessionName);
2343
- const controlPath = join(dir, ".control.json");
2344
- const stopPath = join(dir, ".stop");
2345
- if (!existsSync(controlPath)) return null;
2346
- const control = JSON.parse(readFileSync(controlPath, "utf-8"));
2347
- let alive = false;
2348
- try {
2349
- process.kill(control.pid, 0);
2350
- alive = true;
2351
- } catch {
2352
- alive = false;
2353
- }
2354
- if (!alive) {
2355
- try {
2356
- rmSync(controlPath);
2357
- } catch {
2358
- }
2359
- return control;
2360
- }
2361
- mkdirSync(dir, { recursive: true });
2362
- writeFileSync(stopPath, JSON.stringify({ stoppedAt: (/* @__PURE__ */ new Date()).toISOString() }), "utf-8");
2363
- for (let i = 0; i < 50; i++) {
2364
- await new Promise((r) => setTimeout(r, 200));
2365
- if (!existsSync(controlPath)) return control;
2366
- try {
2367
- process.kill(control.pid, 0);
2368
- } catch {
2369
- try {
2370
- rmSync(controlPath);
2371
- } catch {
2372
- }
2373
- return control;
2374
- }
2375
- }
2376
- try {
2377
- rmSync(controlPath);
2378
- } catch {
2379
- }
2380
- return control;
2381
- }
2382
- // ─── Static: read recording from disk ───────────────────────────
2383
- static readSummary(sessionName) {
2384
- const path = join(_SessionRecorder.getRecordingsDir(sessionName), "summary.json");
2385
- try {
2386
- return JSON.parse(readFileSync(path, "utf-8"));
2387
- } catch {
2388
- return null;
2389
- }
2390
- }
2391
- static readData(sessionName) {
2392
- const path = join(_SessionRecorder.getRecordingsDir(sessionName), "recording.json");
2393
- try {
2394
- return JSON.parse(readFileSync(path, "utf-8"));
2395
- } catch {
2396
- return null;
2397
- }
2398
- }
2399
- // ==================== Private ====================
2400
- /** Whether the initial action-signal script injection succeeded. Check this
2401
- * after start() returns — if false, user actions will NOT be recorded and
2402
- * the caller should surface a clear error to the user instead of silently
2403
- * pretending recording is working. */
2404
- _injectionFailed = false;
2405
- get injectionFailed() {
2406
- return this._injectionFailed;
2407
- }
2408
- async injectActionScript(page) {
2409
- let success = false;
2410
- const maxAttempts = 3;
2411
- let lastError = "";
2412
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
2413
- try {
2414
- await page.evaluate(getSelectorGeneratorScript());
2415
- await page.evaluate(ACTION_SIGNAL_SCRIPT);
2416
- await page.evaluate(`window.__xb_action_script_src = ${JSON.stringify(ACTION_SIGNAL_SCRIPT)};`);
2417
- const injected = await page.evaluate(`(function() {
2418
- try { return !!window.__xb_action_signal; } catch(e) { return false; }
2419
- })()`).catch(() => false);
2420
- if (injected) {
2421
- success = true;
2422
- break;
2423
- }
2424
- lastError = "verification failed (script did not set __xb_action_signal flag)";
2425
- console.error(`[recorder] Action signal injection verification failed (attempt ${attempt}/${maxAttempts})`);
2426
- } catch (e) {
2427
- const err = e instanceof Error ? e : new Error(typeof e === "string" ? e : "unknown error");
2428
- lastError = err.message;
2429
- console.error(`[recorder] Action signal injection error (attempt ${attempt}/${maxAttempts}): ${err.message}`);
2430
- }
2431
- if (attempt < maxAttempts) {
2432
- await new Promise((r) => setTimeout(r, 1e3));
2433
- }
2434
- }
2435
- if (!success) {
2436
- this._injectionFailed = true;
2437
- console.error(`[recorder] WARNING: Action signal injection FAILED after ${maxAttempts} attempts. User actions will NOT be recorded. Last error: ${lastError}`);
2438
- }
2439
- try {
2440
- await page.evaluate(CHECKPOINT_OVERLAY_SCRIPT);
2441
- } catch (e) {
2442
- const msg = e instanceof Error ? e.message : String(e);
2443
- console.error(`[recorder] Checkpoint overlay injection failed (non-fatal): ${msg}`);
2444
- }
2445
- if (success) {
2446
- try {
2447
- await page.evaluate(`(function() {
2448
- if (typeof window.__xb_scanFilters === 'function') {
2449
- setTimeout(window.__xb_scanFilters, 100);
2450
- }
2451
- })()`);
2452
- } catch {
2453
- }
2454
- }
2455
- try {
2456
- await page.evaluate(`
2457
- (function() {
2458
- var _scriptSrc = ${JSON.stringify(ACTION_SIGNAL_SCRIPT)};
2459
- function injectIframe(iframe) {
2460
- try {
2461
- var w = iframe.contentWindow;
2462
- if (!w) return;
2463
- // Force re-injection: clear old flag
2464
- try { delete w.__xb_action_signal; } catch(e) {}
2465
- w.eval(_scriptSrc);
2466
- // Tag iframe so flushIframes knows it's injected
2467
- iframe.__xb_injected = true;
2468
- } catch(e) {}
2469
- }
2470
- function watchIframe(iframe) {
2471
- if (iframe.__xb_watched) return;
2472
- iframe.__xb_watched = true;
2473
- injectIframe(iframe);
2474
- iframe.addEventListener('load', function() { injectIframe(iframe); });
2475
- }
2476
- // Inject into existing iframes
2477
- try {
2478
- var iframes = document.querySelectorAll('iframe');
2479
- for (var i = 0; i < iframes.length; i++) watchIframe(iframes[i]);
2480
- } catch(e) {}
2481
- // Watch for dynamically inserted iframes
2482
- if (!window.__xb_iframe_observer) {
2483
- window.__xb_iframe_observer = new MutationObserver(function(mutations) {
2484
- for (var m = 0; m < mutations.length; m++) {
2485
- for (var n = 0; n < mutations[m].addedNodes.length; n++) {
2486
- var node = mutations[m].addedNodes[n];
2487
- if (node.tagName === 'IFRAME') {
2488
- watchIframe(node);
2489
- } else if (node.querySelectorAll) {
2490
- var sub = node.querySelectorAll('iframe');
2491
- for (var k = 0; k < sub.length; k++) watchIframe(sub[k]);
2492
- }
2493
- }
2494
- }
2495
- });
2496
- window.__xb_iframe_observer.observe(document.documentElement, { childList: true, subtree: true });
2497
- }
2498
- // Periodic re-injection for iframes that load late or navigate internally
2499
- if (!window.__xb_iframe_timer) {
2500
- window.__xb_iframe_timer = setInterval(function() {
2501
- try {
2502
- var iframes = document.querySelectorAll('iframe');
2503
- for (var i = 0; i < iframes.length; i++) {
2504
- if (!iframes[i].__xb_injected) {
2505
- watchIframe(iframes[i]);
2506
- }
2507
- }
2508
- } catch(e) {}
2509
- }, 3000);
2510
- }
2511
- })();
2512
- `);
2513
- } catch {
3083
+ // ─── Cleanup (called on session close) ──────────────────────────
3084
+ static cleanup(sessionName) {
3085
+ const dir = _SessionRecorder.getRecordingsDir(sessionName);
3086
+ if (existsSync(dir)) {
3087
+ rmSync(dir, { recursive: true, force: true });
2514
3088
  }
2515
3089
  }
2516
- // ─── Network capture ────────────────────────────────────────────
2517
- handleRequest = (request) => {
2518
- const resourceType = request.resourceType();
2519
- if (["image", "stylesheet", "font", "manifest", "other"].includes(resourceType)) return;
2520
- const url = request.url();
2521
- if (url.startsWith("data:") || url.startsWith("chrome-extension://") || url.startsWith("blob:")) return;
2522
- const dedupKey = request.method() + " " + url;
2523
- const now = Date.now();
2524
- if (this._lastRequestKey === dedupKey && now - this._lastRequestTs < 100) return;
2525
- this._lastRequestKey = dedupKey;
2526
- this._lastRequestTs = now;
2527
- this.networkCounter++;
2528
- const entry = {
2529
- id: this.networkCounter,
2530
- timestamp: Date.now(),
2531
- method: request.method(),
2532
- url,
2533
- path: new URL(url).pathname,
2534
- status: 0,
2535
- resourceType,
2536
- contentType: "",
2537
- responseSize: 0
2538
- };
2539
- if (["POST", "PATCH", "PUT"].includes(request.method())) {
2540
- try {
2541
- const postData = request.postData();
2542
- if (postData) {
2543
- try {
2544
- entry.requestBody = JSON.parse(postData);
2545
- } catch {
2546
- entry.requestBody = postData.substring(0, 500);
2547
- }
3090
+ // ─── Wait for stop signal (blocks the process) ──────────────────
3091
+ waitForStopSignal() {
3092
+ return new Promise((resolve) => {
3093
+ const check = () => {
3094
+ if (existsSync(this.stopSignalPath)) {
3095
+ resolve();
3096
+ } else {
3097
+ setTimeout(check, 300);
2548
3098
  }
2549
- } catch {
2550
- }
3099
+ };
3100
+ check();
3101
+ });
3102
+ }
3103
+ // ─── Static: send stop signal to a running recorder ─────────────
3104
+ static async sendStopSignal(sessionName) {
3105
+ const dir = _SessionRecorder.getRecordingsDir(sessionName);
3106
+ const controlPath = join3(dir, ".control.json");
3107
+ const stopPath = join3(dir, ".stop");
3108
+ if (!existsSync(controlPath)) return null;
3109
+ const control = JSON.parse(readFileSync2(controlPath, "utf-8"));
3110
+ let alive = false;
3111
+ try {
3112
+ process.kill(control.pid, 0);
3113
+ alive = true;
3114
+ } catch {
3115
+ alive = false;
2551
3116
  }
2552
- this.network.push(entry);
2553
- };
2554
- handleResponse = async (response) => {
2555
- const url = response.url();
2556
- if (url.startsWith("data:") || url.startsWith("chrome-extension://") || url.startsWith("blob:")) return;
2557
- const entry = [...this.network].reverse().find((e) => e.url === url && e.status === 0);
2558
- if (!entry) return;
2559
- entry.status = response.status();
2560
- entry.contentType = response.headers()["content-type"] || "";
2561
- const resourceType = response.request().resourceType();
2562
- const isApi = ["fetch", "xhr"].includes(resourceType) || entry.contentType.includes("json") || entry.contentType.includes("text/");
2563
- if (isApi) {
3117
+ if (!alive) {
2564
3118
  try {
2565
- const text = await response.text();
2566
- entry.responseSize = text.length;
2567
- if (text.length <= 20480) {
2568
- try {
2569
- entry.responseBody = JSON.parse(text);
2570
- } catch {
2571
- entry.responseBody = text.substring(0, 500);
2572
- }
2573
- }
3119
+ rmSync(controlPath);
2574
3120
  } catch {
2575
3121
  }
2576
- } else {
3122
+ return control;
3123
+ }
3124
+ mkdirSync2(dir, { recursive: true });
3125
+ writeFileSync2(stopPath, JSON.stringify({ stoppedAt: (/* @__PURE__ */ new Date()).toISOString() }), "utf-8");
3126
+ for (let i = 0; i < 50; i++) {
3127
+ await new Promise((r) => setTimeout(r, 200));
3128
+ if (!existsSync(controlPath)) return control;
2577
3129
  try {
2578
- entry.responseSize = parseInt(response.headers()["content-length"] || "0", 10);
3130
+ process.kill(control.pid, 0);
2579
3131
  } catch {
3132
+ try {
3133
+ rmSync(controlPath);
3134
+ } catch {
3135
+ }
3136
+ return control;
2580
3137
  }
2581
3138
  }
3139
+ try {
3140
+ rmSync(controlPath);
3141
+ } catch {
3142
+ }
3143
+ return control;
3144
+ }
3145
+ // ─── Static: read recording from disk ───────────────────────────
3146
+ static readSummary(sessionName) {
3147
+ const path = join3(_SessionRecorder.getRecordingsDir(sessionName), "summary.json");
3148
+ try {
3149
+ return JSON.parse(readFileSync2(path, "utf-8"));
3150
+ } catch {
3151
+ return null;
3152
+ }
3153
+ }
3154
+ static readData(sessionName) {
3155
+ const path = join3(_SessionRecorder.getRecordingsDir(sessionName), "recording.json");
3156
+ try {
3157
+ return JSON.parse(readFileSync2(path, "utf-8"));
3158
+ } catch {
3159
+ return null;
3160
+ }
3161
+ }
3162
+ // ==================== Private ====================
3163
+ /** Whether the initial action-signal script injection succeeded. Check this
3164
+ * after start() returns — if false, user actions will NOT be recorded and
3165
+ * the caller should surface a clear error to the user instead of silently
3166
+ * pretending recording is working. */
3167
+ _injectionFailed = false;
3168
+ get injectionFailed() {
3169
+ return this._injectionFailed;
3170
+ }
3171
+ async injectActionScript(page) {
3172
+ this._injectionFailed = !await injectActionScript(page);
3173
+ }
3174
+ // ─── Network capture ────────────────────────────────────────────
3175
+ handleRequest = (request) => {
3176
+ handleNetworkRequest(request, this.networkCapture);
3177
+ };
3178
+ handleResponse = async (response) => {
3179
+ await handleNetworkResponse(response, this.networkCapture);
2582
3180
  };
2583
3181
  // ─── Page tracking ──────────────────────────────────────────────
2584
3182
  handleNewPage = async (page) => {
@@ -2868,7 +3466,7 @@ var SessionRecorder = class _SessionRecorder {
2868
3466
  popupAppear: raw.popupAppear
2869
3467
  };
2870
3468
  this.actions.push(pushed2);
2871
- await this.captureAutoSnapshot(page, pushed2, "after").catch(() => {
3469
+ await captureAutoSnapshot(page, pushed2, "after", this.snapshotsDir, this.snapshotThrottle).catch(() => {
2872
3470
  });
2873
3471
  this.lastActionTs = raw.ts;
2874
3472
  continue;
@@ -2898,7 +3496,7 @@ var SessionRecorder = class _SessionRecorder {
2898
3496
  this.actionCounter++;
2899
3497
  let clickContext;
2900
3498
  if (raw.type === "click" && raw.x !== void 0 && raw.y !== void 0) {
2901
- clickContext = await this.captureClickContext(page, raw.x, raw.y);
3499
+ clickContext = await captureClickContext(page, raw.x, raw.y);
2902
3500
  }
2903
3501
  this.actions.push({
2904
3502
  id: this.actionCounter,
@@ -2925,8 +3523,8 @@ var SessionRecorder = class _SessionRecorder {
2925
3523
  drag: raw.drag
2926
3524
  });
2927
3525
  const pushed = this.actions[this.actions.length - 1];
2928
- pushed.elementScreenshot = await this.captureElementScreenshot(page, raw);
2929
- await this.captureAutoSnapshot(page, pushed, "after").catch(() => {
3526
+ pushed.elementScreenshot = await captureElementScreenshot(page, raw);
3527
+ await captureAutoSnapshot(page, pushed, "after", this.snapshotsDir, this.snapshotThrottle).catch(() => {
2930
3528
  });
2931
3529
  this.lastActionTs = raw.ts;
2932
3530
  const dedupKey = this.dedupKey(raw.type, raw.element?.selector, raw.element?.tag, raw.value);
@@ -2936,13 +3534,13 @@ var SessionRecorder = class _SessionRecorder {
2936
3534
  }
2937
3535
  const verifyTypes = /* @__PURE__ */ new Set(["click", "submit", "input", "change", "cdp-click", "cdp-fill"]);
2938
3536
  if (verifyTypes.has(raw.type)) {
2939
- const signals = await this.verifyAction(page, pushed).catch(() => []);
3537
+ const signals = await verifyAction(page, pushed, this.networkCapture.entries, this.checkpoints).catch(() => []);
2940
3538
  if (signals.length > 0) {
2941
3539
  pushed.__signals = signals;
2942
3540
  }
2943
3541
  }
2944
3542
  if (raw.type === "click" || raw.type === "navigate" || raw.type === "submit") {
2945
- const detected = await this.detectCheckpoints(page);
3543
+ const detected = await detectCheckpoints(page, () => ++this.checkpointCounter);
2946
3544
  for (const cp of detected) {
2947
3545
  cp.relatedActionId = this.actionCounter;
2948
3546
  this.checkpoints.push(cp);
@@ -2950,339 +3548,29 @@ var SessionRecorder = class _SessionRecorder {
2950
3548
  }
2951
3549
  }
2952
3550
  }
2953
- /**
2954
- * Capture a screenshot of the target element for key action types.
2955
- * Returns a base64-encoded PNG string, or undefined if the element has no
2956
- * selector or the screenshot fails (non-critical — never blocks recording).
2957
- *
2958
- * Only captures for: click, input, change, dblclick, and their CDP counterparts.
2959
- *
2960
- * Retry strategy (3 attempts, 3s each):
2961
- * 1. element screenshot via locator
2962
- * 2. retry element screenshot (element may have been animating/detached)
2963
- * 3. fallback to viewport screenshot (so we always get *something*)
2964
- */
2965
- async captureElementScreenshot(page, action) {
2966
- const keyTypes = ["click", "input", "change", "dblclick", "cdp-click", "cdp-fill", "filechooser"];
2967
- if (!keyTypes.includes(action.type)) return;
2968
- if (!action.element?.selector) return;
2969
- const selector = action.element.selector;
2970
- try {
2971
- const buffer = await page.locator(selector).first().screenshot({
2972
- type: "png",
2973
- timeout: 3e3
2974
- });
2975
- return buffer.toString("base64");
2976
- } catch {
2977
- }
2978
- try {
2979
- await page.waitForSelector(selector, { state: "visible", timeout: 2e3 });
2980
- const buffer = await page.locator(selector).first().screenshot({
2981
- type: "png",
2982
- timeout: 3e3
2983
- });
2984
- return buffer.toString("base64");
2985
- } catch {
2986
- }
2987
- try {
2988
- const buffer = await page.screenshot({ type: "png", timeout: 3e3 });
2989
- return buffer.toString("base64");
2990
- } catch {
2991
- return;
2992
- }
2993
- }
2994
- /**
2995
- * Action types that trigger auto-snapshot capture.
2996
- * Hover is excluded — it's too noisy and rarely changes the page visually.
2997
- * Popup_appear captures the popup state (after only).
2998
- */
2999
- static SNAPSHOT_TYPES = /* @__PURE__ */ new Set([
3000
- "click",
3001
- "dblclick",
3002
- "navigation",
3003
- "goto",
3004
- "submit",
3005
- "cdp-click",
3006
- "cdp-fill",
3007
- "input",
3008
- "change",
3009
- "filechooser",
3010
- "popup_appear"
3011
- ]);
3012
- /**
3013
- * Throttle key for snapshot capture to avoid too many during rapid inputs.
3014
- * Returns true if this action should be throttled (skip snapshot).
3015
- */
3016
- isSnapshotThrottled(type, selector) {
3017
- if (type === "input" || type === "change" || type === "cdp-fill") {
3018
- const key = `${type}|${selector || ""}`;
3019
- const last = this.snapshotThrottle.get(key);
3020
- const now = Date.now();
3021
- if (last && now - last < 2e3) return true;
3022
- this.snapshotThrottle.set(key, now);
3023
- }
3024
- return false;
3025
- }
3026
- /**
3027
- * Capture a viewport screenshot + compact accessibility tree for a key action.
3028
- * - PNG stored in .tmp/snapshots/ (temporary, easy to clean up)
3029
- * - aria tree stored inline as compact text on the action (searchable via grep)
3030
- *
3031
- * Non-blocking (errors silently caught). Throttled for rapid inputs.
3032
- */
3033
- async captureAutoSnapshot(page, action, suffix = "after") {
3034
- if (!_SessionRecorder.SNAPSHOT_TYPES.has(action.type)) return;
3035
- if (this.isSnapshotThrottled(action.type, action.element?.selector)) return;
3036
- const snapDir = this.snapshotsDir;
3037
- mkdirSync(snapDir, { recursive: true });
3038
- const stepId = String(action.id).padStart(3, "0");
3039
- const snapshot = {};
3040
- try {
3041
- const pngPath = join(snapDir, `step-${stepId}-${suffix}.png`);
3042
- const buffer = await page.screenshot({ type: "png", timeout: 5e3 });
3043
- writeFileSync(pngPath, buffer);
3044
- snapshot.png = `.tmp/snapshots/step-${stepId}-${suffix}.png`;
3045
- } catch {
3046
- }
3047
- try {
3048
- snapshot.aria = await page.evaluate(`
3049
- (function() {
3050
- try {
3051
- var parts = [];
3052
- var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT, null, false);
3053
- var node;
3054
- while (node = walker.nextNode()) {
3055
- var tag = node.tagName.toLowerCase();
3056
- var role = node.getAttribute('role') || '';
3057
- var text = (node.textContent || '').trim().substring(0, 60);
3058
- var ariaLabel = node.getAttribute('aria-label') || '';
3059
- if (role || tag === 'button' || tag === 'a' || tag === 'input' || tag === 'select' || tag === 'textarea') {
3060
- parts.push((role || tag) + ': ' + (ariaLabel || text).substring(0, 40));
3061
- }
3062
- }
3063
- return parts.slice(0, 100).join(' | ');
3064
- } catch(e) { return ''; }
3065
- })()
3066
- `);
3067
- } catch {
3068
- }
3069
- if (snapshot.png || snapshot.aria) {
3070
- action.snapshots = snapshot;
3071
- }
3072
- }
3073
- /**
3074
- * After a click, wait 300ms then scan for popover/dropdown/menu elements
3075
- * near the click position. This runs server-side to avoid race conditions
3076
- * with the client-side poll interval.
3077
- */
3078
- async captureClickContext(page, cx, cy) {
3079
- await new Promise((r) => setTimeout(r, 300));
3080
- try {
3081
- const ctx = await page.evaluate(`
3082
- (function() {
3083
- var cx = ${cx}, cy = ${cy};
3084
- var POPOVER_SELECTORS = [
3085
- '[role="menu"]','[role="listbox"]','[role="dialog"]','[role="tooltip"]','[role="popover"]',
3086
- '[role="combobox"]','[role="tree"]','[role="grid"]',
3087
- '.popover','.popup','.dropdown','.menu','.modal','.tooltip','.panel',
3088
- '[class*="popover"]','[class*="popup"]','[class*="dropdown"]','[class*="menu"]',
3089
- '[class*="tooltip"]','[class*="modal"]','[class*="panel"]','[class*="overlay"]','[class*="sheet"]',
3090
- '[data-popup]','[data-dropdown]','[data-menu]','[data-popover"]',
3091
- '.semi-dropdown','.semi-popover','.semi-modal',
3092
- '.ant-dropdown','.ant-popover','.ant-modal',
3093
- '.el-dropdown','.el-popover','.el-dialog',
3094
- '.t-dropdown','.t-popup','.t-dialog'
3095
- ];
3096
-
3097
- function isNear(el, x, y, range) {
3098
- try {
3099
- var r = el.getBoundingClientRect();
3100
- if (!r || r.width === 0 || r.height === 0) return false;
3101
- return !(r.left > x + range || r.right < x - range || r.top > y + range || r.bottom < y - range);
3102
- } catch(e) { return false; }
3103
- }
3104
-
3105
- var result = { appeared: [], disappeared: [], stateChanges: [] };
3106
- var seenElements = new Set();
3107
-
3108
- for (var si = 0; si < POPOVER_SELECTORS.length; si++) {
3109
- try {
3110
- var els = document.querySelectorAll(POPOVER_SELECTORS[si]);
3111
- for (var j = 0; j < els.length; j++) {
3112
- var el = els[j];
3113
- if (seenElements.has(el)) continue;
3114
- if (!isNear(el, cx, cy, 300)) continue;
3115
- var rect = el.getBoundingClientRect();
3116
- if (rect.width === 0 || rect.height === 0) continue;
3117
- seenElements.add(el);
3118
-
3119
- var items = [];
3120
- var children = el.querySelectorAll('a,button,[role="menuitem"],[role="option"],[role="treeitem"],li,div[class*="item"]');
3121
- var seenItemTexts = new Set();
3122
- for (var k = 0; k < Math.min(children.length, 30); k++) {
3123
- var child = children[k];
3124
- var childText = (child.textContent || '').trim().substring(0, 60);
3125
- if (!childText || seenItemTexts.has(childText)) continue;
3126
- seenItemTexts.add(childText);
3127
- var ci = { text: childText };
3128
- try { if (child.disabled || child.getAttribute('aria-disabled') === 'true') ci.disabled = true; } catch(e) {}
3129
- try { if (child.tagName) ci.tag = child.tagName.toLowerCase(); } catch(e) {}
3130
- try { if (child.href) ci.href = child.href.substring(0, 80); } catch(e) {}
3131
- items.push(ci);
3132
- }
3133
-
3134
- result.appeared.push({
3135
- tag: el.tagName.toLowerCase(),
3136
- selector: el.id ? '#' + el.id : undefined,
3137
- role: el.getAttribute('role'),
3138
- text: (el.textContent || '').trim().substring(0, 100),
3139
- rect: { x: Math.round(rect.x), y: Math.round(rect.y), w: Math.round(rect.width), h: Math.round(rect.height) },
3140
- items: items
3141
- });
3142
- }
3143
- } catch(e) { /* skip invalid selectors */ }
3144
- }
3145
-
3146
- var allInteractive = document.querySelectorAll('[aria-expanded],[disabled],[aria-disabled],[aria-selected],[data-state]');
3147
- for (var i = 0; i < allInteractive.length; i++) {
3148
- var el2 = allInteractive[i];
3149
- if (!isNear(el2, cx, cy, 200)) continue;
3150
- var info = { tag: el2.tagName.toLowerCase(), text: (el2.textContent || '').trim().substring(0, 60) };
3151
- try { if (el2.id) info.id = el2.id; } catch(e) {}
3152
- try { if (el2.getAttribute('aria-expanded')) info.ariaExpanded = el2.getAttribute('aria-expanded'); } catch(e) {}
3153
- try { if (el2.disabled || el2.getAttribute('aria-disabled') === 'true') info.disabled = true; } catch(e) {}
3154
- try { if (el2.getAttribute('aria-selected')) info.ariaSelected = el2.getAttribute('aria-selected'); } catch(e) {}
3155
- try { if (el2.getAttribute('data-state')) info.dataState = el2.getAttribute('data-state'); } catch(e) {}
3156
- result.stateChanges.push(info);
3157
- }
3158
-
3159
- return result;
3160
- })()
3161
- `);
3162
- if (ctx.appeared.length > 0 || ctx.stateChanges.length > 0) {
3163
- return ctx;
3164
- }
3165
- } catch {
3166
- }
3167
- return void 0;
3168
- }
3169
- async detectCheckpoints(page) {
3170
- const CHECKPOINT_RULES = [
3171
- { type: "captcha", selectors: ['img[src*="captcha"]', 'img[src*="verify"]', '[class*="captcha"]', '[id*="captcha"]', "#captcha", ".captcha"] },
3172
- { type: "slider", selectors: ['[class*="slider"]', '[class*="drag-verify"]', '[class*="slide-verify"]'] },
3173
- { type: "login", selectors: ['input[type="password"]'] },
3174
- { type: "iframe", selectors: ['iframe[src*="captcha"]', 'iframe[src*="verify"]', 'iframe[src*="recaptcha"]', 'iframe[title*="captcha"]'] }
3175
- ];
3176
- try {
3177
- const found = await page.evaluate((rules) => {
3178
- const results = [];
3179
- for (const rule of rules) {
3180
- for (const sel of rule.selectors) {
3181
- try {
3182
- const el = document.querySelector(sel);
3183
- if (el) {
3184
- const rect = el.getBoundingClientRect();
3185
- if (rect.width > 0 && rect.height > 0) {
3186
- results.push({
3187
- type: rule.type,
3188
- selector: sel,
3189
- text: (el.textContent || "").substring(0, 60)
3190
- });
3191
- }
3192
- }
3193
- } catch {
3194
- }
3195
- }
3196
- }
3197
- return results;
3198
- }, CHECKPOINT_RULES);
3199
- const entries = [];
3200
- for (const item of found) {
3201
- this.checkpointCounter++;
3202
- const hints = {
3203
- captcha: "Captcha verification detected",
3204
- slider: "Slider verification detected",
3205
- login: "Login form detected (password field)",
3206
- iframe: "Verification iframe detected"
3207
- };
3208
- entries.push({
3209
- id: this.checkpointCounter,
3210
- type: item.type,
3211
- timestamp: Date.now(),
3212
- url: page.url(),
3213
- pageTitle: await page.title().catch(() => ""),
3214
- hint: hints[item.type] || item.type,
3215
- selector: item.selector,
3216
- source: "auto",
3217
- context: { matchedSelector: item.selector, elementText: item.text }
3218
- });
3219
- }
3220
- return entries;
3221
- } catch {
3222
- return [];
3223
- }
3224
- }
3225
- // ─── Verification: collect success signals after key actions ──────
3226
- /**
3227
- * After a key action (click/submit/input), check for success signals:
3228
- * URL changes, recent successful network responses, dialog appearances.
3229
- */
3230
- async verifyAction(page, action) {
3231
- const signals = [];
3232
- try {
3233
- const currentUrl = page.url();
3234
- if (currentUrl && currentUrl !== "about:blank" && currentUrl !== action.url) {
3235
- signals.push({ type: "url_change", value: currentUrl, label: `URL changed to ${currentUrl}` });
3236
- }
3237
- } catch {
3238
- }
3239
- try {
3240
- const recentNetwork = this.network.filter(
3241
- (n) => n.timestamp > action.timestamp - 100 && n.timestamp < action.timestamp + 5e3 && n.status >= 200 && n.status < 400
3242
- );
3243
- for (const net of recentNetwork.slice(0, 3)) {
3244
- signals.push({
3245
- type: "network_success",
3246
- value: `${net.status}`,
3247
- label: `${net.method} ${net.path} \u2192 ${net.status}`
3248
- });
3249
- }
3250
- } catch {
3251
- }
3252
- try {
3253
- const recentDialog = [...this.checkpoints].reverse().find(
3254
- (cp) => cp.type === "dialog" && Math.abs(cp.timestamp - action.timestamp) < 3e3
3255
- );
3256
- if (recentDialog) {
3257
- signals.push({ type: "dialog", value: recentDialog.type, label: recentDialog.hint });
3258
- }
3259
- } catch {
3260
- }
3261
- return signals;
3262
- }
3263
3551
  // ─── Periodic disk flush ────────────────────────────────────────
3264
3552
  flushToDisk() {
3265
3553
  const data = this.buildData();
3266
3554
  try {
3267
- writeFileSync(
3268
- join(this.recordingsDir, "recording.json"),
3555
+ writeFileSync2(
3556
+ join3(this.recordingsDir, "recording.json"),
3269
3557
  JSON.stringify(data, null, 2),
3270
3558
  "utf-8"
3271
3559
  );
3272
- const jsonlPath = join(this.recordingsDir, "recording.jsonl");
3560
+ const jsonlPath = join3(this.recordingsDir, "recording.jsonl");
3273
3561
  const lines = data.actions.map((a) => JSON.stringify(a)).join("\n") + "\n";
3274
- writeFileSync(jsonlPath, lines, "utf-8");
3562
+ writeFileSync2(jsonlPath, lines, "utf-8");
3275
3563
  } catch {
3276
3564
  }
3277
3565
  }
3278
3566
  writeFinalOutput(data, summary) {
3279
- mkdirSync(this.recordingsDir, { recursive: true });
3280
- writeFileSync(join(this.recordingsDir, "recording.json"), JSON.stringify(data, null, 2), "utf-8");
3281
- const jsonlPath = join(this.recordingsDir, "recording.jsonl");
3567
+ mkdirSync2(this.recordingsDir, { recursive: true });
3568
+ writeFileSync2(join3(this.recordingsDir, "recording.json"), JSON.stringify(data, null, 2), "utf-8");
3569
+ const jsonlPath = join3(this.recordingsDir, "recording.jsonl");
3282
3570
  const lines = data.actions.map((a) => JSON.stringify(a)).join("\n") + "\n";
3283
- writeFileSync(jsonlPath, lines, "utf-8");
3284
- writeFileSync(join(this.recordingsDir, "summary.json"), JSON.stringify(summary, null, 2), "utf-8");
3285
- writeFileSync(join(this.recordingsDir, "summary.md"), this.buildMarkdownSummary(data, summary), "utf-8");
3571
+ writeFileSync2(jsonlPath, lines, "utf-8");
3572
+ writeFileSync2(join3(this.recordingsDir, "summary.json"), JSON.stringify(summary, null, 2), "utf-8");
3573
+ writeFileSync2(join3(this.recordingsDir, "summary.md"), buildMarkdownSummary(data, summary), "utf-8");
3286
3574
  }
3287
3575
  buildData() {
3288
3576
  return {
@@ -3290,321 +3578,15 @@ var SessionRecorder = class _SessionRecorder {
3290
3578
  sessionName: this.sessionName,
3291
3579
  startedAt: new Date(this.startedAt).toISOString(),
3292
3580
  actions: [...this.actions],
3293
- network: [...this.network],
3581
+ network: [...this.networkCapture.entries],
3294
3582
  contextChanges: [...this.contextChanges],
3295
3583
  checkpoints: [...this.checkpoints],
3296
3584
  discoveredFilters: [...this.discoveredFilters.values()]
3297
3585
  };
3298
3586
  }
3299
- // ─── Summary builder with ref compression + input→network matching ──
3300
- buildSummary(data) {
3301
- const POST_WINDOW = 5e3;
3302
- const MERGE_WINDOW = 2e3;
3303
- const steps = [];
3304
- const selectorToRef = /* @__PURE__ */ new Map();
3305
- const elements = {};
3306
- let refCounter = 0;
3307
- function getRef(action) {
3308
- const sel = action.element?.selector || action.element?.tag || "_none";
3309
- if (selectorToRef.has(sel)) return selectorToRef.get(sel);
3310
- refCounter++;
3311
- const ref = "e" + refCounter;
3312
- selectorToRef.set(sel, ref);
3313
- if (action.element) {
3314
- elements[ref] = {
3315
- selector: action.element.selector || action.element.tag,
3316
- tag: action.element.tag,
3317
- text: action.element.text,
3318
- role: action.element.role,
3319
- type: action.element.type,
3320
- placeholder: action.element.placeholder,
3321
- ariaLabel: action.element.ariaLabel,
3322
- href: action.element.href
3323
- };
3324
- } else {
3325
- elements[ref] = { selector: "_none", tag: "_", text: "" };
3326
- }
3327
- return ref;
3328
- }
3329
- const isNoiseNetwork = (n) => {
3330
- const url = n.url || "";
3331
- const path = n.path || "";
3332
- const rt = n.resourceType || "";
3333
- if (["image", "stylesheet", "font", "manifest", "other"].includes(rt)) return true;
3334
- if (n.status === 0) return true;
3335
- if (/\/ztbox|\/mwb2\.gif|\/hmslog|\/log\.gif|\/tongji|hm\.baidu|clickstream|\/actionlog|\/collect\?|\/track|\/beacon/i.test(url)) return true;
3336
- if (/\/favicon\.ico|\/robots\.txt/i.test(path)) return true;
3337
- return false;
3338
- };
3339
- const meaningfulNetwork = data.network.filter((n) => !isNoiseNetwork(n));
3340
- const filtered = data.actions;
3341
- const groups = [];
3342
- let current = null;
3343
- for (const action of filtered) {
3344
- const sameElement = current && current.primary.element?.selector && current.primary.element.selector === action.element?.selector && action.timestamp - current.primary.timestamp < MERGE_WINDOW;
3345
- const isInputLike = action.type === "input" || action.type === "keydown" || action.type === "change";
3346
- if (current && (sameElement || isInputLike && current.actions.some((a) => a.type === "input" || a.type === "click") && action.timestamp - current.primary.timestamp < MERGE_WINDOW)) {
3347
- current.actions.push(action);
3348
- if (action.type === "input") current.primary = action;
3349
- } else {
3350
- current = { actions: [action], primary: action };
3351
- groups.push(current);
3352
- }
3353
- }
3354
- for (const group of groups) {
3355
- const primary = group.primary;
3356
- const tsStart = Math.min(...group.actions.map((a) => a.timestamp));
3357
- const tsEnd = Math.max(...group.actions.map((a) => a.timestamp));
3358
- const inputAction = group.actions.find((a) => a.type === "input");
3359
- const nearbyNetwork = meaningfulNetwork.filter(
3360
- (n) => n.timestamp >= tsStart - 500 && n.timestamp <= tsEnd + POST_WINDOW
3361
- );
3362
- const nearbyContext = data.contextChanges.filter(
3363
- (c) => c.timestamp >= tsStart - 500 && c.timestamp <= tsEnd + POST_WINDOW
3364
- );
3365
- const matchedInputs = inputAction ? this.matchActionToNetwork(inputAction, nearbyNetwork) : [];
3366
- const clickMatches = primary.type === "click" && primary.element?.text ? this.matchActionToNetwork(primary, nearbyNetwork) : [];
3367
- const signals = primary.__signals || [];
3368
- steps.push({
3369
- step: steps.length + 1,
3370
- ref: getRef(primary),
3371
- action: primary,
3372
- network: nearbyNetwork.map((n) => ({
3373
- ...n,
3374
- responseBody: n.responseBody && JSON.stringify(n.responseBody).length > 1e3 ? "[truncated, " + JSON.stringify(n.responseBody).length + " bytes]" : n.responseBody
3375
- })),
3376
- contextChanges: nearbyContext,
3377
- matchedInputs: [...matchedInputs, ...clickMatches],
3378
- signals
3379
- });
3380
- }
3381
- return {
3382
- startUrl: data.startUrl,
3383
- recordedAt: new Date(this.startedAt).toISOString(),
3384
- durationMs: Date.now() - this.startedAt,
3385
- totalActions: data.actions.length,
3386
- totalNetworkRequests: meaningfulNetwork.length,
3387
- steps,
3388
- elements,
3389
- checkpoints: data.checkpoints
3390
- };
3391
- }
3392
- matchActionToNetwork(action, nearbyNetwork) {
3393
- const matches = [];
3394
- const searchValue = (action.value || action.element?.text || "").trim();
3395
- if (!searchValue || searchValue.length < 2) return matches;
3396
- for (const netEntry of nearbyNetwork) {
3397
- if (netEntry.url.includes(encodeURIComponent(searchValue)) || netEntry.url.includes(searchValue)) {
3398
- matches.push({ inputValue: searchValue, networkId: netEntry.id, paramName: "url" });
3399
- }
3400
- if (netEntry.requestBody && typeof netEntry.requestBody === "object") {
3401
- this.searchObjectForValue(
3402
- netEntry.requestBody,
3403
- searchValue,
3404
- netEntry.id,
3405
- "",
3406
- matches
3407
- );
3408
- }
3409
- }
3410
- return matches;
3411
- }
3412
- searchObjectForValue(obj, targetValue, networkId, prefix, results) {
3413
- for (const [key, value] of Object.entries(obj)) {
3414
- const fullKey = prefix ? `${prefix}.${key}` : key;
3415
- if (typeof value === "string" && value.includes(targetValue)) {
3416
- results.push({ inputValue: targetValue, networkId, paramName: fullKey });
3417
- } else if (typeof value === "object" && value !== null) {
3418
- this.searchObjectForValue(value, targetValue, networkId, fullKey, results);
3419
- }
3420
- }
3421
- }
3422
- buildMarkdownSummary(_data, summary) {
3423
- const lines = [];
3424
- const durSec = Math.round(summary.durationMs / 1e3);
3425
- lines.push("# Recording Summary");
3426
- lines.push("");
3427
- lines.push(`- **URL**: ${summary.startUrl}`);
3428
- lines.push(`- **Recorded**: ${summary.recordedAt}`);
3429
- lines.push(`- **Duration**: ${durSec}s`);
3430
- lines.push(`- **Steps**: ${summary.totalActions} actions, ${summary.totalNetworkRequests} network requests`);
3431
- if (summary.checkpoints.length > 0) {
3432
- const cpTypes = summary.checkpoints.map((c) => c.type);
3433
- lines.push(`- **Checkpoints**: ${summary.checkpoints.length} (${[...new Set(cpTypes)].join(", ")})`);
3434
- } else {
3435
- lines.push("- **Checkpoints**: 0");
3436
- }
3437
- const checkpointSteps = /* @__PURE__ */ new Map();
3438
- for (const cp of summary.checkpoints) {
3439
- if (cp.relatedActionId != null) {
3440
- for (const step of summary.steps) {
3441
- if (step.action.id === cp.relatedActionId) {
3442
- checkpointSteps.set(step.step, cp);
3443
- break;
3444
- }
3445
- }
3446
- }
3447
- }
3448
- lines.push("");
3449
- lines.push("## Steps");
3450
- lines.push("");
3451
- for (const step of summary.steps) {
3452
- const a = step.action;
3453
- const el = a.element;
3454
- const cp = checkpointSteps.get(step.step);
3455
- if (cp) {
3456
- lines.push(`### Step ${step.step}: \u26A0\uFE0F CHECKPOINT \u2014 ${cp.hint}`);
3457
- lines.push(`- **Type**: ${cp.type} (${cp.source})`);
3458
- lines.push(`- **Hint**: ${cp.hint}`);
3459
- if (cp.selector) lines.push(`- **Selector**: \`${cp.selector}\``);
3460
- lines.push(`- **Action needed**: Human intervention required before continuing`);
3461
- } else {
3462
- const title = describeActionTitle(a);
3463
- lines.push(`### Step ${step.step}: ${title}`);
3464
- }
3465
- if (el) {
3466
- const parts = [`\`${el.selector || el.tag}\``];
3467
- if (el.text) parts.push(`"${el.text.substring(0, 60)}"`);
3468
- parts.push(`(${el.tag})`);
3469
- if (el.type) parts.push(`type=${el.type}`);
3470
- lines.push(`- **Element**: ${parts.join(" ")}`);
3471
- }
3472
- if (a.value != null && a.type === "input") {
3473
- lines.push(`- **Value**: "${a.value.substring(0, 100)}"`);
3474
- }
3475
- if (step.network.length > 0) {
3476
- const netDescs = step.network.map((n) => {
3477
- let desc = `${n.method} ${n.path}`;
3478
- if (n.status) desc += ` \u2192 ${n.status}`;
3479
- if (n.responseSize > 0) desc += ` (${formatBytes(n.responseSize)})`;
3480
- return desc;
3481
- });
3482
- lines.push(`- **Network**: ${netDescs.join(", ")}`);
3483
- for (const n of step.network) {
3484
- if (n.requestBody && typeof n.requestBody === "object") {
3485
- const bodyStr = JSON.stringify(n.requestBody);
3486
- if (bodyStr.length <= 300) {
3487
- lines.push(` - \`${n.method} ${n.path}\` body: \`${bodyStr}\``);
3488
- } else {
3489
- lines.push(` - \`${n.method} ${n.path}\` body: \`${bodyStr.substring(0, 300)}...\` (${bodyStr.length} bytes)`);
3490
- }
3491
- }
3492
- }
3493
- } else {
3494
- lines.push("- **Network**: none");
3495
- }
3496
- if (step.matchedInputs.length > 0) {
3497
- for (const m of step.matchedInputs) {
3498
- lines.push(`- **Input matched**: "${m.inputValue}" \u2192 ${m.paramName} (network #${m.networkId})`);
3499
- }
3500
- }
3501
- for (const ctx of step.contextChanges) {
3502
- if (ctx.type === "navigate") {
3503
- lines.push(`- **Navigate**: \u2192 ${ctx.url}`);
3504
- } else if (ctx.type === "new_tab") {
3505
- lines.push(`- **New tab**: ${ctx.url}`);
3506
- }
3507
- }
3508
- if (a.clickContext) {
3509
- if (a.clickContext.appeared?.length > 0) {
3510
- for (const popup of a.clickContext.appeared) {
3511
- const roleStr = popup.role ? ` [${popup.role}]` : "";
3512
- lines.push(`- **Popup**: <${popup.tag}${roleStr}> "${(popup.text || "").substring(0, 60)}"`);
3513
- if (popup.items?.length > 0) {
3514
- const itemStrs = popup.items.slice(0, 8).map((i) => {
3515
- const dis = i.disabled ? " [disabled]" : "";
3516
- return `"${i.text}"${dis}`;
3517
- });
3518
- let itemLine = ` - Items: ${itemStrs.join(", ")}`;
3519
- if (popup.items.length > 8) itemLine += ` ... +${popup.items.length - 8} more`;
3520
- lines.push(itemLine);
3521
- }
3522
- }
3523
- }
3524
- if (a.clickContext.stateChanges?.length > 0) {
3525
- for (const sc of a.clickContext.stateChanges) {
3526
- const parts = [];
3527
- if (sc.ariaExpanded !== void 0) parts.push(`expanded=${sc.ariaExpanded}`);
3528
- if (sc.disabled) parts.push("disabled");
3529
- if (sc.ariaSelected !== void 0) parts.push(`selected=${sc.ariaSelected}`);
3530
- if (sc.dataState) parts.push(`state=${sc.dataState}`);
3531
- if (parts.length > 0) {
3532
- lines.push(`- **State**: <${sc.tag}> "${(sc.text || "").substring(0, 30)}" ${parts.join(", ")}`);
3533
- }
3534
- }
3535
- }
3536
- }
3537
- lines.push("");
3538
- }
3539
- const allNetwork = summary.steps.flatMap((s) => s.network);
3540
- if (allNetwork.length > 0) {
3541
- lines.push("## Network Timeline");
3542
- lines.push("");
3543
- allNetwork.forEach((n, i) => {
3544
- let line = `${i + 1}. ${n.method} ${n.path}`;
3545
- if (n.status) line += ` \u2192 ${n.status}`;
3546
- if (n.requestBody && typeof n.requestBody === "object") {
3547
- const bodyStr = JSON.stringify(n.requestBody);
3548
- if (bodyStr.length <= 150) {
3549
- line += ` ${bodyStr}`;
3550
- }
3551
- }
3552
- if (n.responseSize > 0) line += ` (${formatBytes(n.responseSize)})`;
3553
- lines.push(line);
3554
- });
3555
- lines.push("");
3556
- }
3557
- const orphanCheckpoints = summary.checkpoints.filter(
3558
- (cp) => cp.relatedActionId == null || !checkpointSteps.has(
3559
- summary.steps.find((s) => s.action.id === cp.relatedActionId)?.step ?? -1
3560
- )
3561
- );
3562
- if (orphanCheckpoints.length > 0) {
3563
- lines.push("## Unresolved Checkpoints");
3564
- lines.push("");
3565
- for (const cp of orphanCheckpoints) {
3566
- const src = cp.source === "auto" ? "[auto]" : "[manual]";
3567
- lines.push(`- ${src} **${cp.type}**: ${cp.hint}`);
3568
- if (cp.selector) lines.push(` - Selector: \`${cp.selector}\``);
3569
- }
3570
- lines.push("");
3571
- }
3572
- return lines.join("\n");
3573
- }
3574
- static readMarkdownSummary(sessionName) {
3575
- const path = join(_SessionRecorder.getRecordingsDir(sessionName), "summary.md");
3576
- try {
3577
- return readFileSync(path, "utf-8");
3578
- } catch {
3579
- return null;
3580
- }
3581
- }
3582
3587
  };
3583
- function describeActionTitle(a) {
3584
- const el = a.element;
3585
- const elText = el?.text ? `"${el.text.substring(0, 40)}"` : "";
3586
- const elTag = el?.tag ? `<${el.tag}>` : "";
3587
- switch (a.type) {
3588
- case "click":
3589
- return `Click ${elText || elTag} button`.replace(/ +/g, " ").trim();
3590
- case "input":
3591
- return `Input "${(a.value || "").substring(0, 50)}" in ${elText || elTag || "field"}`.replace(/ +/g, " ").trim();
3592
- case "change":
3593
- return `Change ${elText || elTag} to "${(a.value || "").substring(0, 30)}"`;
3594
- case "keydown":
3595
- return `Press ${a.key || "key"} on ${elText || elTag || "element"}`;
3596
- case "submit":
3597
- return `Submit ${elText || elTag || "form"}`;
3598
- default:
3599
- return `${a.type} ${elText || elTag}`.trim() || a.type;
3600
- }
3601
- }
3602
- function formatBytes(bytes) {
3603
- if (bytes < 1024) return `${bytes}B`;
3604
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
3605
- return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
3606
- }
3607
3588
 
3608
3589
  export {
3590
+ readMarkdownSummary,
3609
3591
  SessionRecorder
3610
3592
  };