spana-test 0.6.0 → 0.8.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 (102) hide show
  1. package/.agents/skills/spana-testing/SKILL.md +19 -15
  2. package/dist/agent/index.d.ts +2 -2
  3. package/dist/agent/index.js +9 -9
  4. package/dist/{allure-RNMEYTXS.js → allure-RAEK4SIH.js} +2 -2
  5. package/dist/allure-RAEK4SIH.js.map +1 -0
  6. package/dist/{android-4NVTZMHL.js → android-6BOQTMM3.js} +2 -2
  7. package/dist/app-CgbLADmF.d.ts +1191 -0
  8. package/dist/{chunk-H27IBIGA.js → chunk-2AFWVHQK.js} +63 -43
  9. package/dist/chunk-2AFWVHQK.js.map +1 -0
  10. package/dist/{chunk-KBRLIQRA.js → chunk-2T4K7BJ3.js} +8 -3
  11. package/dist/chunk-2T4K7BJ3.js.map +1 -0
  12. package/dist/{chunk-KEUZLBQS.js → chunk-3FXDOTFI.js} +1361 -327
  13. package/dist/chunk-3FXDOTFI.js.map +1 -0
  14. package/dist/{chunk-4K3FZTSV.js → chunk-54ASKII6.js} +6 -2
  15. package/dist/chunk-54ASKII6.js.map +1 -0
  16. package/dist/{chunk-PWUJT5HE.js → chunk-AJCSETN6.js} +1330 -246
  17. package/dist/chunk-AJCSETN6.js.map +1 -0
  18. package/dist/chunk-JPZCZHL4.js +79 -0
  19. package/dist/chunk-JPZCZHL4.js.map +1 -0
  20. package/dist/{chunk-C4E4XULT.js → chunk-NS2HLJO4.js} +3 -3
  21. package/dist/{chunk-S4JVAHBR.js → chunk-PMXSU5MS.js} +2 -2
  22. package/dist/{chunk-HYSTRWYN.js → chunk-QP4MDUBY.js} +4 -4
  23. package/dist/chunk-RKYKRGHB.js +236 -0
  24. package/dist/chunk-RKYKRGHB.js.map +1 -0
  25. package/dist/{chunk-HCG4CJKR.js → chunk-SF7UYW4I.js} +3 -3
  26. package/dist/{chunk-LCV673G3.js → chunk-SNL4X67N.js} +1166 -94
  27. package/dist/chunk-SNL4X67N.js.map +1 -0
  28. package/dist/{chunk-WBBMEAHU.js → chunk-WKVU24B6.js} +8 -8
  29. package/dist/{chunk-S5JNNDXS.js → chunk-WV3ALL3H.js} +65 -37
  30. package/dist/chunk-WV3ALL3H.js.map +1 -0
  31. package/dist/cli.js +23 -11
  32. package/dist/cli.js.map +1 -1
  33. package/dist/config-loader-5FU45FXK.js +9 -0
  34. package/dist/{console-MI2XB5RG.js → console-BGAK7Z2L.js} +11 -1
  35. package/dist/{console-MI2XB5RG.js.map → console-BGAK7Z2L.js.map} +1 -1
  36. package/dist/{daemon-manager-FBISTX24.js → daemon-manager-DDYQITPD.js} +4 -2
  37. package/dist/{discover-LHEBSUIP.js → discover-RLSKEBAX.js} +5 -5
  38. package/dist/{doctor-command-WEHFANT7.js → doctor-command-HEQQOYUR.js} +26 -18
  39. package/dist/doctor-command-HEQQOYUR.js.map +1 -0
  40. package/dist/{flow-C2JQ7gUu.d.ts → flow-Md5xLwbX.d.ts} +3 -29
  41. package/dist/gherkin/steps.d.ts +2 -2
  42. package/dist/{html-F3X3XPSX.js → html-JO2YNRWX.js} +195 -4
  43. package/dist/html-JO2YNRWX.js.map +1 -0
  44. package/dist/index.d.ts +400 -15
  45. package/dist/index.js +255 -18
  46. package/dist/index.js.map +1 -1
  47. package/dist/{installer-VUPFWP5X.js → installer-IYGMG7LS.js} +4 -4
  48. package/dist/{ios-JPK43TFZ.js → ios-Y4TO5MBR.js} +7 -3
  49. package/dist/{screenshot-compare-5NINZVOK.js → screenshot-compare-POTXVUTL.js} +2 -2
  50. package/dist/{server-3MGZNK67.js → server-4PEREPHY.js} +2 -2
  51. package/dist/{server-OANRDAHN.js → server-JPNH33MX.js} +50 -36
  52. package/dist/server-JPNH33MX.js.map +1 -0
  53. package/dist/{session-Daq0mE_a.d.ts → session-D9e30RVS.d.ts} +1 -1
  54. package/dist/session-V4PYJXNB.js +18 -0
  55. package/dist/{studio-command-RJYLJT4I.js → studio-command-JOIFCOHC.js} +2 -2
  56. package/dist/{test-command-ALH5ZQY5.js → test-command-JCO2HPYI.js} +221 -27
  57. package/dist/test-command-JCO2HPYI.js.map +1 -0
  58. package/native/darwin-arm64/libspana_native.dylib +0 -0
  59. package/native/darwin-x64/libspana_native.dylib +0 -0
  60. package/native/linux-arm64/libspana_native.so +0 -0
  61. package/native/linux-x64/libspana_native.so +0 -0
  62. package/native/win32-x64/spana_native.dll +0 -0
  63. package/package.json +2 -1
  64. package/studio-dist/assets/index-CBFsOh-9.js +193 -0
  65. package/studio-dist/assets/index-DH_18EyL.css +1 -0
  66. package/studio-dist/index.html +2 -2
  67. package/dist/allure-RNMEYTXS.js.map +0 -1
  68. package/dist/app-DcLXtpv4.d.ts +0 -908
  69. package/dist/chunk-4K3FZTSV.js.map +0 -1
  70. package/dist/chunk-DTNK54C2.js +0 -127
  71. package/dist/chunk-DTNK54C2.js.map +0 -1
  72. package/dist/chunk-H27IBIGA.js.map +0 -1
  73. package/dist/chunk-KBRLIQRA.js.map +0 -1
  74. package/dist/chunk-KEUZLBQS.js.map +0 -1
  75. package/dist/chunk-LCV673G3.js.map +0 -1
  76. package/dist/chunk-OBCFACUW.js +0 -28
  77. package/dist/chunk-OBCFACUW.js.map +0 -1
  78. package/dist/chunk-PWUJT5HE.js.map +0 -1
  79. package/dist/chunk-S5JNNDXS.js.map +0 -1
  80. package/dist/config-loader-J4Z2PMUQ.js +0 -9
  81. package/dist/doctor-command-WEHFANT7.js.map +0 -1
  82. package/dist/html-F3X3XPSX.js.map +0 -1
  83. package/dist/server-OANRDAHN.js.map +0 -1
  84. package/dist/session-Q3QYHT4Q.js +0 -18
  85. package/dist/test-command-ALH5ZQY5.js.map +0 -1
  86. package/studio-dist/assets/index-C-Io44gy.js +0 -193
  87. package/studio-dist/assets/index-DfM9lK4p.css +0 -1
  88. /package/dist/{android-4NVTZMHL.js.map → android-6BOQTMM3.js.map} +0 -0
  89. /package/dist/{chunk-C4E4XULT.js.map → chunk-NS2HLJO4.js.map} +0 -0
  90. /package/dist/{chunk-S4JVAHBR.js.map → chunk-PMXSU5MS.js.map} +0 -0
  91. /package/dist/{chunk-HYSTRWYN.js.map → chunk-QP4MDUBY.js.map} +0 -0
  92. /package/dist/{chunk-HCG4CJKR.js.map → chunk-SF7UYW4I.js.map} +0 -0
  93. /package/dist/{chunk-WBBMEAHU.js.map → chunk-WKVU24B6.js.map} +0 -0
  94. /package/dist/{config-loader-J4Z2PMUQ.js.map → config-loader-5FU45FXK.js.map} +0 -0
  95. /package/dist/{daemon-manager-FBISTX24.js.map → daemon-manager-DDYQITPD.js.map} +0 -0
  96. /package/dist/{discover-LHEBSUIP.js.map → discover-RLSKEBAX.js.map} +0 -0
  97. /package/dist/{installer-VUPFWP5X.js.map → installer-IYGMG7LS.js.map} +0 -0
  98. /package/dist/{ios-JPK43TFZ.js.map → ios-Y4TO5MBR.js.map} +0 -0
  99. /package/dist/{screenshot-compare-5NINZVOK.js.map → screenshot-compare-POTXVUTL.js.map} +0 -0
  100. /package/dist/{server-3MGZNK67.js.map → server-4PEREPHY.js.map} +0 -0
  101. /package/dist/{session-Q3QYHT4Q.js.map → session-V4PYJXNB.js.map} +0 -0
  102. /package/dist/{studio-command-RJYLJT4I.js.map → studio-command-JOIFCOHC.js.map} +0 -0
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  connectPlaywrightOverCDP,
3
3
  connectPlaywrightOverWS,
4
- createCoordinator,
5
4
  createPromiseApp,
5
+ createPromiseExpect,
6
6
  createUiAutomator2Driver,
7
7
  createWDADriver,
8
8
  ensureWarmBrowserDaemon,
@@ -16,144 +16,41 @@ import {
16
16
  parseWebHierarchy,
17
17
  resolveNetworkConditions,
18
18
  setupUiAutomator2
19
- } from "./chunk-PWUJT5HE.js";
19
+ } from "./chunk-AJCSETN6.js";
20
20
  import {
21
21
  CdpDomChannel,
22
22
  DriverError,
23
+ SPANA_INJECTED_RUNTIME_SCRIPT,
24
+ buildDomFindElementScript,
23
25
  createSpanaBridgeChannel,
24
26
  makeElectrobunDriver
25
- } from "./chunk-LCV673G3.js";
27
+ } from "./chunk-SNL4X67N.js";
26
28
  import {
27
29
  setupWDA
28
- } from "./chunk-HYSTRWYN.js";
30
+ } from "./chunk-QP4MDUBY.js";
29
31
  import {
30
32
  getHealthyWarmDaemon,
31
33
  registerWarmDaemon,
32
34
  updateWarmDaemonSession
33
- } from "./chunk-DTNK54C2.js";
35
+ } from "./chunk-RKYKRGHB.js";
34
36
  import {
35
37
  connectPhysicalDevice,
36
38
  ensureAppInstalled,
37
39
  ensureIOSSimulator,
38
40
  firstIOSPhysicalDevice
39
- } from "./chunk-S5JNNDXS.js";
41
+ } from "./chunk-WV3ALL3H.js";
40
42
  import {
43
+ allocateFreePort,
41
44
  allocatePort
42
- } from "./chunk-OBCFACUW.js";
45
+ } from "./chunk-JPZCZHL4.js";
43
46
  import {
44
47
  adbReverse,
45
48
  adbReverseRemove,
46
49
  ensureAndroidDevice
47
- } from "./chunk-H27IBIGA.js";
48
-
49
- // src/api/expect.ts
50
- import { Effect } from "effect";
51
- function selectorToCss(sel) {
52
- if (typeof sel === "string") return sel;
53
- if (typeof sel === "object" && sel !== null && "testID" in sel && sel.testID)
54
- return `[data-testid="${sel.testID}"]`;
55
- if (typeof sel === "object" && sel !== null && "accessibilityLabel" in sel && sel.accessibilityLabel)
56
- return `[aria-label="${sel.accessibilityLabel}"]`;
57
- return "";
58
- }
59
- function createPromiseExpect(driver, config, recorder, flowContext, visualRegression) {
60
- const ctx = flowContext ?? {
61
- flowFilePath: "",
62
- flowName: "unknown",
63
- platform: "web"
64
- };
65
- const coord = createCoordinator(driver, config);
66
- const run = (effect) => Effect.runPromise(effect);
67
- const runStep = (command, selector, action) => recorder ? recorder.runStep(command, action, { selector, captureScreenshot: false }) : action();
68
- return (selector) => ({
69
- toBeVisible: (opts) => runStep(
70
- "expect.toBeVisible",
71
- selector,
72
- () => run(coord.assertVisible(selector, opts)).then(() => {
73
- })
74
- ),
75
- toBeHidden: (opts) => runStep("expect.toBeHidden", selector, () => run(coord.assertHidden(selector, opts))),
76
- toHaveText: (expected, opts) => runStep(
77
- `expect.toHaveText(${JSON.stringify(expected)})`,
78
- selector,
79
- () => run(coord.assertText(selector, expected, opts))
80
- ),
81
- toMatchText: (pattern, opts) => runStep(
82
- `expect.toMatchText(${pattern})`,
83
- selector,
84
- () => run(coord.assertMatchesText(selector, pattern, opts))
85
- ),
86
- toHaveValue: (expected, opts) => runStep(
87
- `expect.toHaveValue(${JSON.stringify(expected)})`,
88
- selector,
89
- () => run(coord.assertValue(selector, expected, opts))
90
- ),
91
- toHaveAttribute: (name, value, opts) => runStep(
92
- `expect.toHaveAttribute(${JSON.stringify(name)})`,
93
- selector,
94
- () => run(coord.assertAttribute(selector, name, value, opts))
95
- ),
96
- toBeEnabled: (opts) => runStep("expect.toBeEnabled", selector, () => run(coord.assertEnabled(selector, opts))),
97
- toBeDisabled: (opts) => runStep("expect.toBeDisabled", selector, () => run(coord.assertDisabled(selector, opts))),
98
- toContainText: (expected, opts) => runStep(
99
- `expect.toContainText(${JSON.stringify(expected)})`,
100
- selector,
101
- () => run(coord.assertContainsText(selector, expected, opts))
102
- ),
103
- toMatchScreenshot: (name, options) => runStep(
104
- `expect.toMatchScreenshot(${JSON.stringify(name)})`,
105
- selector,
106
- () => run(
107
- coord.assertScreenshot(selector, name, ctx.flowFilePath, ctx.flowName, ctx.platform, {
108
- threshold: options?.threshold ?? visualRegression?.threshold,
109
- maxDiffPixelRatio: options?.maxDiffPixelRatio ?? visualRegression?.maxDiffPixelRatio,
110
- mask: [],
111
- updateBaselines: ctx.updateBaselines,
112
- baselinesDir: visualRegression?.baselinesDir
113
- })
114
- )
115
- ),
116
- toPassAccessibilityAudit: (options) => {
117
- const excludeCss = options?.exclude?.map(selectorToCss).filter(Boolean) ?? [];
118
- const targetCss = selectorToCss(selector);
119
- return runStep(
120
- "expect.toPassAccessibilityAudit",
121
- selector,
122
- () => run(
123
- coord.assertAccessibilityAudit(ctx.platform, {
124
- severity: options?.severity,
125
- rules: options?.rules,
126
- targetSelector: targetCss || void 0,
127
- excludeSelectors: excludeCss
128
- })
129
- )
130
- );
131
- },
132
- toHaveAccessibilityLabel: (expected) => runStep(
133
- `expect.toHaveAccessibilityLabel(${expected !== void 0 ? JSON.stringify(expected) : ""})`,
134
- selector,
135
- () => run(coord.assertAccessibilityLabel(selector, expected))
136
- ),
137
- toBeFocusable: () => runStep(
138
- "expect.toBeFocusable",
139
- selector,
140
- () => run(coord.assertFocusable(selector, ctx.platform))
141
- ),
142
- toHaveRole: (expected) => runStep(
143
- `expect.toHaveRole(${JSON.stringify(expected)})`,
144
- selector,
145
- () => run(coord.assertRole(selector, expected, ctx.platform))
146
- ),
147
- toHaveMinTouchTarget: (size = 44) => runStep(
148
- `expect.toHaveMinTouchTarget(${size})`,
149
- selector,
150
- () => run(coord.assertMinTouchTarget(selector, size))
151
- )
152
- });
153
- }
50
+ } from "./chunk-2AFWVHQK.js";
154
51
 
155
52
  // src/core/session-manager.ts
156
- import { Effect as Effect2 } from "effect";
53
+ import { Effect } from "effect";
157
54
  function createSessions(manager, driverFactory, coordinatorConfig) {
158
55
  const coordConfig = coordinatorConfig ?? { parse: parseWebHierarchy };
159
56
  return {
@@ -164,7 +61,7 @@ function createSessions(manager, driverFactory, coordinatorConfig) {
164
61
  }
165
62
  const driver = await driverFactory(opts);
166
63
  const baseUrl = opts.baseUrl ?? "http://localhost:3000";
167
- await Effect2.runPromise(driver.launchApp(baseUrl));
64
+ await Effect.runPromise(driver.launchApp(baseUrl));
168
65
  const app = createPromiseApp(driver, baseUrl, coordConfig, void 0, {
169
66
  platform: "web"
170
67
  });
@@ -175,12 +72,12 @@ function createSessions(manager, driverFactory, coordinatorConfig) {
175
72
  app,
176
73
  expect,
177
74
  async disconnect() {
178
- await Effect2.runPromise(driver.killApp(baseUrl));
75
+ await Effect.runPromise(driver.killApp(baseUrl));
179
76
  manager.remove(opts.name);
180
77
  }
181
78
  };
182
79
  const cleanup = async () => {
183
- await Effect2.runPromise(driver.killApp(baseUrl));
80
+ await Effect.runPromise(driver.killApp(baseUrl));
184
81
  };
185
82
  manager.register(session, cleanup);
186
83
  return session;
@@ -224,7 +121,7 @@ import { existsSync, mkdtempSync, rmSync } from "fs";
224
121
  import { copyFile, readFile, writeFile } from "fs/promises";
225
122
  import { tmpdir } from "os";
226
123
  import { join } from "path";
227
- import { Effect as Effect3 } from "effect";
124
+ import { Effect as Effect2 } from "effect";
228
125
  var INSTANT_ANIMATIONS_CDP_SCRIPT = `
229
126
  (() => {
230
127
  const inject = () => {
@@ -243,7 +140,7 @@ var INSTANT_ANIMATIONS_CDP_SCRIPT = `
243
140
  `;
244
141
  function resolveDirectCdpScopeKey(scope) {
245
142
  if (scope && scope.trim().length > 0) return scope.trim();
246
- const cwdHash = createHash("sha1").update(process.cwd()).digest("hex").slice(0, 10);
143
+ const cwdHash = createHash("sha256").update(process.cwd()).digest("hex").slice(0, 10);
247
144
  return `cdp-${cwdHash}`;
248
145
  }
249
146
  function resolveChromiumExecutable(explicit) {
@@ -318,7 +215,7 @@ async function launchDirectCdpBrowser(options = {}) {
318
215
  }
319
216
  }
320
217
  execPath = resolveChromiumExecutable(execPath);
321
- const port = allocatePort(9350);
218
+ const port = await allocateFreePort(9350);
322
219
  const userDataDir = mkdtempSync(join(tmpdir(), "spana-cdp-profile-"));
323
220
  const chromeArgs = [
324
221
  ...options.headless !== false ? ["--headless=new"] : [],
@@ -350,7 +247,17 @@ async function launchDirectCdpBrowser(options = {}) {
350
247
  child.unref();
351
248
  }
352
249
  const httpEndpoint = `http://127.0.0.1:${port}`;
353
- const browserWsUrl = await fetchBrowserWsUrl(httpEndpoint, 1e4);
250
+ let browserWsUrl;
251
+ try {
252
+ browserWsUrl = await fetchBrowserWsUrl(httpEndpoint, 1e4);
253
+ } catch (err) {
254
+ try {
255
+ child.kill("SIGKILL");
256
+ } catch {
257
+ }
258
+ rmSync(userDataDir, { recursive: true, force: true });
259
+ throw err;
260
+ }
354
261
  if (options.warmBrowser) {
355
262
  registerWarmDaemon({
356
263
  kind: "chromium",
@@ -358,6 +265,7 @@ async function launchDirectCdpBrowser(options = {}) {
358
265
  host: "127.0.0.1",
359
266
  port,
360
267
  pid: child.pid,
268
+ userDataDir,
361
269
  startedAt: (/* @__PURE__ */ new Date()).toISOString()
362
270
  });
363
271
  }
@@ -405,6 +313,76 @@ function matchUrl(matcher, url) {
405
313
  }
406
314
  return url.includes(matcher);
407
315
  }
316
+ var CDP_SPECIAL_KEYS = {
317
+ Enter: { code: "Enter", keyCode: 13, text: "\r" },
318
+ Backspace: { code: "Backspace", keyCode: 8 },
319
+ Tab: { code: "Tab", keyCode: 9 },
320
+ Escape: { code: "Escape", keyCode: 27 },
321
+ Delete: { code: "Delete", keyCode: 46 },
322
+ ArrowLeft: { code: "ArrowLeft", keyCode: 37 },
323
+ ArrowUp: { code: "ArrowUp", keyCode: 38 },
324
+ ArrowRight: { code: "ArrowRight", keyCode: 39 },
325
+ ArrowDown: { code: "ArrowDown", keyCode: 40 },
326
+ Home: { code: "Home", keyCode: 36 },
327
+ End: { code: "End", keyCode: 35 },
328
+ PageUp: { code: "PageUp", keyCode: 33 },
329
+ PageDown: { code: "PageDown", keyCode: 34 },
330
+ Space: { code: "Space", keyCode: 32, text: " " },
331
+ " ": { code: "Space", keyCode: 32, text: " " }
332
+ };
333
+ function parseCdpKeyDescriptor(rawKey) {
334
+ const parts = rawKey.split("+");
335
+ let modifiers = 0;
336
+ let baseKey = rawKey;
337
+ if (parts.length > 1) {
338
+ baseKey = parts[parts.length - 1] ?? rawKey;
339
+ for (let i = 0; i < parts.length - 1; i++) {
340
+ const mod = (parts[i] ?? "").toLowerCase();
341
+ if (mod === "alt" || mod === "option") modifiers |= 1;
342
+ else if (mod === "control" || mod === "ctrl") modifiers |= 2;
343
+ else if (mod === "meta" || mod === "cmd" || mod === "command") modifiers |= 4;
344
+ else if (mod === "shift") modifiers |= 8;
345
+ }
346
+ }
347
+ const special = CDP_SPECIAL_KEYS[baseKey];
348
+ if (special) {
349
+ return {
350
+ key: baseKey === "Space" ? " " : baseKey,
351
+ code: special.code,
352
+ windowsVirtualKeyCode: special.keyCode,
353
+ modifiers,
354
+ ...special.text ? { text: special.text } : {}
355
+ };
356
+ }
357
+ if (baseKey.length === 1) {
358
+ const upper = baseKey.toUpperCase();
359
+ const charCode = upper.charCodeAt(0);
360
+ const isLetter = charCode >= 65 && charCode <= 90;
361
+ const isDigit = charCode >= 48 && charCode <= 57;
362
+ const commands = [];
363
+ if ((modifiers & (2 | 4)) !== 0) {
364
+ if (baseKey.toLowerCase() === "a") commands.push("selectAll");
365
+ else if (baseKey.toLowerCase() === "c") commands.push("copy");
366
+ else if (baseKey.toLowerCase() === "v") commands.push("paste");
367
+ else if (baseKey.toLowerCase() === "x") commands.push("cut");
368
+ else if (baseKey.toLowerCase() === "z") commands.push("undo");
369
+ }
370
+ return {
371
+ key: baseKey,
372
+ code: isLetter ? `Key${upper}` : isDigit ? `Digit${baseKey}` : "",
373
+ windowsVirtualKeyCode: charCode,
374
+ modifiers,
375
+ ...modifiers === 0 || modifiers === 8 ? { text: baseKey } : {},
376
+ ...commands.length > 0 ? { commands } : {}
377
+ };
378
+ }
379
+ return {
380
+ key: baseKey,
381
+ code: baseKey,
382
+ windowsVirtualKeyCode: 0,
383
+ modifiers
384
+ };
385
+ }
408
386
  var RESOURCE_BLOCK_PATTERNS = {
409
387
  image: ["*.png", "*.jpg", "*.jpeg", "*.gif", "*.webp", "*.svg", "*.ico", "*.avif"],
410
388
  font: ["*.woff", "*.woff2", "*.ttf", "*.otf", "*.eot"],
@@ -412,7 +390,7 @@ var RESOURCE_BLOCK_PATTERNS = {
412
390
  stylesheet: ["*.css"]
413
391
  };
414
392
  function makeLightweightCdpDriver(options) {
415
- return Effect3.gen(function* () {
393
+ return Effect2.gen(function* () {
416
394
  const isBrowserWs = options.cdpUrl.includes("/devtools/browser/");
417
395
  const useContexts = Boolean(
418
396
  options.useBrowserContexts || options.freshContextPerFlow || isBrowserWs
@@ -421,7 +399,7 @@ function makeLightweightCdpDriver(options) {
421
399
  const httpEndpoint = isWs ? options.cdpUrl.replace(/^ws(s?):\/\//, "http$1://").replace(/\/devtools\/.*$/, "") : options.cdpUrl.replace(/\/+$/, "");
422
400
  let connectWsUrl = isWs ? options.cdpUrl : void 0;
423
401
  if (useContexts && !connectWsUrl) {
424
- connectWsUrl = yield* Effect3.tryPromise({
402
+ connectWsUrl = yield* Effect2.tryPromise({
425
403
  try: () => fetchBrowserWsUrl(httpEndpoint, 5e3),
426
404
  catch: (e) => new DriverError({
427
405
  message: `Failed to resolve browser CDP WebSocket at ${options.cdpUrl}: ${e}`
@@ -434,7 +412,7 @@ function makeLightweightCdpDriver(options) {
434
412
  fetchFn: options.fetchFn,
435
413
  createWebSocket: options.createWebSocket
436
414
  });
437
- yield* Effect3.tryPromise({
415
+ yield* Effect2.tryPromise({
438
416
  try: () => cdpChannel.connect(),
439
417
  catch: (e) => new DriverError({
440
418
  message: `Failed to connect lightweight CDP browser at ${options.cdpUrl}: ${e}`
@@ -499,6 +477,8 @@ function makeLightweightCdpDriver(options) {
499
477
  );
500
478
  return res?.authenticatorId ?? "cdp-virtual-auth-1";
501
479
  };
480
+ const useInjectedRuntime = options.useInjectedRuntime ?? !options.createWebSocket;
481
+ cdpChannel.enableInjectedRuntime(useInjectedRuntime);
502
482
  const configureSession = async (sessionId, storageStatePath) => {
503
483
  const state = await loadStorageStateFile(storageStatePath);
504
484
  const needsNetworkDomain = Boolean(
@@ -509,6 +489,20 @@ function makeLightweightCdpDriver(options) {
509
489
  }),
510
490
  cdpChannel.sendCommand("Runtime.enable", {}, sessionId).catch(() => {
511
491
  }),
492
+ ...useInjectedRuntime ? [
493
+ cdpChannel.sendCommand(
494
+ "Page.addScriptToEvaluateOnNewDocument",
495
+ { source: SPANA_INJECTED_RUNTIME_SCRIPT },
496
+ sessionId
497
+ ).catch(() => {
498
+ })
499
+ ] : [],
500
+ cdpChannel.sendCommand(
501
+ "Target.setAutoAttach",
502
+ { autoAttach: true, waitForDebuggerOnStart: false, flatten: true },
503
+ sessionId
504
+ ).catch(() => {
505
+ }),
512
506
  ...needsNetworkDomain ? [cdpChannel.sendCommand("Network.enable", {}, sessionId).catch(() => {
513
507
  })] : [],
514
508
  cdpChannel.sendCommand(
@@ -613,12 +607,56 @@ function makeLightweightCdpDriver(options) {
613
607
  backgroundDisposals.push(p);
614
608
  };
615
609
  const schedulePrefetch = () => {
616
- if (!useContexts || !options.freshContextPerFlow || prefetchedSlotPromise) return;
610
+ if (!useContexts || !options.freshContextPerFlow || options.contextIsolation === "hot-cache" || prefetchedSlotPromise) {
611
+ return;
612
+ }
617
613
  prefetchedSlotPromise = createContextSlot(options.storageState);
618
614
  prefetchedSlotPromise.catch(() => {
619
615
  prefetchedSlotPromise = void 0;
620
616
  });
621
617
  };
618
+ cdpChannel.onEvent("Target.attachedToTarget", (params) => {
619
+ const targetInfo = params?.targetInfo;
620
+ const childSid = params?.sessionId;
621
+ if (targetInfo?.type === "iframe" && typeof childSid === "string") {
622
+ cdpChannel.addChildSession(childSid, {
623
+ targetId: typeof targetInfo.targetId === "string" ? targetInfo.targetId : void 0,
624
+ url: typeof targetInfo.url === "string" ? targetInfo.url : void 0
625
+ });
626
+ void cdpChannel.sendCommand("Runtime.enable", {}, childSid).catch(() => {
627
+ });
628
+ if (useInjectedRuntime) {
629
+ void cdpChannel.sendCommand(
630
+ "Page.addScriptToEvaluateOnNewDocument",
631
+ { source: SPANA_INJECTED_RUNTIME_SCRIPT },
632
+ childSid
633
+ ).catch(() => {
634
+ });
635
+ }
636
+ }
637
+ });
638
+ cdpChannel.onEvent("Target.detachedFromTarget", (params) => {
639
+ if (typeof params?.sessionId === "string") {
640
+ cdpChannel.removeChildSession(params.sessionId);
641
+ }
642
+ });
643
+ cdpChannel.setFrameOffsetResolver(async (child) => {
644
+ if (!child.targetId) return { x: 0, y: 0 };
645
+ try {
646
+ await cdpChannel.sendCommand("DOM.enable");
647
+ const owner = await cdpChannel.sendCommand("DOM.getFrameOwner", {
648
+ frameId: child.targetId
649
+ });
650
+ const boxParams = owner.backendNodeId ? { backendNodeId: owner.backendNodeId } : { nodeId: owner.nodeId };
651
+ const box = await cdpChannel.sendCommand("DOM.getBoxModel", boxParams);
652
+ const quad = box?.model?.content ?? box?.model?.border;
653
+ if (Array.isArray(quad) && quad.length >= 2) {
654
+ return { x: quad[0] ?? 0, y: quad[1] ?? 0 };
655
+ }
656
+ } catch {
657
+ }
658
+ return { x: 0, y: 0 };
659
+ });
622
660
  cdpChannel.onEvent("Runtime.consoleAPICalled", (params, sid) => {
623
661
  if (activeSlot && sid && sid !== activeSlot.sessionId) return;
624
662
  const args = Array.isArray(params?.args) ? params.args.map((a) => a.value ?? a.description ?? "").join(" ") : "";
@@ -673,7 +711,7 @@ function makeLightweightCdpDriver(options) {
673
711
  });
674
712
  });
675
713
  if (useContexts) {
676
- activeSlot = yield* Effect3.tryPromise({
714
+ activeSlot = yield* Effect2.tryPromise({
677
715
  try: () => createContextSlot(options.storageState),
678
716
  catch: (e) => new DriverError({ message: `Failed to create direct CDP browser context: ${e}` })
679
717
  });
@@ -689,7 +727,7 @@ function makeLightweightCdpDriver(options) {
689
727
  await cdpChannel.sendCommand("Page.navigate", { url: target });
690
728
  return;
691
729
  }
692
- const waitUntil = options.waitUntil ?? "load";
730
+ const waitUntil = options.waitUntil ?? "domcontentloaded";
693
731
  const targetSid = activeSlot?.sessionId;
694
732
  if (waitUntil === "commit" || target === "about:blank") {
695
733
  await cdpChannel.sendCommand("Page.navigate", { url: target });
@@ -713,33 +751,62 @@ function makeLightweightCdpDriver(options) {
713
751
  };
714
752
  const service = {
715
753
  domChannel: cdpChannel,
716
- beginFlow: (_flowName) => Effect3.tryPromise({
754
+ beginFlow: (_flowName) => Effect2.tryPromise({
717
755
  try: async () => {
718
756
  consoleLogs.length = 0;
719
757
  jsErrors.length = 0;
758
+ cdpChannel.clearChildSessions();
720
759
  if (useContexts && options.freshContextPerFlow && hasRunFirstFlow) {
721
- const previousSlot = activeSlot;
722
- const pending = prefetchedSlotPromise;
723
- prefetchedSlotPromise = void 0;
724
- activeSlot = pending ? await pending : await createContextSlot(options.storageState);
725
- cdpChannel.setSessionId(activeSlot.sessionId);
726
- activeAuthenticatorId = activeSlot.authenticatorId;
727
- if (previousSlot) {
728
- disposeSlotInBackground(previousSlot);
760
+ if (options.contextIsolation === "hot-cache" && activeSlot) {
761
+ const origin = options.baseUrl ? (() => {
762
+ try {
763
+ return new URL(options.baseUrl).origin;
764
+ } catch {
765
+ return "*";
766
+ }
767
+ })() : "*";
768
+ await Promise.all([
769
+ cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
770
+ }),
771
+ cdpChannel.sendCommand("Storage.clearDataForOrigin", {
772
+ origin,
773
+ storageTypes: "cookies,local_storage,session_storage,indexeddb,cache_storage,service_workers"
774
+ }).catch(() => {
775
+ }),
776
+ cdpChannel.evaluate("try { localStorage.clear(); sessionStorage.clear(); } catch {}").catch(() => {
777
+ }),
778
+ cdpChannel.sendCommand("Page.navigate", { url: "about:blank" }).catch(() => {
779
+ })
780
+ ]);
781
+ const state = await loadStorageStateFile(options.storageState);
782
+ if (state?.cookies && state.cookies.length > 0) {
783
+ await cdpChannel.sendCommand("Network.setCookies", { cookies: state.cookies }).catch(() => {
784
+ });
785
+ }
786
+ } else {
787
+ const previousSlot = activeSlot;
788
+ const pending = prefetchedSlotPromise;
789
+ prefetchedSlotPromise = void 0;
790
+ activeSlot = pending ? await pending : await createContextSlot(options.storageState);
791
+ cdpChannel.setSessionId(activeSlot.sessionId);
792
+ activeAuthenticatorId = activeSlot.authenticatorId;
793
+ if (previousSlot) {
794
+ disposeSlotInBackground(previousSlot);
795
+ }
729
796
  }
730
797
  }
731
798
  hasRunFirstFlow = true;
732
799
  },
733
800
  catch: (e) => new DriverError({ message: `CDP beginFlow failed: ${e}` })
734
801
  }),
735
- dumpHierarchy: () => Effect3.tryPromise({
802
+ dumpHierarchy: () => Effect2.tryPromise({
736
803
  try: async () => {
737
804
  const raw = await cdpChannel.evaluate(CDP_DUMP_HIERARCHY_SCRIPT);
738
805
  return raw ?? "{}";
739
806
  },
740
807
  catch: (e) => new DriverError({ message: `CDP dumpHierarchy failed: ${e}` })
741
808
  }),
742
- tapAtCoordinate: (x, y) => Effect3.tryPromise({
809
+ tapAtCoordinate: (x, y) => Effect2.tryPromise({
743
810
  try: async () => {
744
811
  await Promise.all([
745
812
  cdpChannel.sendCommand("Input.dispatchMouseEvent", {
@@ -765,7 +832,7 @@ function makeLightweightCdpDriver(options) {
765
832
  },
766
833
  catch: (e) => new DriverError({ message: `CDP tap failed at (${x}, ${y}): ${e}` })
767
834
  }),
768
- doubleTapAtCoordinate: (x, y) => Effect3.tryPromise({
835
+ doubleTapAtCoordinate: (x, y) => Effect2.tryPromise({
769
836
  try: async () => {
770
837
  await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
771
838
  type: "mousePressed",
@@ -784,7 +851,7 @@ function makeLightweightCdpDriver(options) {
784
851
  },
785
852
  catch: (e) => new DriverError({ message: `CDP doubleTap failed: ${e}` })
786
853
  }),
787
- longPressAtCoordinate: (x, y, duration) => Effect3.tryPromise({
854
+ longPressAtCoordinate: (x, y, duration) => Effect2.tryPromise({
788
855
  try: async () => {
789
856
  await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
790
857
  type: "mousePressed",
@@ -804,7 +871,7 @@ function makeLightweightCdpDriver(options) {
804
871
  },
805
872
  catch: (e) => new DriverError({ message: `CDP longPress failed: ${e}` })
806
873
  }),
807
- swipe: (startX, startY, endX, endY) => Effect3.tryPromise({
874
+ swipe: (startX, startY, endX, endY) => Effect2.tryPromise({
808
875
  try: async () => {
809
876
  const dx = startX - endX;
810
877
  const dy = startY - endY;
@@ -812,21 +879,77 @@ function makeLightweightCdpDriver(options) {
812
879
  },
813
880
  catch: (e) => new DriverError({ message: `CDP swipe failed: ${e}` })
814
881
  }),
815
- inputText: (text) => Effect3.tryPromise({
882
+ inputText: (text) => Effect2.tryPromise({
816
883
  try: async () => {
817
884
  await cdpChannel.sendCommand("Input.insertText", { text });
818
885
  },
819
886
  catch: (e) => new DriverError({ message: `CDP inputText failed: ${e}` })
820
887
  }),
821
- pressKey: (key) => Effect3.tryPromise({
888
+ pressKey: (key) => Effect2.tryPromise({
822
889
  try: async () => {
823
- await cdpChannel.sendCommand("Input.dispatchKeyEvent", { type: "keyDown", key });
824
- await cdpChannel.sendCommand("Input.dispatchKeyEvent", { type: "keyUp", key });
890
+ const desc = parseCdpKeyDescriptor(key);
891
+ await cdpChannel.sendCommand("Input.dispatchKeyEvent", {
892
+ type: desc.text ? "keyDown" : "rawKeyDown",
893
+ key: desc.key,
894
+ ...desc.code ? { code: desc.code } : {},
895
+ ...desc.windowsVirtualKeyCode ? {
896
+ windowsVirtualKeyCode: desc.windowsVirtualKeyCode,
897
+ nativeVirtualKeyCode: desc.windowsVirtualKeyCode
898
+ } : {},
899
+ modifiers: desc.modifiers,
900
+ ...desc.text ? { text: desc.text, unmodifiedText: desc.text } : {},
901
+ ...desc.commands ? { commands: desc.commands } : {}
902
+ });
903
+ await cdpChannel.sendCommand("Input.dispatchKeyEvent", {
904
+ type: "keyUp",
905
+ key: desc.key,
906
+ ...desc.code ? { code: desc.code } : {},
907
+ ...desc.windowsVirtualKeyCode ? {
908
+ windowsVirtualKeyCode: desc.windowsVirtualKeyCode,
909
+ nativeVirtualKeyCode: desc.windowsVirtualKeyCode
910
+ } : {},
911
+ modifiers: desc.modifiers
912
+ });
825
913
  },
826
914
  catch: (e) => new DriverError({ message: `CDP pressKey failed: ${e}` })
827
915
  }),
828
- hideKeyboard: () => Effect3.void,
829
- takeScreenshot: () => Effect3.tryPromise({
916
+ hoverAtCoordinate: (x, y) => Effect2.tryPromise({
917
+ try: async () => {
918
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
919
+ type: "mouseMoved",
920
+ x,
921
+ y
922
+ });
923
+ },
924
+ catch: (e) => new DriverError({ message: `CDP hover failed at (${x}, ${y}): ${e}` })
925
+ }),
926
+ reload: (reloadOpts) => Effect2.tryPromise({
927
+ try: async () => {
928
+ const waitUntil = reloadOpts?.waitUntil ?? options.waitUntil ?? "domcontentloaded";
929
+ const targetSid = activeSlot?.sessionId;
930
+ const eventName = waitUntil === "domcontentloaded" ? "Page.domContentEventFired" : "Page.loadEventFired";
931
+ const waiter = cdpChannel.waitForEvent(
932
+ eventName,
933
+ 15e3,
934
+ (_p, sid) => !targetSid || !sid || sid === targetSid
935
+ );
936
+ await cdpChannel.sendCommand("Page.reload", {});
937
+ await waiter.catch(() => {
938
+ });
939
+ },
940
+ catch: (e) => new DriverError({ message: `CDP reload failed: ${e}` })
941
+ }),
942
+ getUrl: () => Effect2.tryPromise({
943
+ try: async () => {
944
+ const url = await cdpChannel.evaluate(
945
+ "typeof window !== 'undefined' && window.location ? String(window.location.href || '') : ''"
946
+ );
947
+ return url ?? "";
948
+ },
949
+ catch: (e) => new DriverError({ message: `CDP getUrl failed: ${e}` })
950
+ }),
951
+ hideKeyboard: () => Effect2.void,
952
+ takeScreenshot: () => Effect2.tryPromise({
830
953
  try: async () => {
831
954
  const res = await cdpChannel.sendCommand("Page.captureScreenshot", {
832
955
  format: "png"
@@ -835,7 +958,7 @@ function makeLightweightCdpDriver(options) {
835
958
  },
836
959
  catch: (e) => new DriverError({ message: `CDP screenshot failed: ${e}` })
837
960
  }),
838
- getDeviceInfo: () => Effect3.succeed({
961
+ getDeviceInfo: () => Effect2.succeed({
839
962
  platform: "web",
840
963
  deviceId: `${label}:${options.cdpUrl}`,
841
964
  name: `${label} (CDP-direct)`,
@@ -844,7 +967,7 @@ function makeLightweightCdpDriver(options) {
844
967
  screenHeight: height,
845
968
  driverType: "cdp"
846
969
  }),
847
- launchApp: (url, opts) => Effect3.tryPromise({
970
+ launchApp: (url, opts) => Effect2.tryPromise({
848
971
  try: async () => {
849
972
  if (opts?.clearState) {
850
973
  await cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
@@ -857,11 +980,11 @@ function makeLightweightCdpDriver(options) {
857
980
  },
858
981
  catch: (e) => new DriverError({ message: `CDP launchApp failed: ${e}` })
859
982
  }),
860
- stopApp: () => Effect3.tryPromise({
983
+ stopApp: () => Effect2.tryPromise({
861
984
  try: () => navigate("about:blank"),
862
985
  catch: (e) => new DriverError({ message: `CDP stopApp failed: ${e}` })
863
986
  }),
864
- killApp: () => Effect3.tryPromise({
987
+ killApp: () => Effect2.tryPromise({
865
988
  try: async () => {
866
989
  const pendingPrefetch = prefetchedSlotPromise;
867
990
  prefetchedSlotPromise = void 0;
@@ -894,7 +1017,7 @@ function makeLightweightCdpDriver(options) {
894
1017
  },
895
1018
  catch: (e) => new DriverError({ message: `CDP disconnect failed: ${e}` })
896
1019
  }),
897
- clearAppState: () => Effect3.tryPromise({
1020
+ clearAppState: () => Effect2.tryPromise({
898
1021
  try: async () => {
899
1022
  await cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
900
1023
  });
@@ -904,17 +1027,17 @@ function makeLightweightCdpDriver(options) {
904
1027
  },
905
1028
  catch: (e) => new DriverError({ message: `CDP clearAppState failed: ${e}` })
906
1029
  }),
907
- openLink: (url) => Effect3.tryPromise({
1030
+ openLink: (url) => Effect2.tryPromise({
908
1031
  try: () => navigate(url),
909
1032
  catch: (e) => new DriverError({ message: `CDP openLink failed: ${e}` })
910
1033
  }),
911
- back: () => Effect3.tryPromise({
1034
+ back: () => Effect2.tryPromise({
912
1035
  try: async () => {
913
1036
  await cdpChannel.evaluate("window.history.back()");
914
1037
  },
915
1038
  catch: (e) => new DriverError({ message: `CDP back failed: ${e}` })
916
1039
  }),
917
- evaluate: (fn, ...args) => Effect3.tryPromise({
1040
+ evaluate: (fn, ...args) => Effect2.tryPromise({
918
1041
  try: async () => {
919
1042
  if (typeof fn === "string") {
920
1043
  return await cdpChannel.evaluate(fn);
@@ -930,21 +1053,34 @@ function makeLightweightCdpDriver(options) {
930
1053
  sessionId: activeSlot?.sessionId ?? null,
931
1054
  browserContextId: activeSlot?.browserContextId ?? null
932
1055
  }),
933
- mockNetwork: (matcher, response) => Effect3.tryPromise({
1056
+ getCdpSession: () => ({
1057
+ send: (method, params) => cdpChannel.sendCommand(method, params ?? {}),
1058
+ on: (event, listener) => cdpChannel.onEvent(event, (params, sid) => {
1059
+ if (activeSlot && sid && sid !== activeSlot.sessionId) return;
1060
+ listener(params ?? {});
1061
+ }),
1062
+ get sessionId() {
1063
+ return activeSlot?.sessionId;
1064
+ },
1065
+ get browserContextId() {
1066
+ return activeSlot?.browserContextId;
1067
+ }
1068
+ }),
1069
+ mockNetwork: (matcher, response) => Effect2.tryPromise({
934
1070
  try: async () => {
935
1071
  routeRules.push({ kind: "mock", matcher, response });
936
1072
  await ensureFetchIntercept();
937
1073
  },
938
1074
  catch: (e) => new DriverError({ message: `CDP mockNetwork failed: ${e}` })
939
1075
  }),
940
- blockNetwork: (matcher) => Effect3.tryPromise({
1076
+ blockNetwork: (matcher) => Effect2.tryPromise({
941
1077
  try: async () => {
942
1078
  routeRules.push({ kind: "block", matcher });
943
1079
  await ensureFetchIntercept();
944
1080
  },
945
1081
  catch: (e) => new DriverError({ message: `CDP blockNetwork failed: ${e}` })
946
1082
  }),
947
- clearNetworkMocks: () => Effect3.tryPromise({
1083
+ clearNetworkMocks: () => Effect2.tryPromise({
948
1084
  try: async () => {
949
1085
  routeRules.length = 0;
950
1086
  if (fetchInterceptEnabled) {
@@ -955,14 +1091,14 @@ function makeLightweightCdpDriver(options) {
955
1091
  },
956
1092
  catch: (e) => new DriverError({ message: `CDP clearNetworkMocks failed: ${e}` })
957
1093
  }),
958
- saveCookies: (path) => Effect3.tryPromise({
1094
+ saveCookies: (path) => Effect2.tryPromise({
959
1095
  try: async () => {
960
1096
  const res = await cdpChannel.sendCommand("Network.getCookies");
961
1097
  await writeFile(path, JSON.stringify(res?.cookies ?? [], null, 2), "utf8");
962
1098
  },
963
1099
  catch: (e) => new DriverError({ message: `CDP saveCookies failed: ${e}` })
964
1100
  }),
965
- loadCookies: (path) => Effect3.tryPromise({
1101
+ loadCookies: (path) => Effect2.tryPromise({
966
1102
  try: async () => {
967
1103
  const cookies = JSON.parse(await readFile(path, "utf8"));
968
1104
  if (Array.isArray(cookies)) {
@@ -971,7 +1107,116 @@ function makeLightweightCdpDriver(options) {
971
1107
  },
972
1108
  catch: (e) => new DriverError({ message: `CDP loadCookies failed: ${e}` })
973
1109
  }),
974
- saveAuthState: (path) => Effect3.tryPromise({
1110
+ getCookies: (urls) => Effect2.tryPromise({
1111
+ try: async () => {
1112
+ const res = await cdpChannel.sendCommand(
1113
+ "Network.getCookies",
1114
+ urls && urls.length > 0 ? { urls } : {}
1115
+ );
1116
+ return Array.isArray(res?.cookies) ? res.cookies : [];
1117
+ },
1118
+ catch: (e) => new DriverError({ message: `CDP getCookies failed: ${e}` })
1119
+ }),
1120
+ setCookies: (cookies) => Effect2.tryPromise({
1121
+ try: async () => {
1122
+ if (cookies.length === 0) return;
1123
+ await cdpChannel.sendCommand("Network.setCookies", { cookies });
1124
+ },
1125
+ catch: (e) => new DriverError({ message: `CDP setCookies failed: ${e}` })
1126
+ }),
1127
+ clearCookies: () => Effect2.tryPromise({
1128
+ try: async () => {
1129
+ await cdpChannel.sendCommand("Network.clearBrowserCookies");
1130
+ },
1131
+ catch: (e) => new DriverError({ message: `CDP clearCookies failed: ${e}` })
1132
+ }),
1133
+ waitForResponse: (matcher, waitOpts) => Effect2.tryPromise({
1134
+ try: async () => {
1135
+ const timeoutMs = waitOpts?.timeout ?? 15e3;
1136
+ const targetSid = activeSlot?.sessionId;
1137
+ await cdpChannel.sendCommand("Network.enable").catch(() => {
1138
+ });
1139
+ const requestMethods = /* @__PURE__ */ new Map();
1140
+ return await new Promise((resolve, reject) => {
1141
+ const cleanup = () => {
1142
+ clearTimeout(timer);
1143
+ offReq();
1144
+ offRes();
1145
+ };
1146
+ const timer = setTimeout(() => {
1147
+ cleanup();
1148
+ reject(new Error(`Timed out waiting for response after ${timeoutMs}ms`));
1149
+ }, timeoutMs);
1150
+ const offReq = cdpChannel.onEvent("Network.requestWillBeSent", (params, sid) => {
1151
+ if (targetSid && sid && sid !== targetSid) return;
1152
+ if (params?.requestId && params?.request?.method) {
1153
+ requestMethods.set(String(params.requestId), String(params.request.method));
1154
+ }
1155
+ });
1156
+ const offRes = cdpChannel.onEvent("Network.responseReceived", (params, sid) => {
1157
+ if (targetSid && sid && sid !== targetSid) return;
1158
+ const resp = params?.response;
1159
+ if (!resp) return;
1160
+ const requestId = String(params?.requestId ?? "");
1161
+ const rawHeaders = resp.headers ?? {};
1162
+ const headers = {};
1163
+ for (const [k, v] of Object.entries(rawHeaders)) {
1164
+ headers[k.toLowerCase()] = String(v);
1165
+ }
1166
+ const info = {
1167
+ url: String(resp.url ?? ""),
1168
+ status: Number(resp.status ?? 0),
1169
+ statusText: String(resp.statusText ?? ""),
1170
+ headers,
1171
+ method: requestMethods.get(requestId),
1172
+ body: async () => {
1173
+ const bodyRes = await cdpChannel.sendCommand("Network.getResponseBody", {
1174
+ requestId
1175
+ });
1176
+ if (bodyRes?.base64Encoded && bodyRes.body) {
1177
+ return Buffer.from(bodyRes.body, "base64").toString("utf8");
1178
+ }
1179
+ return bodyRes?.body ?? "";
1180
+ },
1181
+ json: async () => {
1182
+ const text = await info.body();
1183
+ return JSON.parse(text);
1184
+ }
1185
+ };
1186
+ const matched = typeof matcher === "function" ? matcher(info) : matchUrl(matcher, info.url);
1187
+ if (matched) {
1188
+ cleanup();
1189
+ resolve(info);
1190
+ }
1191
+ });
1192
+ });
1193
+ },
1194
+ catch: (e) => new DriverError({ message: `CDP waitForResponse failed: ${e}` })
1195
+ }),
1196
+ createIsolatedContext: (ctxOpts) => Effect2.tryPromise({
1197
+ try: async () => {
1198
+ const childDriver = await Effect2.runPromise(
1199
+ makeLightweightCdpDriver({
1200
+ ...options,
1201
+ cdpUrl: connectWsUrl ?? options.cdpUrl,
1202
+ useBrowserContexts: true,
1203
+ freshContextPerFlow: false
1204
+ })
1205
+ );
1206
+ if (ctxOpts?.url) {
1207
+ await Effect2.runPromise(childDriver.openLink(ctxOpts.url));
1208
+ }
1209
+ return {
1210
+ driver: childDriver,
1211
+ close: async () => {
1212
+ await Effect2.runPromise(childDriver.killApp("isolated-context")).catch(() => {
1213
+ });
1214
+ }
1215
+ };
1216
+ },
1217
+ catch: (e) => new DriverError({ message: `CDP createIsolatedContext failed: ${e}` })
1218
+ }),
1219
+ saveAuthState: (path) => Effect2.tryPromise({
975
1220
  try: async () => {
976
1221
  const res = await cdpChannel.sendCommand("Network.getCookies");
977
1222
  const originState = await cdpChannel.evaluate(
@@ -994,7 +1239,7 @@ function makeLightweightCdpDriver(options) {
994
1239
  },
995
1240
  catch: (e) => new DriverError({ message: `CDP saveAuthState failed: ${e}` })
996
1241
  }),
997
- loadAuthState: (path) => Effect3.tryPromise({
1242
+ loadAuthState: (path) => Effect2.tryPromise({
998
1243
  try: async () => {
999
1244
  if (useContexts) {
1000
1245
  const previousSlot = activeSlot;
@@ -1011,7 +1256,7 @@ function makeLightweightCdpDriver(options) {
1011
1256
  },
1012
1257
  catch: (e) => new DriverError({ message: `CDP loadAuthState failed: ${e}` })
1013
1258
  }),
1014
- enableVirtualAuthenticator: (opts) => Effect3.tryPromise({
1259
+ enableVirtualAuthenticator: (opts) => Effect2.tryPromise({
1015
1260
  try: async () => {
1016
1261
  activeAuthenticatorId = await attachVirtualAuthenticatorForSession(
1017
1262
  activeSlot?.sessionId ?? null,
@@ -1021,7 +1266,7 @@ function makeLightweightCdpDriver(options) {
1021
1266
  },
1022
1267
  catch: (e) => new DriverError({ message: `CDP enableVirtualAuthenticator failed: ${e}` })
1023
1268
  }),
1024
- removeVirtualAuthenticator: (authenticatorId) => Effect3.tryPromise({
1269
+ removeVirtualAuthenticator: (authenticatorId) => Effect2.tryPromise({
1025
1270
  try: async () => {
1026
1271
  const id = authenticatorId ?? activeAuthenticatorId;
1027
1272
  if (!id) return;
@@ -1032,7 +1277,7 @@ function makeLightweightCdpDriver(options) {
1032
1277
  },
1033
1278
  catch: (e) => new DriverError({ message: `CDP removeVirtualAuthenticator failed: ${e}` })
1034
1279
  }),
1035
- getVirtualCredentials: (authenticatorId) => Effect3.tryPromise({
1280
+ getVirtualCredentials: (authenticatorId) => Effect2.tryPromise({
1036
1281
  try: async () => {
1037
1282
  const id = authenticatorId ?? activeAuthenticatorId;
1038
1283
  if (!id) return [];
@@ -1043,7 +1288,29 @@ function makeLightweightCdpDriver(options) {
1043
1288
  },
1044
1289
  catch: (e) => new DriverError({ message: `CDP getVirtualCredentials failed: ${e}` })
1045
1290
  }),
1046
- clearVirtualCredentials: (authenticatorId) => Effect3.tryPromise({
1291
+ addVirtualCredential: (credential, authenticatorId) => Effect2.tryPromise({
1292
+ try: async () => {
1293
+ let id = authenticatorId ?? activeAuthenticatorId;
1294
+ if (!id) {
1295
+ id = await attachVirtualAuthenticatorForSession(activeSlot?.sessionId ?? null);
1296
+ activeAuthenticatorId = id;
1297
+ }
1298
+ await cdpChannel.sendCommand("WebAuthn.addCredential", {
1299
+ authenticatorId: id,
1300
+ credential: {
1301
+ credentialId: credential.credentialId,
1302
+ isResidentCredential: credential.isResidentCredential,
1303
+ privateKey: credential.privateKey,
1304
+ signCount: credential.signCount ?? 0,
1305
+ ...credential.rpId !== void 0 ? { rpId: credential.rpId } : {},
1306
+ ...credential.userHandle !== void 0 ? { userHandle: credential.userHandle } : {},
1307
+ ...credential.userName !== void 0 ? { userName: credential.userName } : {}
1308
+ }
1309
+ });
1310
+ },
1311
+ catch: (e) => new DriverError({ message: `CDP addVirtualCredential failed: ${e}` })
1312
+ }),
1313
+ clearVirtualCredentials: (authenticatorId) => Effect2.tryPromise({
1047
1314
  try: async () => {
1048
1315
  const id = authenticatorId ?? activeAuthenticatorId;
1049
1316
  if (!id) return;
@@ -1051,9 +1318,9 @@ function makeLightweightCdpDriver(options) {
1051
1318
  },
1052
1319
  catch: (e) => new DriverError({ message: `CDP clearVirtualCredentials failed: ${e}` })
1053
1320
  }),
1054
- getConsoleLogs: () => Effect3.succeed([...consoleLogs]),
1055
- getJSErrors: () => Effect3.succeed([...jsErrors]),
1056
- setNetworkConditions: (conditions) => Effect3.tryPromise({
1321
+ getConsoleLogs: () => Effect2.succeed([...consoleLogs]),
1322
+ getJSErrors: () => Effect2.succeed([...jsErrors]),
1323
+ setNetworkConditions: (conditions) => Effect2.tryPromise({
1057
1324
  try: async () => {
1058
1325
  const resolved = resolveNetworkConditions(conditions);
1059
1326
  await cdpChannel.sendCommand("Network.enable");
@@ -1066,39 +1333,39 @@ function makeLightweightCdpDriver(options) {
1066
1333
  },
1067
1334
  catch: (e) => new DriverError({ message: `CDP setNetworkConditions failed: ${e}` })
1068
1335
  }),
1069
- uploadFile: (selector, filePath) => Effect3.tryPromise({
1336
+ uploadFile: (selector, filePath) => Effect2.tryPromise({
1070
1337
  try: async () => {
1071
- const serialized = JSON.stringify(selector);
1072
- const expr = `(function(sel) {
1073
- if (typeof sel === "object" && sel !== null && "testID" in sel) {
1074
- return document.querySelector('[data-testid="' + sel.testID + '"], [testID="' + sel.testID + '"]');
1075
- }
1076
- if (typeof sel === "object" && sel !== null && "accessibilityLabel" in sel) {
1077
- return document.querySelector('[aria-label="' + sel.accessibilityLabel + '"]');
1078
- }
1079
- return document.querySelector('input[type="file"]');
1080
- })(${serialized})`;
1338
+ const files = Array.isArray(filePath) ? filePath : [filePath];
1339
+ const expr = buildDomFindElementScript(selector);
1081
1340
  await cdpChannel.sendCommand("DOM.enable");
1341
+ await cdpChannel.sendCommand("DOM.getDocument", { depth: 0 }).catch(() => {
1342
+ });
1082
1343
  const evalRes = await cdpChannel.sendCommand("Runtime.evaluate", {
1083
1344
  expression: expr,
1084
1345
  returnByValue: false
1085
1346
  });
1086
1347
  const objectId = evalRes?.result?.objectId;
1087
1348
  if (!objectId) {
1088
- throw new Error(`No matching file input found for selector ${serialized}`);
1349
+ throw new Error(
1350
+ `No matching file input found for selector ${JSON.stringify(selector)}`
1351
+ );
1089
1352
  }
1090
- const nodeRes = await cdpChannel.sendCommand("DOM.requestNode", { objectId });
1091
- if (!nodeRes?.nodeId) {
1092
- throw new Error("Failed to resolve DOM nodeId for file input");
1353
+ const nodeRes = await cdpChannel.sendCommand("DOM.requestNode", { objectId }).catch(() => ({}));
1354
+ if (nodeRes?.nodeId && nodeRes.nodeId > 0) {
1355
+ await cdpChannel.sendCommand("DOM.setFileInputFiles", {
1356
+ nodeId: nodeRes.nodeId,
1357
+ files
1358
+ });
1359
+ } else {
1360
+ await cdpChannel.sendCommand("DOM.setFileInputFiles", {
1361
+ objectId,
1362
+ files
1363
+ });
1093
1364
  }
1094
- await cdpChannel.sendCommand("DOM.setFileInputFiles", {
1095
- nodeId: nodeRes.nodeId,
1096
- files: [filePath]
1097
- });
1098
1365
  },
1099
1366
  catch: (e) => new DriverError({ message: `CDP uploadFile failed: ${e}` })
1100
1367
  }),
1101
- downloadFile: (destPath) => Effect3.tryPromise({
1368
+ downloadFile: (destPath) => Effect2.tryPromise({
1102
1369
  try: async () => {
1103
1370
  if (!downloadDir) {
1104
1371
  downloadDir = mkdtempSync(join(tmpdir(), "spana-cdp-dl-"));
@@ -1132,7 +1399,7 @@ function makeLightweightCdpDriver(options) {
1132
1399
  },
1133
1400
  catch: (e) => new DriverError({ message: `CDP downloadFile failed: ${e}` })
1134
1401
  }),
1135
- newTab: (url) => Effect3.tryPromise({
1402
+ newTab: (url) => Effect2.tryPromise({
1136
1403
  try: async () => {
1137
1404
  if (!activeSlot) {
1138
1405
  throw new Error("newTab() requires browser-context mode (engine: 'cdp')");
@@ -1166,7 +1433,7 @@ function makeLightweightCdpDriver(options) {
1166
1433
  },
1167
1434
  catch: (e) => new DriverError({ message: `CDP newTab failed: ${e}` })
1168
1435
  }),
1169
- switchToTab: (index) => Effect3.tryPromise({
1436
+ switchToTab: (index) => Effect2.tryPromise({
1170
1437
  try: async () => {
1171
1438
  if (!activeSlot || !activeSlot.tabs[index]) {
1172
1439
  throw new Error(`Tab index ${index} is out of range.`);
@@ -1180,7 +1447,7 @@ function makeLightweightCdpDriver(options) {
1180
1447
  },
1181
1448
  catch: (e) => new DriverError({ message: `CDP switchToTab failed: ${e}` })
1182
1449
  }),
1183
- closeTab: () => Effect3.tryPromise({
1450
+ closeTab: () => Effect2.tryPromise({
1184
1451
  try: async () => {
1185
1452
  if (!activeSlot) return;
1186
1453
  if (activeSlot.tabs.length <= 1) {
@@ -1199,14 +1466,14 @@ function makeLightweightCdpDriver(options) {
1199
1466
  },
1200
1467
  catch: (e) => new DriverError({ message: `CDP closeTab failed: ${e}` })
1201
1468
  }),
1202
- getTabIds: () => Effect3.sync(() => activeSlot ? activeSlot.tabs.map((t) => t.tabId) : ["tab-1"])
1469
+ getTabIds: () => Effect2.sync(() => activeSlot ? activeSlot.tabs.map((t) => t.tabId) : ["tab-1"])
1203
1470
  };
1204
1471
  return service;
1205
1472
  });
1206
1473
  }
1207
1474
 
1208
1475
  // src/runtime/local.ts
1209
- import { Effect as Effect4 } from "effect";
1476
+ import { Effect as Effect3 } from "effect";
1210
1477
  async function safeCleanup(...fns) {
1211
1478
  for (const fn of fns) {
1212
1479
  try {
@@ -1260,19 +1527,35 @@ function buildEngineConfig(appId, platform, parseFn, config, screenSize) {
1260
1527
  visualRegression: config.visualRegression
1261
1528
  };
1262
1529
  }
1530
+ function resolveWebEngine(config) {
1531
+ const webExecution = config.execution?.web;
1532
+ const requested = webExecution?.engine;
1533
+ if (requested === "cdp" || requested === "lightpanda" || requested === "playwright") {
1534
+ return requested;
1535
+ }
1536
+ if (requested === "auto") {
1537
+ const isChromium = (webExecution?.browser ?? "chromium") === "chromium";
1538
+ const needsPlaywrightOnly = Boolean(
1539
+ webExecution?.wsEndpoint || webExecution?.channel || config.artifacts?.har
1540
+ );
1541
+ return isChromium && !needsPlaywrightOnly ? "cdp" : "playwright";
1542
+ }
1543
+ return "playwright";
1544
+ }
1263
1545
  function speculativelyPrelaunchWebBrowser(config) {
1264
1546
  const webExecution = config.execution?.web;
1265
- if (webExecution?.engine === "lightpanda") {
1547
+ const engine = resolveWebEngine(config);
1548
+ if (engine === "lightpanda") {
1266
1549
  return void 0;
1267
1550
  }
1268
- if (webExecution?.engine === "cdp") {
1269
- if (webExecution.cdpUrl) return void 0;
1270
- const useWarm2 = webExecution.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false;
1551
+ if (engine === "cdp") {
1552
+ if (webExecution?.cdpUrl) return void 0;
1553
+ const useWarm2 = webExecution?.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false;
1271
1554
  const cdpBrowserPromise = launchDirectCdpBrowser({
1272
- executablePath: webExecution.executablePath,
1273
- headless: webExecution.headless ?? true,
1555
+ executablePath: webExecution?.executablePath,
1556
+ headless: webExecution?.headless ?? true,
1274
1557
  warmBrowser: useWarm2,
1275
- warmBrowserScope: webExecution.warmBrowserScope ? `${webExecution.warmBrowserScope}-w0` : void 0
1558
+ warmBrowserScope: webExecution?.warmBrowserScope ? `${webExecution.warmBrowserScope}-w0` : void 0
1276
1559
  });
1277
1560
  cdpBrowserPromise.catch(() => {
1278
1561
  });
@@ -1305,34 +1588,36 @@ async function buildWebRuntime(config, prelaunched) {
1305
1588
  const prelaunchedBrowser = prelaunched && !prelaunched.cdpBrowserPromise ? await prelaunched.browserPromise : void 0;
1306
1589
  let launchedDirectCdp;
1307
1590
  let rawDriver;
1308
- if (webExecution?.engine === "cdp" || webExecution?.engine === "lightpanda") {
1309
- let targetCdpUrl = webExecution.cdpUrl;
1310
- const useContexts = webExecution.engine === "cdp";
1311
- if (!targetCdpUrl && webExecution.engine === "cdp") {
1591
+ const engine = resolveWebEngine(config);
1592
+ if (engine === "cdp" || engine === "lightpanda") {
1593
+ let targetCdpUrl = webExecution?.cdpUrl;
1594
+ const useContexts = engine === "cdp";
1595
+ if (!targetCdpUrl && engine === "cdp") {
1312
1596
  launchedDirectCdp = prelaunched?.cdpBrowserPromise ? await prelaunched.cdpBrowserPromise : await launchDirectCdpBrowser({
1313
- executablePath: webExecution.executablePath,
1314
- headless: webExecution.headless ?? true,
1315
- warmBrowser: webExecution.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false,
1316
- warmBrowserScope: webExecution.warmBrowserScope ? `${webExecution.warmBrowserScope}-w0` : void 0
1597
+ executablePath: webExecution?.executablePath,
1598
+ headless: webExecution?.headless ?? true,
1599
+ warmBrowser: webExecution?.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false,
1600
+ warmBrowserScope: webExecution?.warmBrowserScope ? `${webExecution.warmBrowserScope}-w0` : void 0
1317
1601
  });
1318
1602
  targetCdpUrl = launchedDirectCdp.browserWsUrl;
1319
1603
  }
1320
- rawDriver = await Effect4.runPromise(
1604
+ rawDriver = await Effect3.runPromise(
1321
1605
  makeLightweightCdpDriver({
1322
1606
  cdpUrl: targetCdpUrl ?? "http://127.0.0.1:9222",
1323
1607
  baseUrl: webUrl,
1324
- engineLabel: webExecution.engine,
1608
+ engineLabel: engine,
1325
1609
  useBrowserContexts: useContexts,
1326
- freshContextPerFlow: webExecution.freshContextPerFlow,
1327
- waitUntil: webExecution.waitUntil,
1328
- instantAnimations: webExecution.instantAnimations,
1329
- blockResources: webExecution.blockResources,
1330
- virtualAuthenticator: webExecution.virtualAuthenticator,
1331
- storageState: webExecution.storageState
1610
+ freshContextPerFlow: webExecution?.freshContextPerFlow,
1611
+ contextIsolation: webExecution?.contextIsolation,
1612
+ waitUntil: webExecution?.waitUntil,
1613
+ instantAnimations: webExecution?.instantAnimations,
1614
+ blockResources: webExecution?.blockResources,
1615
+ virtualAuthenticator: webExecution?.virtualAuthenticator,
1616
+ storageState: webExecution?.storageState
1332
1617
  })
1333
1618
  );
1334
1619
  } else {
1335
- rawDriver = await Effect4.runPromise(
1620
+ rawDriver = await Effect3.runPromise(
1336
1621
  makePlaywrightDriver({
1337
1622
  browser: webExecution?.browser,
1338
1623
  headless: webExecution?.headless ?? true,
@@ -1356,12 +1641,12 @@ async function buildWebRuntime(config, prelaunched) {
1356
1641
  );
1357
1642
  }
1358
1643
  const driver = bridge ? { ...rawDriver, domChannel: bridge } : rawDriver;
1359
- const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
1644
+ const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
1360
1645
  return {
1361
1646
  runtime: {
1362
1647
  driver,
1363
1648
  cleanup: () => safeCleanup(
1364
- () => Effect4.runPromise(driver.killApp("")),
1649
+ () => Effect3.runPromise(driver.killApp("")),
1365
1650
  () => prelaunchedBrowser && prelaunched?.ownsBrowser ? prelaunchedBrowser.close() : Promise.resolve(),
1366
1651
  () => launchedDirectCdp ? launchedDirectCdp.close() : Promise.resolve(),
1367
1652
  () => bridge?.disconnect() ?? Promise.resolve()
@@ -1379,29 +1664,30 @@ async function buildWebRuntime(config, prelaunched) {
1379
1664
  }
1380
1665
  async function buildWebRuntimePool(config, workerCount, prelaunched) {
1381
1666
  const webExecution = config.execution?.web;
1382
- if (workerCount <= 1 || webExecution?.engine === "lightpanda") {
1667
+ const engine = resolveWebEngine(config);
1668
+ if (workerCount <= 1 || engine === "lightpanda") {
1383
1669
  return [await buildWebRuntime(config, prelaunched)];
1384
1670
  }
1385
1671
  const webUrl = config.apps?.web?.url ?? "http://localhost:3000";
1386
1672
  const maxPerBrowser = Math.max(
1387
1673
  1,
1388
- webExecution?.maxContextsPerBrowser ?? (webExecution?.engine === "cdp" ? 1 : 2)
1674
+ webExecution?.maxContextsPerBrowser ?? (engine === "cdp" ? 1 : 2)
1389
1675
  );
1390
- if (webExecution?.engine === "cdp") {
1391
- const useExternalCdp = Boolean(webExecution.cdpUrl);
1676
+ if (engine === "cdp") {
1677
+ const useExternalCdp = Boolean(webExecution?.cdpUrl);
1392
1678
  const browserCount2 = useExternalCdp ? 1 : Math.ceil(workerCount / maxPerBrowser);
1393
1679
  const handles = [];
1394
1680
  if (useExternalCdp) {
1395
1681
  handles.push({ cdpUrl: webExecution.cdpUrl, remaining: workerCount });
1396
1682
  } else {
1397
- const useWarm2 = webExecution.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false;
1398
- const baseScope = webExecution.warmBrowserScope ?? "pool";
1683
+ const useWarm2 = webExecution?.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false;
1684
+ const baseScope = webExecution?.warmBrowserScope ?? "pool";
1399
1685
  const launched = await Promise.all(
1400
1686
  Array.from(
1401
1687
  { length: browserCount2 },
1402
1688
  (_v, bIdx) => bIdx === 0 && prelaunched?.cdpBrowserPromise ? prelaunched.cdpBrowserPromise : launchDirectCdpBrowser({
1403
- executablePath: webExecution.executablePath,
1404
- headless: webExecution.headless ?? true,
1689
+ executablePath: webExecution?.executablePath,
1690
+ headless: webExecution?.headless ?? true,
1405
1691
  warmBrowser: useWarm2,
1406
1692
  warmBrowserScope: `${baseScope}-w${bIdx}`
1407
1693
  })
@@ -1417,21 +1703,22 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1417
1703
  const results2 = [];
1418
1704
  for (let i = 0; i < workerCount; i++) {
1419
1705
  const bucket = handles[i % handles.length];
1420
- const driver = await Effect4.runPromise(
1706
+ const driver = await Effect3.runPromise(
1421
1707
  makeLightweightCdpDriver({
1422
1708
  cdpUrl: bucket.cdpUrl,
1423
1709
  baseUrl: webUrl,
1424
1710
  engineLabel: "cdp",
1425
1711
  useBrowserContexts: true,
1426
- freshContextPerFlow: webExecution.freshContextPerFlow,
1427
- waitUntil: webExecution.waitUntil,
1428
- instantAnimations: webExecution.instantAnimations,
1429
- blockResources: webExecution.blockResources,
1430
- virtualAuthenticator: webExecution.virtualAuthenticator,
1431
- storageState: webExecution.storageState
1712
+ freshContextPerFlow: webExecution?.freshContextPerFlow,
1713
+ contextIsolation: webExecution?.contextIsolation,
1714
+ waitUntil: webExecution?.waitUntil,
1715
+ instantAnimations: webExecution?.instantAnimations,
1716
+ blockResources: webExecution?.blockResources,
1717
+ virtualAuthenticator: webExecution?.virtualAuthenticator,
1718
+ storageState: webExecution?.storageState
1432
1719
  })
1433
1720
  );
1434
- const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
1721
+ const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
1435
1722
  let cleaned = false;
1436
1723
  results2.push({
1437
1724
  runtime: {
@@ -1439,7 +1726,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1439
1726
  cleanup: () => safeCleanup(async () => {
1440
1727
  if (cleaned) return;
1441
1728
  cleaned = true;
1442
- await Effect4.runPromise(driver.killApp(""));
1729
+ await Effect3.runPromise(driver.killApp(""));
1443
1730
  bucket.remaining -= 1;
1444
1731
  if (bucket.remaining <= 0 && bucket.handle) {
1445
1732
  await bucket.handle.close();
@@ -1512,7 +1799,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1512
1799
  const results = [];
1513
1800
  for (let i = 0; i < workerCount; i++) {
1514
1801
  const bucket = browserBuckets[i % browserBuckets.length];
1515
- const driver = await Effect4.runPromise(
1802
+ const driver = await Effect3.runPromise(
1516
1803
  makePlaywrightDriver({
1517
1804
  browser: webExecution?.browser,
1518
1805
  headless: webExecution?.headless ?? true,
@@ -1531,7 +1818,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1531
1818
  warmBrowserScope: webExecution?.warmBrowserScope
1532
1819
  })
1533
1820
  );
1534
- const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
1821
+ const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
1535
1822
  let cleaned = false;
1536
1823
  results.push({
1537
1824
  runtime: {
@@ -1539,7 +1826,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1539
1826
  cleanup: () => safeCleanup(async () => {
1540
1827
  if (cleaned) return;
1541
1828
  cleaned = true;
1542
- await Effect4.runPromise(driver.killApp(""));
1829
+ await Effect3.runPromise(driver.killApp(""));
1543
1830
  bucket.remaining -= 1;
1544
1831
  if (bucket.remaining <= 0 && bucket.owns) {
1545
1832
  await bucket.browser.close();
@@ -1562,7 +1849,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1562
1849
  async function buildElectronRuntime(config, resolveFromConfig) {
1563
1850
  const electronCfg = config.apps?.electron ?? {};
1564
1851
  const bridge = await maybeStartBridge(electronCfg.bridge, config.execution?.bridge);
1565
- const driver = await Effect4.runPromise(
1852
+ const driver = await Effect3.runPromise(
1566
1853
  makeElectronDriver({
1567
1854
  entry: electronCfg.entry ? resolveFromConfig(electronCfg.entry) : void 0,
1568
1855
  executablePath: electronCfg.executablePath ? resolveFromConfig(electronCfg.executablePath) : void 0,
@@ -1578,12 +1865,12 @@ async function buildElectronRuntime(config, resolveFromConfig) {
1578
1865
  domChannel: bridge
1579
1866
  })
1580
1867
  );
1581
- const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
1868
+ const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
1582
1869
  return {
1583
1870
  runtime: {
1584
1871
  driver,
1585
1872
  cleanup: () => safeCleanup(
1586
- () => Effect4.runPromise(driver.killApp("")),
1873
+ () => Effect3.runPromise(driver.killApp("")),
1587
1874
  () => bridge?.disconnect() ?? Promise.resolve()
1588
1875
  ),
1589
1876
  metadata: {
@@ -1607,7 +1894,7 @@ async function buildElectronRuntime(config, resolveFromConfig) {
1607
1894
  async function buildElectrobunRuntime(config, resolveFromConfig) {
1608
1895
  const electrobunCfg = config.apps?.electrobun ?? {};
1609
1896
  const bridge = await maybeStartBridge(electrobunCfg.bridge, config.execution?.bridge);
1610
- const driver = await Effect4.runPromise(
1897
+ const driver = await Effect3.runPromise(
1611
1898
  makeElectrobunDriver({
1612
1899
  executablePath: electrobunCfg.executablePath ? resolveFromConfig(electrobunCfg.executablePath) : void 0,
1613
1900
  appDir: electrobunCfg.appDir ? resolveFromConfig(electrobunCfg.appDir) : void 0,
@@ -1625,12 +1912,12 @@ async function buildElectrobunRuntime(config, resolveFromConfig) {
1625
1912
  domChannel: bridge
1626
1913
  })
1627
1914
  );
1628
- const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
1915
+ const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
1629
1916
  return {
1630
1917
  runtime: {
1631
1918
  driver,
1632
1919
  cleanup: () => safeCleanup(
1633
- () => Effect4.runPromise(driver.killApp("")),
1920
+ () => Effect3.runPromise(driver.killApp("")),
1634
1921
  () => bridge?.disconnect() ?? Promise.resolve()
1635
1922
  ),
1636
1923
  metadata: {
@@ -1665,7 +1952,7 @@ async function buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig)
1665
1952
  const androidAppPath = config.apps?.android?.appPath;
1666
1953
  if (androidAppPath && packageName) {
1667
1954
  try {
1668
- const { adbShell, adbInstall } = await import("./android-4NVTZMHL.js");
1955
+ const { adbShell, adbInstall } = await import("./android-6BOQTMM3.js");
1669
1956
  const output = adbShell(device.serial, `pm list packages ${packageName}`);
1670
1957
  if (!output.includes(packageName)) {
1671
1958
  console.log(`Installing ${packageName} on Android device...`);
@@ -1673,7 +1960,7 @@ async function buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig)
1673
1960
  }
1674
1961
  } catch {
1675
1962
  console.log(`Installing ${packageName} on Android device...`);
1676
- const { adbInstall } = await import("./android-4NVTZMHL.js");
1963
+ const { adbInstall } = await import("./android-6BOQTMM3.js");
1677
1964
  adbInstall(device.serial, resolveFromConfig(androidAppPath));
1678
1965
  }
1679
1966
  }
@@ -1692,18 +1979,18 @@ async function buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig)
1692
1979
  warm: warmDaemons?.enabled,
1693
1980
  daemonStateFile: warmDaemons?.stateFile
1694
1981
  });
1695
- const driver = await Effect4.runPromise(
1982
+ const driver = await Effect3.runPromise(
1696
1983
  createUiAutomator2Driver(conn.host, conn.port, device.serial, packageName, {
1697
1984
  domChannel: bridge,
1698
1985
  cdpPort: config.apps?.android?.cdpPort
1699
1986
  })
1700
1987
  );
1701
- const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
1988
+ const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
1702
1989
  return {
1703
1990
  runtime: {
1704
1991
  driver,
1705
1992
  cleanup: () => safeCleanup(
1706
- () => Effect4.runPromise(driver.killApp("")),
1993
+ () => Effect3.runPromise(driver.killApp("")),
1707
1994
  () => bridge?.disconnect() ?? Promise.resolve(),
1708
1995
  () => {
1709
1996
  if (reversedBridgePort !== null) {
@@ -1740,7 +2027,7 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
1740
2027
  const bridge = await maybeStartBridge(config.apps?.ios?.bridge, config.execution?.bridge);
1741
2028
  const createIOSRuntime = async (deviceId, conn, simulatorUdid) => {
1742
2029
  const reuseSession = warmDaemons?.enabled && warmDaemons.reuseSession !== false;
1743
- const driver = await Effect4.runPromise(
2030
+ const driver = await Effect3.runPromise(
1744
2031
  createWDADriver(conn.host, conn.port, bundleId, simulatorUdid, snapshotMaxDepth, {
1745
2032
  domChannel: bridge,
1746
2033
  webkitInspectorUrl: config.apps?.ios?.webkitInspectorUrl,
@@ -1750,12 +2037,12 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
1750
2037
  onSessionCreated: reuseSession ? (sessionId) => updateWarmDaemonSession("wda", deviceId, sessionId, bundleId, warmDaemons?.stateFile) : void 0
1751
2038
  })
1752
2039
  );
1753
- const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
2040
+ const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
1754
2041
  return {
1755
2042
  runtime: {
1756
2043
  driver,
1757
2044
  cleanup: () => safeCleanup(
1758
- () => Effect4.runPromise(driver.killApp("")),
2045
+ () => Effect3.runPromise(driver.killApp("")),
1759
2046
  () => bridge?.disconnect() ?? Promise.resolve(),
1760
2047
  () => conn.cleanup?.() ?? Promise.resolve()
1761
2048
  ),
@@ -1784,7 +2071,7 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
1784
2071
  });
1785
2072
  }
1786
2073
  if (signing?.teamId) {
1787
- const { setupWDAForDevice } = await import("./installer-VUPFWP5X.js");
2074
+ const { setupWDAForDevice } = await import("./installer-IYGMG7LS.js");
1788
2075
  const wdaPort2 = allocatePort(8100);
1789
2076
  conn = await setupWDAForDevice(
1790
2077
  physicalDevice2.udid,
@@ -1886,13 +2173,403 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
1886
2173
  }
1887
2174
  }
1888
2175
 
2176
+ // src/report/code-frame.ts
2177
+ import { existsSync as existsSync2, readFileSync } from "fs";
2178
+ import { fileURLToPath } from "url";
2179
+ var INTERNAL_FRAME_PATTERNS = [
2180
+ /node_modules\//,
2181
+ /^node:/,
2182
+ /^bun:/,
2183
+ /^internal\//,
2184
+ /\/packages\/spana\/(?:src|dist)\/(?!.*\.test\.[jt]sx?$)/,
2185
+ /\/spana(?:-test)?\/dist\//
2186
+ ];
2187
+ function normalizeStackFile(raw) {
2188
+ const trimmed = raw.trim();
2189
+ if (trimmed.startsWith("file://")) {
2190
+ try {
2191
+ return fileURLToPath(trimmed);
2192
+ } catch {
2193
+ return trimmed.replace(/^file:\/\//, "");
2194
+ }
2195
+ }
2196
+ return trimmed;
2197
+ }
2198
+ function parseStackFrames(stack) {
2199
+ const frames = [];
2200
+ for (const rawLine of stack.split("\n")) {
2201
+ const line = rawLine.trim();
2202
+ if (!line.startsWith("at ")) continue;
2203
+ const match = line.match(/\((.+):(\d+):(\d+)\)$/) ?? line.match(/^at\s+(.+):(\d+):(\d+)$/);
2204
+ if (!match) continue;
2205
+ const file = normalizeStackFile(match[1]);
2206
+ const lineNum = Number.parseInt(match[2], 10);
2207
+ const colNum = Number.parseInt(match[3], 10);
2208
+ if (!file || !Number.isFinite(lineNum) || lineNum < 1) continue;
2209
+ frames.push({
2210
+ file,
2211
+ line: lineNum,
2212
+ column: Number.isFinite(colNum) && colNum > 0 ? colNum : 1
2213
+ });
2214
+ }
2215
+ return frames;
2216
+ }
2217
+ function isInternalFrame(file) {
2218
+ const normalized = file.replaceAll("\\", "/");
2219
+ return INTERNAL_FRAME_PATTERNS.some((re) => re.test(normalized));
2220
+ }
2221
+ function formatCodeFrame(source, line, column, contextLines = 3) {
2222
+ const lines = source.split(/\r?\n/);
2223
+ if (line < 1 || line > lines.length) return "";
2224
+ const startLine = Math.max(1, line - contextLines);
2225
+ const endLine = Math.min(lines.length, line + contextLines);
2226
+ const gutterWidth = String(endLine).length;
2227
+ const out = [];
2228
+ for (let current = startLine; current <= endLine; current++) {
2229
+ const marker = current === line ? ">" : " ";
2230
+ const num = String(current).padStart(gutterWidth, " ");
2231
+ const content = lines[current - 1] ?? "";
2232
+ out.push(`${marker} ${num} | ${content}`);
2233
+ if (current === line) {
2234
+ const caretOffset = Math.max(0, Math.min(column - 1, content.length));
2235
+ out.push(` ${" ".repeat(gutterWidth)} | ${" ".repeat(caretOffset)}^`);
2236
+ }
2237
+ }
2238
+ return out.join("\n");
2239
+ }
2240
+ function extractCodeFrame(stack, preferredFile, contextLines = 3) {
2241
+ if (!stack) return void 0;
2242
+ const frames = parseStackFrames(stack);
2243
+ if (frames.length === 0) return void 0;
2244
+ const normalizedPreferred = preferredFile ? normalizeStackFile(preferredFile) : void 0;
2245
+ let chosen = normalizedPreferred ? frames.find(
2246
+ (f) => (f.file === normalizedPreferred || f.file.endsWith(normalizedPreferred)) && existsSync2(f.file)
2247
+ ) : void 0;
2248
+ if (!chosen) {
2249
+ chosen = frames.find((f) => /\.flow\.[cm]?[jt]sx?$/.test(f.file) && existsSync2(f.file));
2250
+ }
2251
+ if (!chosen) {
2252
+ chosen = frames.find((f) => !isInternalFrame(f.file) && existsSync2(f.file));
2253
+ }
2254
+ if (!chosen) return void 0;
2255
+ try {
2256
+ const source = readFileSync(chosen.file, "utf8");
2257
+ const frame = formatCodeFrame(source, chosen.line, chosen.column, contextLines);
2258
+ if (!frame) return void 0;
2259
+ return {
2260
+ location: { file: chosen.file, line: chosen.line, column: chosen.column },
2261
+ frame
2262
+ };
2263
+ } catch {
2264
+ return void 0;
2265
+ }
2266
+ }
2267
+
2268
+ // src/core/video-recorder.ts
2269
+ import { execFileSync, spawn as spawn2 } from "child_process";
2270
+ import {
2271
+ existsSync as existsSync3,
2272
+ mkdirSync,
2273
+ mkdtempSync as mkdtempSync2,
2274
+ readFileSync as readFileSync2,
2275
+ rmSync as rmSync2,
2276
+ unlinkSync,
2277
+ writeFileSync
2278
+ } from "fs";
2279
+ import { tmpdir as tmpdir2 } from "os";
2280
+ import { join as join2 } from "path";
2281
+ function hasFfmpegOnPath() {
2282
+ try {
2283
+ execFileSync(process.platform === "win32" ? "where" : "which", ["ffmpeg"], {
2284
+ stdio: "ignore"
2285
+ });
2286
+ return true;
2287
+ } catch {
2288
+ return false;
2289
+ }
2290
+ }
2291
+ async function exportFramesToMp4(frames, outputPath, spawnFn = spawn2) {
2292
+ if (frames.length === 0 || !hasFfmpegOnPath()) return void 0;
2293
+ const tempDir = mkdtempSync2(join2(tmpdir2(), "spana-vid-"));
2294
+ try {
2295
+ const ext = frames[0].mimeType === "image/png" ? "png" : "jpg";
2296
+ const listLines = [];
2297
+ for (let i = 0; i < frames.length; i++) {
2298
+ const f = frames[i];
2299
+ const framePath = join2(tempDir, `frame-${String(i).padStart(5, "0")}.${ext}`);
2300
+ writeFileSync(framePath, Buffer.from(f.dataBase64, "base64"));
2301
+ const nextTs = frames[i + 1]?.timestampMs ?? f.timestampMs + 250;
2302
+ const durSec = Math.max(0.05, Math.min(2, (nextTs - f.timestampMs) / 1e3));
2303
+ listLines.push(`file '${framePath.replaceAll("'", "'\\''")}'`);
2304
+ listLines.push(`duration ${durSec.toFixed(3)}`);
2305
+ }
2306
+ const lastPath = join2(tempDir, `frame-${String(frames.length - 1).padStart(5, "0")}.${ext}`);
2307
+ listLines.push(`file '${lastPath.replaceAll("'", "'\\''")}'`);
2308
+ const listFile = join2(tempDir, "frames.txt");
2309
+ writeFileSync(listFile, listLines.join("\n"), "utf8");
2310
+ const ok = await new Promise((resolve) => {
2311
+ const child = spawnFn(
2312
+ "ffmpeg",
2313
+ [
2314
+ "-y",
2315
+ "-f",
2316
+ "concat",
2317
+ "-safe",
2318
+ "0",
2319
+ "-i",
2320
+ listFile,
2321
+ "-vf",
2322
+ "pad=ceil(iw/2)*2:ceil(ih/2)*2",
2323
+ "-c:v",
2324
+ "libx264",
2325
+ "-pix_fmt",
2326
+ "yuv420p",
2327
+ "-movflags",
2328
+ "+faststart",
2329
+ outputPath
2330
+ ],
2331
+ { stdio: "ignore" }
2332
+ );
2333
+ child.on("error", () => resolve(false));
2334
+ child.on("close", (code) => resolve(code === 0));
2335
+ });
2336
+ return ok && existsSync3(outputPath) ? outputPath : void 0;
2337
+ } catch {
2338
+ return void 0;
2339
+ } finally {
2340
+ try {
2341
+ rmSync2(tempDir, { recursive: true, force: true });
2342
+ } catch {
2343
+ }
2344
+ }
2345
+ }
2346
+ async function startCdpScreencastRecorder(cdp, options) {
2347
+ const startedAt = Date.now();
2348
+ const startedAtIso = new Date(startedAt).toISOString();
2349
+ const maxFrames = options.maxFrames ?? 180;
2350
+ const frames = [];
2351
+ let stopped = false;
2352
+ const unsubscribe = cdp.onEvent("Page.screencastFrame", (params) => {
2353
+ if (stopped) return;
2354
+ const sessionId = params?.sessionId;
2355
+ if (sessionId !== void 0) {
2356
+ void cdp.sendCommand("Page.screencastFrameAck", { sessionId }).catch(() => {
2357
+ });
2358
+ }
2359
+ if (typeof params?.data === "string" && params.data.length > 0) {
2360
+ if (frames.length >= maxFrames) {
2361
+ frames.splice(1, 1);
2362
+ }
2363
+ frames.push({
2364
+ timestampMs: Math.max(0, Date.now() - startedAt),
2365
+ dataBase64: params.data,
2366
+ mimeType: "image/jpeg"
2367
+ });
2368
+ }
2369
+ });
2370
+ await cdp.sendCommand("Page.startScreencast", {
2371
+ format: "jpeg",
2372
+ quality: options.quality ?? 65,
2373
+ maxWidth: options.maxWidth ?? 1280,
2374
+ maxHeight: options.maxHeight ?? 720,
2375
+ everyNthFrame: options.everyNthFrame ?? 2
2376
+ }).catch(() => {
2377
+ });
2378
+ return {
2379
+ stop: async (stopOpts) => {
2380
+ if (stopped) return { frameCount: frames.length };
2381
+ stopped = true;
2382
+ unsubscribe();
2383
+ await cdp.sendCommand("Page.stopScreencast").catch(() => {
2384
+ });
2385
+ if (!stopOpts.keep) {
2386
+ return { frameCount: 0 };
2387
+ }
2388
+ if (frames.length === 0) {
2389
+ try {
2390
+ const snap = await cdp.sendCommand("Page.captureScreenshot", {
2391
+ format: "jpeg",
2392
+ quality: options.quality ?? 65
2393
+ });
2394
+ if (typeof snap?.data === "string" && snap.data.length > 0) {
2395
+ frames.push({
2396
+ timestampMs: Math.max(0, Date.now() - startedAt),
2397
+ dataBase64: snap.data,
2398
+ mimeType: "image/jpeg"
2399
+ });
2400
+ }
2401
+ } catch {
2402
+ }
2403
+ }
2404
+ if (frames.length === 0) {
2405
+ return { frameCount: 0 };
2406
+ }
2407
+ mkdirSync(stopOpts.outputDir, { recursive: true });
2408
+ let videoPath;
2409
+ if (options.exportMp4 !== false) {
2410
+ const mp4Target = join2(stopOpts.outputDir, `${stopOpts.fileStem}.mp4`);
2411
+ videoPath = await exportFramesToMp4(frames, mp4Target, options.spawnFn);
2412
+ }
2413
+ const trace = {
2414
+ version: 1,
2415
+ flowName: options.flowName,
2416
+ platform: options.platform,
2417
+ startedAtIso,
2418
+ durationMs: Math.max(1, Date.now() - startedAt),
2419
+ viewport: stopOpts.viewport,
2420
+ frames,
2421
+ steps: stopOpts.steps ?? [],
2422
+ ...videoPath ? { videoPath } : {}
2423
+ };
2424
+ const playbackJsonPath = join2(stopOpts.outputDir, `${stopOpts.fileStem}-playback.json`);
2425
+ writeFileSync(playbackJsonPath, JSON.stringify(trace), "utf8");
2426
+ return { playbackJsonPath, videoPath, frameCount: frames.length };
2427
+ }
2428
+ };
2429
+ }
2430
+ function startAndroidVideoRecorder(serial, options) {
2431
+ const spawnFn = options.spawnFn ?? spawn2;
2432
+ const execSyncFn = options.execFileSyncFn ?? execFileSync;
2433
+ const remotePath = `/sdcard/spana-rec-${Date.now()}-${Math.floor(Math.random() * 1e4)}.mp4`;
2434
+ const child = spawnFn(
2435
+ "adb",
2436
+ ["-s", serial, "shell", "screenrecord", "--time-limit", "180", remotePath],
2437
+ { stdio: "ignore" }
2438
+ );
2439
+ let stopped = false;
2440
+ return {
2441
+ stop: async ({ keep }) => {
2442
+ if (stopped) return { frameCount: 0 };
2443
+ stopped = true;
2444
+ try {
2445
+ child.kill("SIGINT");
2446
+ } catch {
2447
+ }
2448
+ await new Promise((resolve) => {
2449
+ const timer = setTimeout(resolve, 1200);
2450
+ child.once("close", () => {
2451
+ clearTimeout(timer);
2452
+ resolve();
2453
+ });
2454
+ });
2455
+ let savedPath;
2456
+ if (keep) {
2457
+ try {
2458
+ execSyncFn("adb", ["-s", serial, "pull", remotePath, options.outputPath], {
2459
+ stdio: "ignore"
2460
+ });
2461
+ if (existsSync3(options.outputPath)) savedPath = options.outputPath;
2462
+ } catch {
2463
+ }
2464
+ }
2465
+ try {
2466
+ execSyncFn("adb", ["-s", serial, "shell", "rm", "-f", remotePath], { stdio: "ignore" });
2467
+ } catch {
2468
+ }
2469
+ return { videoPath: savedPath, frameCount: savedPath ? 1 : 0 };
2470
+ }
2471
+ };
2472
+ }
2473
+ function startIosSimulatorVideoRecorder(udid, options) {
2474
+ const spawnFn = options.spawnFn ?? spawn2;
2475
+ const child = spawnFn(
2476
+ "xcrun",
2477
+ ["simctl", "io", udid, "recordVideo", "--codec=h264", "--force", options.outputPath],
2478
+ { stdio: "ignore" }
2479
+ );
2480
+ let stopped = false;
2481
+ return {
2482
+ stop: async ({ keep }) => {
2483
+ if (stopped) return { frameCount: 0 };
2484
+ stopped = true;
2485
+ try {
2486
+ child.kill("SIGINT");
2487
+ } catch {
2488
+ }
2489
+ await new Promise((resolve) => {
2490
+ const timer = setTimeout(resolve, 1500);
2491
+ child.once("close", () => {
2492
+ clearTimeout(timer);
2493
+ resolve();
2494
+ });
2495
+ });
2496
+ if (!keep) {
2497
+ try {
2498
+ if (existsSync3(options.outputPath)) unlinkSync(options.outputPath);
2499
+ } catch {
2500
+ }
2501
+ return { frameCount: 0 };
2502
+ }
2503
+ return {
2504
+ videoPath: existsSync3(options.outputPath) ? options.outputPath : void 0,
2505
+ frameCount: existsSync3(options.outputPath) ? 1 : 0
2506
+ };
2507
+ }
2508
+ };
2509
+ }
2510
+ function buildPlaybackTraceFromSteps(input) {
2511
+ const frames = [];
2512
+ const markers = [];
2513
+ let cursorMs = 0;
2514
+ for (let i = 0; i < input.steps.length; i++) {
2515
+ const step = input.steps[i];
2516
+ const tapPoint = extractTapPointFromStep(step);
2517
+ markers.push({
2518
+ index: i,
2519
+ command: step.command,
2520
+ selector: step.selector,
2521
+ startedAtMs: cursorMs,
2522
+ durationMs: step.durationMs,
2523
+ status: step.status,
2524
+ error: step.error,
2525
+ ...tapPoint ? { tapPoint } : {}
2526
+ });
2527
+ const img = step.attachments?.find(
2528
+ (a) => a.contentType === "image/png" || a.contentType === "image/jpeg"
2529
+ );
2530
+ if (img && existsSync3(img.path)) {
2531
+ try {
2532
+ const dataBase64 = readFileSync2(img.path).toString("base64");
2533
+ frames.push({
2534
+ timestampMs: cursorMs + step.durationMs,
2535
+ dataBase64,
2536
+ mimeType: img.contentType === "image/jpeg" ? "image/jpeg" : "image/png"
2537
+ });
2538
+ } catch {
2539
+ }
2540
+ }
2541
+ cursorMs += Math.max(1, step.durationMs);
2542
+ }
2543
+ if (frames.length === 0 && !input.videoPath) return null;
2544
+ return {
2545
+ version: 1,
2546
+ flowName: input.flowName,
2547
+ platform: input.platform,
2548
+ startedAtIso: (/* @__PURE__ */ new Date()).toISOString(),
2549
+ durationMs: Math.max(1, input.durationMs),
2550
+ viewport: input.viewport,
2551
+ frames,
2552
+ steps: markers,
2553
+ ...input.videoPath ? { videoPath: input.videoPath } : {}
2554
+ };
2555
+ }
2556
+ function extractTapPointFromStep(step) {
2557
+ const sel = step.selector;
2558
+ if (!sel || typeof sel !== "object") return void 0;
2559
+ const pt = sel["point"];
2560
+ if (pt && typeof pt["x"] === "number" && typeof pt["y"] === "number") {
2561
+ return { x: pt["x"], y: pt["y"] };
2562
+ }
2563
+ return void 0;
2564
+ }
2565
+
1889
2566
  // src/core/engine.ts
1890
- import { Effect as Effect7 } from "effect";
2567
+ import { Effect as Effect6 } from "effect";
1891
2568
 
1892
2569
  // src/core/artifacts.ts
1893
- import { writeFileSync, mkdirSync } from "fs";
1894
- import { join as join2 } from "path";
1895
- import { Effect as Effect5 } from "effect";
2570
+ import { writeFileSync as writeFileSync2, mkdirSync as mkdirSync2 } from "fs";
2571
+ import { join as join3 } from "path";
2572
+ import { Effect as Effect4 } from "effect";
1896
2573
  var DEFAULT_ARTIFACT_CONFIG = {
1897
2574
  outputDir: "./spana-output",
1898
2575
  captureOnFailure: true,
@@ -1902,27 +2579,30 @@ var DEFAULT_ARTIFACT_CONFIG = {
1902
2579
  uiHierarchy: true,
1903
2580
  consoleLogs: true,
1904
2581
  jsErrors: true,
1905
- har: true
2582
+ har: true,
2583
+ video: "off",
2584
+ playback: false
1906
2585
  };
1907
- function safeName(value) {
2586
+ function safeArtifactName(value) {
1908
2587
  return value.replaceAll(/[^a-zA-Z0-9-_]/g, "_").replaceAll(/_+/g, "_").replaceAll(/^_+|_+$/g, "").slice(0, 80) || "artifact";
1909
2588
  }
2589
+ var safeName = safeArtifactName;
1910
2590
  function flowArtifactDir(config, flowName, platform) {
1911
- const dir = join2(config.outputDir, `${safeName(flowName)}-${platform}`);
1912
- mkdirSync(dir, { recursive: true });
2591
+ const dir = join3(config.outputDir, `${safeName(flowName)}-${platform}`);
2592
+ mkdirSync2(dir, { recursive: true });
1913
2593
  return dir;
1914
2594
  }
1915
2595
  function createAttachment(name, contentType, path) {
1916
2596
  return { name, contentType, path };
1917
2597
  }
1918
2598
  function writeJsonAttachment(dir, fileName, attachmentName, value) {
1919
- const path = join2(dir, fileName);
1920
- writeFileSync(path, JSON.stringify(value, null, 2), "utf-8");
2599
+ const path = join3(dir, fileName);
2600
+ writeFileSync2(path, JSON.stringify(value, null, 2), "utf-8");
1921
2601
  return createAttachment(attachmentName, "application/json", path);
1922
2602
  }
1923
2603
  function writeTextAttachment(dir, fileName, attachmentName, value) {
1924
- const path = join2(dir, fileName);
1925
- writeFileSync(path, value, "utf-8");
2604
+ const path = join3(dir, fileName);
2605
+ writeFileSync2(path, value, "utf-8");
1926
2606
  return createAttachment(attachmentName, "text/plain", path);
1927
2607
  }
1928
2608
  function resolveArtifactConfig(...configs) {
@@ -1941,25 +2621,25 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
1941
2621
  const dir = flowArtifactDir(config, flowName, platform);
1942
2622
  if (config.screenshot) {
1943
2623
  try {
1944
- const screenshot = await Effect5.runPromise(Effect5.orDie(driver.takeScreenshot()));
1945
- const path = join2(dir, "screenshot.png");
1946
- writeFileSync(path, screenshot);
2624
+ const screenshot = await Effect4.runPromise(Effect4.orDie(driver.takeScreenshot()));
2625
+ const path = join3(dir, "screenshot.png");
2626
+ writeFileSync2(path, screenshot);
1947
2627
  attachments.push(createAttachment(`${status}-screenshot`, "image/png", path));
1948
2628
  } catch {
1949
2629
  }
1950
2630
  }
1951
2631
  if (config.uiHierarchy) {
1952
2632
  try {
1953
- const hierarchy = await Effect5.runPromise(Effect5.orDie(driver.dumpHierarchy()));
1954
- const path = join2(dir, "hierarchy.json");
1955
- writeFileSync(path, hierarchy, "utf-8");
2633
+ const hierarchy = await Effect4.runPromise(Effect4.orDie(driver.dumpHierarchy()));
2634
+ const path = join3(dir, "hierarchy.json");
2635
+ writeFileSync2(path, hierarchy, "utf-8");
1956
2636
  attachments.push(createAttachment(`${status}-hierarchy`, "application/json", path));
1957
2637
  } catch {
1958
2638
  }
1959
2639
  }
1960
2640
  if (config.consoleLogs && driver.getConsoleLogs) {
1961
2641
  try {
1962
- const consoleLogs = await Effect5.runPromise(Effect5.orDie(driver.getConsoleLogs()));
2642
+ const consoleLogs = await Effect4.runPromise(Effect4.orDie(driver.getConsoleLogs()));
1963
2643
  if (consoleLogs.length > 0) {
1964
2644
  attachments.push(
1965
2645
  writeJsonAttachment(dir, "console-logs.json", `${status}-console-logs`, consoleLogs)
@@ -1970,7 +2650,7 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
1970
2650
  }
1971
2651
  if (config.jsErrors && driver.getJSErrors) {
1972
2652
  try {
1973
- const jsErrors = await Effect5.runPromise(Effect5.orDie(driver.getJSErrors()));
2653
+ const jsErrors = await Effect4.runPromise(Effect4.orDie(driver.getJSErrors()));
1974
2654
  if (jsErrors.length > 0) {
1975
2655
  attachments.push(
1976
2656
  writeJsonAttachment(dir, "js-errors.json", `${status}-js-errors`, jsErrors)
@@ -1981,7 +2661,7 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
1981
2661
  }
1982
2662
  if (config.har && driver.getHAR) {
1983
2663
  try {
1984
- const har = await Effect5.runPromise(Effect5.orDie(driver.getHAR()));
2664
+ const har = await Effect4.runPromise(Effect4.orDie(driver.getHAR()));
1985
2665
  if (har.log.entries.length > 0) {
1986
2666
  attachments.push(writeJsonAttachment(dir, "network.har", `${status}-network-har`, har));
1987
2667
  }
@@ -1990,7 +2670,7 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
1990
2670
  }
1991
2671
  if (status === "failed" && driver.getDriverLogs) {
1992
2672
  try {
1993
- const driverLogs = await Effect5.runPromise(Effect5.orDie(driver.getDriverLogs()));
2673
+ const driverLogs = await Effect4.runPromise(Effect4.orDie(driver.getDriverLogs()));
1994
2674
  if (driverLogs.length > 0) {
1995
2675
  attachments.push(
1996
2676
  writeTextAttachment(
@@ -2009,12 +2689,12 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
2009
2689
  async function captureStepScreenshot(driver, config, flowName, platform, stepIndex, stepName, screenshot) {
2010
2690
  if (!config.screenshot) return void 0;
2011
2691
  try {
2012
- const dir = join2(flowArtifactDir(config, flowName, platform), "steps");
2013
- mkdirSync(dir, { recursive: true });
2692
+ const dir = join3(flowArtifactDir(config, flowName, platform), "steps");
2693
+ mkdirSync2(dir, { recursive: true });
2014
2694
  const fileName = `${String(stepIndex).padStart(3, "0")}-${safeName(stepName)}.png`;
2015
- const path = join2(dir, fileName);
2016
- const bytes = screenshot ?? await Effect5.runPromise(Effect5.orDie(driver.takeScreenshot()));
2017
- writeFileSync(path, bytes);
2695
+ const path = join3(dir, fileName);
2696
+ const bytes = screenshot ?? await Effect4.runPromise(Effect4.orDie(driver.takeScreenshot()));
2697
+ writeFileSync2(path, bytes);
2018
2698
  return createAttachment(stepName, "image/png", path);
2019
2699
  } catch {
2020
2700
  return void 0;
@@ -2023,7 +2703,7 @@ async function captureStepScreenshot(driver, config, flowName, platform, stepInd
2023
2703
 
2024
2704
  // src/core/debug-repl.ts
2025
2705
  import * as repl from "repl";
2026
- import { Effect as Effect6 } from "effect";
2706
+ import { Effect as Effect5 } from "effect";
2027
2707
  var didStartDebugRepl = false;
2028
2708
  function toSuggestedSelectors(root) {
2029
2709
  return flattenElements(root).filter((el) => el.visible !== false && (el.id || el.text || el.accessibilityLabel)).map((el) => ({
@@ -2044,7 +2724,7 @@ async function runDebugReplOnce(context) {
2044
2724
  console.log("Skipping debug REPL because stdin/stdout is not interactive.");
2045
2725
  return false;
2046
2726
  }
2047
- const hierarchy = async () => context.parseHierarchy(await Effect6.runPromise(context.driver.dumpHierarchy()));
2727
+ const hierarchy = async () => context.parseHierarchy(await Effect5.runPromise(context.driver.dumpHierarchy()));
2048
2728
  const selectors = async () => toSuggestedSelectors(await hierarchy());
2049
2729
  console.log("");
2050
2730
  console.log(`Entering debug REPL for failed flow "${context.flowName}" on ${context.platform}.`);
@@ -2094,9 +2774,11 @@ function createStepResult(command, durationMs, status, selector, error, attachme
2094
2774
  }
2095
2775
  function createStepRecorder(driver, artifactConfig, flowName, platform) {
2096
2776
  const steps = [];
2777
+ let lastFailureStack;
2097
2778
  return {
2098
2779
  async runStep(command, action, opts) {
2099
2780
  const startedAt = Date.now();
2781
+ const callSiteStack = new Error().stack;
2100
2782
  try {
2101
2783
  const result = await action();
2102
2784
  const attachments = [];
@@ -2123,6 +2805,7 @@ function createStepRecorder(driver, artifactConfig, flowName, platform) {
2123
2805
  );
2124
2806
  return result;
2125
2807
  } catch (error) {
2808
+ lastFailureStack = callSiteStack;
2126
2809
  steps.push(
2127
2810
  createStepResult(
2128
2811
  command,
@@ -2137,6 +2820,7 @@ function createStepRecorder(driver, artifactConfig, flowName, platform) {
2137
2820
  },
2138
2821
  async runScreenshotStep(command, action, opts) {
2139
2822
  const startedAt = Date.now();
2823
+ const callSiteStack = new Error().stack;
2140
2824
  try {
2141
2825
  const screenshot = await action();
2142
2826
  const attachment = await captureStepScreenshot(
@@ -2160,6 +2844,7 @@ function createStepRecorder(driver, artifactConfig, flowName, platform) {
2160
2844
  );
2161
2845
  return screenshot;
2162
2846
  } catch (error) {
2847
+ lastFailureStack = callSiteStack;
2163
2848
  steps.push(
2164
2849
  createStepResult(
2165
2850
  command,
@@ -2174,6 +2859,9 @@ function createStepRecorder(driver, artifactConfig, flowName, platform) {
2174
2859
  },
2175
2860
  getSteps() {
2176
2861
  return steps;
2862
+ },
2863
+ getLastFailureStack() {
2864
+ return lastFailureStack;
2177
2865
  }
2178
2866
  };
2179
2867
  }
@@ -2426,23 +3114,26 @@ function categorize(error) {
2426
3114
  }
2427
3115
  return { category: "unknown" };
2428
3116
  }
2429
- function classifyError(error) {
3117
+ function classifyError(error, opts) {
2430
3118
  const tagged = error;
2431
3119
  const { category, suggestion } = categorize(tagged);
3120
+ const extracted = extractCodeFrame(error.stack, opts?.flowFilePath) ?? extractCodeFrame(opts?.fallbackStack, opts?.flowFilePath);
2432
3121
  return {
2433
3122
  message: error.message,
2434
3123
  stack: error.stack,
2435
3124
  category,
2436
- suggestion
3125
+ suggestion,
3126
+ ...extracted ? { location: extracted.location, codeFrame: extracted.frame } : {}
2437
3127
  };
2438
3128
  }
2439
3129
 
2440
3130
  // src/core/engine.ts
2441
- import { join as join4 } from "path";
3131
+ import { writeFileSync as writeFileSync4 } from "fs";
3132
+ import { join as join5 } from "path";
2442
3133
 
2443
3134
  // src/report/failure-bundle.ts
2444
- import { writeFileSync as writeFileSync2, readFileSync, existsSync as existsSync2 } from "fs";
2445
- import { join as join3, basename } from "path";
3135
+ import { writeFileSync as writeFileSync3, readFileSync as readFileSync3, existsSync as existsSync4 } from "fs";
3136
+ import { join as join4, basename } from "path";
2446
3137
  function levenshtein(a, b) {
2447
3138
  const m = a.length;
2448
3139
  const n = b.length;
@@ -2549,11 +3240,11 @@ function createFailureBundle(flowName, platform, steps, error, artifactDir, atta
2549
3240
  } : null;
2550
3241
  let selectorContext;
2551
3242
  if (failedStep?.selector && (error.category === "element-not-found" || error.category === "element-not-visible")) {
2552
- const hierarchyPath = join3(artifactDir, "hierarchy.json");
3243
+ const hierarchyPath = join4(artifactDir, "hierarchy.json");
2553
3244
  let hierarchyJson = null;
2554
- if (existsSync2(hierarchyPath)) {
3245
+ if (existsSync4(hierarchyPath)) {
2555
3246
  try {
2556
- hierarchyJson = readFileSync(hierarchyPath, "utf-8");
3247
+ hierarchyJson = readFileSync3(hierarchyPath, "utf-8");
2557
3248
  } catch {
2558
3249
  }
2559
3250
  }
@@ -2566,17 +3257,17 @@ function createFailureBundle(flowName, platform, steps, error, artifactDir, atta
2566
3257
  const flowFile = flowPath ?? `flows/${flowName.replaceAll(" ", "-")}.flow.ts`;
2567
3258
  const reproCommand = `spana test ${flowFile} --platform ${platform} --grep '${flowName}'`;
2568
3259
  let runtimeDiagnostics;
2569
- const consolePath = join3(artifactDir, "console-logs.json");
2570
- const jsErrPath = join3(artifactDir, "js-errors.json");
2571
- if (existsSync2(consolePath) || existsSync2(jsErrPath)) {
3260
+ const consolePath = join4(artifactDir, "console-logs.json");
3261
+ const jsErrPath = join4(artifactDir, "js-errors.json");
3262
+ if (existsSync4(consolePath) || existsSync4(jsErrPath)) {
2572
3263
  let consoleErrorCount = 0;
2573
3264
  let consoleWarnCount = 0;
2574
3265
  const recentConsoleErrors = [];
2575
3266
  let jsErrorCount = 0;
2576
3267
  const recentJsErrors = [];
2577
- if (existsSync2(consolePath)) {
3268
+ if (existsSync4(consolePath)) {
2578
3269
  try {
2579
- const logs = JSON.parse(readFileSync(consolePath, "utf-8"));
3270
+ const logs = JSON.parse(readFileSync3(consolePath, "utf-8"));
2580
3271
  if (Array.isArray(logs)) {
2581
3272
  for (const entry of logs) {
2582
3273
  const lvl = (entry.type ?? entry.level ?? "").toLowerCase();
@@ -2592,9 +3283,9 @@ function createFailureBundle(flowName, platform, steps, error, artifactDir, atta
2592
3283
  } catch {
2593
3284
  }
2594
3285
  }
2595
- if (existsSync2(jsErrPath)) {
3286
+ if (existsSync4(jsErrPath)) {
2596
3287
  try {
2597
- const errs = JSON.parse(readFileSync(jsErrPath, "utf-8"));
3288
+ const errs = JSON.parse(readFileSync3(jsErrPath, "utf-8"));
2598
3289
  if (Array.isArray(errs)) {
2599
3290
  jsErrorCount = errs.length;
2600
3291
  for (const e of errs.slice(-5)) {
@@ -2626,7 +3317,9 @@ function createFailureBundle(flowName, platform, steps, error, artifactDir, atta
2626
3317
  message: error.message,
2627
3318
  category: error.category,
2628
3319
  suggestion: error.suggestion,
2629
- errorCode: error.errorCode
3320
+ errorCode: error.errorCode,
3321
+ ...error.location ? { location: error.location } : {},
3322
+ ...error.codeFrame ? { codeFrame: error.codeFrame } : {}
2630
3323
  },
2631
3324
  selectorContext,
2632
3325
  ...runtimeDiagnostics ? { runtimeDiagnostics } : {},
@@ -2637,12 +3330,35 @@ function createFailureBundle(flowName, platform, steps, error, artifactDir, atta
2637
3330
  return bundle;
2638
3331
  }
2639
3332
  function writeFailureBundle(bundle, artifactDir) {
2640
- const path = join3(artifactDir, "failure-bundle.json");
2641
- writeFileSync2(path, JSON.stringify(bundle, null, 2), "utf-8");
3333
+ const path = join4(artifactDir, "failure-bundle.json");
3334
+ writeFileSync3(path, JSON.stringify(bundle, null, 2), "utf-8");
2642
3335
  return path;
2643
3336
  }
2644
3337
 
2645
3338
  // src/core/engine.ts
3339
+ function isCdpScreencastCapable(channel) {
3340
+ return Boolean(channel) && typeof channel.sendCommand === "function" && typeof channel.onEvent === "function";
3341
+ }
3342
+ function buildPlaybackStepMarkers(steps) {
3343
+ let cursorMs = 0;
3344
+ return steps.map((step, index) => {
3345
+ const startedAtMs = cursorMs;
3346
+ cursorMs += Math.max(1, step.durationMs);
3347
+ const sel = step.selector;
3348
+ const pt = sel && typeof sel === "object" ? sel["point"] : void 0;
3349
+ const tapPoint = pt && typeof pt["x"] === "number" && typeof pt["y"] === "number" ? { x: pt["x"], y: pt["y"] } : void 0;
3350
+ return {
3351
+ index,
3352
+ command: step.command,
3353
+ selector: step.selector,
3354
+ startedAtMs,
3355
+ durationMs: step.durationMs,
3356
+ status: step.status,
3357
+ error: step.error,
3358
+ ...tapPoint ? { tapPoint } : {}
3359
+ };
3360
+ });
3361
+ }
2646
3362
  async function executeFlow(flow, driver, config) {
2647
3363
  const start2 = Date.now();
2648
3364
  const { platform, coordinatorConfig, appId } = config;
@@ -2665,17 +3381,21 @@ async function executeFlow(flow, driver, config) {
2665
3381
  typingDelay: flowDefaults.typingDelay ?? coordinatorConfig.typingDelay,
2666
3382
  hierarchyCacheTtl: flowDefaults.hierarchyCacheTtl ?? coordinatorConfig.hierarchyCacheTtl
2667
3383
  } : coordinatorConfig;
2668
- const app = createPromiseApp(driver, appId, mergedCoordinatorConfig, stepRecorder, {
2669
- platform,
2670
- storybook: config.storybook,
2671
- launchOptions
2672
- });
2673
3384
  const flowMeta = {
2674
3385
  flowFilePath: flow.sourcePath ?? "",
2675
3386
  flowName: flow.name,
2676
3387
  platform,
2677
3388
  updateBaselines: config.updateBaselines ?? false
2678
3389
  };
3390
+ const extraCleanups = [];
3391
+ const app = createPromiseApp(driver, appId, mergedCoordinatorConfig, stepRecorder, {
3392
+ platform,
3393
+ storybook: config.storybook,
3394
+ launchOptions,
3395
+ onRegisterCleanup: (fn) => extraCleanups.push(fn),
3396
+ flowContext: flowMeta,
3397
+ visualRegression: config.visualRegression
3398
+ });
2679
3399
  const expect = createPromiseExpect(
2680
3400
  driver,
2681
3401
  mergedCoordinatorConfig,
@@ -2688,7 +3408,7 @@ async function executeFlow(flow, driver, config) {
2688
3408
  const sessions = createSessions(
2689
3409
  sessionManager,
2690
3410
  async (opts) => {
2691
- const pwDriver = await Effect7.runPromise(
3411
+ const pwDriver = await Effect6.runPromise(
2692
3412
  makePlaywrightDriver({
2693
3413
  browser: opts.browser,
2694
3414
  headless: opts.headless ?? true,
@@ -2702,6 +3422,70 @@ async function executeFlow(flow, driver, config) {
2702
3422
  { parse: (raw) => parseWebHierarchy(raw) }
2703
3423
  );
2704
3424
  flowCtx.sessions = sessions;
3425
+ let videoRecorder;
3426
+ let recordingFinalized = false;
3427
+ const wantRecording = artifactConfig.video !== "off" || artifactConfig.playback;
3428
+ const finalizeRecording = async (status, attachments, steps, durationMs) => {
3429
+ if (recordingFinalized || !wantRecording) return;
3430
+ recordingFinalized = true;
3431
+ const keep = artifactConfig.video === "on" || artifactConfig.playback || artifactConfig.video === "retain-on-failure" && status === "failed";
3432
+ const fileStem = safeArtifactName(flow.name);
3433
+ const outputDir = keep ? flowArtifactDir(artifactConfig, flow.name, platform) : artifactConfig.outputDir;
3434
+ let viewport;
3435
+ try {
3436
+ const info = await Effect6.runPromise(Effect6.orDie(driver.getDeviceInfo()));
3437
+ if (info.screenWidth > 0 && info.screenHeight > 0) {
3438
+ viewport = { width: info.screenWidth, height: info.screenHeight };
3439
+ }
3440
+ } catch {
3441
+ }
3442
+ let stopRes;
3443
+ if (videoRecorder) {
3444
+ try {
3445
+ stopRes = await videoRecorder.stop({
3446
+ keep,
3447
+ outputDir,
3448
+ fileStem,
3449
+ steps: buildPlaybackStepMarkers(steps),
3450
+ viewport
3451
+ });
3452
+ } catch {
3453
+ }
3454
+ }
3455
+ if (!keep) return;
3456
+ if (stopRes?.videoPath) {
3457
+ attachments.push({
3458
+ name: "video",
3459
+ contentType: stopRes.videoPath.endsWith(".webm") ? "video/webm" : "video/mp4",
3460
+ path: stopRes.videoPath
3461
+ });
3462
+ }
3463
+ if (stopRes?.playbackJsonPath) {
3464
+ attachments.push({
3465
+ name: "playback",
3466
+ contentType: "application/json",
3467
+ path: stopRes.playbackJsonPath
3468
+ });
3469
+ return;
3470
+ }
3471
+ const fallbackTrace = buildPlaybackTraceFromSteps({
3472
+ flowName: flow.name,
3473
+ platform,
3474
+ durationMs,
3475
+ steps,
3476
+ viewport,
3477
+ videoPath: stopRes?.videoPath
3478
+ });
3479
+ if (fallbackTrace) {
3480
+ const playbackPath = join5(outputDir, `${fileStem}-playback.json`);
3481
+ writeFileSync4(playbackPath, JSON.stringify(fallbackTrace), "utf8");
3482
+ attachments.push({
3483
+ name: "playback",
3484
+ contentType: "application/json",
3485
+ path: playbackPath
3486
+ });
3487
+ }
3488
+ };
2705
3489
  const buildFailureResult = async (error) => {
2706
3490
  const attachments = await captureArtifacts(
2707
3491
  driver,
@@ -2710,25 +3494,52 @@ async function executeFlow(flow, driver, config) {
2710
3494
  platform,
2711
3495
  "failed"
2712
3496
  );
3497
+ const steps = stepRecorder.getSteps();
3498
+ const durationMs = Date.now() - start2;
3499
+ await finalizeRecording("failed", attachments, steps, durationMs);
2713
3500
  const normalized = error instanceof Error ? error : new Error(String(error));
2714
3501
  return {
2715
3502
  name: flow.name,
2716
3503
  platform,
2717
3504
  status: "failed",
2718
- durationMs: Date.now() - start2,
2719
- error: classifyError(normalized),
3505
+ durationMs,
3506
+ error: classifyError(normalized, {
3507
+ flowFilePath: flow.sourcePath,
3508
+ fallbackStack: stepRecorder.getLastFailureStack?.()
3509
+ }),
2720
3510
  attachments,
2721
- steps: stepRecorder.getSteps(),
3511
+ steps,
2722
3512
  scenarioSteps: flowCtx.__scenarioSteps
2723
3513
  };
2724
3514
  };
2725
3515
  if (driver.beginFlow) {
2726
3516
  try {
2727
- await Effect7.runPromise(driver.beginFlow(flow.name));
3517
+ await Effect6.runPromise(driver.beginFlow(flow.name));
2728
3518
  } catch (error) {
2729
3519
  return buildFailureResult(error);
2730
3520
  }
2731
3521
  }
3522
+ if (wantRecording) {
3523
+ try {
3524
+ if (isCdpScreencastCapable(driver.domChannel)) {
3525
+ videoRecorder = await startCdpScreencastRecorder(driver.domChannel, {
3526
+ flowName: flow.name,
3527
+ platform,
3528
+ exportMp4: artifactConfig.video !== "off"
3529
+ });
3530
+ } else if (artifactConfig.video !== "off" && (platform === "android" || platform === "ios")) {
3531
+ const info = await Effect6.runPromise(Effect6.orDie(driver.getDeviceInfo())).catch(
3532
+ () => void 0
3533
+ );
3534
+ if (info?.deviceId) {
3535
+ const outDir = flowArtifactDir(artifactConfig, flow.name, platform);
3536
+ const videoOut = join5(outDir, `${safeArtifactName(flow.name)}.mp4`);
3537
+ videoRecorder = platform === "android" ? startAndroidVideoRecorder(info.deviceId, { outputPath: videoOut }) : startIosSimulatorVideoRecorder(info.deviceId, { outputPath: videoOut });
3538
+ }
3539
+ }
3540
+ } catch {
3541
+ }
3542
+ }
2732
3543
  if (config.hooks?.beforeEach) {
2733
3544
  try {
2734
3545
  await config.hooks.beforeEach({ app, platform });
@@ -2757,13 +3568,16 @@ async function executeFlow(flow, driver, config) {
2757
3568
  platform,
2758
3569
  "passed"
2759
3570
  );
3571
+ const steps = stepRecorder.getSteps();
3572
+ const durationMs = Date.now() - start2;
3573
+ await finalizeRecording("passed", attachments, steps, durationMs);
2760
3574
  result = {
2761
3575
  name: flow.name,
2762
3576
  platform,
2763
3577
  status: "passed",
2764
- durationMs: Date.now() - start2,
3578
+ durationMs,
2765
3579
  attachments,
2766
- steps: stepRecorder.getSteps(),
3580
+ steps,
2767
3581
  scenarioSteps: flowCtx.__scenarioSteps
2768
3582
  };
2769
3583
  } catch (error) {
@@ -2774,20 +3588,26 @@ async function executeFlow(flow, driver, config) {
2774
3588
  platform,
2775
3589
  "failed"
2776
3590
  );
3591
+ const steps = stepRecorder.getSteps();
3592
+ const durationMs = Date.now() - start2;
3593
+ await finalizeRecording("failed", attachments, steps, durationMs);
2777
3594
  const flowError = error instanceof Error ? error : new Error(String(error));
2778
3595
  result = {
2779
3596
  name: flow.name,
2780
3597
  platform,
2781
3598
  status: "failed",
2782
- durationMs: Date.now() - start2,
2783
- error: classifyError(flowError),
3599
+ durationMs,
3600
+ error: classifyError(flowError, {
3601
+ flowFilePath: flow.sourcePath,
3602
+ fallbackStack: stepRecorder.getLastFailureStack?.()
3603
+ }),
2784
3604
  attachments,
2785
- steps: stepRecorder.getSteps(),
3605
+ steps,
2786
3606
  scenarioSteps: flowCtx.__scenarioSteps
2787
3607
  };
2788
3608
  if (artifactConfig.captureOnFailure && result.error) {
2789
3609
  try {
2790
- const artDir = join4(
3610
+ const artDir = join5(
2791
3611
  artifactConfig.outputDir,
2792
3612
  `${flow.name.replaceAll(/[^a-zA-Z0-9-_]/g, "_").replaceAll(/_+/g, "_").slice(0, 80) || "artifact"}-${platform}`
2793
3613
  );
@@ -2797,7 +3617,8 @@ async function executeFlow(flow, driver, config) {
2797
3617
  stepRecorder.getSteps(),
2798
3618
  result.error,
2799
3619
  artDir,
2800
- attachments
3620
+ attachments,
3621
+ flow.sourcePath
2801
3622
  );
2802
3623
  writeFailureBundle(bundle, artDir);
2803
3624
  } catch {
@@ -2815,6 +3636,12 @@ async function executeFlow(flow, driver, config) {
2815
3636
  });
2816
3637
  }
2817
3638
  }
3639
+ for (const cleanup of extraCleanups.toReversed()) {
3640
+ try {
3641
+ await cleanup();
3642
+ } catch {
3643
+ }
3644
+ }
2818
3645
  try {
2819
3646
  await sessionManager.disconnectAll();
2820
3647
  } catch {
@@ -2847,7 +3674,8 @@ async function runParallel(config) {
2847
3674
  retries = 0,
2848
3675
  retryDelay = 0,
2849
3676
  bail,
2850
- durationHintsMs
3677
+ durationHintsMs,
3678
+ claimNextFlow
2851
3679
  } = config;
2852
3680
  const flows = orderFlowsLongestFirst(rawFlows, durationHintsMs);
2853
3681
  const start2 = Date.now();
@@ -2859,9 +3687,16 @@ async function runParallel(config) {
2859
3687
  const stats = { flowCount: 0, totalMs: 0 };
2860
3688
  while (true) {
2861
3689
  if (bail !== void 0 && failureCount >= bail) break;
2862
- const flowIdx = nextFlowIndex++;
2863
- if (flowIdx >= flows.length) break;
2864
- const flow = flows[flowIdx];
3690
+ let flow;
3691
+ if (claimNextFlow) {
3692
+ const claimed = await claimNextFlow();
3693
+ if (!claimed) break;
3694
+ flow = claimed;
3695
+ } else {
3696
+ const flowIdx = nextFlowIndex++;
3697
+ if (flowIdx >= flows.length) break;
3698
+ flow = flows[flowIdx];
3699
+ }
2865
3700
  let result;
2866
3701
  let attempts = 0;
2867
3702
  onFlowStart?.(flow.name, worker.name);
@@ -2888,7 +3723,7 @@ async function runParallel(config) {
2888
3723
  return { workerId: worker.id, stats };
2889
3724
  });
2890
3725
  const workerResults = await Promise.all(workerPromises);
2891
- if (bail !== void 0 && failureCount >= bail) {
3726
+ if (!claimNextFlow && bail !== void 0 && failureCount >= bail) {
2892
3727
  bailedOut = true;
2893
3728
  while (nextFlowIndex < flows.length) {
2894
3729
  const flow = flows[nextFlowIndex++];
@@ -2917,9 +3752,195 @@ async function runParallel(config) {
2917
3752
  };
2918
3753
  }
2919
3754
 
3755
+ // src/core/worker-pool.ts
3756
+ import { spawn as spawn3 } from "child_process";
3757
+ import { readFile as readFile2, unlink } from "fs/promises";
3758
+ import { createServer } from "http";
3759
+ var DEFAULT_MAX_WORKERS_PER_PROCESS = 8;
3760
+ async function startSharedFlowQueueServer(orderedFlowNames) {
3761
+ const queue = [...orderedFlowNames];
3762
+ let cursor = 0;
3763
+ const server = createServer((req, res) => {
3764
+ if (req.url === "/claim" && (req.method === "POST" || req.method === "GET")) {
3765
+ const flowName = cursor < queue.length ? queue[cursor++] : null;
3766
+ const body = JSON.stringify({ flowName });
3767
+ res.writeHead(200, { "content-type": "application/json" });
3768
+ res.end(body);
3769
+ return;
3770
+ }
3771
+ res.writeHead(404);
3772
+ res.end();
3773
+ });
3774
+ await new Promise((resolve, reject) => {
3775
+ server.once("error", reject);
3776
+ server.listen(0, "127.0.0.1", () => resolve());
3777
+ });
3778
+ const addr = server.address();
3779
+ const url = `http://127.0.0.1:${addr.port}`;
3780
+ return {
3781
+ url,
3782
+ remaining: () => Math.max(0, queue.length - cursor),
3783
+ close: () => new Promise((resolve) => {
3784
+ server.close(() => resolve());
3785
+ })
3786
+ };
3787
+ }
3788
+ function createRemoteFlowClaimer(queueUrl) {
3789
+ const endpoint = `${queueUrl.replace(/\/+$/, "")}/claim`;
3790
+ return async () => {
3791
+ const res = await fetch(endpoint, { method: "POST" });
3792
+ if (!res.ok) return null;
3793
+ const data = await res.json();
3794
+ return typeof data.flowName === "string" ? data.flowName : null;
3795
+ };
3796
+ }
3797
+ function planProcessPool(totalWorkers, maxWorkersPerProcess = DEFAULT_MAX_WORKERS_PER_PROCESS, explicitProcesses) {
3798
+ const safeTotal = Math.max(1, Math.floor(totalWorkers));
3799
+ const safeMax = Math.max(1, Math.floor(maxWorkersPerProcess));
3800
+ const processCount = explicitProcesses !== void 0 && explicitProcesses >= 1 ? Math.min(Math.floor(explicitProcesses), safeTotal) : safeTotal <= safeMax ? 1 : Math.ceil(safeTotal / safeMax);
3801
+ if (processCount <= 1) {
3802
+ return {
3803
+ totalWorkers: safeTotal,
3804
+ maxWorkersPerProcess: safeMax,
3805
+ processCount: 1,
3806
+ workersPerProcess: [safeTotal]
3807
+ };
3808
+ }
3809
+ const base = Math.floor(safeTotal / processCount);
3810
+ const remainder = safeTotal % processCount;
3811
+ const workersPerProcess = Array.from(
3812
+ { length: processCount },
3813
+ (_v, i) => base + (i < remainder ? 1 : 0)
3814
+ );
3815
+ return {
3816
+ totalWorkers: safeTotal,
3817
+ maxWorkersPerProcess: safeMax,
3818
+ processCount,
3819
+ workersPerProcess
3820
+ };
3821
+ }
3822
+ function partitionFlowsAcrossProcesses(items, processCount, options) {
3823
+ const count = Math.max(1, Math.min(Math.floor(processCount), Math.max(1, items.length)));
3824
+ if (count === 1 || items.length === 0) {
3825
+ return items.length === 0 ? [] : [items];
3826
+ }
3827
+ const hints = options?.durationHintsMs;
3828
+ const getName = options?.getName;
3829
+ const known = hints ? Object.values(hints).filter((v) => typeof v === "number" && v > 0) : [];
3830
+ const defaultWeight = known.length > 0 ? known.reduce((a, b) => a + b, 0) / known.length : 1e3;
3831
+ const indexed = items.map((item, idx) => ({
3832
+ item,
3833
+ idx,
3834
+ weight: hints && getName ? hints[getName(item)] ?? defaultWeight : 1e3
3835
+ }));
3836
+ const ordered = hints && getName && Object.keys(hints).length > 0 ? indexed.toSorted((a, b) => b.weight - a.weight || a.idx - b.idx) : indexed;
3837
+ const loads = Array.from({ length: count }, () => 0);
3838
+ const buckets = Array.from({ length: count }, () => []);
3839
+ for (const entry of ordered) {
3840
+ let best = 0;
3841
+ for (let i = 1; i < count; i++) {
3842
+ if (loads[i] < loads[best]) best = i;
3843
+ }
3844
+ loads[best] = loads[best] + entry.weight;
3845
+ buckets[best].push({ item: entry.item, idx: entry.idx });
3846
+ }
3847
+ return buckets.map((bucket) => bucket.toSorted((a, b) => a.idx - b.idx).map((e) => e.item)).filter((b) => b.length > 0);
3848
+ }
3849
+ async function defaultReadJsonReport(reportJsonPath) {
3850
+ let content;
3851
+ try {
3852
+ content = await readFile2(reportJsonPath, "utf8");
3853
+ } catch {
3854
+ return [];
3855
+ }
3856
+ const raw = JSON.parse(content);
3857
+ return Array.isArray(raw.results) ? raw.results : [];
3858
+ }
3859
+ async function runMultiProcessPool(options) {
3860
+ const plan = planProcessPool(
3861
+ options.totalWorkers,
3862
+ options.maxWorkersPerProcess,
3863
+ options.processes
3864
+ );
3865
+ const spawnFn = options.spawnFn ?? spawn3;
3866
+ const readReport = options.readReportFn ?? defaultReadJsonReport;
3867
+ const shouldCleanup = options.cleanupReportFiles !== false;
3868
+ const startedAt = Date.now();
3869
+ const processResults = await Promise.all(
3870
+ plan.workersPerProcess.map(async (workerCount, shardIdx) => {
3871
+ const shardStart = Date.now();
3872
+ const spec = options.buildShardCommand(shardIdx + 1, plan.processCount, workerCount);
3873
+ let exitCode = null;
3874
+ let spawnError;
3875
+ try {
3876
+ exitCode = await new Promise((resolve, reject) => {
3877
+ const child = spawnFn(spec.command, spec.args, {
3878
+ env: { ...process.env, ...spec.env },
3879
+ stdio: "inherit"
3880
+ });
3881
+ child.on("error", reject);
3882
+ child.on("close", (code) => resolve(code));
3883
+ });
3884
+ } catch (err) {
3885
+ spawnError = err instanceof Error ? err.message : String(err);
3886
+ }
3887
+ let shardResults = [];
3888
+ try {
3889
+ shardResults = await readReport(spec.reportJsonPath);
3890
+ } catch (err) {
3891
+ if (!spawnError) {
3892
+ spawnError = `Failed to parse shard ${shardIdx + 1} report: ${err instanceof Error ? err.message : String(err)}`;
3893
+ }
3894
+ }
3895
+ if (shouldCleanup) {
3896
+ try {
3897
+ await unlink(spec.reportJsonPath);
3898
+ } catch {
3899
+ }
3900
+ }
3901
+ if (exitCode !== 0 && shardResults.length === 0) {
3902
+ shardResults.push({
3903
+ name: `worker-process-${shardIdx + 1}`,
3904
+ platform: "web",
3905
+ status: "failed",
3906
+ durationMs: Date.now() - shardStart,
3907
+ error: {
3908
+ category: "driver-error",
3909
+ message: spawnError ?? `Worker process ${shardIdx + 1} exited with code ${exitCode ?? "unknown"}`
3910
+ }
3911
+ });
3912
+ }
3913
+ return {
3914
+ shardIndex: shardIdx + 1,
3915
+ workerCount,
3916
+ exitCode,
3917
+ durationMs: Date.now() - shardStart,
3918
+ results: shardResults,
3919
+ ...spawnError ? { error: spawnError } : {}
3920
+ };
3921
+ })
3922
+ );
3923
+ const results = processResults.flatMap((p) => p.results);
3924
+ const passed = results.filter((r) => r.status === "passed").length;
3925
+ const failed = results.filter((r) => r.status === "failed").length;
3926
+ const skipped = results.filter((r) => r.status === "skipped").length;
3927
+ const flaky = results.filter((r) => r.flaky).length;
3928
+ return {
3929
+ results,
3930
+ totalDurationMs: Date.now() - startedAt,
3931
+ passed,
3932
+ failed,
3933
+ skipped,
3934
+ flaky,
3935
+ processCount: plan.processCount,
3936
+ processResults
3937
+ };
3938
+ }
3939
+
2920
3940
  export {
2921
3941
  launchDirectCdpBrowser,
2922
3942
  makeLightweightCdpDriver,
3943
+ resolveWebEngine,
2923
3944
  speculativelyPrelaunchWebBrowser,
2924
3945
  buildWebRuntime,
2925
3946
  buildWebRuntimePool,
@@ -2927,9 +3948,22 @@ export {
2927
3948
  buildElectrobunRuntime,
2928
3949
  buildLocalAndroidRuntime,
2929
3950
  buildLocalIOSRuntime,
3951
+ formatCodeFrame,
3952
+ extractCodeFrame,
2930
3953
  classifyError,
3954
+ exportFramesToMp4,
3955
+ startCdpScreencastRecorder,
3956
+ startAndroidVideoRecorder,
3957
+ startIosSimulatorVideoRecorder,
3958
+ buildPlaybackTraceFromSteps,
2931
3959
  executeFlow,
2932
3960
  orderFlowsLongestFirst,
2933
- runParallel
3961
+ runParallel,
3962
+ DEFAULT_MAX_WORKERS_PER_PROCESS,
3963
+ startSharedFlowQueueServer,
3964
+ createRemoteFlowClaimer,
3965
+ planProcessPool,
3966
+ partitionFlowsAcrossProcesses,
3967
+ runMultiProcessPool
2934
3968
  };
2935
- //# sourceMappingURL=chunk-KEUZLBQS.js.map
3969
+ //# sourceMappingURL=chunk-3FXDOTFI.js.map