spana-test 0.7.0 → 0.9.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 (96) hide show
  1. package/dist/agent/index.d.ts +2 -2
  2. package/dist/agent/index.js +9 -9
  3. package/dist/{allure-RNMEYTXS.js → allure-RAEK4SIH.js} +2 -2
  4. package/dist/allure-RAEK4SIH.js.map +1 -0
  5. package/dist/{android-4NVTZMHL.js → android-6BOQTMM3.js} +2 -2
  6. package/dist/app-DSh1ejLh.d.ts +1266 -0
  7. package/dist/{chunk-H27IBIGA.js → chunk-2AFWVHQK.js} +63 -43
  8. package/dist/chunk-2AFWVHQK.js.map +1 -0
  9. package/dist/{chunk-RURZVMZ7.js → chunk-2KRVN4WN.js} +3 -3
  10. package/dist/{chunk-T5CROOR7.js → chunk-3UVSUVHW.js} +1828 -299
  11. package/dist/chunk-3UVSUVHW.js.map +1 -0
  12. package/dist/{chunk-6B5Y75V4.js → chunk-ALPQES3J.js} +1001 -281
  13. package/dist/chunk-ALPQES3J.js.map +1 -0
  14. package/dist/{chunk-2IXXEXTL.js → chunk-FP6PVHHR.js} +2 -2
  15. package/dist/{chunk-KNSAHEXI.js → chunk-IGTK5MHB.js} +8 -8
  16. package/dist/chunk-JPZCZHL4.js +79 -0
  17. package/dist/chunk-JPZCZHL4.js.map +1 -0
  18. package/dist/{chunk-JYFPZRCN.js → chunk-JZZ2W2XH.js} +5 -2
  19. package/dist/chunk-JZZ2W2XH.js.map +1 -0
  20. package/dist/{chunk-HCG4CJKR.js → chunk-SF7UYW4I.js} +3 -3
  21. package/dist/{chunk-T3EBOYLS.js → chunk-UEWZ2EXL.js} +1314 -129
  22. package/dist/chunk-UEWZ2EXL.js.map +1 -0
  23. package/dist/{chunk-HYSTRWYN.js → chunk-VP6V4XEJ.js} +4 -4
  24. package/dist/{chunk-S5JNNDXS.js → chunk-WV3ALL3H.js} +65 -37
  25. package/dist/chunk-WV3ALL3H.js.map +1 -0
  26. package/dist/chunk-Z6K4QQAR.js +358 -0
  27. package/dist/chunk-Z6K4QQAR.js.map +1 -0
  28. package/dist/cli.js +23 -11
  29. package/dist/cli.js.map +1 -1
  30. package/dist/config-loader-F5YAY7RP.js +9 -0
  31. package/dist/{console-MI2XB5RG.js → console-BGAK7Z2L.js} +11 -1
  32. package/dist/{console-MI2XB5RG.js.map → console-BGAK7Z2L.js.map} +1 -1
  33. package/dist/{daemon-manager-FBISTX24.js → daemon-manager-2EQDVUVM.js} +10 -2
  34. package/dist/{discover-LHEBSUIP.js → discover-RLSKEBAX.js} +5 -5
  35. package/dist/{doctor-command-WPEVZEZ4.js → doctor-command-YTCQ2SC7.js} +26 -18
  36. package/dist/doctor-command-YTCQ2SC7.js.map +1 -0
  37. package/dist/{flow-g6AICPAl.d.ts → flow-CSMwD9Fh.d.ts} +3 -29
  38. package/dist/gherkin/steps.d.ts +2 -2
  39. package/dist/{html-IKCTZH2U.js → html-JO2YNRWX.js} +3 -3
  40. package/dist/html-JO2YNRWX.js.map +1 -0
  41. package/dist/index.d.ts +215 -21
  42. package/dist/index.js +246 -147
  43. package/dist/index.js.map +1 -1
  44. package/dist/{installer-VUPFWP5X.js → installer-5UHTYQTB.js} +4 -4
  45. package/dist/{ios-JPK43TFZ.js → ios-Y4TO5MBR.js} +7 -3
  46. package/dist/{server-EBPYK3VE.js → server-4YLBAZEM.js} +50 -36
  47. package/dist/server-4YLBAZEM.js.map +1 -0
  48. package/dist/{server-IGLBFEU7.js → server-IS4K5FCT.js} +2 -2
  49. package/dist/{session-cJ_tZjCL.d.ts → session-CgvT-Oso.d.ts} +3 -1
  50. package/dist/session-K7FCRKOC.js +18 -0
  51. package/dist/{studio-command-FLA5HKRK.js → studio-command-RFPV2DS7.js} +2 -2
  52. package/dist/{test-command-P5W7UD52.js → test-command-UEJG5AI6.js} +223 -27
  53. package/dist/test-command-UEJG5AI6.js.map +1 -0
  54. package/native/darwin-arm64/libspana_native.dylib +0 -0
  55. package/native/darwin-x64/libspana_native.dylib +0 -0
  56. package/native/linux-arm64/libspana_native.so +0 -0
  57. package/native/linux-x64/libspana_native.so +0 -0
  58. package/native/win32-x64/spana_native.dll +0 -0
  59. package/package.json +1 -1
  60. package/studio-dist/assets/index-CBFsOh-9.js +193 -0
  61. package/studio-dist/assets/index-DH_18EyL.css +1 -0
  62. package/studio-dist/index.html +2 -2
  63. package/dist/allure-RNMEYTXS.js.map +0 -1
  64. package/dist/app-D_UyZBsl.d.ts +0 -915
  65. package/dist/chunk-6B5Y75V4.js.map +0 -1
  66. package/dist/chunk-DTNK54C2.js +0 -127
  67. package/dist/chunk-DTNK54C2.js.map +0 -1
  68. package/dist/chunk-H27IBIGA.js.map +0 -1
  69. package/dist/chunk-JYFPZRCN.js.map +0 -1
  70. package/dist/chunk-OBCFACUW.js +0 -28
  71. package/dist/chunk-OBCFACUW.js.map +0 -1
  72. package/dist/chunk-S5JNNDXS.js.map +0 -1
  73. package/dist/chunk-T3EBOYLS.js.map +0 -1
  74. package/dist/chunk-T5CROOR7.js.map +0 -1
  75. package/dist/config-loader-NIDQGP3K.js +0 -9
  76. package/dist/doctor-command-WPEVZEZ4.js.map +0 -1
  77. package/dist/html-IKCTZH2U.js.map +0 -1
  78. package/dist/server-EBPYK3VE.js.map +0 -1
  79. package/dist/session-QRWH3SPW.js +0 -18
  80. package/dist/test-command-P5W7UD52.js.map +0 -1
  81. package/studio-dist/assets/index-C-Io44gy.js +0 -193
  82. package/studio-dist/assets/index-DfM9lK4p.css +0 -1
  83. /package/dist/{android-4NVTZMHL.js.map → android-6BOQTMM3.js.map} +0 -0
  84. /package/dist/{chunk-RURZVMZ7.js.map → chunk-2KRVN4WN.js.map} +0 -0
  85. /package/dist/{chunk-2IXXEXTL.js.map → chunk-FP6PVHHR.js.map} +0 -0
  86. /package/dist/{chunk-KNSAHEXI.js.map → chunk-IGTK5MHB.js.map} +0 -0
  87. /package/dist/{chunk-HCG4CJKR.js.map → chunk-SF7UYW4I.js.map} +0 -0
  88. /package/dist/{chunk-HYSTRWYN.js.map → chunk-VP6V4XEJ.js.map} +0 -0
  89. /package/dist/{config-loader-NIDQGP3K.js.map → config-loader-F5YAY7RP.js.map} +0 -0
  90. /package/dist/{daemon-manager-FBISTX24.js.map → daemon-manager-2EQDVUVM.js.map} +0 -0
  91. /package/dist/{discover-LHEBSUIP.js.map → discover-RLSKEBAX.js.map} +0 -0
  92. /package/dist/{installer-VUPFWP5X.js.map → installer-5UHTYQTB.js.map} +0 -0
  93. /package/dist/{ios-JPK43TFZ.js.map → ios-Y4TO5MBR.js.map} +0 -0
  94. /package/dist/{server-IGLBFEU7.js.map → server-IS4K5FCT.js.map} +0 -0
  95. /package/dist/{session-QRWH3SPW.js.map → session-K7FCRKOC.js.map} +0 -0
  96. /package/dist/{studio-command-FLA5HKRK.js.map → studio-command-RFPV2DS7.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-T5CROOR7.js";
19
+ } from "./chunk-3UVSUVHW.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-T3EBOYLS.js";
27
+ } from "./chunk-UEWZ2EXL.js";
26
28
  import {
27
29
  setupWDA
28
- } from "./chunk-HYSTRWYN.js";
30
+ } from "./chunk-VP6V4XEJ.js";
29
31
  import {
30
32
  getHealthyWarmDaemon,
31
33
  registerWarmDaemon,
32
34
  updateWarmDaemonSession
33
- } from "./chunk-DTNK54C2.js";
35
+ } from "./chunk-Z6K4QQAR.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,77 @@ 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
+ }
386
+ var UPLOAD_ATTACH_TIMEOUT_MS = 3e4;
408
387
  var RESOURCE_BLOCK_PATTERNS = {
409
388
  image: ["*.png", "*.jpg", "*.jpeg", "*.gif", "*.webp", "*.svg", "*.ico", "*.avif"],
410
389
  font: ["*.woff", "*.woff2", "*.ttf", "*.otf", "*.eot"],
@@ -412,7 +391,7 @@ var RESOURCE_BLOCK_PATTERNS = {
412
391
  stylesheet: ["*.css"]
413
392
  };
414
393
  function makeLightweightCdpDriver(options) {
415
- return Effect3.gen(function* () {
394
+ return Effect2.gen(function* () {
416
395
  const isBrowserWs = options.cdpUrl.includes("/devtools/browser/");
417
396
  const useContexts = Boolean(
418
397
  options.useBrowserContexts || options.freshContextPerFlow || isBrowserWs
@@ -421,7 +400,7 @@ function makeLightweightCdpDriver(options) {
421
400
  const httpEndpoint = isWs ? options.cdpUrl.replace(/^ws(s?):\/\//, "http$1://").replace(/\/devtools\/.*$/, "") : options.cdpUrl.replace(/\/+$/, "");
422
401
  let connectWsUrl = isWs ? options.cdpUrl : void 0;
423
402
  if (useContexts && !connectWsUrl) {
424
- connectWsUrl = yield* Effect3.tryPromise({
403
+ connectWsUrl = yield* Effect2.tryPromise({
425
404
  try: () => fetchBrowserWsUrl(httpEndpoint, 5e3),
426
405
  catch: (e) => new DriverError({
427
406
  message: `Failed to resolve browser CDP WebSocket at ${options.cdpUrl}: ${e}`
@@ -434,7 +413,7 @@ function makeLightweightCdpDriver(options) {
434
413
  fetchFn: options.fetchFn,
435
414
  createWebSocket: options.createWebSocket
436
415
  });
437
- yield* Effect3.tryPromise({
416
+ yield* Effect2.tryPromise({
438
417
  try: () => cdpChannel.connect(),
439
418
  catch: (e) => new DriverError({
440
419
  message: `Failed to connect lightweight CDP browser at ${options.cdpUrl}: ${e}`
@@ -452,6 +431,7 @@ function makeLightweightCdpDriver(options) {
452
431
  const jsErrors = [];
453
432
  const routeRules = [];
454
433
  let fetchInterceptEnabled = false;
434
+ let activeResponseWatchers = 0;
455
435
  let nextTabSeq = 1;
456
436
  let downloadDir;
457
437
  const completedDownloads = [];
@@ -499,6 +479,8 @@ function makeLightweightCdpDriver(options) {
499
479
  );
500
480
  return res?.authenticatorId ?? "cdp-virtual-auth-1";
501
481
  };
482
+ const useInjectedRuntime = options.useInjectedRuntime ?? !options.createWebSocket;
483
+ cdpChannel.enableInjectedRuntime(useInjectedRuntime);
502
484
  const configureSession = async (sessionId, storageStatePath) => {
503
485
  const state = await loadStorageStateFile(storageStatePath);
504
486
  const needsNetworkDomain = Boolean(
@@ -509,6 +491,14 @@ function makeLightweightCdpDriver(options) {
509
491
  }),
510
492
  cdpChannel.sendCommand("Runtime.enable", {}, sessionId).catch(() => {
511
493
  }),
494
+ ...useInjectedRuntime ? [
495
+ cdpChannel.sendCommand(
496
+ "Page.addScriptToEvaluateOnNewDocument",
497
+ { source: SPANA_INJECTED_RUNTIME_SCRIPT },
498
+ sessionId
499
+ ).catch(() => {
500
+ })
501
+ ] : [],
512
502
  cdpChannel.sendCommand(
513
503
  "Target.setAutoAttach",
514
504
  { autoAttach: true, waitForDebuggerOnStart: false, flatten: true },
@@ -619,7 +609,9 @@ function makeLightweightCdpDriver(options) {
619
609
  backgroundDisposals.push(p);
620
610
  };
621
611
  const schedulePrefetch = () => {
622
- if (!useContexts || !options.freshContextPerFlow || prefetchedSlotPromise) return;
612
+ if (!useContexts || !options.freshContextPerFlow || options.contextIsolation === "hot-cache" || prefetchedSlotPromise) {
613
+ return;
614
+ }
623
615
  prefetchedSlotPromise = createContextSlot(options.storageState);
624
616
  prefetchedSlotPromise.catch(() => {
625
617
  prefetchedSlotPromise = void 0;
@@ -628,20 +620,84 @@ function makeLightweightCdpDriver(options) {
628
620
  cdpChannel.onEvent("Target.attachedToTarget", (params) => {
629
621
  const targetInfo = params?.targetInfo;
630
622
  const childSid = params?.sessionId;
623
+ const waiting = Boolean(params?.waitingForDebugger);
631
624
  if (targetInfo?.type === "iframe" && typeof childSid === "string") {
632
625
  cdpChannel.addChildSession(childSid, {
633
626
  targetId: typeof targetInfo.targetId === "string" ? targetInfo.targetId : void 0,
634
627
  url: typeof targetInfo.url === "string" ? targetInfo.url : void 0
635
628
  });
636
- void cdpChannel.sendCommand("Runtime.enable", {}, childSid).catch(() => {
629
+ void (async () => {
630
+ await cdpChannel.sendCommand("Runtime.enable", {}, childSid).catch(() => {
631
+ });
632
+ if (useInjectedRuntime) {
633
+ await cdpChannel.sendCommand(
634
+ "Page.addScriptToEvaluateOnNewDocument",
635
+ { source: SPANA_INJECTED_RUNTIME_SCRIPT },
636
+ childSid
637
+ ).catch(() => {
638
+ });
639
+ }
640
+ if (waiting) {
641
+ await cdpChannel.sendCommand("Runtime.runIfWaitingForDebugger", {}, childSid).catch(() => {
642
+ });
643
+ }
644
+ })();
645
+ } else if (targetInfo?.type === "page" && typeof childSid === "string" && activeSlot && targetInfo.browserContextId === activeSlot.browserContextId) {
646
+ const alreadyTracked = activeSlot.tabs.some(
647
+ (t) => t.sessionId === childSid || t.targetId === targetInfo.targetId
648
+ );
649
+ if (!alreadyTracked) {
650
+ activeSlot.tabs.push({
651
+ tabId: `tab-${nextTabSeq++}`,
652
+ targetId: String(targetInfo.targetId ?? ""),
653
+ sessionId: childSid
654
+ });
655
+ }
656
+ void (async () => {
657
+ const setupCalls = [
658
+ cdpChannel.sendCommand("Page.enable", {}, childSid).catch(() => {
659
+ }),
660
+ cdpChannel.sendCommand("Runtime.enable", {}, childSid).catch(() => {
661
+ })
662
+ ];
663
+ if (activeResponseWatchers > 0) {
664
+ setupCalls.push(cdpChannel.sendCommand("Network.enable", {}, childSid).catch(() => {
665
+ }));
666
+ }
667
+ if (useInjectedRuntime) {
668
+ setupCalls.push(
669
+ cdpChannel.sendCommand(
670
+ "Page.addScriptToEvaluateOnNewDocument",
671
+ { source: SPANA_INJECTED_RUNTIME_SCRIPT },
672
+ childSid
673
+ ).catch(() => {
674
+ })
675
+ );
676
+ }
677
+ await Promise.all(setupCalls);
678
+ if (waiting) {
679
+ await cdpChannel.sendCommand("Runtime.runIfWaitingForDebugger", {}, childSid).catch(() => {
680
+ });
681
+ }
682
+ })();
683
+ } else if (waiting && typeof childSid === "string") {
684
+ void cdpChannel.sendCommand("Runtime.runIfWaitingForDebugger", {}, childSid).catch(() => {
637
685
  });
638
686
  }
639
687
  });
640
688
  cdpChannel.onEvent("Target.detachedFromTarget", (params) => {
641
689
  if (typeof params?.sessionId === "string") {
642
690
  cdpChannel.removeChildSession(params.sessionId);
691
+ if (activeSlot) {
692
+ activeSlot.tabs = activeSlot.tabs.filter((t) => t.sessionId !== params.sessionId);
693
+ }
643
694
  }
644
695
  });
696
+ cdpChannel.onEvent("Page.javascriptDialogOpening", (params, sid) => {
697
+ const accept = params?.type === "beforeunload";
698
+ void cdpChannel.sendCommand("Page.handleJavaScriptDialog", { accept }, sid ?? null).catch(() => {
699
+ });
700
+ });
645
701
  cdpChannel.setFrameOffsetResolver(async (child) => {
646
702
  if (!child.targetId) return { x: 0, y: 0 };
647
703
  try {
@@ -713,7 +769,21 @@ function makeLightweightCdpDriver(options) {
713
769
  });
714
770
  });
715
771
  if (useContexts) {
716
- activeSlot = yield* Effect3.tryPromise({
772
+ yield* Effect2.tryPromise({
773
+ try: () => cdpChannel.sendCommand(
774
+ "Target.setAutoAttach",
775
+ {
776
+ autoAttach: true,
777
+ waitForDebuggerOnStart: true,
778
+ flatten: true,
779
+ filter: [{ type: "page" }]
780
+ },
781
+ null
782
+ ).catch(() => {
783
+ }),
784
+ catch: () => new DriverError({ message: "Failed to enable Target.setAutoAttach" })
785
+ }).pipe(Effect2.catchAll(() => Effect2.void));
786
+ activeSlot = yield* Effect2.tryPromise({
717
787
  try: () => createContextSlot(options.storageState),
718
788
  catch: (e) => new DriverError({ message: `Failed to create direct CDP browser context: ${e}` })
719
789
  });
@@ -729,7 +799,7 @@ function makeLightweightCdpDriver(options) {
729
799
  await cdpChannel.sendCommand("Page.navigate", { url: target });
730
800
  return;
731
801
  }
732
- const waitUntil = options.waitUntil ?? "load";
802
+ const waitUntil = options.waitUntil ?? "domcontentloaded";
733
803
  const targetSid = activeSlot?.sessionId;
734
804
  if (waitUntil === "commit" || target === "about:blank") {
735
805
  await cdpChannel.sendCommand("Page.navigate", { url: target });
@@ -753,34 +823,62 @@ function makeLightweightCdpDriver(options) {
753
823
  };
754
824
  const service = {
755
825
  domChannel: cdpChannel,
756
- beginFlow: (_flowName) => Effect3.tryPromise({
826
+ beginFlow: (_flowName) => Effect2.tryPromise({
757
827
  try: async () => {
758
828
  consoleLogs.length = 0;
759
829
  jsErrors.length = 0;
760
830
  cdpChannel.clearChildSessions();
761
831
  if (useContexts && options.freshContextPerFlow && hasRunFirstFlow) {
762
- const previousSlot = activeSlot;
763
- const pending = prefetchedSlotPromise;
764
- prefetchedSlotPromise = void 0;
765
- activeSlot = pending ? await pending : await createContextSlot(options.storageState);
766
- cdpChannel.setSessionId(activeSlot.sessionId);
767
- activeAuthenticatorId = activeSlot.authenticatorId;
768
- if (previousSlot) {
769
- disposeSlotInBackground(previousSlot);
832
+ if (options.contextIsolation === "hot-cache" && activeSlot) {
833
+ const origin = options.baseUrl ? (() => {
834
+ try {
835
+ return new URL(options.baseUrl).origin;
836
+ } catch {
837
+ return "*";
838
+ }
839
+ })() : "*";
840
+ await Promise.all([
841
+ cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
842
+ }),
843
+ cdpChannel.sendCommand("Storage.clearDataForOrigin", {
844
+ origin,
845
+ storageTypes: "cookies,local_storage,session_storage,indexeddb,cache_storage,service_workers"
846
+ }).catch(() => {
847
+ }),
848
+ cdpChannel.evaluate("try { localStorage.clear(); sessionStorage.clear(); } catch {}").catch(() => {
849
+ }),
850
+ cdpChannel.sendCommand("Page.navigate", { url: "about:blank" }).catch(() => {
851
+ })
852
+ ]);
853
+ const state = await loadStorageStateFile(options.storageState);
854
+ if (state?.cookies && state.cookies.length > 0) {
855
+ await cdpChannel.sendCommand("Network.setCookies", { cookies: state.cookies }).catch(() => {
856
+ });
857
+ }
858
+ } else {
859
+ const previousSlot = activeSlot;
860
+ const pending = prefetchedSlotPromise;
861
+ prefetchedSlotPromise = void 0;
862
+ activeSlot = pending ? await pending : await createContextSlot(options.storageState);
863
+ cdpChannel.setSessionId(activeSlot.sessionId);
864
+ activeAuthenticatorId = activeSlot.authenticatorId;
865
+ if (previousSlot) {
866
+ disposeSlotInBackground(previousSlot);
867
+ }
770
868
  }
771
869
  }
772
870
  hasRunFirstFlow = true;
773
871
  },
774
872
  catch: (e) => new DriverError({ message: `CDP beginFlow failed: ${e}` })
775
873
  }),
776
- dumpHierarchy: () => Effect3.tryPromise({
874
+ dumpHierarchy: () => Effect2.tryPromise({
777
875
  try: async () => {
778
876
  const raw = await cdpChannel.evaluate(CDP_DUMP_HIERARCHY_SCRIPT);
779
877
  return raw ?? "{}";
780
878
  },
781
879
  catch: (e) => new DriverError({ message: `CDP dumpHierarchy failed: ${e}` })
782
880
  }),
783
- tapAtCoordinate: (x, y) => Effect3.tryPromise({
881
+ tapAtCoordinate: (x, y) => Effect2.tryPromise({
784
882
  try: async () => {
785
883
  await Promise.all([
786
884
  cdpChannel.sendCommand("Input.dispatchMouseEvent", {
@@ -806,7 +904,7 @@ function makeLightweightCdpDriver(options) {
806
904
  },
807
905
  catch: (e) => new DriverError({ message: `CDP tap failed at (${x}, ${y}): ${e}` })
808
906
  }),
809
- doubleTapAtCoordinate: (x, y) => Effect3.tryPromise({
907
+ doubleTapAtCoordinate: (x, y) => Effect2.tryPromise({
810
908
  try: async () => {
811
909
  await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
812
910
  type: "mousePressed",
@@ -825,7 +923,7 @@ function makeLightweightCdpDriver(options) {
825
923
  },
826
924
  catch: (e) => new DriverError({ message: `CDP doubleTap failed: ${e}` })
827
925
  }),
828
- longPressAtCoordinate: (x, y, duration) => Effect3.tryPromise({
926
+ longPressAtCoordinate: (x, y, duration) => Effect2.tryPromise({
829
927
  try: async () => {
830
928
  await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
831
929
  type: "mousePressed",
@@ -845,7 +943,7 @@ function makeLightweightCdpDriver(options) {
845
943
  },
846
944
  catch: (e) => new DriverError({ message: `CDP longPress failed: ${e}` })
847
945
  }),
848
- swipe: (startX, startY, endX, endY) => Effect3.tryPromise({
946
+ swipe: (startX, startY, endX, endY) => Effect2.tryPromise({
849
947
  try: async () => {
850
948
  const dx = startX - endX;
851
949
  const dy = startY - endY;
@@ -853,21 +951,77 @@ function makeLightweightCdpDriver(options) {
853
951
  },
854
952
  catch: (e) => new DriverError({ message: `CDP swipe failed: ${e}` })
855
953
  }),
856
- inputText: (text) => Effect3.tryPromise({
954
+ inputText: (text) => Effect2.tryPromise({
857
955
  try: async () => {
858
956
  await cdpChannel.sendCommand("Input.insertText", { text });
859
957
  },
860
958
  catch: (e) => new DriverError({ message: `CDP inputText failed: ${e}` })
861
959
  }),
862
- pressKey: (key) => Effect3.tryPromise({
960
+ pressKey: (key) => Effect2.tryPromise({
863
961
  try: async () => {
864
- await cdpChannel.sendCommand("Input.dispatchKeyEvent", { type: "keyDown", key });
865
- await cdpChannel.sendCommand("Input.dispatchKeyEvent", { type: "keyUp", key });
962
+ const desc = parseCdpKeyDescriptor(key);
963
+ await cdpChannel.sendCommand("Input.dispatchKeyEvent", {
964
+ type: desc.text ? "keyDown" : "rawKeyDown",
965
+ key: desc.key,
966
+ ...desc.code ? { code: desc.code } : {},
967
+ ...desc.windowsVirtualKeyCode ? {
968
+ windowsVirtualKeyCode: desc.windowsVirtualKeyCode,
969
+ nativeVirtualKeyCode: desc.windowsVirtualKeyCode
970
+ } : {},
971
+ modifiers: desc.modifiers,
972
+ ...desc.text ? { text: desc.text, unmodifiedText: desc.text } : {},
973
+ ...desc.commands ? { commands: desc.commands } : {}
974
+ });
975
+ await cdpChannel.sendCommand("Input.dispatchKeyEvent", {
976
+ type: "keyUp",
977
+ key: desc.key,
978
+ ...desc.code ? { code: desc.code } : {},
979
+ ...desc.windowsVirtualKeyCode ? {
980
+ windowsVirtualKeyCode: desc.windowsVirtualKeyCode,
981
+ nativeVirtualKeyCode: desc.windowsVirtualKeyCode
982
+ } : {},
983
+ modifiers: desc.modifiers
984
+ });
866
985
  },
867
986
  catch: (e) => new DriverError({ message: `CDP pressKey failed: ${e}` })
868
987
  }),
869
- hideKeyboard: () => Effect3.void,
870
- takeScreenshot: () => Effect3.tryPromise({
988
+ hoverAtCoordinate: (x, y) => Effect2.tryPromise({
989
+ try: async () => {
990
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
991
+ type: "mouseMoved",
992
+ x,
993
+ y
994
+ });
995
+ },
996
+ catch: (e) => new DriverError({ message: `CDP hover failed at (${x}, ${y}): ${e}` })
997
+ }),
998
+ reload: (reloadOpts) => Effect2.tryPromise({
999
+ try: async () => {
1000
+ const waitUntil = reloadOpts?.waitUntil ?? options.waitUntil ?? "domcontentloaded";
1001
+ const targetSid = activeSlot?.sessionId;
1002
+ const eventName = waitUntil === "domcontentloaded" ? "Page.domContentEventFired" : "Page.loadEventFired";
1003
+ const waiter = cdpChannel.waitForEvent(
1004
+ eventName,
1005
+ 15e3,
1006
+ (_p, sid) => !targetSid || !sid || sid === targetSid
1007
+ );
1008
+ await cdpChannel.sendCommand("Page.reload", {});
1009
+ await waiter.catch(() => {
1010
+ });
1011
+ },
1012
+ catch: (e) => new DriverError({ message: `CDP reload failed: ${e}` })
1013
+ }),
1014
+ getUrl: () => Effect2.tryPromise({
1015
+ try: async () => {
1016
+ const url = await cdpChannel.evaluate(
1017
+ "typeof window !== 'undefined' && window.location ? String(window.location.href || '') : ''"
1018
+ );
1019
+ return url ?? "";
1020
+ },
1021
+ catch: (e) => new DriverError({ message: `CDP getUrl failed: ${e}` })
1022
+ }),
1023
+ hideKeyboard: () => Effect2.void,
1024
+ takeScreenshot: () => Effect2.tryPromise({
871
1025
  try: async () => {
872
1026
  const res = await cdpChannel.sendCommand("Page.captureScreenshot", {
873
1027
  format: "png"
@@ -876,7 +1030,7 @@ function makeLightweightCdpDriver(options) {
876
1030
  },
877
1031
  catch: (e) => new DriverError({ message: `CDP screenshot failed: ${e}` })
878
1032
  }),
879
- getDeviceInfo: () => Effect3.succeed({
1033
+ getDeviceInfo: () => Effect2.succeed({
880
1034
  platform: "web",
881
1035
  deviceId: `${label}:${options.cdpUrl}`,
882
1036
  name: `${label} (CDP-direct)`,
@@ -885,7 +1039,7 @@ function makeLightweightCdpDriver(options) {
885
1039
  screenHeight: height,
886
1040
  driverType: "cdp"
887
1041
  }),
888
- launchApp: (url, opts) => Effect3.tryPromise({
1042
+ launchApp: (url, opts) => Effect2.tryPromise({
889
1043
  try: async () => {
890
1044
  if (opts?.clearState) {
891
1045
  await cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
@@ -898,11 +1052,11 @@ function makeLightweightCdpDriver(options) {
898
1052
  },
899
1053
  catch: (e) => new DriverError({ message: `CDP launchApp failed: ${e}` })
900
1054
  }),
901
- stopApp: () => Effect3.tryPromise({
1055
+ stopApp: () => Effect2.tryPromise({
902
1056
  try: () => navigate("about:blank"),
903
1057
  catch: (e) => new DriverError({ message: `CDP stopApp failed: ${e}` })
904
1058
  }),
905
- killApp: () => Effect3.tryPromise({
1059
+ killApp: () => Effect2.tryPromise({
906
1060
  try: async () => {
907
1061
  const pendingPrefetch = prefetchedSlotPromise;
908
1062
  prefetchedSlotPromise = void 0;
@@ -935,7 +1089,7 @@ function makeLightweightCdpDriver(options) {
935
1089
  },
936
1090
  catch: (e) => new DriverError({ message: `CDP disconnect failed: ${e}` })
937
1091
  }),
938
- clearAppState: () => Effect3.tryPromise({
1092
+ clearAppState: () => Effect2.tryPromise({
939
1093
  try: async () => {
940
1094
  await cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
941
1095
  });
@@ -945,17 +1099,17 @@ function makeLightweightCdpDriver(options) {
945
1099
  },
946
1100
  catch: (e) => new DriverError({ message: `CDP clearAppState failed: ${e}` })
947
1101
  }),
948
- openLink: (url) => Effect3.tryPromise({
1102
+ openLink: (url) => Effect2.tryPromise({
949
1103
  try: () => navigate(url),
950
1104
  catch: (e) => new DriverError({ message: `CDP openLink failed: ${e}` })
951
1105
  }),
952
- back: () => Effect3.tryPromise({
1106
+ back: () => Effect2.tryPromise({
953
1107
  try: async () => {
954
1108
  await cdpChannel.evaluate("window.history.back()");
955
1109
  },
956
1110
  catch: (e) => new DriverError({ message: `CDP back failed: ${e}` })
957
1111
  }),
958
- evaluate: (fn, ...args) => Effect3.tryPromise({
1112
+ evaluate: (fn, ...args) => Effect2.tryPromise({
959
1113
  try: async () => {
960
1114
  if (typeof fn === "string") {
961
1115
  return await cdpChannel.evaluate(fn);
@@ -971,21 +1125,34 @@ function makeLightweightCdpDriver(options) {
971
1125
  sessionId: activeSlot?.sessionId ?? null,
972
1126
  browserContextId: activeSlot?.browserContextId ?? null
973
1127
  }),
974
- mockNetwork: (matcher, response) => Effect3.tryPromise({
1128
+ getCdpSession: () => ({
1129
+ send: (method, params) => cdpChannel.sendCommand(method, params ?? {}),
1130
+ on: (event, listener) => cdpChannel.onEvent(event, (params, sid) => {
1131
+ if (activeSlot && sid && sid !== activeSlot.sessionId) return;
1132
+ listener(params ?? {});
1133
+ }),
1134
+ get sessionId() {
1135
+ return activeSlot?.sessionId;
1136
+ },
1137
+ get browserContextId() {
1138
+ return activeSlot?.browserContextId;
1139
+ }
1140
+ }),
1141
+ mockNetwork: (matcher, response) => Effect2.tryPromise({
975
1142
  try: async () => {
976
1143
  routeRules.push({ kind: "mock", matcher, response });
977
1144
  await ensureFetchIntercept();
978
1145
  },
979
1146
  catch: (e) => new DriverError({ message: `CDP mockNetwork failed: ${e}` })
980
1147
  }),
981
- blockNetwork: (matcher) => Effect3.tryPromise({
1148
+ blockNetwork: (matcher) => Effect2.tryPromise({
982
1149
  try: async () => {
983
1150
  routeRules.push({ kind: "block", matcher });
984
1151
  await ensureFetchIntercept();
985
1152
  },
986
1153
  catch: (e) => new DriverError({ message: `CDP blockNetwork failed: ${e}` })
987
1154
  }),
988
- clearNetworkMocks: () => Effect3.tryPromise({
1155
+ clearNetworkMocks: () => Effect2.tryPromise({
989
1156
  try: async () => {
990
1157
  routeRules.length = 0;
991
1158
  if (fetchInterceptEnabled) {
@@ -996,14 +1163,14 @@ function makeLightweightCdpDriver(options) {
996
1163
  },
997
1164
  catch: (e) => new DriverError({ message: `CDP clearNetworkMocks failed: ${e}` })
998
1165
  }),
999
- saveCookies: (path) => Effect3.tryPromise({
1166
+ saveCookies: (path) => Effect2.tryPromise({
1000
1167
  try: async () => {
1001
1168
  const res = await cdpChannel.sendCommand("Network.getCookies");
1002
1169
  await writeFile(path, JSON.stringify(res?.cookies ?? [], null, 2), "utf8");
1003
1170
  },
1004
1171
  catch: (e) => new DriverError({ message: `CDP saveCookies failed: ${e}` })
1005
1172
  }),
1006
- loadCookies: (path) => Effect3.tryPromise({
1173
+ loadCookies: (path) => Effect2.tryPromise({
1007
1174
  try: async () => {
1008
1175
  const cookies = JSON.parse(await readFile(path, "utf8"));
1009
1176
  if (Array.isArray(cookies)) {
@@ -1012,7 +1179,149 @@ function makeLightweightCdpDriver(options) {
1012
1179
  },
1013
1180
  catch: (e) => new DriverError({ message: `CDP loadCookies failed: ${e}` })
1014
1181
  }),
1015
- saveAuthState: (path) => Effect3.tryPromise({
1182
+ getCookies: (urls) => Effect2.tryPromise({
1183
+ try: async () => {
1184
+ const res = await cdpChannel.sendCommand(
1185
+ "Network.getCookies",
1186
+ urls && urls.length > 0 ? { urls } : {}
1187
+ );
1188
+ return Array.isArray(res?.cookies) ? res.cookies : [];
1189
+ },
1190
+ catch: (e) => new DriverError({ message: `CDP getCookies failed: ${e}` })
1191
+ }),
1192
+ setCookies: (cookies) => Effect2.tryPromise({
1193
+ try: async () => {
1194
+ if (cookies.length === 0) return;
1195
+ await cdpChannel.sendCommand("Network.setCookies", { cookies });
1196
+ },
1197
+ catch: (e) => new DriverError({ message: `CDP setCookies failed: ${e}` })
1198
+ }),
1199
+ clearCookies: () => Effect2.tryPromise({
1200
+ try: async () => {
1201
+ await cdpChannel.sendCommand("Network.clearBrowserCookies");
1202
+ },
1203
+ catch: (e) => new DriverError({ message: `CDP clearCookies failed: ${e}` })
1204
+ }),
1205
+ waitForResponse: (matcher, waitOpts) => Effect2.tryPromise({
1206
+ try: async () => {
1207
+ const timeoutMs = waitOpts?.timeout ?? 15e3;
1208
+ const slotSessions = () => {
1209
+ if (!activeSlot) return null;
1210
+ const set = /* @__PURE__ */ new Set([activeSlot.sessionId]);
1211
+ for (const t of activeSlot.tabs) {
1212
+ if (t.sessionId) set.add(t.sessionId);
1213
+ }
1214
+ return set;
1215
+ };
1216
+ const matchesActiveSlot = (sid) => {
1217
+ const allowed = slotSessions();
1218
+ if (!allowed || !sid) return true;
1219
+ return allowed.has(sid);
1220
+ };
1221
+ activeResponseWatchers += 1;
1222
+ const initialSessions = slotSessions();
1223
+ if (initialSessions && initialSessions.size > 0) {
1224
+ await Promise.all(
1225
+ Array.from(initialSessions).map(
1226
+ (sid) => cdpChannel.sendCommand("Network.enable", {}, sid).catch(() => {
1227
+ })
1228
+ )
1229
+ );
1230
+ } else {
1231
+ await cdpChannel.sendCommand("Network.enable").catch(() => {
1232
+ });
1233
+ }
1234
+ const requestMethods = /* @__PURE__ */ new Map();
1235
+ return await new Promise((resolve, reject) => {
1236
+ let cleaned = false;
1237
+ const cleanup = () => {
1238
+ if (cleaned) return;
1239
+ cleaned = true;
1240
+ activeResponseWatchers = Math.max(0, activeResponseWatchers - 1);
1241
+ clearTimeout(timer);
1242
+ offReq();
1243
+ offRes();
1244
+ };
1245
+ const timer = setTimeout(() => {
1246
+ cleanup();
1247
+ reject(new Error(`Timed out waiting for response after ${timeoutMs}ms`));
1248
+ }, timeoutMs);
1249
+ const offReq = cdpChannel.onEvent("Network.requestWillBeSent", (params, sid) => {
1250
+ if (!matchesActiveSlot(sid)) return;
1251
+ if (params?.requestId && params?.request?.method) {
1252
+ requestMethods.set(
1253
+ `${sid ?? ""}:${String(params.requestId)}`,
1254
+ String(params.request.method)
1255
+ );
1256
+ }
1257
+ });
1258
+ const offRes = cdpChannel.onEvent("Network.responseReceived", (params, sid) => {
1259
+ if (!matchesActiveSlot(sid)) return;
1260
+ const resp = params?.response;
1261
+ if (!resp) return;
1262
+ const requestId = String(params?.requestId ?? "");
1263
+ const rawHeaders = resp.headers ?? {};
1264
+ const headers = {};
1265
+ for (const [k, v] of Object.entries(rawHeaders)) {
1266
+ headers[k.toLowerCase()] = String(v);
1267
+ }
1268
+ const responseSid = sid ?? activeSlot?.sessionId ?? null;
1269
+ const info = {
1270
+ url: String(resp.url ?? ""),
1271
+ status: Number(resp.status ?? 0),
1272
+ statusText: String(resp.statusText ?? ""),
1273
+ headers,
1274
+ method: requestMethods.get(`${sid ?? ""}:${requestId}`),
1275
+ body: async () => {
1276
+ const bodyRes = await cdpChannel.sendCommand(
1277
+ "Network.getResponseBody",
1278
+ { requestId },
1279
+ responseSid
1280
+ );
1281
+ if (bodyRes?.base64Encoded && bodyRes.body) {
1282
+ return Buffer.from(bodyRes.body, "base64").toString("utf8");
1283
+ }
1284
+ return bodyRes?.body ?? "";
1285
+ },
1286
+ json: async () => {
1287
+ const text = await info.body();
1288
+ return JSON.parse(text);
1289
+ }
1290
+ };
1291
+ const matched = typeof matcher === "function" ? matcher(info) : matchUrl(matcher, info.url);
1292
+ if (matched) {
1293
+ cleanup();
1294
+ resolve(info);
1295
+ }
1296
+ });
1297
+ });
1298
+ },
1299
+ catch: (e) => new DriverError({ message: `CDP waitForResponse failed: ${e}` })
1300
+ }),
1301
+ createIsolatedContext: (ctxOpts) => Effect2.tryPromise({
1302
+ try: async () => {
1303
+ const childDriver = await Effect2.runPromise(
1304
+ makeLightweightCdpDriver({
1305
+ ...options,
1306
+ cdpUrl: connectWsUrl ?? options.cdpUrl,
1307
+ useBrowserContexts: true,
1308
+ freshContextPerFlow: false
1309
+ })
1310
+ );
1311
+ if (ctxOpts?.url) {
1312
+ await Effect2.runPromise(childDriver.openLink(ctxOpts.url));
1313
+ }
1314
+ return {
1315
+ driver: childDriver,
1316
+ close: async () => {
1317
+ await Effect2.runPromise(childDriver.killApp("isolated-context")).catch(() => {
1318
+ });
1319
+ }
1320
+ };
1321
+ },
1322
+ catch: (e) => new DriverError({ message: `CDP createIsolatedContext failed: ${e}` })
1323
+ }),
1324
+ saveAuthState: (path) => Effect2.tryPromise({
1016
1325
  try: async () => {
1017
1326
  const res = await cdpChannel.sendCommand("Network.getCookies");
1018
1327
  const originState = await cdpChannel.evaluate(
@@ -1035,7 +1344,7 @@ function makeLightweightCdpDriver(options) {
1035
1344
  },
1036
1345
  catch: (e) => new DriverError({ message: `CDP saveAuthState failed: ${e}` })
1037
1346
  }),
1038
- loadAuthState: (path) => Effect3.tryPromise({
1347
+ loadAuthState: (path) => Effect2.tryPromise({
1039
1348
  try: async () => {
1040
1349
  if (useContexts) {
1041
1350
  const previousSlot = activeSlot;
@@ -1052,7 +1361,7 @@ function makeLightweightCdpDriver(options) {
1052
1361
  },
1053
1362
  catch: (e) => new DriverError({ message: `CDP loadAuthState failed: ${e}` })
1054
1363
  }),
1055
- enableVirtualAuthenticator: (opts) => Effect3.tryPromise({
1364
+ enableVirtualAuthenticator: (opts) => Effect2.tryPromise({
1056
1365
  try: async () => {
1057
1366
  activeAuthenticatorId = await attachVirtualAuthenticatorForSession(
1058
1367
  activeSlot?.sessionId ?? null,
@@ -1062,7 +1371,7 @@ function makeLightweightCdpDriver(options) {
1062
1371
  },
1063
1372
  catch: (e) => new DriverError({ message: `CDP enableVirtualAuthenticator failed: ${e}` })
1064
1373
  }),
1065
- removeVirtualAuthenticator: (authenticatorId) => Effect3.tryPromise({
1374
+ removeVirtualAuthenticator: (authenticatorId) => Effect2.tryPromise({
1066
1375
  try: async () => {
1067
1376
  const id = authenticatorId ?? activeAuthenticatorId;
1068
1377
  if (!id) return;
@@ -1073,7 +1382,7 @@ function makeLightweightCdpDriver(options) {
1073
1382
  },
1074
1383
  catch: (e) => new DriverError({ message: `CDP removeVirtualAuthenticator failed: ${e}` })
1075
1384
  }),
1076
- getVirtualCredentials: (authenticatorId) => Effect3.tryPromise({
1385
+ getVirtualCredentials: (authenticatorId) => Effect2.tryPromise({
1077
1386
  try: async () => {
1078
1387
  const id = authenticatorId ?? activeAuthenticatorId;
1079
1388
  if (!id) return [];
@@ -1084,7 +1393,29 @@ function makeLightweightCdpDriver(options) {
1084
1393
  },
1085
1394
  catch: (e) => new DriverError({ message: `CDP getVirtualCredentials failed: ${e}` })
1086
1395
  }),
1087
- clearVirtualCredentials: (authenticatorId) => Effect3.tryPromise({
1396
+ addVirtualCredential: (credential, authenticatorId) => Effect2.tryPromise({
1397
+ try: async () => {
1398
+ let id = authenticatorId ?? activeAuthenticatorId;
1399
+ if (!id) {
1400
+ id = await attachVirtualAuthenticatorForSession(activeSlot?.sessionId ?? null);
1401
+ activeAuthenticatorId = id;
1402
+ }
1403
+ await cdpChannel.sendCommand("WebAuthn.addCredential", {
1404
+ authenticatorId: id,
1405
+ credential: {
1406
+ credentialId: credential.credentialId,
1407
+ isResidentCredential: credential.isResidentCredential,
1408
+ privateKey: credential.privateKey,
1409
+ signCount: credential.signCount ?? 0,
1410
+ ...credential.rpId !== void 0 ? { rpId: credential.rpId } : {},
1411
+ ...credential.userHandle !== void 0 ? { userHandle: credential.userHandle } : {},
1412
+ ...credential.userName !== void 0 ? { userName: credential.userName } : {}
1413
+ }
1414
+ });
1415
+ },
1416
+ catch: (e) => new DriverError({ message: `CDP addVirtualCredential failed: ${e}` })
1417
+ }),
1418
+ clearVirtualCredentials: (authenticatorId) => Effect2.tryPromise({
1088
1419
  try: async () => {
1089
1420
  const id = authenticatorId ?? activeAuthenticatorId;
1090
1421
  if (!id) return;
@@ -1092,9 +1423,9 @@ function makeLightweightCdpDriver(options) {
1092
1423
  },
1093
1424
  catch: (e) => new DriverError({ message: `CDP clearVirtualCredentials failed: ${e}` })
1094
1425
  }),
1095
- getConsoleLogs: () => Effect3.succeed([...consoleLogs]),
1096
- getJSErrors: () => Effect3.succeed([...jsErrors]),
1097
- setNetworkConditions: (conditions) => Effect3.tryPromise({
1426
+ getConsoleLogs: () => Effect2.succeed([...consoleLogs]),
1427
+ getJSErrors: () => Effect2.succeed([...jsErrors]),
1428
+ setNetworkConditions: (conditions) => Effect2.tryPromise({
1098
1429
  try: async () => {
1099
1430
  const resolved = resolveNetworkConditions(conditions);
1100
1431
  await cdpChannel.sendCommand("Network.enable");
@@ -1107,39 +1438,49 @@ function makeLightweightCdpDriver(options) {
1107
1438
  },
1108
1439
  catch: (e) => new DriverError({ message: `CDP setNetworkConditions failed: ${e}` })
1109
1440
  }),
1110
- uploadFile: (selector, filePath) => Effect3.tryPromise({
1441
+ uploadFile: (selector, filePath) => Effect2.tryPromise({
1111
1442
  try: async () => {
1112
- const serialized = JSON.stringify(selector);
1113
- const expr = `(function(sel) {
1114
- if (typeof sel === "object" && sel !== null && "testID" in sel) {
1115
- return document.querySelector('[data-testid="' + sel.testID + '"], [testID="' + sel.testID + '"]');
1116
- }
1117
- if (typeof sel === "object" && sel !== null && "accessibilityLabel" in sel) {
1118
- return document.querySelector('[aria-label="' + sel.accessibilityLabel + '"]');
1119
- }
1120
- return document.querySelector('input[type="file"]');
1121
- })(${serialized})`;
1443
+ const files = Array.isArray(filePath) ? filePath : [filePath];
1444
+ const expr = buildDomFindElementScript(selector);
1122
1445
  await cdpChannel.sendCommand("DOM.enable");
1123
- const evalRes = await cdpChannel.sendCommand("Runtime.evaluate", {
1124
- expression: expr,
1125
- returnByValue: false
1446
+ await cdpChannel.sendCommand("DOM.getDocument", { depth: 0 }).catch(() => {
1126
1447
  });
1127
- const objectId = evalRes?.result?.objectId;
1448
+ const envTimeout = Number(process.env["SPANA_UPLOAD_TIMEOUT_MS"]);
1449
+ const attachTimeout = Number.isFinite(envTimeout) && envTimeout > 0 ? envTimeout : UPLOAD_ATTACH_TIMEOUT_MS;
1450
+ const deadline = Date.now() + attachTimeout;
1451
+ let objectId;
1452
+ while (Date.now() < deadline) {
1453
+ const evalRes = await cdpChannel.sendCommand("Runtime.evaluate", {
1454
+ expression: expr,
1455
+ returnByValue: false
1456
+ });
1457
+ if (evalRes?.result?.objectId) {
1458
+ objectId = evalRes.result.objectId;
1459
+ break;
1460
+ }
1461
+ await new Promise((r) => setTimeout(r, 50));
1462
+ }
1128
1463
  if (!objectId) {
1129
- throw new Error(`No matching file input found for selector ${serialized}`);
1464
+ throw new Error(
1465
+ `No matching file input found within ${attachTimeout}ms for selector ${JSON.stringify(selector)}`
1466
+ );
1130
1467
  }
1131
- const nodeRes = await cdpChannel.sendCommand("DOM.requestNode", { objectId });
1132
- if (!nodeRes?.nodeId) {
1133
- throw new Error("Failed to resolve DOM nodeId for file input");
1468
+ const nodeRes = await cdpChannel.sendCommand("DOM.requestNode", { objectId }).catch(() => ({}));
1469
+ if (nodeRes?.nodeId && nodeRes.nodeId > 0) {
1470
+ await cdpChannel.sendCommand("DOM.setFileInputFiles", {
1471
+ nodeId: nodeRes.nodeId,
1472
+ files
1473
+ });
1474
+ } else {
1475
+ await cdpChannel.sendCommand("DOM.setFileInputFiles", {
1476
+ objectId,
1477
+ files
1478
+ });
1134
1479
  }
1135
- await cdpChannel.sendCommand("DOM.setFileInputFiles", {
1136
- nodeId: nodeRes.nodeId,
1137
- files: [filePath]
1138
- });
1139
1480
  },
1140
1481
  catch: (e) => new DriverError({ message: `CDP uploadFile failed: ${e}` })
1141
1482
  }),
1142
- downloadFile: (destPath) => Effect3.tryPromise({
1483
+ downloadFile: (destPath) => Effect2.tryPromise({
1143
1484
  try: async () => {
1144
1485
  if (!downloadDir) {
1145
1486
  downloadDir = mkdtempSync(join(tmpdir(), "spana-cdp-dl-"));
@@ -1173,7 +1514,7 @@ function makeLightweightCdpDriver(options) {
1173
1514
  },
1174
1515
  catch: (e) => new DriverError({ message: `CDP downloadFile failed: ${e}` })
1175
1516
  }),
1176
- newTab: (url) => Effect3.tryPromise({
1517
+ newTab: (url) => Effect2.tryPromise({
1177
1518
  try: async () => {
1178
1519
  if (!activeSlot) {
1179
1520
  throw new Error("newTab() requires browser-context mode (engine: 'cdp')");
@@ -1207,7 +1548,7 @@ function makeLightweightCdpDriver(options) {
1207
1548
  },
1208
1549
  catch: (e) => new DriverError({ message: `CDP newTab failed: ${e}` })
1209
1550
  }),
1210
- switchToTab: (index) => Effect3.tryPromise({
1551
+ switchToTab: (index) => Effect2.tryPromise({
1211
1552
  try: async () => {
1212
1553
  if (!activeSlot || !activeSlot.tabs[index]) {
1213
1554
  throw new Error(`Tab index ${index} is out of range.`);
@@ -1221,7 +1562,7 @@ function makeLightweightCdpDriver(options) {
1221
1562
  },
1222
1563
  catch: (e) => new DriverError({ message: `CDP switchToTab failed: ${e}` })
1223
1564
  }),
1224
- closeTab: () => Effect3.tryPromise({
1565
+ closeTab: () => Effect2.tryPromise({
1225
1566
  try: async () => {
1226
1567
  if (!activeSlot) return;
1227
1568
  if (activeSlot.tabs.length <= 1) {
@@ -1240,14 +1581,14 @@ function makeLightweightCdpDriver(options) {
1240
1581
  },
1241
1582
  catch: (e) => new DriverError({ message: `CDP closeTab failed: ${e}` })
1242
1583
  }),
1243
- getTabIds: () => Effect3.sync(() => activeSlot ? activeSlot.tabs.map((t) => t.tabId) : ["tab-1"])
1584
+ getTabIds: () => Effect2.sync(() => activeSlot ? activeSlot.tabs.map((t) => t.tabId) : ["tab-1"])
1244
1585
  };
1245
1586
  return service;
1246
1587
  });
1247
1588
  }
1248
1589
 
1249
1590
  // src/runtime/local.ts
1250
- import { Effect as Effect4 } from "effect";
1591
+ import { Effect as Effect3 } from "effect";
1251
1592
  async function safeCleanup(...fns) {
1252
1593
  for (const fn of fns) {
1253
1594
  try {
@@ -1282,7 +1623,8 @@ function buildEngineConfig(appId, platform, parseFn, config, screenSize) {
1282
1623
  initialPollInterval: config.defaults?.initialPollInterval,
1283
1624
  tapMode: config.defaults?.tapMode,
1284
1625
  platform,
1285
- failFastWhenIdle: config.defaults?.failFastWhenIdle
1626
+ failFastWhenIdle: config.defaults?.failFastWhenIdle,
1627
+ actionStableFrames: config.defaults?.actionStableFrames
1286
1628
  },
1287
1629
  waitForIdleTimeout: config.defaults?.waitForIdleTimeout,
1288
1630
  typingDelay: config.defaults?.typingDelay,
@@ -1375,13 +1717,14 @@ async function buildWebRuntime(config, prelaunched) {
1375
1717
  });
1376
1718
  targetCdpUrl = launchedDirectCdp.browserWsUrl;
1377
1719
  }
1378
- rawDriver = await Effect4.runPromise(
1720
+ rawDriver = await Effect3.runPromise(
1379
1721
  makeLightweightCdpDriver({
1380
1722
  cdpUrl: targetCdpUrl ?? "http://127.0.0.1:9222",
1381
1723
  baseUrl: webUrl,
1382
1724
  engineLabel: engine,
1383
1725
  useBrowserContexts: useContexts,
1384
1726
  freshContextPerFlow: webExecution?.freshContextPerFlow,
1727
+ contextIsolation: webExecution?.contextIsolation,
1385
1728
  waitUntil: webExecution?.waitUntil,
1386
1729
  instantAnimations: webExecution?.instantAnimations,
1387
1730
  blockResources: webExecution?.blockResources,
@@ -1390,7 +1733,7 @@ async function buildWebRuntime(config, prelaunched) {
1390
1733
  })
1391
1734
  );
1392
1735
  } else {
1393
- rawDriver = await Effect4.runPromise(
1736
+ rawDriver = await Effect3.runPromise(
1394
1737
  makePlaywrightDriver({
1395
1738
  browser: webExecution?.browser,
1396
1739
  headless: webExecution?.headless ?? true,
@@ -1414,12 +1757,12 @@ async function buildWebRuntime(config, prelaunched) {
1414
1757
  );
1415
1758
  }
1416
1759
  const driver = bridge ? { ...rawDriver, domChannel: bridge } : rawDriver;
1417
- const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
1760
+ const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
1418
1761
  return {
1419
1762
  runtime: {
1420
1763
  driver,
1421
1764
  cleanup: () => safeCleanup(
1422
- () => Effect4.runPromise(driver.killApp("")),
1765
+ () => Effect3.runPromise(driver.killApp("")),
1423
1766
  () => prelaunchedBrowser && prelaunched?.ownsBrowser ? prelaunchedBrowser.close() : Promise.resolve(),
1424
1767
  () => launchedDirectCdp ? launchedDirectCdp.close() : Promise.resolve(),
1425
1768
  () => bridge?.disconnect() ?? Promise.resolve()
@@ -1476,13 +1819,14 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1476
1819
  const results2 = [];
1477
1820
  for (let i = 0; i < workerCount; i++) {
1478
1821
  const bucket = handles[i % handles.length];
1479
- const driver = await Effect4.runPromise(
1822
+ const driver = await Effect3.runPromise(
1480
1823
  makeLightweightCdpDriver({
1481
1824
  cdpUrl: bucket.cdpUrl,
1482
1825
  baseUrl: webUrl,
1483
1826
  engineLabel: "cdp",
1484
1827
  useBrowserContexts: true,
1485
1828
  freshContextPerFlow: webExecution?.freshContextPerFlow,
1829
+ contextIsolation: webExecution?.contextIsolation,
1486
1830
  waitUntil: webExecution?.waitUntil,
1487
1831
  instantAnimations: webExecution?.instantAnimations,
1488
1832
  blockResources: webExecution?.blockResources,
@@ -1490,7 +1834,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1490
1834
  storageState: webExecution?.storageState
1491
1835
  })
1492
1836
  );
1493
- const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
1837
+ const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
1494
1838
  let cleaned = false;
1495
1839
  results2.push({
1496
1840
  runtime: {
@@ -1498,7 +1842,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1498
1842
  cleanup: () => safeCleanup(async () => {
1499
1843
  if (cleaned) return;
1500
1844
  cleaned = true;
1501
- await Effect4.runPromise(driver.killApp(""));
1845
+ await Effect3.runPromise(driver.killApp(""));
1502
1846
  bucket.remaining -= 1;
1503
1847
  if (bucket.remaining <= 0 && bucket.handle) {
1504
1848
  await bucket.handle.close();
@@ -1571,7 +1915,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1571
1915
  const results = [];
1572
1916
  for (let i = 0; i < workerCount; i++) {
1573
1917
  const bucket = browserBuckets[i % browserBuckets.length];
1574
- const driver = await Effect4.runPromise(
1918
+ const driver = await Effect3.runPromise(
1575
1919
  makePlaywrightDriver({
1576
1920
  browser: webExecution?.browser,
1577
1921
  headless: webExecution?.headless ?? true,
@@ -1590,7 +1934,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1590
1934
  warmBrowserScope: webExecution?.warmBrowserScope
1591
1935
  })
1592
1936
  );
1593
- const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
1937
+ const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
1594
1938
  let cleaned = false;
1595
1939
  results.push({
1596
1940
  runtime: {
@@ -1598,7 +1942,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1598
1942
  cleanup: () => safeCleanup(async () => {
1599
1943
  if (cleaned) return;
1600
1944
  cleaned = true;
1601
- await Effect4.runPromise(driver.killApp(""));
1945
+ await Effect3.runPromise(driver.killApp(""));
1602
1946
  bucket.remaining -= 1;
1603
1947
  if (bucket.remaining <= 0 && bucket.owns) {
1604
1948
  await bucket.browser.close();
@@ -1621,7 +1965,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1621
1965
  async function buildElectronRuntime(config, resolveFromConfig) {
1622
1966
  const electronCfg = config.apps?.electron ?? {};
1623
1967
  const bridge = await maybeStartBridge(electronCfg.bridge, config.execution?.bridge);
1624
- const driver = await Effect4.runPromise(
1968
+ const driver = await Effect3.runPromise(
1625
1969
  makeElectronDriver({
1626
1970
  entry: electronCfg.entry ? resolveFromConfig(electronCfg.entry) : void 0,
1627
1971
  executablePath: electronCfg.executablePath ? resolveFromConfig(electronCfg.executablePath) : void 0,
@@ -1637,12 +1981,12 @@ async function buildElectronRuntime(config, resolveFromConfig) {
1637
1981
  domChannel: bridge
1638
1982
  })
1639
1983
  );
1640
- const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
1984
+ const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
1641
1985
  return {
1642
1986
  runtime: {
1643
1987
  driver,
1644
1988
  cleanup: () => safeCleanup(
1645
- () => Effect4.runPromise(driver.killApp("")),
1989
+ () => Effect3.runPromise(driver.killApp("")),
1646
1990
  () => bridge?.disconnect() ?? Promise.resolve()
1647
1991
  ),
1648
1992
  metadata: {
@@ -1666,7 +2010,7 @@ async function buildElectronRuntime(config, resolveFromConfig) {
1666
2010
  async function buildElectrobunRuntime(config, resolveFromConfig) {
1667
2011
  const electrobunCfg = config.apps?.electrobun ?? {};
1668
2012
  const bridge = await maybeStartBridge(electrobunCfg.bridge, config.execution?.bridge);
1669
- const driver = await Effect4.runPromise(
2013
+ const driver = await Effect3.runPromise(
1670
2014
  makeElectrobunDriver({
1671
2015
  executablePath: electrobunCfg.executablePath ? resolveFromConfig(electrobunCfg.executablePath) : void 0,
1672
2016
  appDir: electrobunCfg.appDir ? resolveFromConfig(electrobunCfg.appDir) : void 0,
@@ -1684,12 +2028,12 @@ async function buildElectrobunRuntime(config, resolveFromConfig) {
1684
2028
  domChannel: bridge
1685
2029
  })
1686
2030
  );
1687
- const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
2031
+ const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
1688
2032
  return {
1689
2033
  runtime: {
1690
2034
  driver,
1691
2035
  cleanup: () => safeCleanup(
1692
- () => Effect4.runPromise(driver.killApp("")),
2036
+ () => Effect3.runPromise(driver.killApp("")),
1693
2037
  () => bridge?.disconnect() ?? Promise.resolve()
1694
2038
  ),
1695
2039
  metadata: {
@@ -1724,7 +2068,7 @@ async function buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig)
1724
2068
  const androidAppPath = config.apps?.android?.appPath;
1725
2069
  if (androidAppPath && packageName) {
1726
2070
  try {
1727
- const { adbShell, adbInstall } = await import("./android-4NVTZMHL.js");
2071
+ const { adbShell, adbInstall } = await import("./android-6BOQTMM3.js");
1728
2072
  const output = adbShell(device.serial, `pm list packages ${packageName}`);
1729
2073
  if (!output.includes(packageName)) {
1730
2074
  console.log(`Installing ${packageName} on Android device...`);
@@ -1732,7 +2076,7 @@ async function buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig)
1732
2076
  }
1733
2077
  } catch {
1734
2078
  console.log(`Installing ${packageName} on Android device...`);
1735
- const { adbInstall } = await import("./android-4NVTZMHL.js");
2079
+ const { adbInstall } = await import("./android-6BOQTMM3.js");
1736
2080
  adbInstall(device.serial, resolveFromConfig(androidAppPath));
1737
2081
  }
1738
2082
  }
@@ -1751,18 +2095,18 @@ async function buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig)
1751
2095
  warm: warmDaemons?.enabled,
1752
2096
  daemonStateFile: warmDaemons?.stateFile
1753
2097
  });
1754
- const driver = await Effect4.runPromise(
2098
+ const driver = await Effect3.runPromise(
1755
2099
  createUiAutomator2Driver(conn.host, conn.port, device.serial, packageName, {
1756
2100
  domChannel: bridge,
1757
2101
  cdpPort: config.apps?.android?.cdpPort
1758
2102
  })
1759
2103
  );
1760
- const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
2104
+ const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
1761
2105
  return {
1762
2106
  runtime: {
1763
2107
  driver,
1764
2108
  cleanup: () => safeCleanup(
1765
- () => Effect4.runPromise(driver.killApp("")),
2109
+ () => Effect3.runPromise(driver.killApp("")),
1766
2110
  () => bridge?.disconnect() ?? Promise.resolve(),
1767
2111
  () => {
1768
2112
  if (reversedBridgePort !== null) {
@@ -1799,7 +2143,7 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
1799
2143
  const bridge = await maybeStartBridge(config.apps?.ios?.bridge, config.execution?.bridge);
1800
2144
  const createIOSRuntime = async (deviceId, conn, simulatorUdid) => {
1801
2145
  const reuseSession = warmDaemons?.enabled && warmDaemons.reuseSession !== false;
1802
- const driver = await Effect4.runPromise(
2146
+ const driver = await Effect3.runPromise(
1803
2147
  createWDADriver(conn.host, conn.port, bundleId, simulatorUdid, snapshotMaxDepth, {
1804
2148
  domChannel: bridge,
1805
2149
  webkitInspectorUrl: config.apps?.ios?.webkitInspectorUrl,
@@ -1809,12 +2153,12 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
1809
2153
  onSessionCreated: reuseSession ? (sessionId) => updateWarmDaemonSession("wda", deviceId, sessionId, bundleId, warmDaemons?.stateFile) : void 0
1810
2154
  })
1811
2155
  );
1812
- const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
2156
+ const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
1813
2157
  return {
1814
2158
  runtime: {
1815
2159
  driver,
1816
2160
  cleanup: () => safeCleanup(
1817
- () => Effect4.runPromise(driver.killApp("")),
2161
+ () => Effect3.runPromise(driver.killApp("")),
1818
2162
  () => bridge?.disconnect() ?? Promise.resolve(),
1819
2163
  () => conn.cleanup?.() ?? Promise.resolve()
1820
2164
  ),
@@ -1843,7 +2187,7 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
1843
2187
  });
1844
2188
  }
1845
2189
  if (signing?.teamId) {
1846
- const { setupWDAForDevice } = await import("./installer-VUPFWP5X.js");
2190
+ const { setupWDAForDevice } = await import("./installer-5UHTYQTB.js");
1847
2191
  const wdaPort2 = allocatePort(8100);
1848
2192
  conn = await setupWDAForDevice(
1849
2193
  physicalDevice2.udid,
@@ -1945,13 +2289,105 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
1945
2289
  }
1946
2290
  }
1947
2291
 
2292
+ // src/report/code-frame.ts
2293
+ import { existsSync as existsSync2, readFileSync } from "fs";
2294
+ import { fileURLToPath } from "url";
2295
+ var INTERNAL_FRAME_PATTERNS = [
2296
+ /node_modules\//,
2297
+ /^node:/,
2298
+ /^bun:/,
2299
+ /^internal\//,
2300
+ /\/packages\/spana\/(?:src|dist)\/(?!.*\.test\.[jt]sx?$)/,
2301
+ /\/spana(?:-test)?\/dist\//
2302
+ ];
2303
+ function normalizeStackFile(raw) {
2304
+ const trimmed = raw.trim();
2305
+ if (trimmed.startsWith("file://")) {
2306
+ try {
2307
+ return fileURLToPath(trimmed);
2308
+ } catch {
2309
+ return trimmed.replace(/^file:\/\//, "");
2310
+ }
2311
+ }
2312
+ return trimmed;
2313
+ }
2314
+ function parseStackFrames(stack) {
2315
+ const frames = [];
2316
+ for (const rawLine of stack.split("\n")) {
2317
+ const line = rawLine.trim();
2318
+ if (!line.startsWith("at ")) continue;
2319
+ const match = line.match(/\((.+):(\d+):(\d+)\)$/) ?? line.match(/^at\s+(.+):(\d+):(\d+)$/);
2320
+ if (!match) continue;
2321
+ const file = normalizeStackFile(match[1]);
2322
+ const lineNum = Number.parseInt(match[2], 10);
2323
+ const colNum = Number.parseInt(match[3], 10);
2324
+ if (!file || !Number.isFinite(lineNum) || lineNum < 1) continue;
2325
+ frames.push({
2326
+ file,
2327
+ line: lineNum,
2328
+ column: Number.isFinite(colNum) && colNum > 0 ? colNum : 1
2329
+ });
2330
+ }
2331
+ return frames;
2332
+ }
2333
+ function isInternalFrame(file) {
2334
+ const normalized = file.replaceAll("\\", "/");
2335
+ return INTERNAL_FRAME_PATTERNS.some((re) => re.test(normalized));
2336
+ }
2337
+ function formatCodeFrame(source, line, column, contextLines = 3) {
2338
+ const lines = source.split(/\r?\n/);
2339
+ if (line < 1 || line > lines.length) return "";
2340
+ const startLine = Math.max(1, line - contextLines);
2341
+ const endLine = Math.min(lines.length, line + contextLines);
2342
+ const gutterWidth = String(endLine).length;
2343
+ const out = [];
2344
+ for (let current = startLine; current <= endLine; current++) {
2345
+ const marker = current === line ? ">" : " ";
2346
+ const num = String(current).padStart(gutterWidth, " ");
2347
+ const content = lines[current - 1] ?? "";
2348
+ out.push(`${marker} ${num} | ${content}`);
2349
+ if (current === line) {
2350
+ const caretOffset = Math.max(0, Math.min(column - 1, content.length));
2351
+ out.push(` ${" ".repeat(gutterWidth)} | ${" ".repeat(caretOffset)}^`);
2352
+ }
2353
+ }
2354
+ return out.join("\n");
2355
+ }
2356
+ function extractCodeFrame(stack, preferredFile, contextLines = 3) {
2357
+ if (!stack) return void 0;
2358
+ const frames = parseStackFrames(stack);
2359
+ if (frames.length === 0) return void 0;
2360
+ const normalizedPreferred = preferredFile ? normalizeStackFile(preferredFile) : void 0;
2361
+ let chosen = normalizedPreferred ? frames.find(
2362
+ (f) => (f.file === normalizedPreferred || f.file.endsWith(normalizedPreferred)) && existsSync2(f.file)
2363
+ ) : void 0;
2364
+ if (!chosen) {
2365
+ chosen = frames.find((f) => /\.flow\.[cm]?[jt]sx?$/.test(f.file) && existsSync2(f.file));
2366
+ }
2367
+ if (!chosen) {
2368
+ chosen = frames.find((f) => !isInternalFrame(f.file) && existsSync2(f.file));
2369
+ }
2370
+ if (!chosen) return void 0;
2371
+ try {
2372
+ const source = readFileSync(chosen.file, "utf8");
2373
+ const frame = formatCodeFrame(source, chosen.line, chosen.column, contextLines);
2374
+ if (!frame) return void 0;
2375
+ return {
2376
+ location: { file: chosen.file, line: chosen.line, column: chosen.column },
2377
+ frame
2378
+ };
2379
+ } catch {
2380
+ return void 0;
2381
+ }
2382
+ }
2383
+
1948
2384
  // src/core/video-recorder.ts
1949
2385
  import { execFileSync, spawn as spawn2 } from "child_process";
1950
2386
  import {
1951
- existsSync as existsSync2,
2387
+ existsSync as existsSync3,
1952
2388
  mkdirSync,
1953
2389
  mkdtempSync as mkdtempSync2,
1954
- readFileSync,
2390
+ readFileSync as readFileSync2,
1955
2391
  rmSync as rmSync2,
1956
2392
  unlinkSync,
1957
2393
  writeFileSync
@@ -2013,7 +2449,7 @@ async function exportFramesToMp4(frames, outputPath, spawnFn = spawn2) {
2013
2449
  child.on("error", () => resolve(false));
2014
2450
  child.on("close", (code) => resolve(code === 0));
2015
2451
  });
2016
- return ok && existsSync2(outputPath) ? outputPath : void 0;
2452
+ return ok && existsSync3(outputPath) ? outputPath : void 0;
2017
2453
  } catch {
2018
2454
  return void 0;
2019
2455
  } finally {
@@ -2062,7 +2498,26 @@ async function startCdpScreencastRecorder(cdp, options) {
2062
2498
  unsubscribe();
2063
2499
  await cdp.sendCommand("Page.stopScreencast").catch(() => {
2064
2500
  });
2065
- if (!stopOpts.keep || frames.length === 0) {
2501
+ if (!stopOpts.keep) {
2502
+ return { frameCount: 0 };
2503
+ }
2504
+ if (frames.length === 0) {
2505
+ try {
2506
+ const snap = await cdp.sendCommand("Page.captureScreenshot", {
2507
+ format: "jpeg",
2508
+ quality: options.quality ?? 65
2509
+ });
2510
+ if (typeof snap?.data === "string" && snap.data.length > 0) {
2511
+ frames.push({
2512
+ timestampMs: Math.max(0, Date.now() - startedAt),
2513
+ dataBase64: snap.data,
2514
+ mimeType: "image/jpeg"
2515
+ });
2516
+ }
2517
+ } catch {
2518
+ }
2519
+ }
2520
+ if (frames.length === 0) {
2066
2521
  return { frameCount: 0 };
2067
2522
  }
2068
2523
  mkdirSync(stopOpts.outputDir, { recursive: true });
@@ -2119,7 +2574,7 @@ function startAndroidVideoRecorder(serial, options) {
2119
2574
  execSyncFn("adb", ["-s", serial, "pull", remotePath, options.outputPath], {
2120
2575
  stdio: "ignore"
2121
2576
  });
2122
- if (existsSync2(options.outputPath)) savedPath = options.outputPath;
2577
+ if (existsSync3(options.outputPath)) savedPath = options.outputPath;
2123
2578
  } catch {
2124
2579
  }
2125
2580
  }
@@ -2156,14 +2611,14 @@ function startIosSimulatorVideoRecorder(udid, options) {
2156
2611
  });
2157
2612
  if (!keep) {
2158
2613
  try {
2159
- if (existsSync2(options.outputPath)) unlinkSync(options.outputPath);
2614
+ if (existsSync3(options.outputPath)) unlinkSync(options.outputPath);
2160
2615
  } catch {
2161
2616
  }
2162
2617
  return { frameCount: 0 };
2163
2618
  }
2164
2619
  return {
2165
- videoPath: existsSync2(options.outputPath) ? options.outputPath : void 0,
2166
- frameCount: existsSync2(options.outputPath) ? 1 : 0
2620
+ videoPath: existsSync3(options.outputPath) ? options.outputPath : void 0,
2621
+ frameCount: existsSync3(options.outputPath) ? 1 : 0
2167
2622
  };
2168
2623
  }
2169
2624
  };
@@ -2188,9 +2643,9 @@ function buildPlaybackTraceFromSteps(input) {
2188
2643
  const img = step.attachments?.find(
2189
2644
  (a) => a.contentType === "image/png" || a.contentType === "image/jpeg"
2190
2645
  );
2191
- if (img && existsSync2(img.path)) {
2646
+ if (img && existsSync3(img.path)) {
2192
2647
  try {
2193
- const dataBase64 = readFileSync(img.path).toString("base64");
2648
+ const dataBase64 = readFileSync2(img.path).toString("base64");
2194
2649
  frames.push({
2195
2650
  timestampMs: cursorMs + step.durationMs,
2196
2651
  dataBase64,
@@ -2225,12 +2680,12 @@ function extractTapPointFromStep(step) {
2225
2680
  }
2226
2681
 
2227
2682
  // src/core/engine.ts
2228
- import { Effect as Effect7 } from "effect";
2683
+ import { Effect as Effect6 } from "effect";
2229
2684
 
2230
2685
  // src/core/artifacts.ts
2231
2686
  import { writeFileSync as writeFileSync2, mkdirSync as mkdirSync2 } from "fs";
2232
2687
  import { join as join3 } from "path";
2233
- import { Effect as Effect5 } from "effect";
2688
+ import { Effect as Effect4 } from "effect";
2234
2689
  var DEFAULT_ARTIFACT_CONFIG = {
2235
2690
  outputDir: "./spana-output",
2236
2691
  captureOnFailure: true,
@@ -2282,7 +2737,7 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
2282
2737
  const dir = flowArtifactDir(config, flowName, platform);
2283
2738
  if (config.screenshot) {
2284
2739
  try {
2285
- const screenshot = await Effect5.runPromise(Effect5.orDie(driver.takeScreenshot()));
2740
+ const screenshot = await Effect4.runPromise(Effect4.orDie(driver.takeScreenshot()));
2286
2741
  const path = join3(dir, "screenshot.png");
2287
2742
  writeFileSync2(path, screenshot);
2288
2743
  attachments.push(createAttachment(`${status}-screenshot`, "image/png", path));
@@ -2291,7 +2746,7 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
2291
2746
  }
2292
2747
  if (config.uiHierarchy) {
2293
2748
  try {
2294
- const hierarchy = await Effect5.runPromise(Effect5.orDie(driver.dumpHierarchy()));
2749
+ const hierarchy = await Effect4.runPromise(Effect4.orDie(driver.dumpHierarchy()));
2295
2750
  const path = join3(dir, "hierarchy.json");
2296
2751
  writeFileSync2(path, hierarchy, "utf-8");
2297
2752
  attachments.push(createAttachment(`${status}-hierarchy`, "application/json", path));
@@ -2300,7 +2755,7 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
2300
2755
  }
2301
2756
  if (config.consoleLogs && driver.getConsoleLogs) {
2302
2757
  try {
2303
- const consoleLogs = await Effect5.runPromise(Effect5.orDie(driver.getConsoleLogs()));
2758
+ const consoleLogs = await Effect4.runPromise(Effect4.orDie(driver.getConsoleLogs()));
2304
2759
  if (consoleLogs.length > 0) {
2305
2760
  attachments.push(
2306
2761
  writeJsonAttachment(dir, "console-logs.json", `${status}-console-logs`, consoleLogs)
@@ -2311,7 +2766,7 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
2311
2766
  }
2312
2767
  if (config.jsErrors && driver.getJSErrors) {
2313
2768
  try {
2314
- const jsErrors = await Effect5.runPromise(Effect5.orDie(driver.getJSErrors()));
2769
+ const jsErrors = await Effect4.runPromise(Effect4.orDie(driver.getJSErrors()));
2315
2770
  if (jsErrors.length > 0) {
2316
2771
  attachments.push(
2317
2772
  writeJsonAttachment(dir, "js-errors.json", `${status}-js-errors`, jsErrors)
@@ -2322,7 +2777,7 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
2322
2777
  }
2323
2778
  if (config.har && driver.getHAR) {
2324
2779
  try {
2325
- const har = await Effect5.runPromise(Effect5.orDie(driver.getHAR()));
2780
+ const har = await Effect4.runPromise(Effect4.orDie(driver.getHAR()));
2326
2781
  if (har.log.entries.length > 0) {
2327
2782
  attachments.push(writeJsonAttachment(dir, "network.har", `${status}-network-har`, har));
2328
2783
  }
@@ -2331,7 +2786,7 @@ async function captureArtifacts(driver, config, flowName, platform, status) {
2331
2786
  }
2332
2787
  if (status === "failed" && driver.getDriverLogs) {
2333
2788
  try {
2334
- const driverLogs = await Effect5.runPromise(Effect5.orDie(driver.getDriverLogs()));
2789
+ const driverLogs = await Effect4.runPromise(Effect4.orDie(driver.getDriverLogs()));
2335
2790
  if (driverLogs.length > 0) {
2336
2791
  attachments.push(
2337
2792
  writeTextAttachment(
@@ -2354,7 +2809,7 @@ async function captureStepScreenshot(driver, config, flowName, platform, stepInd
2354
2809
  mkdirSync2(dir, { recursive: true });
2355
2810
  const fileName = `${String(stepIndex).padStart(3, "0")}-${safeName(stepName)}.png`;
2356
2811
  const path = join3(dir, fileName);
2357
- const bytes = screenshot ?? await Effect5.runPromise(Effect5.orDie(driver.takeScreenshot()));
2812
+ const bytes = screenshot ?? await Effect4.runPromise(Effect4.orDie(driver.takeScreenshot()));
2358
2813
  writeFileSync2(path, bytes);
2359
2814
  return createAttachment(stepName, "image/png", path);
2360
2815
  } catch {
@@ -2364,7 +2819,7 @@ async function captureStepScreenshot(driver, config, flowName, platform, stepInd
2364
2819
 
2365
2820
  // src/core/debug-repl.ts
2366
2821
  import * as repl from "repl";
2367
- import { Effect as Effect6 } from "effect";
2822
+ import { Effect as Effect5 } from "effect";
2368
2823
  var didStartDebugRepl = false;
2369
2824
  function toSuggestedSelectors(root) {
2370
2825
  return flattenElements(root).filter((el) => el.visible !== false && (el.id || el.text || el.accessibilityLabel)).map((el) => ({
@@ -2385,7 +2840,7 @@ async function runDebugReplOnce(context) {
2385
2840
  console.log("Skipping debug REPL because stdin/stdout is not interactive.");
2386
2841
  return false;
2387
2842
  }
2388
- const hierarchy = async () => context.parseHierarchy(await Effect6.runPromise(context.driver.dumpHierarchy()));
2843
+ const hierarchy = async () => context.parseHierarchy(await Effect5.runPromise(context.driver.dumpHierarchy()));
2389
2844
  const selectors = async () => toSuggestedSelectors(await hierarchy());
2390
2845
  console.log("");
2391
2846
  console.log(`Entering debug REPL for failed flow "${context.flowName}" on ${context.platform}.`);
@@ -2435,9 +2890,11 @@ function createStepResult(command, durationMs, status, selector, error, attachme
2435
2890
  }
2436
2891
  function createStepRecorder(driver, artifactConfig, flowName, platform) {
2437
2892
  const steps = [];
2893
+ let lastFailureStack;
2438
2894
  return {
2439
2895
  async runStep(command, action, opts) {
2440
2896
  const startedAt = Date.now();
2897
+ const callSiteStack = new Error().stack;
2441
2898
  try {
2442
2899
  const result = await action();
2443
2900
  const attachments = [];
@@ -2464,6 +2921,7 @@ function createStepRecorder(driver, artifactConfig, flowName, platform) {
2464
2921
  );
2465
2922
  return result;
2466
2923
  } catch (error) {
2924
+ lastFailureStack = callSiteStack;
2467
2925
  steps.push(
2468
2926
  createStepResult(
2469
2927
  command,
@@ -2478,6 +2936,7 @@ function createStepRecorder(driver, artifactConfig, flowName, platform) {
2478
2936
  },
2479
2937
  async runScreenshotStep(command, action, opts) {
2480
2938
  const startedAt = Date.now();
2939
+ const callSiteStack = new Error().stack;
2481
2940
  try {
2482
2941
  const screenshot = await action();
2483
2942
  const attachment = await captureStepScreenshot(
@@ -2501,6 +2960,7 @@ function createStepRecorder(driver, artifactConfig, flowName, platform) {
2501
2960
  );
2502
2961
  return screenshot;
2503
2962
  } catch (error) {
2963
+ lastFailureStack = callSiteStack;
2504
2964
  steps.push(
2505
2965
  createStepResult(
2506
2966
  command,
@@ -2515,12 +2975,31 @@ function createStepRecorder(driver, artifactConfig, flowName, platform) {
2515
2975
  },
2516
2976
  getSteps() {
2517
2977
  return steps;
2978
+ },
2979
+ getLastFailureStack() {
2980
+ return lastFailureStack;
2518
2981
  }
2519
2982
  };
2520
2983
  }
2521
2984
 
2522
2985
  // src/report/classify-error.ts
2523
2986
  var TAG_KEY = "_tag";
2987
+ var FIBER_FAILURE_CAUSE_SYMBOL = /* @__PURE__ */ Symbol.for("effect/Runtime/FiberFailure/Cause");
2988
+ function unwrapTaggedError(error) {
2989
+ if (!error || typeof error !== "object") return {};
2990
+ const obj = error;
2991
+ if (typeof obj[TAG_KEY] === "string") {
2992
+ return obj;
2993
+ }
2994
+ const cause = obj[FIBER_FAILURE_CAUSE_SYMBOL];
2995
+ if (cause && typeof cause === "object") {
2996
+ const inner = cause["error"] ?? cause["defect"];
2997
+ if (inner && typeof inner === "object" && typeof inner[TAG_KEY] === "string") {
2998
+ return inner;
2999
+ }
3000
+ }
3001
+ return obj;
3002
+ }
2524
3003
  function selectorHint(selector) {
2525
3004
  if (selector && typeof selector === "object") {
2526
3005
  const s = selector;
@@ -2715,7 +3194,7 @@ var heuristicRules = [
2715
3194
  suggestion: "The operation timed out. Try increasing `defaults.waitTimeout` in spana.config.ts."
2716
3195
  },
2717
3196
  {
2718
- pattern: /not found|not visible/,
3197
+ pattern: /not found|not visible|not fillable|covered by/,
2719
3198
  category: (msg) => categorizeElementFailure(msg),
2720
3199
  suggestion: (_error, msg) => {
2721
3200
  if (msg.includes("scroll(s) toward")) {
@@ -2767,14 +3246,16 @@ function categorize(error) {
2767
3246
  }
2768
3247
  return { category: "unknown" };
2769
3248
  }
2770
- function classifyError(error) {
2771
- const tagged = error;
3249
+ function classifyError(error, opts) {
3250
+ const tagged = unwrapTaggedError(error);
2772
3251
  const { category, suggestion } = categorize(tagged);
3252
+ const extracted = extractCodeFrame(error.stack, opts?.flowFilePath) ?? extractCodeFrame(opts?.fallbackStack, opts?.flowFilePath);
2773
3253
  return {
2774
- message: error.message,
3254
+ message: tagged.message ?? error.message,
2775
3255
  stack: error.stack,
2776
3256
  category,
2777
- suggestion
3257
+ suggestion,
3258
+ ...extracted ? { location: extracted.location, codeFrame: extracted.frame } : {}
2778
3259
  };
2779
3260
  }
2780
3261
 
@@ -2783,7 +3264,7 @@ import { writeFileSync as writeFileSync4 } from "fs";
2783
3264
  import { join as join5 } from "path";
2784
3265
 
2785
3266
  // src/report/failure-bundle.ts
2786
- import { writeFileSync as writeFileSync3, readFileSync as readFileSync2, existsSync as existsSync3 } from "fs";
3267
+ import { writeFileSync as writeFileSync3, readFileSync as readFileSync3, existsSync as existsSync4 } from "fs";
2787
3268
  import { join as join4, basename } from "path";
2788
3269
  function levenshtein(a, b) {
2789
3270
  const m = a.length;
@@ -2893,9 +3374,9 @@ function createFailureBundle(flowName, platform, steps, error, artifactDir, atta
2893
3374
  if (failedStep?.selector && (error.category === "element-not-found" || error.category === "element-not-visible")) {
2894
3375
  const hierarchyPath = join4(artifactDir, "hierarchy.json");
2895
3376
  let hierarchyJson = null;
2896
- if (existsSync3(hierarchyPath)) {
3377
+ if (existsSync4(hierarchyPath)) {
2897
3378
  try {
2898
- hierarchyJson = readFileSync2(hierarchyPath, "utf-8");
3379
+ hierarchyJson = readFileSync3(hierarchyPath, "utf-8");
2899
3380
  } catch {
2900
3381
  }
2901
3382
  }
@@ -2905,20 +3386,21 @@ function createFailureBundle(flowName, platform, steps, error, artifactDir, atta
2905
3386
  nearbyAlternatives
2906
3387
  };
2907
3388
  }
3389
+ const shellQuote = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
2908
3390
  const flowFile = flowPath ?? `flows/${flowName.replaceAll(" ", "-")}.flow.ts`;
2909
- const reproCommand = `spana test ${flowFile} --platform ${platform} --grep '${flowName}'`;
3391
+ const reproCommand = `spana test ${shellQuote(flowFile)} --platform ${platform} --grep ${shellQuote(flowName)}`;
2910
3392
  let runtimeDiagnostics;
2911
3393
  const consolePath = join4(artifactDir, "console-logs.json");
2912
3394
  const jsErrPath = join4(artifactDir, "js-errors.json");
2913
- if (existsSync3(consolePath) || existsSync3(jsErrPath)) {
3395
+ if (existsSync4(consolePath) || existsSync4(jsErrPath)) {
2914
3396
  let consoleErrorCount = 0;
2915
3397
  let consoleWarnCount = 0;
2916
3398
  const recentConsoleErrors = [];
2917
3399
  let jsErrorCount = 0;
2918
3400
  const recentJsErrors = [];
2919
- if (existsSync3(consolePath)) {
3401
+ if (existsSync4(consolePath)) {
2920
3402
  try {
2921
- const logs = JSON.parse(readFileSync2(consolePath, "utf-8"));
3403
+ const logs = JSON.parse(readFileSync3(consolePath, "utf-8"));
2922
3404
  if (Array.isArray(logs)) {
2923
3405
  for (const entry of logs) {
2924
3406
  const lvl = (entry.type ?? entry.level ?? "").toLowerCase();
@@ -2934,9 +3416,9 @@ function createFailureBundle(flowName, platform, steps, error, artifactDir, atta
2934
3416
  } catch {
2935
3417
  }
2936
3418
  }
2937
- if (existsSync3(jsErrPath)) {
3419
+ if (existsSync4(jsErrPath)) {
2938
3420
  try {
2939
- const errs = JSON.parse(readFileSync2(jsErrPath, "utf-8"));
3421
+ const errs = JSON.parse(readFileSync3(jsErrPath, "utf-8"));
2940
3422
  if (Array.isArray(errs)) {
2941
3423
  jsErrorCount = errs.length;
2942
3424
  for (const e of errs.slice(-5)) {
@@ -2964,11 +3446,21 @@ function createFailureBundle(flowName, platform, steps, error, artifactDir, atta
2964
3446
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2965
3447
  failedStep,
2966
3448
  lastPassedStep,
3449
+ steps: steps.map((s, index) => ({
3450
+ index,
3451
+ command: s.command,
3452
+ selector: s.selector ?? null,
3453
+ durationMs: s.durationMs,
3454
+ status: s.status,
3455
+ ...s.error !== void 0 ? { error: s.error } : {}
3456
+ })),
2967
3457
  error: {
2968
3458
  message: error.message,
2969
3459
  category: error.category,
2970
3460
  suggestion: error.suggestion,
2971
- errorCode: error.errorCode
3461
+ errorCode: error.errorCode,
3462
+ ...error.location ? { location: error.location } : {},
3463
+ ...error.codeFrame ? { codeFrame: error.codeFrame } : {}
2972
3464
  },
2973
3465
  selectorContext,
2974
3466
  ...runtimeDiagnostics ? { runtimeDiagnostics } : {},
@@ -3030,17 +3522,21 @@ async function executeFlow(flow, driver, config) {
3030
3522
  typingDelay: flowDefaults.typingDelay ?? coordinatorConfig.typingDelay,
3031
3523
  hierarchyCacheTtl: flowDefaults.hierarchyCacheTtl ?? coordinatorConfig.hierarchyCacheTtl
3032
3524
  } : coordinatorConfig;
3033
- const app = createPromiseApp(driver, appId, mergedCoordinatorConfig, stepRecorder, {
3034
- platform,
3035
- storybook: config.storybook,
3036
- launchOptions
3037
- });
3038
3525
  const flowMeta = {
3039
3526
  flowFilePath: flow.sourcePath ?? "",
3040
3527
  flowName: flow.name,
3041
3528
  platform,
3042
3529
  updateBaselines: config.updateBaselines ?? false
3043
3530
  };
3531
+ const extraCleanups = [];
3532
+ const app = createPromiseApp(driver, appId, mergedCoordinatorConfig, stepRecorder, {
3533
+ platform,
3534
+ storybook: config.storybook,
3535
+ launchOptions,
3536
+ onRegisterCleanup: (fn) => extraCleanups.push(fn),
3537
+ flowContext: flowMeta,
3538
+ visualRegression: config.visualRegression
3539
+ });
3044
3540
  const expect = createPromiseExpect(
3045
3541
  driver,
3046
3542
  mergedCoordinatorConfig,
@@ -3053,7 +3549,7 @@ async function executeFlow(flow, driver, config) {
3053
3549
  const sessions = createSessions(
3054
3550
  sessionManager,
3055
3551
  async (opts) => {
3056
- const pwDriver = await Effect7.runPromise(
3552
+ const pwDriver = await Effect6.runPromise(
3057
3553
  makePlaywrightDriver({
3058
3554
  browser: opts.browser,
3059
3555
  headless: opts.headless ?? true,
@@ -3078,7 +3574,7 @@ async function executeFlow(flow, driver, config) {
3078
3574
  const outputDir = keep ? flowArtifactDir(artifactConfig, flow.name, platform) : artifactConfig.outputDir;
3079
3575
  let viewport;
3080
3576
  try {
3081
- const info = await Effect7.runPromise(Effect7.orDie(driver.getDeviceInfo()));
3577
+ const info = await Effect6.runPromise(Effect6.orDie(driver.getDeviceInfo()));
3082
3578
  if (info.screenWidth > 0 && info.screenHeight > 0) {
3083
3579
  viewport = { width: info.screenWidth, height: info.screenHeight };
3084
3580
  }
@@ -3148,7 +3644,10 @@ async function executeFlow(flow, driver, config) {
3148
3644
  platform,
3149
3645
  status: "failed",
3150
3646
  durationMs,
3151
- error: classifyError(normalized),
3647
+ error: classifyError(normalized, {
3648
+ flowFilePath: flow.sourcePath,
3649
+ fallbackStack: stepRecorder.getLastFailureStack?.()
3650
+ }),
3152
3651
  attachments,
3153
3652
  steps,
3154
3653
  scenarioSteps: flowCtx.__scenarioSteps
@@ -3156,7 +3655,7 @@ async function executeFlow(flow, driver, config) {
3156
3655
  };
3157
3656
  if (driver.beginFlow) {
3158
3657
  try {
3159
- await Effect7.runPromise(driver.beginFlow(flow.name));
3658
+ await Effect6.runPromise(driver.beginFlow(flow.name));
3160
3659
  } catch (error) {
3161
3660
  return buildFailureResult(error);
3162
3661
  }
@@ -3170,7 +3669,7 @@ async function executeFlow(flow, driver, config) {
3170
3669
  exportMp4: artifactConfig.video !== "off"
3171
3670
  });
3172
3671
  } else if (artifactConfig.video !== "off" && (platform === "android" || platform === "ios")) {
3173
- const info = await Effect7.runPromise(Effect7.orDie(driver.getDeviceInfo())).catch(
3672
+ const info = await Effect6.runPromise(Effect6.orDie(driver.getDeviceInfo())).catch(
3174
3673
  () => void 0
3175
3674
  );
3176
3675
  if (info?.deviceId) {
@@ -3239,7 +3738,10 @@ async function executeFlow(flow, driver, config) {
3239
3738
  platform,
3240
3739
  status: "failed",
3241
3740
  durationMs,
3242
- error: classifyError(flowError),
3741
+ error: classifyError(flowError, {
3742
+ flowFilePath: flow.sourcePath,
3743
+ fallbackStack: stepRecorder.getLastFailureStack?.()
3744
+ }),
3243
3745
  attachments,
3244
3746
  steps,
3245
3747
  scenarioSteps: flowCtx.__scenarioSteps
@@ -3256,7 +3758,8 @@ async function executeFlow(flow, driver, config) {
3256
3758
  stepRecorder.getSteps(),
3257
3759
  result.error,
3258
3760
  artDir,
3259
- attachments
3761
+ attachments,
3762
+ flow.sourcePath
3260
3763
  );
3261
3764
  writeFailureBundle(bundle, artDir);
3262
3765
  } catch {
@@ -3274,6 +3777,12 @@ async function executeFlow(flow, driver, config) {
3274
3777
  });
3275
3778
  }
3276
3779
  }
3780
+ for (const cleanup of extraCleanups.toReversed()) {
3781
+ try {
3782
+ await cleanup();
3783
+ } catch {
3784
+ }
3785
+ }
3277
3786
  try {
3278
3787
  await sessionManager.disconnectAll();
3279
3788
  } catch {
@@ -3306,7 +3815,8 @@ async function runParallel(config) {
3306
3815
  retries = 0,
3307
3816
  retryDelay = 0,
3308
3817
  bail,
3309
- durationHintsMs
3818
+ durationHintsMs,
3819
+ claimNextFlow
3310
3820
  } = config;
3311
3821
  const flows = orderFlowsLongestFirst(rawFlows, durationHintsMs);
3312
3822
  const start2 = Date.now();
@@ -3318,9 +3828,16 @@ async function runParallel(config) {
3318
3828
  const stats = { flowCount: 0, totalMs: 0 };
3319
3829
  while (true) {
3320
3830
  if (bail !== void 0 && failureCount >= bail) break;
3321
- const flowIdx = nextFlowIndex++;
3322
- if (flowIdx >= flows.length) break;
3323
- const flow = flows[flowIdx];
3831
+ let flow;
3832
+ if (claimNextFlow) {
3833
+ const claimed = await claimNextFlow();
3834
+ if (!claimed) break;
3835
+ flow = claimed;
3836
+ } else {
3837
+ const flowIdx = nextFlowIndex++;
3838
+ if (flowIdx >= flows.length) break;
3839
+ flow = flows[flowIdx];
3840
+ }
3324
3841
  let result;
3325
3842
  let attempts = 0;
3326
3843
  onFlowStart?.(flow.name, worker.name);
@@ -3347,7 +3864,7 @@ async function runParallel(config) {
3347
3864
  return { workerId: worker.id, stats };
3348
3865
  });
3349
3866
  const workerResults = await Promise.all(workerPromises);
3350
- if (bail !== void 0 && failureCount >= bail) {
3867
+ if (!claimNextFlow && bail !== void 0 && failureCount >= bail) {
3351
3868
  bailedOut = true;
3352
3869
  while (nextFlowIndex < flows.length) {
3353
3870
  const flow = flows[nextFlowIndex++];
@@ -3376,8 +3893,202 @@ async function runParallel(config) {
3376
3893
  };
3377
3894
  }
3378
3895
 
3896
+ // src/core/worker-pool.ts
3897
+ import { spawn as spawn3 } from "child_process";
3898
+ import { mkdir, readFile as readFile2, unlink, writeFile as writeFile2 } from "fs/promises";
3899
+ import { createServer } from "http";
3900
+ import { dirname } from "path";
3901
+ var DEFAULT_MAX_WORKERS_PER_PROCESS = 8;
3902
+ async function startSharedFlowQueueServer(orderedFlowNames) {
3903
+ const queue = [...orderedFlowNames];
3904
+ let cursor = 0;
3905
+ const server = createServer((req, res) => {
3906
+ if (req.url === "/claim" && (req.method === "POST" || req.method === "GET")) {
3907
+ const flowName = cursor < queue.length ? queue[cursor++] : null;
3908
+ const body = JSON.stringify({ flowName });
3909
+ res.writeHead(200, { "content-type": "application/json" });
3910
+ res.end(body);
3911
+ return;
3912
+ }
3913
+ res.writeHead(404);
3914
+ res.end();
3915
+ });
3916
+ await new Promise((resolve, reject) => {
3917
+ server.once("error", reject);
3918
+ server.listen(0, "127.0.0.1", () => resolve());
3919
+ });
3920
+ const addr = server.address();
3921
+ const url = `http://127.0.0.1:${addr.port}`;
3922
+ return {
3923
+ url,
3924
+ remaining: () => Math.max(0, queue.length - cursor),
3925
+ close: () => new Promise((resolve) => {
3926
+ server.close(() => resolve());
3927
+ })
3928
+ };
3929
+ }
3930
+ function createRemoteFlowClaimer(queueUrl) {
3931
+ const endpoint = `${queueUrl.replace(/\/+$/, "")}/claim`;
3932
+ return async () => {
3933
+ const res = await fetch(endpoint, { method: "POST" });
3934
+ if (!res.ok) return null;
3935
+ const data = await res.json();
3936
+ return typeof data.flowName === "string" ? data.flowName : null;
3937
+ };
3938
+ }
3939
+ function planProcessPool(totalWorkers, maxWorkersPerProcess = DEFAULT_MAX_WORKERS_PER_PROCESS, explicitProcesses) {
3940
+ const safeTotal = Math.max(1, Math.floor(totalWorkers));
3941
+ const safeMax = Math.max(1, Math.floor(maxWorkersPerProcess));
3942
+ const processCount = explicitProcesses !== void 0 && explicitProcesses >= 1 ? Math.min(Math.floor(explicitProcesses), safeTotal) : safeTotal <= safeMax ? 1 : Math.ceil(safeTotal / safeMax);
3943
+ if (processCount <= 1) {
3944
+ return {
3945
+ totalWorkers: safeTotal,
3946
+ maxWorkersPerProcess: safeMax,
3947
+ processCount: 1,
3948
+ workersPerProcess: [safeTotal]
3949
+ };
3950
+ }
3951
+ const base = Math.floor(safeTotal / processCount);
3952
+ const remainder = safeTotal % processCount;
3953
+ const workersPerProcess = Array.from(
3954
+ { length: processCount },
3955
+ (_v, i) => base + (i < remainder ? 1 : 0)
3956
+ );
3957
+ return {
3958
+ totalWorkers: safeTotal,
3959
+ maxWorkersPerProcess: safeMax,
3960
+ processCount,
3961
+ workersPerProcess
3962
+ };
3963
+ }
3964
+ function partitionFlowsAcrossProcesses(items, processCount, options) {
3965
+ const count = Math.max(1, Math.min(Math.floor(processCount), Math.max(1, items.length)));
3966
+ if (count === 1 || items.length === 0) {
3967
+ return items.length === 0 ? [] : [items];
3968
+ }
3969
+ const hints = options?.durationHintsMs;
3970
+ const getName = options?.getName;
3971
+ const known = hints ? Object.values(hints).filter((v) => typeof v === "number" && v > 0) : [];
3972
+ const defaultWeight = known.length > 0 ? known.reduce((a, b) => a + b, 0) / known.length : 1e3;
3973
+ const indexed = items.map((item, idx) => ({
3974
+ item,
3975
+ idx,
3976
+ weight: hints && getName ? hints[getName(item)] ?? defaultWeight : 1e3
3977
+ }));
3978
+ const ordered = hints && getName && Object.keys(hints).length > 0 ? indexed.toSorted((a, b) => b.weight - a.weight || a.idx - b.idx) : indexed;
3979
+ const loads = Array.from({ length: count }, () => 0);
3980
+ const buckets = Array.from({ length: count }, () => []);
3981
+ for (const entry of ordered) {
3982
+ let best = 0;
3983
+ for (let i = 1; i < count; i++) {
3984
+ if (loads[i] < loads[best]) best = i;
3985
+ }
3986
+ loads[best] = loads[best] + entry.weight;
3987
+ buckets[best].push({ item: entry.item, idx: entry.idx });
3988
+ }
3989
+ return buckets.map((bucket) => bucket.toSorted((a, b) => a.idx - b.idx).map((e) => e.item)).filter((b) => b.length > 0);
3990
+ }
3991
+ async function writeWorkerProcessReport(results, env = process.env) {
3992
+ const reportPath = env["SPANA_WORKER_REPORT_PATH"];
3993
+ if (!reportPath) return null;
3994
+ await mkdir(dirname(reportPath), { recursive: true });
3995
+ await writeFile2(reportPath, JSON.stringify({ results }, null, 2), "utf8");
3996
+ return reportPath;
3997
+ }
3998
+ async function defaultReadJsonReport(reportJsonPath) {
3999
+ let content;
4000
+ try {
4001
+ content = await readFile2(reportJsonPath, "utf8");
4002
+ } catch {
4003
+ return [];
4004
+ }
4005
+ const raw = JSON.parse(content);
4006
+ return Array.isArray(raw.results) ? raw.results : [];
4007
+ }
4008
+ async function runMultiProcessPool(options) {
4009
+ const plan = planProcessPool(
4010
+ options.totalWorkers,
4011
+ options.maxWorkersPerProcess,
4012
+ options.processes
4013
+ );
4014
+ const spawnFn = options.spawnFn ?? spawn3;
4015
+ const readReport = options.readReportFn ?? defaultReadJsonReport;
4016
+ const shouldCleanup = options.cleanupReportFiles !== false;
4017
+ const startedAt = Date.now();
4018
+ const processResults = await Promise.all(
4019
+ plan.workersPerProcess.map(async (workerCount, shardIdx) => {
4020
+ const shardStart = Date.now();
4021
+ const spec = options.buildShardCommand(shardIdx + 1, plan.processCount, workerCount);
4022
+ let exitCode = null;
4023
+ let spawnError;
4024
+ try {
4025
+ exitCode = await new Promise((resolve, reject) => {
4026
+ const child = spawnFn(spec.command, spec.args, {
4027
+ env: { ...process.env, ...spec.env },
4028
+ stdio: "inherit"
4029
+ });
4030
+ child.on("error", reject);
4031
+ child.on("close", (code) => resolve(code));
4032
+ });
4033
+ } catch (err) {
4034
+ spawnError = err instanceof Error ? err.message : String(err);
4035
+ }
4036
+ let shardResults = [];
4037
+ try {
4038
+ shardResults = await readReport(spec.reportJsonPath);
4039
+ } catch (err) {
4040
+ if (!spawnError) {
4041
+ spawnError = `Failed to parse shard ${shardIdx + 1} report: ${err instanceof Error ? err.message : String(err)}`;
4042
+ }
4043
+ }
4044
+ if (shouldCleanup) {
4045
+ try {
4046
+ await unlink(spec.reportJsonPath);
4047
+ } catch {
4048
+ }
4049
+ }
4050
+ if (exitCode !== 0 && shardResults.length === 0) {
4051
+ shardResults.push({
4052
+ name: `worker-process-${shardIdx + 1}`,
4053
+ platform: "web",
4054
+ status: "failed",
4055
+ durationMs: Date.now() - shardStart,
4056
+ error: {
4057
+ category: "driver-error",
4058
+ message: spawnError ?? `Worker process ${shardIdx + 1} exited with code ${exitCode ?? "unknown"}`
4059
+ }
4060
+ });
4061
+ }
4062
+ return {
4063
+ shardIndex: shardIdx + 1,
4064
+ workerCount,
4065
+ exitCode,
4066
+ durationMs: Date.now() - shardStart,
4067
+ results: shardResults,
4068
+ ...spawnError ? { error: spawnError } : {}
4069
+ };
4070
+ })
4071
+ );
4072
+ const results = processResults.flatMap((p) => p.results);
4073
+ const passed = results.filter((r) => r.status === "passed").length;
4074
+ const failed = results.filter((r) => r.status === "failed").length;
4075
+ const skipped = results.filter((r) => r.status === "skipped").length;
4076
+ const flaky = results.filter((r) => r.flaky).length;
4077
+ return {
4078
+ results,
4079
+ totalDurationMs: Date.now() - startedAt,
4080
+ passed,
4081
+ failed,
4082
+ skipped,
4083
+ flaky,
4084
+ processCount: plan.processCount,
4085
+ processResults
4086
+ };
4087
+ }
4088
+
3379
4089
  export {
3380
4090
  launchDirectCdpBrowser,
4091
+ UPLOAD_ATTACH_TIMEOUT_MS,
3381
4092
  makeLightweightCdpDriver,
3382
4093
  resolveWebEngine,
3383
4094
  speculativelyPrelaunchWebBrowser,
@@ -3387,6 +4098,8 @@ export {
3387
4098
  buildElectrobunRuntime,
3388
4099
  buildLocalAndroidRuntime,
3389
4100
  buildLocalIOSRuntime,
4101
+ formatCodeFrame,
4102
+ extractCodeFrame,
3390
4103
  classifyError,
3391
4104
  exportFramesToMp4,
3392
4105
  startCdpScreencastRecorder,
@@ -3395,6 +4108,13 @@ export {
3395
4108
  buildPlaybackTraceFromSteps,
3396
4109
  executeFlow,
3397
4110
  orderFlowsLongestFirst,
3398
- runParallel
4111
+ runParallel,
4112
+ DEFAULT_MAX_WORKERS_PER_PROCESS,
4113
+ startSharedFlowQueueServer,
4114
+ createRemoteFlowClaimer,
4115
+ planProcessPool,
4116
+ partitionFlowsAcrossProcesses,
4117
+ writeWorkerProcessReport,
4118
+ runMultiProcessPool
3399
4119
  };
3400
- //# sourceMappingURL=chunk-6B5Y75V4.js.map
4120
+ //# sourceMappingURL=chunk-ALPQES3J.js.map