spana-test 0.9.0 → 0.11.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 (94) hide show
  1. package/dist/agent/index.d.ts +2 -2
  2. package/dist/agent/index.js +11 -8
  3. package/dist/agent-fixture-5C4MCWRD.js +20 -0
  4. package/dist/{allure-RAEK4SIH.js → allure-FGVR5LND.js} +5 -1
  5. package/dist/allure-FGVR5LND.js.map +1 -0
  6. package/dist/app-RSDPDTKT.js +10 -0
  7. package/dist/cache-command-PANUAEMZ.js +12 -0
  8. package/dist/{chunk-Y2RZNOKU.js → chunk-26NJXP55.js} +2 -2
  9. package/dist/{chunk-ALPQES3J.js → chunk-3IZMPNE7.js} +549 -2002
  10. package/dist/chunk-3IZMPNE7.js.map +1 -0
  11. package/dist/chunk-4KK4E3N3.js +3587 -0
  12. package/dist/chunk-4KK4E3N3.js.map +1 -0
  13. package/dist/{chunk-IGTK5MHB.js → chunk-4SA7JK5D.js} +23 -15
  14. package/dist/chunk-4SA7JK5D.js.map +1 -0
  15. package/dist/{chunk-PLE7RFQE.js → chunk-64UZQP7Z.js} +52 -3
  16. package/dist/chunk-64UZQP7Z.js.map +1 -0
  17. package/dist/chunk-6PTUVG6A.js +127 -0
  18. package/dist/chunk-6PTUVG6A.js.map +1 -0
  19. package/dist/chunk-FPQAJNE3.js +2874 -0
  20. package/dist/chunk-FPQAJNE3.js.map +1 -0
  21. package/dist/{chunk-3UVSUVHW.js → chunk-FXBWACUT.js} +530 -3360
  22. package/dist/chunk-FXBWACUT.js.map +1 -0
  23. package/dist/chunk-OPTNFLBL.js +556 -0
  24. package/dist/chunk-OPTNFLBL.js.map +1 -0
  25. package/dist/chunk-S7MSBZ3F.js +72 -0
  26. package/dist/chunk-S7MSBZ3F.js.map +1 -0
  27. package/dist/chunk-SGZMO456.js +2125 -0
  28. package/dist/chunk-SGZMO456.js.map +1 -0
  29. package/dist/{chunk-2KRVN4WN.js → chunk-SIJJVN2D.js} +358 -3
  30. package/dist/chunk-SIJJVN2D.js.map +1 -0
  31. package/dist/{chunk-SF7UYW4I.js → chunk-VUNH4AJD.js} +4 -4
  32. package/dist/{chunk-UEWZ2EXL.js → chunk-WS2TVNMY.js} +107 -1976
  33. package/dist/chunk-WS2TVNMY.js.map +1 -0
  34. package/dist/{chunk-FP6PVHHR.js → chunk-WZAQANN6.js} +2 -2
  35. package/dist/{chunk-JZZ2W2XH.js → chunk-XA6LWLZQ.js} +65 -3
  36. package/dist/chunk-XA6LWLZQ.js.map +1 -0
  37. package/dist/cli.js +195 -17
  38. package/dist/cli.js.map +1 -1
  39. package/dist/config-loader-CNGIW2XK.js +9 -0
  40. package/dist/{console-BGAK7Z2L.js → console-DIYEJSSP.js} +9 -2
  41. package/dist/console-DIYEJSSP.js.map +1 -0
  42. package/dist/{discover-RLSKEBAX.js → discover-NKDMB4UI.js} +3 -3
  43. package/dist/{doctor-command-YTCQ2SC7.js → doctor-command-6ZVJWCW7.js} +5 -4
  44. package/dist/{doctor-command-YTCQ2SC7.js.map → doctor-command-6ZVJWCW7.js.map} +1 -1
  45. package/dist/{app-DSh1ejLh.d.ts → flow-DddAj1xv.d.ts} +1002 -355
  46. package/dist/gherkin/steps.d.ts +1 -2
  47. package/dist/{html-JO2YNRWX.js → html-FLMWPFQD.js} +2 -1
  48. package/dist/html-FLMWPFQD.js.map +1 -0
  49. package/dist/index.d.ts +498 -131
  50. package/dist/index.js +491 -278
  51. package/dist/index.js.map +1 -1
  52. package/dist/{junit-HLC62MK6.js → junit-CGB3LKHD.js} +3 -2
  53. package/dist/junit-CGB3LKHD.js.map +1 -0
  54. package/dist/local-DM3YBSV5.js +31 -0
  55. package/dist/{runner-TF4OKPYP.js → runner-WOVZWUQR.js} +6 -2
  56. package/dist/runner-WOVZWUQR.js.map +1 -0
  57. package/dist/{server-IS4K5FCT.js → server-ING5D5ZJ.js} +2 -2
  58. package/dist/server-ING5D5ZJ.js.map +1 -0
  59. package/dist/{server-4YLBAZEM.js → server-JNQ2PLCC.js} +17 -14
  60. package/dist/{server-4YLBAZEM.js.map → server-JNQ2PLCC.js.map} +1 -1
  61. package/dist/session-5TNWVGQQ.js +21 -0
  62. package/dist/session-5TNWVGQQ.js.map +1 -0
  63. package/dist/{session-CgvT-Oso.d.ts → session-uT8xL03K.d.ts} +5 -1
  64. package/dist/{studio-command-RFPV2DS7.js → studio-command-KK7A3KN6.js} +2 -2
  65. package/dist/{test-command-UEJG5AI6.js → test-command-QGIJBRH7.js} +278 -41
  66. package/dist/test-command-QGIJBRH7.js.map +1 -0
  67. package/dist/{validator-BLOLIHUY.js → validator-WO5IL7IY.js} +3 -3
  68. package/dist/validator-WO5IL7IY.js.map +1 -0
  69. package/package.json +10 -10
  70. package/dist/allure-RAEK4SIH.js.map +0 -1
  71. package/dist/chunk-2KRVN4WN.js.map +0 -1
  72. package/dist/chunk-3UVSUVHW.js.map +0 -1
  73. package/dist/chunk-ALPQES3J.js.map +0 -1
  74. package/dist/chunk-IGTK5MHB.js.map +0 -1
  75. package/dist/chunk-JZZ2W2XH.js.map +0 -1
  76. package/dist/chunk-PLE7RFQE.js.map +0 -1
  77. package/dist/chunk-UEWZ2EXL.js.map +0 -1
  78. package/dist/config-loader-F5YAY7RP.js +0 -9
  79. package/dist/console-BGAK7Z2L.js.map +0 -1
  80. package/dist/flow-CSMwD9Fh.d.ts +0 -69
  81. package/dist/html-JO2YNRWX.js.map +0 -1
  82. package/dist/junit-HLC62MK6.js.map +0 -1
  83. package/dist/session-K7FCRKOC.js +0 -18
  84. package/dist/test-command-UEJG5AI6.js.map +0 -1
  85. /package/dist/{config-loader-F5YAY7RP.js.map → agent-fixture-5C4MCWRD.js.map} +0 -0
  86. /package/dist/{discover-RLSKEBAX.js.map → app-RSDPDTKT.js.map} +0 -0
  87. /package/dist/{runner-TF4OKPYP.js.map → cache-command-PANUAEMZ.js.map} +0 -0
  88. /package/dist/{chunk-Y2RZNOKU.js.map → chunk-26NJXP55.js.map} +0 -0
  89. /package/dist/{chunk-SF7UYW4I.js.map → chunk-VUNH4AJD.js.map} +0 -0
  90. /package/dist/{chunk-FP6PVHHR.js.map → chunk-WZAQANN6.js.map} +0 -0
  91. /package/dist/{server-IS4K5FCT.js.map → config-loader-CNGIW2XK.js.map} +0 -0
  92. /package/dist/{session-K7FCRKOC.js.map → discover-NKDMB4UI.js.map} +0 -0
  93. /package/dist/{validator-BLOLIHUY.js.map → local-DM3YBSV5.js.map} +0 -0
  94. /package/dist/{studio-command-RFPV2DS7.js.map → studio-command-KK7A3KN6.js.map} +0 -0
@@ -1,30 +1,34 @@
1
1
  import {
2
2
  connectPlaywrightOverCDP,
3
3
  connectPlaywrightOverWS,
4
- createPromiseApp,
5
- createPromiseExpect,
6
4
  createUiAutomator2Driver,
7
5
  createWDADriver,
8
6
  ensureWarmBrowserDaemon,
9
- flattenElements,
10
7
  launchPlaywrightBrowser,
11
8
  makeElectronDriver,
12
9
  makePlaywrightDriver,
13
- mergeLaunchOptions,
14
10
  parseAndroidHierarchy,
15
11
  parseIOSHierarchy,
16
12
  parseWebHierarchy,
17
13
  resolveNetworkConditions,
18
14
  setupUiAutomator2
19
- } from "./chunk-3UVSUVHW.js";
15
+ } from "./chunk-FXBWACUT.js";
20
16
  import {
21
17
  CdpDomChannel,
22
- DriverError,
23
- SPANA_INJECTED_RUNTIME_SCRIPT,
24
- buildDomFindElementScript,
25
18
  createSpanaBridgeChannel,
26
19
  makeElectrobunDriver
27
- } from "./chunk-UEWZ2EXL.js";
20
+ } from "./chunk-WS2TVNMY.js";
21
+ import {
22
+ adbReverse,
23
+ adbReverseRemove,
24
+ ensureAndroidDevice
25
+ } from "./chunk-2AFWVHQK.js";
26
+ import {
27
+ connectPhysicalDevice,
28
+ ensureAppInstalled,
29
+ ensureIOSSimulator,
30
+ firstIOSPhysicalDevice
31
+ } from "./chunk-WV3ALL3H.js";
28
32
  import {
29
33
  setupWDA
30
34
  } from "./chunk-VP6V4XEJ.js";
@@ -33,95 +37,121 @@ import {
33
37
  registerWarmDaemon,
34
38
  updateWarmDaemonSession
35
39
  } from "./chunk-Z6K4QQAR.js";
36
- import {
37
- connectPhysicalDevice,
38
- ensureAppInstalled,
39
- ensureIOSSimulator,
40
- firstIOSPhysicalDevice
41
- } from "./chunk-WV3ALL3H.js";
42
40
  import {
43
41
  allocateFreePort,
44
42
  allocatePort
45
43
  } from "./chunk-JPZCZHL4.js";
46
44
  import {
47
- adbReverse,
48
- adbReverseRemove,
49
- ensureAndroidDevice
50
- } from "./chunk-2AFWVHQK.js";
45
+ DriverError,
46
+ SPANA_INJECTED_RUNTIME_SCRIPT,
47
+ buildDomFindElementScript
48
+ } from "./chunk-SGZMO456.js";
49
+
50
+ // src/runtime/local.ts
51
+ import { Effect as Effect2 } from "effect";
51
52
 
52
- // src/core/session-manager.ts
53
+ // src/drivers/cdp-browser.ts
54
+ import { spawn } from "child_process";
55
+ import { createHash } from "crypto";
56
+ import { existsSync as existsSync2, mkdtempSync, rmSync } from "fs";
57
+ import { copyFile, readFile, writeFile } from "fs/promises";
58
+ import { tmpdir } from "os";
59
+ import { join as join2 } from "path";
53
60
  import { Effect } from "effect";
54
- function createSessions(manager, driverFactory, coordinatorConfig) {
55
- const coordConfig = coordinatorConfig ?? { parse: parseWebHierarchy };
56
- return {
57
- async open(opts) {
58
- const existing = manager.all().find((s) => s.name === opts.name);
59
- if (existing) {
60
- throw new Error(`Session "${opts.name}" already exists`);
61
- }
62
- const driver = await driverFactory(opts);
63
- const baseUrl = opts.baseUrl ?? "http://localhost:3000";
64
- await Effect.runPromise(driver.launchApp(baseUrl));
65
- const app = createPromiseApp(driver, baseUrl, coordConfig, void 0, {
66
- platform: "web"
67
- });
68
- const expect = createPromiseExpect(driver, coordConfig);
69
- const session = {
70
- name: opts.name,
71
- platform: "web",
72
- app,
73
- expect,
74
- async disconnect() {
75
- await Effect.runPromise(driver.killApp(baseUrl));
76
- manager.remove(opts.name);
77
- }
78
- };
79
- const cleanup = async () => {
80
- await Effect.runPromise(driver.killApp(baseUrl));
81
- };
82
- manager.register(session, cleanup);
83
- return session;
84
- }
85
- };
61
+
62
+ // src/drivers/browser-extensions.ts
63
+ import { existsSync, readFileSync, statSync } from "fs";
64
+ import { join, resolve } from "path";
65
+ function resolveBrowserExtensions(extensionPaths, baseDir = process.cwd()) {
66
+ return extensionPaths.map((rawPath) => {
67
+ const absPath = resolve(baseDir, rawPath);
68
+ if (!existsSync(absPath) || !statSync(absPath).isDirectory()) {
69
+ throw new Error(`Browser extension directory not found: ${absPath}`);
70
+ }
71
+ const manifestPath = join(absPath, "manifest.json");
72
+ if (!existsSync(manifestPath)) {
73
+ throw new Error(`Browser extension at ${absPath} is missing manifest.json`);
74
+ }
75
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
76
+ const manifestVersion = Number(manifest["manifest_version"] ?? 3);
77
+ const action = manifest["action"] ?? manifest["browser_action"];
78
+ return {
79
+ path: absPath,
80
+ name: String(manifest["name"] ?? "Unnamed Extension"),
81
+ version: String(manifest["version"] ?? "0.0.0"),
82
+ manifestVersion,
83
+ ...action?.default_popup ? { defaultPopup: action.default_popup } : {}
84
+ };
85
+ });
86
+ }
87
+ function applyExtensionChromeArgs(baseArgs, extensions) {
88
+ if (extensions.length === 0) return [...baseArgs];
89
+ const paths = extensions.map((e) => typeof e === "string" ? resolve(e) : e.path);
90
+ const joined = paths.join(",");
91
+ const filtered = baseArgs.filter(
92
+ (arg) => arg !== "--disable-extensions" && !arg.startsWith("--disable-extensions-except=") && !arg.startsWith("--load-extension=")
93
+ );
94
+ return [...filtered, `--disable-extensions-except=${joined}`, `--load-extension=${joined}`];
86
95
  }
87
- var SessionManager = class {
88
- sessions = [];
89
- all() {
90
- return this.sessions.map((s) => s.session);
96
+ async function getLoadedExtensions(cdp) {
97
+ const res = await cdp.send("Target.getTargets");
98
+ const targets = Array.isArray(res?.targetInfos) ? res.targetInfos : [];
99
+ const results = [];
100
+ for (const t of targets) {
101
+ const url = String(t.url ?? "");
102
+ const match = url.match(/^chrome-extension:\/\/([a-z0-9]{16,})\//i);
103
+ if (!match?.[1]) continue;
104
+ results.push({
105
+ extensionId: match[1],
106
+ targetId: String(t.targetId ?? ""),
107
+ type: String(t.type ?? "unknown"),
108
+ url,
109
+ ...t.title ? { title: t.title } : {}
110
+ });
91
111
  }
92
- register(session, cleanup) {
93
- this.sessions.push({ session, cleanup });
112
+ return results;
113
+ }
114
+ async function runOAuthPopupFlow(app, options) {
115
+ const timeoutMs = options.timeoutMs ?? 1e4;
116
+ const pollIntervalMs = options.pollIntervalMs ?? 100;
117
+ const returnToOpener = options.returnToOpener !== false;
118
+ const beforeTabs = await app.getTabIds();
119
+ const openerTabIndex = Math.max(0, beforeTabs.length - 1);
120
+ const beforeSet = new Set(beforeTabs);
121
+ await options.trigger();
122
+ const deadline = Date.now() + timeoutMs;
123
+ let popupIndex = -1;
124
+ let popupTabId = "";
125
+ while (Date.now() < deadline) {
126
+ const currentTabs = await app.getTabIds();
127
+ const foundIdx = currentTabs.findIndex((id) => !beforeSet.has(id));
128
+ if (foundIdx >= 0) {
129
+ popupIndex = foundIdx;
130
+ popupTabId = currentTabs[foundIdx];
131
+ break;
132
+ }
133
+ await new Promise((r) => setTimeout(r, pollIntervalMs));
94
134
  }
95
- remove(name) {
96
- this.sessions = this.sessions.filter((s) => s.session.name !== name);
135
+ if (popupIndex < 0) {
136
+ throw new Error(`Timed out after ${timeoutMs}ms waiting for OAuth popup tab to open.`);
97
137
  }
98
- async disconnectAll() {
99
- const errors = [];
100
- for (const entry of [...this.sessions].toReversed()) {
101
- try {
102
- await entry.cleanup();
103
- } catch (err) {
104
- errors.push(err);
138
+ await app.switchToTab(popupIndex);
139
+ try {
140
+ await options.inPopup(app);
141
+ } finally {
142
+ if (returnToOpener) {
143
+ const remaining = await app.getTabIds().catch(() => []);
144
+ if (remaining.length > 0) {
145
+ const targetIdx = Math.min(openerTabIndex, remaining.length - 1);
146
+ await app.switchToTab(targetIdx).catch(() => {
147
+ });
105
148
  }
106
149
  }
107
- this.sessions = [];
108
- if (errors.length > 0) {
109
- console.warn(
110
- `SessionManager: ${errors.length} error(s) during cleanup:`,
111
- errors.map((e) => e instanceof Error ? e.message : String(e))
112
- );
113
- }
114
150
  }
115
- };
151
+ return { popupTabId, openerTabIndex };
152
+ }
116
153
 
117
154
  // src/drivers/cdp-browser.ts
118
- import { spawn } from "child_process";
119
- import { createHash } from "crypto";
120
- import { existsSync, mkdtempSync, rmSync } from "fs";
121
- import { copyFile, readFile, writeFile } from "fs/promises";
122
- import { tmpdir } from "os";
123
- import { join } from "path";
124
- import { Effect as Effect2 } from "effect";
125
155
  var INSTANT_ANIMATIONS_CDP_SCRIPT = `
126
156
  (() => {
127
157
  const inject = () => {
@@ -144,7 +174,7 @@ function resolveDirectCdpScopeKey(scope) {
144
174
  return `cdp-${cwdHash}`;
145
175
  }
146
176
  function resolveChromiumExecutable(explicit) {
147
- if (explicit && existsSync(explicit)) return explicit;
177
+ if (explicit && existsSync2(explicit)) return explicit;
148
178
  const candidates = process.platform === "darwin" ? [
149
179
  "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
150
180
  "/Applications/Chromium.app/Contents/MacOS/Chromium",
@@ -160,7 +190,7 @@ function resolveChromiumExecutable(explicit) {
160
190
  "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
161
191
  ];
162
192
  for (const path of candidates) {
163
- if (existsSync(path)) return path;
193
+ if (existsSync2(path)) return path;
164
194
  }
165
195
  return explicit ?? "google-chrome";
166
196
  }
@@ -208,7 +238,7 @@ async function launchDirectCdpBrowser(options = {}) {
208
238
  try {
209
239
  const { chromium } = await import("playwright-core");
210
240
  const pwPath = chromium.executablePath();
211
- if (pwPath && existsSync(pwPath)) {
241
+ if (pwPath && existsSync2(pwPath)) {
212
242
  execPath = pwPath;
213
243
  }
214
244
  } catch {
@@ -216,8 +246,8 @@ async function launchDirectCdpBrowser(options = {}) {
216
246
  }
217
247
  execPath = resolveChromiumExecutable(execPath);
218
248
  const port = await allocateFreePort(9350);
219
- const userDataDir = mkdtempSync(join(tmpdir(), "spana-cdp-profile-"));
220
- const chromeArgs = [
249
+ const userDataDir = mkdtempSync(join2(tmpdir(), "spana-cdp-profile-"));
250
+ const baseChromeArgs = [
221
251
  ...options.headless !== false ? ["--headless=new"] : [],
222
252
  `--remote-debugging-port=${port}`,
223
253
  "--remote-debugging-address=127.0.0.1",
@@ -239,6 +269,8 @@ async function launchDirectCdpBrowser(options = {}) {
239
269
  ...options.args ?? [],
240
270
  "about:blank"
241
271
  ];
272
+ const resolvedExts = options.extensions && options.extensions.length > 0 ? resolveBrowserExtensions(options.extensions) : [];
273
+ const chromeArgs = resolvedExts.length > 0 ? applyExtensionChromeArgs(baseChromeArgs, resolvedExts) : baseChromeArgs;
242
274
  const child = spawn(execPath, chromeArgs, {
243
275
  detached: Boolean(options.warmBrowser),
244
276
  stdio: "ignore"
@@ -391,7 +423,7 @@ var RESOURCE_BLOCK_PATTERNS = {
391
423
  stylesheet: ["*.css"]
392
424
  };
393
425
  function makeLightweightCdpDriver(options) {
394
- return Effect2.gen(function* () {
426
+ return Effect.gen(function* () {
395
427
  const isBrowserWs = options.cdpUrl.includes("/devtools/browser/");
396
428
  const useContexts = Boolean(
397
429
  options.useBrowserContexts || options.freshContextPerFlow || isBrowserWs
@@ -400,7 +432,7 @@ function makeLightweightCdpDriver(options) {
400
432
  const httpEndpoint = isWs ? options.cdpUrl.replace(/^ws(s?):\/\//, "http$1://").replace(/\/devtools\/.*$/, "") : options.cdpUrl.replace(/\/+$/, "");
401
433
  let connectWsUrl = isWs ? options.cdpUrl : void 0;
402
434
  if (useContexts && !connectWsUrl) {
403
- connectWsUrl = yield* Effect2.tryPromise({
435
+ connectWsUrl = yield* Effect.tryPromise({
404
436
  try: () => fetchBrowserWsUrl(httpEndpoint, 5e3),
405
437
  catch: (e) => new DriverError({
406
438
  message: `Failed to resolve browser CDP WebSocket at ${options.cdpUrl}: ${e}`
@@ -413,19 +445,20 @@ function makeLightweightCdpDriver(options) {
413
445
  fetchFn: options.fetchFn,
414
446
  createWebSocket: options.createWebSocket
415
447
  });
416
- yield* Effect2.tryPromise({
448
+ yield* Effect.tryPromise({
417
449
  try: () => cdpChannel.connect(),
418
450
  catch: (e) => new DriverError({
419
451
  message: `Failed to connect lightweight CDP browser at ${options.cdpUrl}: ${e}`
420
452
  })
421
453
  });
422
- const width = options.viewport?.width ?? 1280;
423
- const height = options.viewport?.height ?? 720;
454
+ let width = options.viewport?.width ?? 1280;
455
+ let height = options.viewport?.height ?? 720;
424
456
  const label = options.engineLabel ?? "cdp";
425
457
  let activeSlot;
426
458
  let prefetchedSlotPromise;
427
459
  let hasRunFirstFlow = false;
428
460
  let activeAuthenticatorId;
461
+ let dialogHandler = null;
429
462
  const backgroundDisposals = [];
430
463
  const consoleLogs = [];
431
464
  const jsErrors = [];
@@ -439,17 +472,27 @@ function makeLightweightCdpDriver(options) {
439
472
  const pendingDownloadGuids = /* @__PURE__ */ new Map();
440
473
  cdpChannel.onEvent("Browser.downloadWillBegin", (params) => {
441
474
  if (params?.guid && downloadDir) {
442
- pendingDownloadGuids.set(String(params.guid), join(downloadDir, String(params.guid)));
475
+ const guid = String(params.guid);
476
+ pendingDownloadGuids.set(guid, {
477
+ filePath: join2(downloadDir, guid),
478
+ suggestedFilename: String(params?.suggestedFilename ?? guid),
479
+ url: String(params?.url ?? "")
480
+ });
443
481
  }
444
482
  });
445
483
  cdpChannel.onEvent("Browser.downloadProgress", (params) => {
446
484
  if (params?.state === "completed" && params?.guid) {
447
- const filePath = pendingDownloadGuids.get(String(params.guid)) ?? (downloadDir ? join(downloadDir, String(params.guid)) : "");
448
- pendingDownloadGuids.delete(String(params.guid));
449
- if (!filePath) return;
485
+ const guid = String(params.guid);
486
+ const entry = pendingDownloadGuids.get(guid) ?? (downloadDir ? {
487
+ filePath: join2(downloadDir, guid),
488
+ suggestedFilename: guid,
489
+ url: ""
490
+ } : void 0);
491
+ pendingDownloadGuids.delete(guid);
492
+ if (!entry) return;
450
493
  const waiter = downloadWaiters.shift();
451
- if (waiter) waiter.resolve(filePath);
452
- else completedDownloads.push(filePath);
494
+ if (waiter) waiter.resolve(entry);
495
+ else completedDownloads.push(entry);
453
496
  }
454
497
  });
455
498
  const loadStorageStateFile = async (path) => {
@@ -556,6 +599,41 @@ function makeLightweightCdpDriver(options) {
556
599
  await cdpChannel.sendCommand("Fetch.enable", { patterns: [{ urlPattern: "*" }] }, sessionId).catch(() => {
557
600
  });
558
601
  }
602
+ if (options.emulation) {
603
+ const emuFeatures = [];
604
+ if (options.emulation.colorScheme !== void 0) {
605
+ emuFeatures.push({
606
+ name: "prefers-color-scheme",
607
+ value: options.emulation.colorScheme === "no-preference" ? "" : options.emulation.colorScheme
608
+ });
609
+ }
610
+ if (options.emulation.reducedMotion !== void 0) {
611
+ emuFeatures.push({
612
+ name: "prefers-reduced-motion",
613
+ value: options.emulation.reducedMotion === "no-preference" ? "" : options.emulation.reducedMotion
614
+ });
615
+ }
616
+ if (emuFeatures.length > 0) {
617
+ await cdpChannel.sendCommand("Emulation.setEmulatedMedia", { features: emuFeatures }, sessionId).catch(() => {
618
+ });
619
+ }
620
+ if (options.emulation.locale) {
621
+ await cdpChannel.sendCommand(
622
+ "Emulation.setLocaleOverride",
623
+ { locale: options.emulation.locale },
624
+ sessionId
625
+ ).catch(() => {
626
+ });
627
+ }
628
+ if (options.emulation.timezoneId) {
629
+ await cdpChannel.sendCommand(
630
+ "Emulation.setTimezoneOverride",
631
+ { timezoneId: options.emulation.timezoneId },
632
+ sessionId
633
+ ).catch(() => {
634
+ });
635
+ }
636
+ }
559
637
  let authenticatorId;
560
638
  if (options.virtualAuthenticator) {
561
639
  const authOpts = typeof options.virtualAuthenticator === "object" ? options.virtualAuthenticator : void 0;
@@ -694,8 +772,51 @@ function makeLightweightCdpDriver(options) {
694
772
  }
695
773
  });
696
774
  cdpChannel.onEvent("Page.javascriptDialogOpening", (params, sid) => {
697
- const accept = params?.type === "beforeunload";
698
- void cdpChannel.sendCommand("Page.handleJavaScriptDialog", { accept }, sid ?? null).catch(() => {
775
+ const targetSid = sid ?? null;
776
+ const dialogType = String(params?.type ?? "alert");
777
+ const message = String(params?.message ?? "");
778
+ const defaultValue = String(params?.defaultPrompt ?? "");
779
+ const activeHandler = dialogHandler;
780
+ if (!activeHandler) {
781
+ const accept = dialogType === "beforeunload";
782
+ void cdpChannel.sendCommand("Page.handleJavaScriptDialog", { accept }, targetSid).catch(() => {
783
+ });
784
+ return;
785
+ }
786
+ let handled = false;
787
+ const info = {
788
+ type: dialogType,
789
+ message,
790
+ defaultValue,
791
+ accept: async (promptText) => {
792
+ if (handled) return;
793
+ handled = true;
794
+ await cdpChannel.sendCommand(
795
+ "Page.handleJavaScriptDialog",
796
+ {
797
+ accept: true,
798
+ ...promptText !== void 0 ? { promptText } : {}
799
+ },
800
+ targetSid
801
+ );
802
+ },
803
+ dismiss: async () => {
804
+ if (handled) return;
805
+ handled = true;
806
+ await cdpChannel.sendCommand("Page.handleJavaScriptDialog", { accept: false }, targetSid);
807
+ }
808
+ };
809
+ void Promise.resolve(activeHandler(info)).catch(() => {
810
+ }).finally(() => {
811
+ if (!handled) {
812
+ handled = true;
813
+ void cdpChannel.sendCommand(
814
+ "Page.handleJavaScriptDialog",
815
+ { accept: dialogType === "beforeunload" },
816
+ targetSid
817
+ ).catch(() => {
818
+ });
819
+ }
699
820
  });
700
821
  });
701
822
  cdpChannel.setFrameOffsetResolver(async (child) => {
@@ -769,7 +890,7 @@ function makeLightweightCdpDriver(options) {
769
890
  });
770
891
  });
771
892
  if (useContexts) {
772
- yield* Effect2.tryPromise({
893
+ yield* Effect.tryPromise({
773
894
  try: () => cdpChannel.sendCommand(
774
895
  "Target.setAutoAttach",
775
896
  {
@@ -782,8 +903,8 @@ function makeLightweightCdpDriver(options) {
782
903
  ).catch(() => {
783
904
  }),
784
905
  catch: () => new DriverError({ message: "Failed to enable Target.setAutoAttach" })
785
- }).pipe(Effect2.catchAll(() => Effect2.void));
786
- activeSlot = yield* Effect2.tryPromise({
906
+ }).pipe(Effect.catchAll(() => Effect.void));
907
+ activeSlot = yield* Effect.tryPromise({
787
908
  try: () => createContextSlot(options.storageState),
788
909
  catch: (e) => new DriverError({ message: `Failed to create direct CDP browser context: ${e}` })
789
910
  });
@@ -821,12 +942,54 @@ function makeLightweightCdpDriver(options) {
821
942
  fetchInterceptEnabled = true;
822
943
  await cdpChannel.sendCommand("Fetch.enable", { patterns: [{ urlPattern: "*" }] });
823
944
  };
945
+ let coverageSession;
824
946
  const service = {
825
947
  domChannel: cdpChannel,
826
- beginFlow: (_flowName) => Effect2.tryPromise({
948
+ startJSCoverage: () => Effect.tryPromise({
949
+ try: async () => {
950
+ const session = activeSlot?.sessionId ?? null;
951
+ await cdpChannel.sendCommand("Profiler.enable", {}, session);
952
+ try {
953
+ await cdpChannel.sendCommand(
954
+ "Profiler.startPreciseCoverage",
955
+ { callCount: true, detailed: true },
956
+ session
957
+ );
958
+ coverageSession = session;
959
+ } catch (error) {
960
+ await cdpChannel.sendCommand("Profiler.disable", {}, session).catch(() => {
961
+ });
962
+ throw error;
963
+ }
964
+ },
965
+ catch: (error) => new DriverError({ message: `CDP JavaScript coverage is unavailable: ${error}` })
966
+ }),
967
+ stopJSCoverage: () => Effect.tryPromise({
968
+ try: async () => {
969
+ const session = coverageSession;
970
+ coverageSession = void 0;
971
+ if (session === void 0) throw new Error("JavaScript coverage was not started");
972
+ try {
973
+ const { result } = await cdpChannel.sendCommand(
974
+ "Profiler.takePreciseCoverage",
975
+ {},
976
+ session
977
+ );
978
+ return result.filter(({ url }) => url && !url.startsWith("extensions::"));
979
+ } finally {
980
+ await cdpChannel.sendCommand("Profiler.stopPreciseCoverage", {}, session).catch(() => {
981
+ });
982
+ await cdpChannel.sendCommand("Profiler.disable", {}, session).catch(() => {
983
+ });
984
+ }
985
+ },
986
+ catch: (error) => new DriverError({ message: `CDP JavaScript coverage collection failed: ${error}` })
987
+ }),
988
+ beginFlow: (_flowName) => Effect.tryPromise({
827
989
  try: async () => {
828
990
  consoleLogs.length = 0;
829
991
  jsErrors.length = 0;
992
+ dialogHandler = null;
830
993
  cdpChannel.clearChildSessions();
831
994
  if (useContexts && options.freshContextPerFlow && hasRunFirstFlow) {
832
995
  if (options.contextIsolation === "hot-cache" && activeSlot) {
@@ -871,14 +1034,14 @@ function makeLightweightCdpDriver(options) {
871
1034
  },
872
1035
  catch: (e) => new DriverError({ message: `CDP beginFlow failed: ${e}` })
873
1036
  }),
874
- dumpHierarchy: () => Effect2.tryPromise({
1037
+ dumpHierarchy: () => Effect.tryPromise({
875
1038
  try: async () => {
876
1039
  const raw = await cdpChannel.evaluate(CDP_DUMP_HIERARCHY_SCRIPT);
877
1040
  return raw ?? "{}";
878
1041
  },
879
1042
  catch: (e) => new DriverError({ message: `CDP dumpHierarchy failed: ${e}` })
880
1043
  }),
881
- tapAtCoordinate: (x, y) => Effect2.tryPromise({
1044
+ tapAtCoordinate: (x, y) => Effect.tryPromise({
882
1045
  try: async () => {
883
1046
  await Promise.all([
884
1047
  cdpChannel.sendCommand("Input.dispatchMouseEvent", {
@@ -904,7 +1067,7 @@ function makeLightweightCdpDriver(options) {
904
1067
  },
905
1068
  catch: (e) => new DriverError({ message: `CDP tap failed at (${x}, ${y}): ${e}` })
906
1069
  }),
907
- doubleTapAtCoordinate: (x, y) => Effect2.tryPromise({
1070
+ doubleTapAtCoordinate: (x, y) => Effect.tryPromise({
908
1071
  try: async () => {
909
1072
  await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
910
1073
  type: "mousePressed",
@@ -923,7 +1086,7 @@ function makeLightweightCdpDriver(options) {
923
1086
  },
924
1087
  catch: (e) => new DriverError({ message: `CDP doubleTap failed: ${e}` })
925
1088
  }),
926
- longPressAtCoordinate: (x, y, duration) => Effect2.tryPromise({
1089
+ longPressAtCoordinate: (x, y, duration) => Effect.tryPromise({
927
1090
  try: async () => {
928
1091
  await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
929
1092
  type: "mousePressed",
@@ -943,7 +1106,7 @@ function makeLightweightCdpDriver(options) {
943
1106
  },
944
1107
  catch: (e) => new DriverError({ message: `CDP longPress failed: ${e}` })
945
1108
  }),
946
- swipe: (startX, startY, endX, endY) => Effect2.tryPromise({
1109
+ swipe: (startX, startY, endX, endY) => Effect.tryPromise({
947
1110
  try: async () => {
948
1111
  const dx = startX - endX;
949
1112
  const dy = startY - endY;
@@ -951,13 +1114,13 @@ function makeLightweightCdpDriver(options) {
951
1114
  },
952
1115
  catch: (e) => new DriverError({ message: `CDP swipe failed: ${e}` })
953
1116
  }),
954
- inputText: (text) => Effect2.tryPromise({
1117
+ inputText: (text) => Effect.tryPromise({
955
1118
  try: async () => {
956
1119
  await cdpChannel.sendCommand("Input.insertText", { text });
957
1120
  },
958
1121
  catch: (e) => new DriverError({ message: `CDP inputText failed: ${e}` })
959
1122
  }),
960
- pressKey: (key) => Effect2.tryPromise({
1123
+ pressKey: (key) => Effect.tryPromise({
961
1124
  try: async () => {
962
1125
  const desc = parseCdpKeyDescriptor(key);
963
1126
  await cdpChannel.sendCommand("Input.dispatchKeyEvent", {
@@ -985,7 +1148,7 @@ function makeLightweightCdpDriver(options) {
985
1148
  },
986
1149
  catch: (e) => new DriverError({ message: `CDP pressKey failed: ${e}` })
987
1150
  }),
988
- hoverAtCoordinate: (x, y) => Effect2.tryPromise({
1151
+ hoverAtCoordinate: (x, y) => Effect.tryPromise({
989
1152
  try: async () => {
990
1153
  await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
991
1154
  type: "mouseMoved",
@@ -995,7 +1158,7 @@ function makeLightweightCdpDriver(options) {
995
1158
  },
996
1159
  catch: (e) => new DriverError({ message: `CDP hover failed at (${x}, ${y}): ${e}` })
997
1160
  }),
998
- reload: (reloadOpts) => Effect2.tryPromise({
1161
+ reload: (reloadOpts) => Effect.tryPromise({
999
1162
  try: async () => {
1000
1163
  const waitUntil = reloadOpts?.waitUntil ?? options.waitUntil ?? "domcontentloaded";
1001
1164
  const targetSid = activeSlot?.sessionId;
@@ -1011,7 +1174,7 @@ function makeLightweightCdpDriver(options) {
1011
1174
  },
1012
1175
  catch: (e) => new DriverError({ message: `CDP reload failed: ${e}` })
1013
1176
  }),
1014
- getUrl: () => Effect2.tryPromise({
1177
+ getUrl: () => Effect.tryPromise({
1015
1178
  try: async () => {
1016
1179
  const url = await cdpChannel.evaluate(
1017
1180
  "typeof window !== 'undefined' && window.location ? String(window.location.href || '') : ''"
@@ -1020,8 +1183,8 @@ function makeLightweightCdpDriver(options) {
1020
1183
  },
1021
1184
  catch: (e) => new DriverError({ message: `CDP getUrl failed: ${e}` })
1022
1185
  }),
1023
- hideKeyboard: () => Effect2.void,
1024
- takeScreenshot: () => Effect2.tryPromise({
1186
+ hideKeyboard: () => Effect.void,
1187
+ takeScreenshot: () => Effect.tryPromise({
1025
1188
  try: async () => {
1026
1189
  const res = await cdpChannel.sendCommand("Page.captureScreenshot", {
1027
1190
  format: "png"
@@ -1030,7 +1193,7 @@ function makeLightweightCdpDriver(options) {
1030
1193
  },
1031
1194
  catch: (e) => new DriverError({ message: `CDP screenshot failed: ${e}` })
1032
1195
  }),
1033
- getDeviceInfo: () => Effect2.succeed({
1196
+ getDeviceInfo: () => Effect.succeed({
1034
1197
  platform: "web",
1035
1198
  deviceId: `${label}:${options.cdpUrl}`,
1036
1199
  name: `${label} (CDP-direct)`,
@@ -1039,7 +1202,7 @@ function makeLightweightCdpDriver(options) {
1039
1202
  screenHeight: height,
1040
1203
  driverType: "cdp"
1041
1204
  }),
1042
- launchApp: (url, opts) => Effect2.tryPromise({
1205
+ launchApp: (url, opts) => Effect.tryPromise({
1043
1206
  try: async () => {
1044
1207
  if (opts?.clearState) {
1045
1208
  await cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
@@ -1052,11 +1215,11 @@ function makeLightweightCdpDriver(options) {
1052
1215
  },
1053
1216
  catch: (e) => new DriverError({ message: `CDP launchApp failed: ${e}` })
1054
1217
  }),
1055
- stopApp: () => Effect2.tryPromise({
1218
+ stopApp: () => Effect.tryPromise({
1056
1219
  try: () => navigate("about:blank"),
1057
1220
  catch: (e) => new DriverError({ message: `CDP stopApp failed: ${e}` })
1058
1221
  }),
1059
- killApp: () => Effect2.tryPromise({
1222
+ killApp: () => Effect.tryPromise({
1060
1223
  try: async () => {
1061
1224
  const pendingPrefetch = prefetchedSlotPromise;
1062
1225
  prefetchedSlotPromise = void 0;
@@ -1089,7 +1252,7 @@ function makeLightweightCdpDriver(options) {
1089
1252
  },
1090
1253
  catch: (e) => new DriverError({ message: `CDP disconnect failed: ${e}` })
1091
1254
  }),
1092
- clearAppState: () => Effect2.tryPromise({
1255
+ clearAppState: () => Effect.tryPromise({
1093
1256
  try: async () => {
1094
1257
  await cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
1095
1258
  });
@@ -1099,17 +1262,17 @@ function makeLightweightCdpDriver(options) {
1099
1262
  },
1100
1263
  catch: (e) => new DriverError({ message: `CDP clearAppState failed: ${e}` })
1101
1264
  }),
1102
- openLink: (url) => Effect2.tryPromise({
1265
+ openLink: (url) => Effect.tryPromise({
1103
1266
  try: () => navigate(url),
1104
1267
  catch: (e) => new DriverError({ message: `CDP openLink failed: ${e}` })
1105
1268
  }),
1106
- back: () => Effect2.tryPromise({
1269
+ back: () => Effect.tryPromise({
1107
1270
  try: async () => {
1108
1271
  await cdpChannel.evaluate("window.history.back()");
1109
1272
  },
1110
1273
  catch: (e) => new DriverError({ message: `CDP back failed: ${e}` })
1111
1274
  }),
1112
- evaluate: (fn, ...args) => Effect2.tryPromise({
1275
+ evaluate: (fn, ...args) => Effect.tryPromise({
1113
1276
  try: async () => {
1114
1277
  if (typeof fn === "string") {
1115
1278
  return await cdpChannel.evaluate(fn);
@@ -1138,21 +1301,21 @@ function makeLightweightCdpDriver(options) {
1138
1301
  return activeSlot?.browserContextId;
1139
1302
  }
1140
1303
  }),
1141
- mockNetwork: (matcher, response) => Effect2.tryPromise({
1304
+ mockNetwork: (matcher, response) => Effect.tryPromise({
1142
1305
  try: async () => {
1143
1306
  routeRules.push({ kind: "mock", matcher, response });
1144
1307
  await ensureFetchIntercept();
1145
1308
  },
1146
1309
  catch: (e) => new DriverError({ message: `CDP mockNetwork failed: ${e}` })
1147
1310
  }),
1148
- blockNetwork: (matcher) => Effect2.tryPromise({
1311
+ blockNetwork: (matcher) => Effect.tryPromise({
1149
1312
  try: async () => {
1150
1313
  routeRules.push({ kind: "block", matcher });
1151
1314
  await ensureFetchIntercept();
1152
1315
  },
1153
1316
  catch: (e) => new DriverError({ message: `CDP blockNetwork failed: ${e}` })
1154
1317
  }),
1155
- clearNetworkMocks: () => Effect2.tryPromise({
1318
+ clearNetworkMocks: () => Effect.tryPromise({
1156
1319
  try: async () => {
1157
1320
  routeRules.length = 0;
1158
1321
  if (fetchInterceptEnabled) {
@@ -1163,14 +1326,14 @@ function makeLightweightCdpDriver(options) {
1163
1326
  },
1164
1327
  catch: (e) => new DriverError({ message: `CDP clearNetworkMocks failed: ${e}` })
1165
1328
  }),
1166
- saveCookies: (path) => Effect2.tryPromise({
1329
+ saveCookies: (path) => Effect.tryPromise({
1167
1330
  try: async () => {
1168
1331
  const res = await cdpChannel.sendCommand("Network.getCookies");
1169
1332
  await writeFile(path, JSON.stringify(res?.cookies ?? [], null, 2), "utf8");
1170
1333
  },
1171
1334
  catch: (e) => new DriverError({ message: `CDP saveCookies failed: ${e}` })
1172
1335
  }),
1173
- loadCookies: (path) => Effect2.tryPromise({
1336
+ loadCookies: (path) => Effect.tryPromise({
1174
1337
  try: async () => {
1175
1338
  const cookies = JSON.parse(await readFile(path, "utf8"));
1176
1339
  if (Array.isArray(cookies)) {
@@ -1179,7 +1342,7 @@ function makeLightweightCdpDriver(options) {
1179
1342
  },
1180
1343
  catch: (e) => new DriverError({ message: `CDP loadCookies failed: ${e}` })
1181
1344
  }),
1182
- getCookies: (urls) => Effect2.tryPromise({
1345
+ getCookies: (urls) => Effect.tryPromise({
1183
1346
  try: async () => {
1184
1347
  const res = await cdpChannel.sendCommand(
1185
1348
  "Network.getCookies",
@@ -1189,20 +1352,20 @@ function makeLightweightCdpDriver(options) {
1189
1352
  },
1190
1353
  catch: (e) => new DriverError({ message: `CDP getCookies failed: ${e}` })
1191
1354
  }),
1192
- setCookies: (cookies) => Effect2.tryPromise({
1355
+ setCookies: (cookies) => Effect.tryPromise({
1193
1356
  try: async () => {
1194
1357
  if (cookies.length === 0) return;
1195
1358
  await cdpChannel.sendCommand("Network.setCookies", { cookies });
1196
1359
  },
1197
1360
  catch: (e) => new DriverError({ message: `CDP setCookies failed: ${e}` })
1198
1361
  }),
1199
- clearCookies: () => Effect2.tryPromise({
1362
+ clearCookies: () => Effect.tryPromise({
1200
1363
  try: async () => {
1201
1364
  await cdpChannel.sendCommand("Network.clearBrowserCookies");
1202
1365
  },
1203
1366
  catch: (e) => new DriverError({ message: `CDP clearCookies failed: ${e}` })
1204
1367
  }),
1205
- waitForResponse: (matcher, waitOpts) => Effect2.tryPromise({
1368
+ waitForResponse: (matcher, waitOpts) => Effect.tryPromise({
1206
1369
  try: async () => {
1207
1370
  const timeoutMs = waitOpts?.timeout ?? 15e3;
1208
1371
  const slotSessions = () => {
@@ -1232,7 +1395,7 @@ function makeLightweightCdpDriver(options) {
1232
1395
  });
1233
1396
  }
1234
1397
  const requestMethods = /* @__PURE__ */ new Map();
1235
- return await new Promise((resolve, reject) => {
1398
+ return await new Promise((resolve2, reject) => {
1236
1399
  let cleaned = false;
1237
1400
  const cleanup = () => {
1238
1401
  if (cleaned) return;
@@ -1291,16 +1454,16 @@ function makeLightweightCdpDriver(options) {
1291
1454
  const matched = typeof matcher === "function" ? matcher(info) : matchUrl(matcher, info.url);
1292
1455
  if (matched) {
1293
1456
  cleanup();
1294
- resolve(info);
1457
+ resolve2(info);
1295
1458
  }
1296
1459
  });
1297
1460
  });
1298
1461
  },
1299
1462
  catch: (e) => new DriverError({ message: `CDP waitForResponse failed: ${e}` })
1300
1463
  }),
1301
- createIsolatedContext: (ctxOpts) => Effect2.tryPromise({
1464
+ createIsolatedContext: (ctxOpts) => Effect.tryPromise({
1302
1465
  try: async () => {
1303
- const childDriver = await Effect2.runPromise(
1466
+ const childDriver = await Effect.runPromise(
1304
1467
  makeLightweightCdpDriver({
1305
1468
  ...options,
1306
1469
  cdpUrl: connectWsUrl ?? options.cdpUrl,
@@ -1309,19 +1472,19 @@ function makeLightweightCdpDriver(options) {
1309
1472
  })
1310
1473
  );
1311
1474
  if (ctxOpts?.url) {
1312
- await Effect2.runPromise(childDriver.openLink(ctxOpts.url));
1475
+ await Effect.runPromise(childDriver.openLink(ctxOpts.url));
1313
1476
  }
1314
1477
  return {
1315
1478
  driver: childDriver,
1316
1479
  close: async () => {
1317
- await Effect2.runPromise(childDriver.killApp("isolated-context")).catch(() => {
1480
+ await Effect.runPromise(childDriver.killApp("isolated-context")).catch(() => {
1318
1481
  });
1319
1482
  }
1320
1483
  };
1321
1484
  },
1322
1485
  catch: (e) => new DriverError({ message: `CDP createIsolatedContext failed: ${e}` })
1323
1486
  }),
1324
- saveAuthState: (path) => Effect2.tryPromise({
1487
+ saveAuthState: (path) => Effect.tryPromise({
1325
1488
  try: async () => {
1326
1489
  const res = await cdpChannel.sendCommand("Network.getCookies");
1327
1490
  const originState = await cdpChannel.evaluate(
@@ -1344,7 +1507,7 @@ function makeLightweightCdpDriver(options) {
1344
1507
  },
1345
1508
  catch: (e) => new DriverError({ message: `CDP saveAuthState failed: ${e}` })
1346
1509
  }),
1347
- loadAuthState: (path) => Effect2.tryPromise({
1510
+ loadAuthState: (path) => Effect.tryPromise({
1348
1511
  try: async () => {
1349
1512
  if (useContexts) {
1350
1513
  const previousSlot = activeSlot;
@@ -1361,7 +1524,7 @@ function makeLightweightCdpDriver(options) {
1361
1524
  },
1362
1525
  catch: (e) => new DriverError({ message: `CDP loadAuthState failed: ${e}` })
1363
1526
  }),
1364
- enableVirtualAuthenticator: (opts) => Effect2.tryPromise({
1527
+ enableVirtualAuthenticator: (opts) => Effect.tryPromise({
1365
1528
  try: async () => {
1366
1529
  activeAuthenticatorId = await attachVirtualAuthenticatorForSession(
1367
1530
  activeSlot?.sessionId ?? null,
@@ -1371,7 +1534,7 @@ function makeLightweightCdpDriver(options) {
1371
1534
  },
1372
1535
  catch: (e) => new DriverError({ message: `CDP enableVirtualAuthenticator failed: ${e}` })
1373
1536
  }),
1374
- removeVirtualAuthenticator: (authenticatorId) => Effect2.tryPromise({
1537
+ removeVirtualAuthenticator: (authenticatorId) => Effect.tryPromise({
1375
1538
  try: async () => {
1376
1539
  const id = authenticatorId ?? activeAuthenticatorId;
1377
1540
  if (!id) return;
@@ -1382,7 +1545,7 @@ function makeLightweightCdpDriver(options) {
1382
1545
  },
1383
1546
  catch: (e) => new DriverError({ message: `CDP removeVirtualAuthenticator failed: ${e}` })
1384
1547
  }),
1385
- getVirtualCredentials: (authenticatorId) => Effect2.tryPromise({
1548
+ getVirtualCredentials: (authenticatorId) => Effect.tryPromise({
1386
1549
  try: async () => {
1387
1550
  const id = authenticatorId ?? activeAuthenticatorId;
1388
1551
  if (!id) return [];
@@ -1393,7 +1556,7 @@ function makeLightweightCdpDriver(options) {
1393
1556
  },
1394
1557
  catch: (e) => new DriverError({ message: `CDP getVirtualCredentials failed: ${e}` })
1395
1558
  }),
1396
- addVirtualCredential: (credential, authenticatorId) => Effect2.tryPromise({
1559
+ addVirtualCredential: (credential, authenticatorId) => Effect.tryPromise({
1397
1560
  try: async () => {
1398
1561
  let id = authenticatorId ?? activeAuthenticatorId;
1399
1562
  if (!id) {
@@ -1415,7 +1578,7 @@ function makeLightweightCdpDriver(options) {
1415
1578
  },
1416
1579
  catch: (e) => new DriverError({ message: `CDP addVirtualCredential failed: ${e}` })
1417
1580
  }),
1418
- clearVirtualCredentials: (authenticatorId) => Effect2.tryPromise({
1581
+ clearVirtualCredentials: (authenticatorId) => Effect.tryPromise({
1419
1582
  try: async () => {
1420
1583
  const id = authenticatorId ?? activeAuthenticatorId;
1421
1584
  if (!id) return;
@@ -1423,9 +1586,9 @@ function makeLightweightCdpDriver(options) {
1423
1586
  },
1424
1587
  catch: (e) => new DriverError({ message: `CDP clearVirtualCredentials failed: ${e}` })
1425
1588
  }),
1426
- getConsoleLogs: () => Effect2.succeed([...consoleLogs]),
1427
- getJSErrors: () => Effect2.succeed([...jsErrors]),
1428
- setNetworkConditions: (conditions) => Effect2.tryPromise({
1589
+ getConsoleLogs: () => Effect.succeed([...consoleLogs]),
1590
+ getJSErrors: () => Effect.succeed([...jsErrors]),
1591
+ setNetworkConditions: (conditions) => Effect.tryPromise({
1429
1592
  try: async () => {
1430
1593
  const resolved = resolveNetworkConditions(conditions);
1431
1594
  await cdpChannel.sendCommand("Network.enable");
@@ -1438,7 +1601,7 @@ function makeLightweightCdpDriver(options) {
1438
1601
  },
1439
1602
  catch: (e) => new DriverError({ message: `CDP setNetworkConditions failed: ${e}` })
1440
1603
  }),
1441
- uploadFile: (selector, filePath) => Effect2.tryPromise({
1604
+ uploadFile: (selector, filePath) => Effect.tryPromise({
1442
1605
  try: async () => {
1443
1606
  const files = Array.isArray(filePath) ? filePath : [filePath];
1444
1607
  const expr = buildDomFindElementScript(selector);
@@ -1480,10 +1643,10 @@ function makeLightweightCdpDriver(options) {
1480
1643
  },
1481
1644
  catch: (e) => new DriverError({ message: `CDP uploadFile failed: ${e}` })
1482
1645
  }),
1483
- downloadFile: (destPath) => Effect2.tryPromise({
1646
+ downloadFile: (destPath) => Effect.tryPromise({
1484
1647
  try: async () => {
1485
1648
  if (!downloadDir) {
1486
- downloadDir = mkdtempSync(join(tmpdir(), "spana-cdp-dl-"));
1649
+ downloadDir = mkdtempSync(join2(tmpdir(), "spana-cdp-dl-"));
1487
1650
  await cdpChannel.sendCommand(
1488
1651
  "Browser.setDownloadBehavior",
1489
1652
  {
@@ -1495,14 +1658,14 @@ function makeLightweightCdpDriver(options) {
1495
1658
  null
1496
1659
  );
1497
1660
  }
1498
- const downloaded = completedDownloads.shift() ?? await new Promise((resolve, reject) => {
1661
+ const downloaded = completedDownloads.shift() ?? await new Promise((resolve2, reject) => {
1499
1662
  const timer = setTimeout(() => {
1500
1663
  reject(new Error("Timed out waiting for CDP file download"));
1501
1664
  }, 15e3);
1502
1665
  downloadWaiters.push({
1503
- resolve: (fp) => {
1666
+ resolve: (entry) => {
1504
1667
  clearTimeout(timer);
1505
- resolve(fp);
1668
+ resolve2(entry);
1506
1669
  },
1507
1670
  reject: (err) => {
1508
1671
  clearTimeout(timer);
@@ -1510,11 +1673,197 @@ function makeLightweightCdpDriver(options) {
1510
1673
  }
1511
1674
  });
1512
1675
  });
1513
- await copyFile(downloaded, destPath);
1676
+ await copyFile(downloaded.filePath, destPath);
1514
1677
  },
1515
1678
  catch: (e) => new DriverError({ message: `CDP downloadFile failed: ${e}` })
1516
1679
  }),
1517
- newTab: (url) => Effect2.tryPromise({
1680
+ dragAndDrop: (fromX, fromY, toX, toY, steps = 10) => Effect.tryPromise({
1681
+ try: async () => {
1682
+ const totalSteps = Math.max(1, Math.round(steps));
1683
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
1684
+ type: "mouseMoved",
1685
+ x: fromX,
1686
+ y: fromY
1687
+ });
1688
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
1689
+ type: "mousePressed",
1690
+ x: fromX,
1691
+ y: fromY,
1692
+ button: "left",
1693
+ buttons: 1,
1694
+ clickCount: 1
1695
+ });
1696
+ for (let i = 1; i <= totalSteps; i++) {
1697
+ const t = i / totalSteps;
1698
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
1699
+ type: "mouseMoved",
1700
+ x: fromX + (toX - fromX) * t,
1701
+ y: fromY + (toY - fromY) * t,
1702
+ button: "left",
1703
+ buttons: 1
1704
+ });
1705
+ }
1706
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
1707
+ type: "mouseReleased",
1708
+ x: toX,
1709
+ y: toY,
1710
+ button: "left",
1711
+ buttons: 0,
1712
+ clickCount: 1
1713
+ });
1714
+ },
1715
+ catch: (e) => new DriverError({ message: `CDP dragAndDrop failed: ${e}` })
1716
+ }),
1717
+ setViewport: (viewport) => Effect.tryPromise({
1718
+ try: async () => {
1719
+ width = viewport.width;
1720
+ height = viewport.height;
1721
+ await cdpChannel.sendCommand("Emulation.setDeviceMetricsOverride", {
1722
+ width: viewport.width,
1723
+ height: viewport.height,
1724
+ deviceScaleFactor: viewport.deviceScaleFactor ?? 1,
1725
+ mobile: viewport.mobile ?? false
1726
+ });
1727
+ },
1728
+ catch: (e) => new DriverError({ message: `CDP setViewport failed: ${e}` })
1729
+ }),
1730
+ setEmulation: (emulationOpts) => Effect.tryPromise({
1731
+ try: async () => {
1732
+ const features = [];
1733
+ if (emulationOpts.colorScheme !== void 0) {
1734
+ features.push({
1735
+ name: "prefers-color-scheme",
1736
+ value: emulationOpts.colorScheme === "no-preference" ? "" : emulationOpts.colorScheme
1737
+ });
1738
+ }
1739
+ if (emulationOpts.reducedMotion !== void 0) {
1740
+ features.push({
1741
+ name: "prefers-reduced-motion",
1742
+ value: emulationOpts.reducedMotion === "no-preference" ? "" : emulationOpts.reducedMotion
1743
+ });
1744
+ }
1745
+ if (features.length > 0) {
1746
+ await cdpChannel.sendCommand("Emulation.setEmulatedMedia", { features });
1747
+ }
1748
+ if (emulationOpts.locale !== void 0) {
1749
+ await cdpChannel.sendCommand("Emulation.setLocaleOverride", { locale: emulationOpts.locale }).catch(() => {
1750
+ });
1751
+ }
1752
+ if (emulationOpts.timezoneId !== void 0) {
1753
+ await cdpChannel.sendCommand("Emulation.setTimezoneOverride", {
1754
+ timezoneId: emulationOpts.timezoneId
1755
+ }).catch(() => {
1756
+ });
1757
+ }
1758
+ },
1759
+ catch: (e) => new DriverError({ message: `CDP setEmulation failed: ${e}` })
1760
+ }),
1761
+ setDialogHandler: (handler) => Effect.sync(() => {
1762
+ dialogHandler = handler;
1763
+ }),
1764
+ getClipboard: () => Effect.tryPromise({
1765
+ try: async () => {
1766
+ if (activeSlot?.browserContextId) {
1767
+ await cdpChannel.sendCommand(
1768
+ "Browser.grantPermissions",
1769
+ {
1770
+ permissions: ["clipboardReadWrite", "clipboardSanitizedWrite"],
1771
+ browserContextId: activeSlot.browserContextId
1772
+ },
1773
+ null
1774
+ ).catch(() => {
1775
+ });
1776
+ }
1777
+ const res = await cdpChannel.sendCommand("Runtime.evaluate", {
1778
+ expression: `(async () => {
1779
+ if (navigator.clipboard && typeof navigator.clipboard.readText === "function") {
1780
+ try { return await navigator.clipboard.readText(); } catch {}
1781
+ }
1782
+ return typeof window.__spanaClipboardText === "string" ? window.__spanaClipboardText : "";
1783
+ })()`,
1784
+ awaitPromise: true,
1785
+ returnByValue: true,
1786
+ userGesture: true
1787
+ });
1788
+ return typeof res?.result?.value === "string" ? res.result.value : "";
1789
+ },
1790
+ catch: (e) => new DriverError({ message: `CDP getClipboard failed: ${e}` })
1791
+ }),
1792
+ setClipboard: (text) => Effect.tryPromise({
1793
+ try: async () => {
1794
+ if (activeSlot?.browserContextId) {
1795
+ await cdpChannel.sendCommand(
1796
+ "Browser.grantPermissions",
1797
+ {
1798
+ permissions: ["clipboardReadWrite", "clipboardSanitizedWrite"],
1799
+ browserContextId: activeSlot.browserContextId
1800
+ },
1801
+ null
1802
+ ).catch(() => {
1803
+ });
1804
+ }
1805
+ const encoded = JSON.stringify(text);
1806
+ await cdpChannel.sendCommand("Runtime.evaluate", {
1807
+ expression: `(async (txt) => {
1808
+ window.__spanaClipboardText = txt;
1809
+ if (navigator.clipboard && typeof navigator.clipboard.writeText === "function") {
1810
+ try { await navigator.clipboard.writeText(txt); return; } catch {}
1811
+ }
1812
+ })(${encoded})`,
1813
+ awaitPromise: true,
1814
+ returnByValue: true,
1815
+ userGesture: true
1816
+ });
1817
+ },
1818
+ catch: (e) => new DriverError({ message: `CDP setClipboard failed: ${e}` })
1819
+ }),
1820
+ waitForDownload: (triggerFn, dlOpts) => Effect.tryPromise({
1821
+ try: async () => {
1822
+ const timeoutMs = dlOpts?.timeout ?? 15e3;
1823
+ if (!downloadDir) {
1824
+ downloadDir = mkdtempSync(join2(tmpdir(), "spana-cdp-dl-"));
1825
+ await cdpChannel.sendCommand(
1826
+ "Browser.setDownloadBehavior",
1827
+ {
1828
+ behavior: "allowAndName",
1829
+ downloadPath: downloadDir,
1830
+ eventsEnabled: true,
1831
+ ...activeSlot?.browserContextId ? { browserContextId: activeSlot.browserContextId } : {}
1832
+ },
1833
+ null
1834
+ );
1835
+ }
1836
+ const downloadPromise = new Promise((resolve2, reject) => {
1837
+ const timer = setTimeout(() => {
1838
+ reject(new Error(`Timed out waiting for download after ${timeoutMs}ms`));
1839
+ }, timeoutMs);
1840
+ downloadWaiters.push({
1841
+ resolve: (entry2) => {
1842
+ clearTimeout(timer);
1843
+ resolve2(entry2);
1844
+ },
1845
+ reject: (err) => {
1846
+ clearTimeout(timer);
1847
+ reject(err);
1848
+ }
1849
+ });
1850
+ });
1851
+ await triggerFn();
1852
+ const entry = await downloadPromise;
1853
+ return {
1854
+ suggestedFilename: entry.suggestedFilename,
1855
+ path: entry.filePath,
1856
+ url: entry.url,
1857
+ text: () => readFile(entry.filePath, "utf8"),
1858
+ bytes: async () => new Uint8Array(await readFile(entry.filePath)),
1859
+ saveAs: async (destPath) => {
1860
+ await copyFile(entry.filePath, destPath);
1861
+ }
1862
+ };
1863
+ },
1864
+ catch: (e) => new DriverError({ message: `CDP waitForDownload failed: ${e}` })
1865
+ }),
1866
+ newTab: (url) => Effect.tryPromise({
1518
1867
  try: async () => {
1519
1868
  if (!activeSlot) {
1520
1869
  throw new Error("newTab() requires browser-context mode (engine: 'cdp')");
@@ -1548,7 +1897,7 @@ function makeLightweightCdpDriver(options) {
1548
1897
  },
1549
1898
  catch: (e) => new DriverError({ message: `CDP newTab failed: ${e}` })
1550
1899
  }),
1551
- switchToTab: (index) => Effect2.tryPromise({
1900
+ switchToTab: (index) => Effect.tryPromise({
1552
1901
  try: async () => {
1553
1902
  if (!activeSlot || !activeSlot.tabs[index]) {
1554
1903
  throw new Error(`Tab index ${index} is out of range.`);
@@ -1562,7 +1911,7 @@ function makeLightweightCdpDriver(options) {
1562
1911
  },
1563
1912
  catch: (e) => new DriverError({ message: `CDP switchToTab failed: ${e}` })
1564
1913
  }),
1565
- closeTab: () => Effect2.tryPromise({
1914
+ closeTab: () => Effect.tryPromise({
1566
1915
  try: async () => {
1567
1916
  if (!activeSlot) return;
1568
1917
  if (activeSlot.tabs.length <= 1) {
@@ -1581,14 +1930,13 @@ function makeLightweightCdpDriver(options) {
1581
1930
  },
1582
1931
  catch: (e) => new DriverError({ message: `CDP closeTab failed: ${e}` })
1583
1932
  }),
1584
- getTabIds: () => Effect2.sync(() => activeSlot ? activeSlot.tabs.map((t) => t.tabId) : ["tab-1"])
1933
+ getTabIds: () => Effect.sync(() => activeSlot ? activeSlot.tabs.map((t) => t.tabId) : ["tab-1"])
1585
1934
  };
1586
1935
  return service;
1587
1936
  });
1588
1937
  }
1589
1938
 
1590
1939
  // src/runtime/local.ts
1591
- import { Effect as Effect3 } from "effect";
1592
1940
  async function safeCleanup(...fns) {
1593
1941
  for (const fn of fns) {
1594
1942
  try {
@@ -1640,7 +1988,9 @@ function buildEngineConfig(appId, platform, parseFn, config, screenSize) {
1640
1988
  launchOptions: config.launchOptions,
1641
1989
  hooks: config.hooks,
1642
1990
  storybook: platform === "web" ? config.execution?.web?.storybook : void 0,
1643
- visualRegression: config.visualRegression
1991
+ visualRegression: config.visualRegression,
1992
+ replayCache: config.replayCache,
1993
+ agent: config.agent
1644
1994
  };
1645
1995
  }
1646
1996
  function resolveWebEngine(config) {
@@ -1670,6 +2020,7 @@ function speculativelyPrelaunchWebBrowser(config) {
1670
2020
  const cdpBrowserPromise = launchDirectCdpBrowser({
1671
2021
  executablePath: webExecution?.executablePath,
1672
2022
  headless: webExecution?.headless ?? true,
2023
+ extensions: webExecution?.extensions,
1673
2024
  warmBrowser: useWarm2,
1674
2025
  warmBrowserScope: webExecution?.warmBrowserScope ? `${webExecution.warmBrowserScope}-w0` : void 0
1675
2026
  });
@@ -1712,12 +2063,18 @@ async function buildWebRuntime(config, prelaunched) {
1712
2063
  launchedDirectCdp = prelaunched?.cdpBrowserPromise ? await prelaunched.cdpBrowserPromise : await launchDirectCdpBrowser({
1713
2064
  executablePath: webExecution?.executablePath,
1714
2065
  headless: webExecution?.headless ?? true,
2066
+ extensions: webExecution?.extensions,
1715
2067
  warmBrowser: webExecution?.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false,
1716
2068
  warmBrowserScope: webExecution?.warmBrowserScope ? `${webExecution.warmBrowserScope}-w0` : void 0
1717
2069
  });
1718
2070
  targetCdpUrl = launchedDirectCdp.browserWsUrl;
1719
2071
  }
1720
- rawDriver = await Effect3.runPromise(
2072
+ const cdpEmulation = webExecution?.colorScheme || webExecution?.reducedMotion || webExecution?.timezoneId ? {
2073
+ colorScheme: webExecution.colorScheme,
2074
+ reducedMotion: webExecution.reducedMotion,
2075
+ timezoneId: webExecution.timezoneId
2076
+ } : void 0;
2077
+ rawDriver = await Effect2.runPromise(
1721
2078
  makeLightweightCdpDriver({
1722
2079
  cdpUrl: targetCdpUrl ?? "http://127.0.0.1:9222",
1723
2080
  baseUrl: webUrl,
@@ -1729,11 +2086,12 @@ async function buildWebRuntime(config, prelaunched) {
1729
2086
  instantAnimations: webExecution?.instantAnimations,
1730
2087
  blockResources: webExecution?.blockResources,
1731
2088
  virtualAuthenticator: webExecution?.virtualAuthenticator,
1732
- storageState: webExecution?.storageState
2089
+ storageState: webExecution?.storageState,
2090
+ emulation: cdpEmulation
1733
2091
  })
1734
2092
  );
1735
2093
  } else {
1736
- rawDriver = await Effect3.runPromise(
2094
+ rawDriver = await Effect2.runPromise(
1737
2095
  makePlaywrightDriver({
1738
2096
  browser: webExecution?.browser,
1739
2097
  headless: webExecution?.headless ?? true,
@@ -1757,12 +2115,12 @@ async function buildWebRuntime(config, prelaunched) {
1757
2115
  );
1758
2116
  }
1759
2117
  const driver = bridge ? { ...rawDriver, domChannel: bridge } : rawDriver;
1760
- const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
2118
+ const deviceInfo = await Effect2.runPromise(driver.getDeviceInfo());
1761
2119
  return {
1762
2120
  runtime: {
1763
2121
  driver,
1764
2122
  cleanup: () => safeCleanup(
1765
- () => Effect3.runPromise(driver.killApp("")),
2123
+ () => Effect2.runPromise(driver.killApp("")),
1766
2124
  () => prelaunchedBrowser && prelaunched?.ownsBrowser ? prelaunchedBrowser.close() : Promise.resolve(),
1767
2125
  () => launchedDirectCdp ? launchedDirectCdp.close() : Promise.resolve(),
1768
2126
  () => bridge?.disconnect() ?? Promise.resolve()
@@ -1819,7 +2177,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1819
2177
  const results2 = [];
1820
2178
  for (let i = 0; i < workerCount; i++) {
1821
2179
  const bucket = handles[i % handles.length];
1822
- const driver = await Effect3.runPromise(
2180
+ const driver = await Effect2.runPromise(
1823
2181
  makeLightweightCdpDriver({
1824
2182
  cdpUrl: bucket.cdpUrl,
1825
2183
  baseUrl: webUrl,
@@ -1834,7 +2192,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1834
2192
  storageState: webExecution?.storageState
1835
2193
  })
1836
2194
  );
1837
- const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
2195
+ const deviceInfo = await Effect2.runPromise(driver.getDeviceInfo());
1838
2196
  let cleaned = false;
1839
2197
  results2.push({
1840
2198
  runtime: {
@@ -1842,7 +2200,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1842
2200
  cleanup: () => safeCleanup(async () => {
1843
2201
  if (cleaned) return;
1844
2202
  cleaned = true;
1845
- await Effect3.runPromise(driver.killApp(""));
2203
+ await Effect2.runPromise(driver.killApp(""));
1846
2204
  bucket.remaining -= 1;
1847
2205
  if (bucket.remaining <= 0 && bucket.handle) {
1848
2206
  await bucket.handle.close();
@@ -1915,7 +2273,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1915
2273
  const results = [];
1916
2274
  for (let i = 0; i < workerCount; i++) {
1917
2275
  const bucket = browserBuckets[i % browserBuckets.length];
1918
- const driver = await Effect3.runPromise(
2276
+ const driver = await Effect2.runPromise(
1919
2277
  makePlaywrightDriver({
1920
2278
  browser: webExecution?.browser,
1921
2279
  headless: webExecution?.headless ?? true,
@@ -1934,7 +2292,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1934
2292
  warmBrowserScope: webExecution?.warmBrowserScope
1935
2293
  })
1936
2294
  );
1937
- const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
2295
+ const deviceInfo = await Effect2.runPromise(driver.getDeviceInfo());
1938
2296
  let cleaned = false;
1939
2297
  results.push({
1940
2298
  runtime: {
@@ -1942,7 +2300,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1942
2300
  cleanup: () => safeCleanup(async () => {
1943
2301
  if (cleaned) return;
1944
2302
  cleaned = true;
1945
- await Effect3.runPromise(driver.killApp(""));
2303
+ await Effect2.runPromise(driver.killApp(""));
1946
2304
  bucket.remaining -= 1;
1947
2305
  if (bucket.remaining <= 0 && bucket.owns) {
1948
2306
  await bucket.browser.close();
@@ -1965,7 +2323,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1965
2323
  async function buildElectronRuntime(config, resolveFromConfig) {
1966
2324
  const electronCfg = config.apps?.electron ?? {};
1967
2325
  const bridge = await maybeStartBridge(electronCfg.bridge, config.execution?.bridge);
1968
- const driver = await Effect3.runPromise(
2326
+ const driver = await Effect2.runPromise(
1969
2327
  makeElectronDriver({
1970
2328
  entry: electronCfg.entry ? resolveFromConfig(electronCfg.entry) : void 0,
1971
2329
  executablePath: electronCfg.executablePath ? resolveFromConfig(electronCfg.executablePath) : void 0,
@@ -1981,12 +2339,12 @@ async function buildElectronRuntime(config, resolveFromConfig) {
1981
2339
  domChannel: bridge
1982
2340
  })
1983
2341
  );
1984
- const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
2342
+ const deviceInfo = await Effect2.runPromise(driver.getDeviceInfo());
1985
2343
  return {
1986
2344
  runtime: {
1987
2345
  driver,
1988
2346
  cleanup: () => safeCleanup(
1989
- () => Effect3.runPromise(driver.killApp("")),
2347
+ () => Effect2.runPromise(driver.killApp("")),
1990
2348
  () => bridge?.disconnect() ?? Promise.resolve()
1991
2349
  ),
1992
2350
  metadata: {
@@ -2010,7 +2368,7 @@ async function buildElectronRuntime(config, resolveFromConfig) {
2010
2368
  async function buildElectrobunRuntime(config, resolveFromConfig) {
2011
2369
  const electrobunCfg = config.apps?.electrobun ?? {};
2012
2370
  const bridge = await maybeStartBridge(electrobunCfg.bridge, config.execution?.bridge);
2013
- const driver = await Effect3.runPromise(
2371
+ const driver = await Effect2.runPromise(
2014
2372
  makeElectrobunDriver({
2015
2373
  executablePath: electrobunCfg.executablePath ? resolveFromConfig(electrobunCfg.executablePath) : void 0,
2016
2374
  appDir: electrobunCfg.appDir ? resolveFromConfig(electrobunCfg.appDir) : void 0,
@@ -2028,12 +2386,12 @@ async function buildElectrobunRuntime(config, resolveFromConfig) {
2028
2386
  domChannel: bridge
2029
2387
  })
2030
2388
  );
2031
- const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
2389
+ const deviceInfo = await Effect2.runPromise(driver.getDeviceInfo());
2032
2390
  return {
2033
2391
  runtime: {
2034
2392
  driver,
2035
2393
  cleanup: () => safeCleanup(
2036
- () => Effect3.runPromise(driver.killApp("")),
2394
+ () => Effect2.runPromise(driver.killApp("")),
2037
2395
  () => bridge?.disconnect() ?? Promise.resolve()
2038
2396
  ),
2039
2397
  metadata: {
@@ -2095,18 +2453,18 @@ async function buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig)
2095
2453
  warm: warmDaemons?.enabled,
2096
2454
  daemonStateFile: warmDaemons?.stateFile
2097
2455
  });
2098
- const driver = await Effect3.runPromise(
2456
+ const driver = await Effect2.runPromise(
2099
2457
  createUiAutomator2Driver(conn.host, conn.port, device.serial, packageName, {
2100
2458
  domChannel: bridge,
2101
2459
  cdpPort: config.apps?.android?.cdpPort
2102
2460
  })
2103
2461
  );
2104
- const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
2462
+ const deviceInfo = await Effect2.runPromise(driver.getDeviceInfo());
2105
2463
  return {
2106
2464
  runtime: {
2107
2465
  driver,
2108
2466
  cleanup: () => safeCleanup(
2109
- () => Effect3.runPromise(driver.killApp("")),
2467
+ () => Effect2.runPromise(driver.killApp("")),
2110
2468
  () => bridge?.disconnect() ?? Promise.resolve(),
2111
2469
  () => {
2112
2470
  if (reversedBridgePort !== null) {
@@ -2143,7 +2501,7 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
2143
2501
  const bridge = await maybeStartBridge(config.apps?.ios?.bridge, config.execution?.bridge);
2144
2502
  const createIOSRuntime = async (deviceId, conn, simulatorUdid) => {
2145
2503
  const reuseSession = warmDaemons?.enabled && warmDaemons.reuseSession !== false;
2146
- const driver = await Effect3.runPromise(
2504
+ const driver = await Effect2.runPromise(
2147
2505
  createWDADriver(conn.host, conn.port, bundleId, simulatorUdid, snapshotMaxDepth, {
2148
2506
  domChannel: bridge,
2149
2507
  webkitInspectorUrl: config.apps?.ios?.webkitInspectorUrl,
@@ -2153,12 +2511,12 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
2153
2511
  onSessionCreated: reuseSession ? (sessionId) => updateWarmDaemonSession("wda", deviceId, sessionId, bundleId, warmDaemons?.stateFile) : void 0
2154
2512
  })
2155
2513
  );
2156
- const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
2514
+ const deviceInfo = await Effect2.runPromise(driver.getDeviceInfo());
2157
2515
  return {
2158
2516
  runtime: {
2159
2517
  driver,
2160
2518
  cleanup: () => safeCleanup(
2161
- () => Effect3.runPromise(driver.killApp("")),
2519
+ () => Effect2.runPromise(driver.killApp("")),
2162
2520
  () => bridge?.disconnect() ?? Promise.resolve(),
2163
2521
  () => conn.cleanup?.() ?? Promise.resolve()
2164
2522
  ),
@@ -2289,1804 +2647,11 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
2289
2647
  }
2290
2648
  }
2291
2649
 
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
-
2384
- // src/core/video-recorder.ts
2385
- import { execFileSync, spawn as spawn2 } from "child_process";
2386
- import {
2387
- existsSync as existsSync3,
2388
- mkdirSync,
2389
- mkdtempSync as mkdtempSync2,
2390
- readFileSync as readFileSync2,
2391
- rmSync as rmSync2,
2392
- unlinkSync,
2393
- writeFileSync
2394
- } from "fs";
2395
- import { tmpdir as tmpdir2 } from "os";
2396
- import { join as join2 } from "path";
2397
- function hasFfmpegOnPath() {
2398
- try {
2399
- execFileSync(process.platform === "win32" ? "where" : "which", ["ffmpeg"], {
2400
- stdio: "ignore"
2401
- });
2402
- return true;
2403
- } catch {
2404
- return false;
2405
- }
2406
- }
2407
- async function exportFramesToMp4(frames, outputPath, spawnFn = spawn2) {
2408
- if (frames.length === 0 || !hasFfmpegOnPath()) return void 0;
2409
- const tempDir = mkdtempSync2(join2(tmpdir2(), "spana-vid-"));
2410
- try {
2411
- const ext = frames[0].mimeType === "image/png" ? "png" : "jpg";
2412
- const listLines = [];
2413
- for (let i = 0; i < frames.length; i++) {
2414
- const f = frames[i];
2415
- const framePath = join2(tempDir, `frame-${String(i).padStart(5, "0")}.${ext}`);
2416
- writeFileSync(framePath, Buffer.from(f.dataBase64, "base64"));
2417
- const nextTs = frames[i + 1]?.timestampMs ?? f.timestampMs + 250;
2418
- const durSec = Math.max(0.05, Math.min(2, (nextTs - f.timestampMs) / 1e3));
2419
- listLines.push(`file '${framePath.replaceAll("'", "'\\''")}'`);
2420
- listLines.push(`duration ${durSec.toFixed(3)}`);
2421
- }
2422
- const lastPath = join2(tempDir, `frame-${String(frames.length - 1).padStart(5, "0")}.${ext}`);
2423
- listLines.push(`file '${lastPath.replaceAll("'", "'\\''")}'`);
2424
- const listFile = join2(tempDir, "frames.txt");
2425
- writeFileSync(listFile, listLines.join("\n"), "utf8");
2426
- const ok = await new Promise((resolve) => {
2427
- const child = spawnFn(
2428
- "ffmpeg",
2429
- [
2430
- "-y",
2431
- "-f",
2432
- "concat",
2433
- "-safe",
2434
- "0",
2435
- "-i",
2436
- listFile,
2437
- "-vf",
2438
- "pad=ceil(iw/2)*2:ceil(ih/2)*2",
2439
- "-c:v",
2440
- "libx264",
2441
- "-pix_fmt",
2442
- "yuv420p",
2443
- "-movflags",
2444
- "+faststart",
2445
- outputPath
2446
- ],
2447
- { stdio: "ignore" }
2448
- );
2449
- child.on("error", () => resolve(false));
2450
- child.on("close", (code) => resolve(code === 0));
2451
- });
2452
- return ok && existsSync3(outputPath) ? outputPath : void 0;
2453
- } catch {
2454
- return void 0;
2455
- } finally {
2456
- try {
2457
- rmSync2(tempDir, { recursive: true, force: true });
2458
- } catch {
2459
- }
2460
- }
2461
- }
2462
- async function startCdpScreencastRecorder(cdp, options) {
2463
- const startedAt = Date.now();
2464
- const startedAtIso = new Date(startedAt).toISOString();
2465
- const maxFrames = options.maxFrames ?? 180;
2466
- const frames = [];
2467
- let stopped = false;
2468
- const unsubscribe = cdp.onEvent("Page.screencastFrame", (params) => {
2469
- if (stopped) return;
2470
- const sessionId = params?.sessionId;
2471
- if (sessionId !== void 0) {
2472
- void cdp.sendCommand("Page.screencastFrameAck", { sessionId }).catch(() => {
2473
- });
2474
- }
2475
- if (typeof params?.data === "string" && params.data.length > 0) {
2476
- if (frames.length >= maxFrames) {
2477
- frames.splice(1, 1);
2478
- }
2479
- frames.push({
2480
- timestampMs: Math.max(0, Date.now() - startedAt),
2481
- dataBase64: params.data,
2482
- mimeType: "image/jpeg"
2483
- });
2484
- }
2485
- });
2486
- await cdp.sendCommand("Page.startScreencast", {
2487
- format: "jpeg",
2488
- quality: options.quality ?? 65,
2489
- maxWidth: options.maxWidth ?? 1280,
2490
- maxHeight: options.maxHeight ?? 720,
2491
- everyNthFrame: options.everyNthFrame ?? 2
2492
- }).catch(() => {
2493
- });
2494
- return {
2495
- stop: async (stopOpts) => {
2496
- if (stopped) return { frameCount: frames.length };
2497
- stopped = true;
2498
- unsubscribe();
2499
- await cdp.sendCommand("Page.stopScreencast").catch(() => {
2500
- });
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) {
2521
- return { frameCount: 0 };
2522
- }
2523
- mkdirSync(stopOpts.outputDir, { recursive: true });
2524
- let videoPath;
2525
- if (options.exportMp4 !== false) {
2526
- const mp4Target = join2(stopOpts.outputDir, `${stopOpts.fileStem}.mp4`);
2527
- videoPath = await exportFramesToMp4(frames, mp4Target, options.spawnFn);
2528
- }
2529
- const trace = {
2530
- version: 1,
2531
- flowName: options.flowName,
2532
- platform: options.platform,
2533
- startedAtIso,
2534
- durationMs: Math.max(1, Date.now() - startedAt),
2535
- viewport: stopOpts.viewport,
2536
- frames,
2537
- steps: stopOpts.steps ?? [],
2538
- ...videoPath ? { videoPath } : {}
2539
- };
2540
- const playbackJsonPath = join2(stopOpts.outputDir, `${stopOpts.fileStem}-playback.json`);
2541
- writeFileSync(playbackJsonPath, JSON.stringify(trace), "utf8");
2542
- return { playbackJsonPath, videoPath, frameCount: frames.length };
2543
- }
2544
- };
2545
- }
2546
- function startAndroidVideoRecorder(serial, options) {
2547
- const spawnFn = options.spawnFn ?? spawn2;
2548
- const execSyncFn = options.execFileSyncFn ?? execFileSync;
2549
- const remotePath = `/sdcard/spana-rec-${Date.now()}-${Math.floor(Math.random() * 1e4)}.mp4`;
2550
- const child = spawnFn(
2551
- "adb",
2552
- ["-s", serial, "shell", "screenrecord", "--time-limit", "180", remotePath],
2553
- { stdio: "ignore" }
2554
- );
2555
- let stopped = false;
2556
- return {
2557
- stop: async ({ keep }) => {
2558
- if (stopped) return { frameCount: 0 };
2559
- stopped = true;
2560
- try {
2561
- child.kill("SIGINT");
2562
- } catch {
2563
- }
2564
- await new Promise((resolve) => {
2565
- const timer = setTimeout(resolve, 1200);
2566
- child.once("close", () => {
2567
- clearTimeout(timer);
2568
- resolve();
2569
- });
2570
- });
2571
- let savedPath;
2572
- if (keep) {
2573
- try {
2574
- execSyncFn("adb", ["-s", serial, "pull", remotePath, options.outputPath], {
2575
- stdio: "ignore"
2576
- });
2577
- if (existsSync3(options.outputPath)) savedPath = options.outputPath;
2578
- } catch {
2579
- }
2580
- }
2581
- try {
2582
- execSyncFn("adb", ["-s", serial, "shell", "rm", "-f", remotePath], { stdio: "ignore" });
2583
- } catch {
2584
- }
2585
- return { videoPath: savedPath, frameCount: savedPath ? 1 : 0 };
2586
- }
2587
- };
2588
- }
2589
- function startIosSimulatorVideoRecorder(udid, options) {
2590
- const spawnFn = options.spawnFn ?? spawn2;
2591
- const child = spawnFn(
2592
- "xcrun",
2593
- ["simctl", "io", udid, "recordVideo", "--codec=h264", "--force", options.outputPath],
2594
- { stdio: "ignore" }
2595
- );
2596
- let stopped = false;
2597
- return {
2598
- stop: async ({ keep }) => {
2599
- if (stopped) return { frameCount: 0 };
2600
- stopped = true;
2601
- try {
2602
- child.kill("SIGINT");
2603
- } catch {
2604
- }
2605
- await new Promise((resolve) => {
2606
- const timer = setTimeout(resolve, 1500);
2607
- child.once("close", () => {
2608
- clearTimeout(timer);
2609
- resolve();
2610
- });
2611
- });
2612
- if (!keep) {
2613
- try {
2614
- if (existsSync3(options.outputPath)) unlinkSync(options.outputPath);
2615
- } catch {
2616
- }
2617
- return { frameCount: 0 };
2618
- }
2619
- return {
2620
- videoPath: existsSync3(options.outputPath) ? options.outputPath : void 0,
2621
- frameCount: existsSync3(options.outputPath) ? 1 : 0
2622
- };
2623
- }
2624
- };
2625
- }
2626
- function buildPlaybackTraceFromSteps(input) {
2627
- const frames = [];
2628
- const markers = [];
2629
- let cursorMs = 0;
2630
- for (let i = 0; i < input.steps.length; i++) {
2631
- const step = input.steps[i];
2632
- const tapPoint = extractTapPointFromStep(step);
2633
- markers.push({
2634
- index: i,
2635
- command: step.command,
2636
- selector: step.selector,
2637
- startedAtMs: cursorMs,
2638
- durationMs: step.durationMs,
2639
- status: step.status,
2640
- error: step.error,
2641
- ...tapPoint ? { tapPoint } : {}
2642
- });
2643
- const img = step.attachments?.find(
2644
- (a) => a.contentType === "image/png" || a.contentType === "image/jpeg"
2645
- );
2646
- if (img && existsSync3(img.path)) {
2647
- try {
2648
- const dataBase64 = readFileSync2(img.path).toString("base64");
2649
- frames.push({
2650
- timestampMs: cursorMs + step.durationMs,
2651
- dataBase64,
2652
- mimeType: img.contentType === "image/jpeg" ? "image/jpeg" : "image/png"
2653
- });
2654
- } catch {
2655
- }
2656
- }
2657
- cursorMs += Math.max(1, step.durationMs);
2658
- }
2659
- if (frames.length === 0 && !input.videoPath) return null;
2660
- return {
2661
- version: 1,
2662
- flowName: input.flowName,
2663
- platform: input.platform,
2664
- startedAtIso: (/* @__PURE__ */ new Date()).toISOString(),
2665
- durationMs: Math.max(1, input.durationMs),
2666
- viewport: input.viewport,
2667
- frames,
2668
- steps: markers,
2669
- ...input.videoPath ? { videoPath: input.videoPath } : {}
2670
- };
2671
- }
2672
- function extractTapPointFromStep(step) {
2673
- const sel = step.selector;
2674
- if (!sel || typeof sel !== "object") return void 0;
2675
- const pt = sel["point"];
2676
- if (pt && typeof pt["x"] === "number" && typeof pt["y"] === "number") {
2677
- return { x: pt["x"], y: pt["y"] };
2678
- }
2679
- return void 0;
2680
- }
2681
-
2682
- // src/core/engine.ts
2683
- import { Effect as Effect6 } from "effect";
2684
-
2685
- // src/core/artifacts.ts
2686
- import { writeFileSync as writeFileSync2, mkdirSync as mkdirSync2 } from "fs";
2687
- import { join as join3 } from "path";
2688
- import { Effect as Effect4 } from "effect";
2689
- var DEFAULT_ARTIFACT_CONFIG = {
2690
- outputDir: "./spana-output",
2691
- captureOnFailure: true,
2692
- captureOnSuccess: false,
2693
- captureSteps: false,
2694
- screenshot: true,
2695
- uiHierarchy: true,
2696
- consoleLogs: true,
2697
- jsErrors: true,
2698
- har: true,
2699
- video: "off",
2700
- playback: false
2701
- };
2702
- function safeArtifactName(value) {
2703
- return value.replaceAll(/[^a-zA-Z0-9-_]/g, "_").replaceAll(/_+/g, "_").replaceAll(/^_+|_+$/g, "").slice(0, 80) || "artifact";
2704
- }
2705
- var safeName = safeArtifactName;
2706
- function flowArtifactDir(config, flowName, platform) {
2707
- const dir = join3(config.outputDir, `${safeName(flowName)}-${platform}`);
2708
- mkdirSync2(dir, { recursive: true });
2709
- return dir;
2710
- }
2711
- function createAttachment(name, contentType, path) {
2712
- return { name, contentType, path };
2713
- }
2714
- function writeJsonAttachment(dir, fileName, attachmentName, value) {
2715
- const path = join3(dir, fileName);
2716
- writeFileSync2(path, JSON.stringify(value, null, 2), "utf-8");
2717
- return createAttachment(attachmentName, "application/json", path);
2718
- }
2719
- function writeTextAttachment(dir, fileName, attachmentName, value) {
2720
- const path = join3(dir, fileName);
2721
- writeFileSync2(path, value, "utf-8");
2722
- return createAttachment(attachmentName, "text/plain", path);
2723
- }
2724
- function resolveArtifactConfig(...configs) {
2725
- return configs.reduce(
2726
- (resolved, config) => ({
2727
- ...resolved,
2728
- ...config
2729
- }),
2730
- { ...DEFAULT_ARTIFACT_CONFIG }
2731
- );
2732
- }
2733
- async function captureArtifacts(driver, config, flowName, platform, status) {
2734
- const shouldCapture = status === "failed" && config.captureOnFailure || status === "passed" && config.captureOnSuccess;
2735
- if (!shouldCapture) return [];
2736
- const attachments = [];
2737
- const dir = flowArtifactDir(config, flowName, platform);
2738
- if (config.screenshot) {
2739
- try {
2740
- const screenshot = await Effect4.runPromise(Effect4.orDie(driver.takeScreenshot()));
2741
- const path = join3(dir, "screenshot.png");
2742
- writeFileSync2(path, screenshot);
2743
- attachments.push(createAttachment(`${status}-screenshot`, "image/png", path));
2744
- } catch {
2745
- }
2746
- }
2747
- if (config.uiHierarchy) {
2748
- try {
2749
- const hierarchy = await Effect4.runPromise(Effect4.orDie(driver.dumpHierarchy()));
2750
- const path = join3(dir, "hierarchy.json");
2751
- writeFileSync2(path, hierarchy, "utf-8");
2752
- attachments.push(createAttachment(`${status}-hierarchy`, "application/json", path));
2753
- } catch {
2754
- }
2755
- }
2756
- if (config.consoleLogs && driver.getConsoleLogs) {
2757
- try {
2758
- const consoleLogs = await Effect4.runPromise(Effect4.orDie(driver.getConsoleLogs()));
2759
- if (consoleLogs.length > 0) {
2760
- attachments.push(
2761
- writeJsonAttachment(dir, "console-logs.json", `${status}-console-logs`, consoleLogs)
2762
- );
2763
- }
2764
- } catch {
2765
- }
2766
- }
2767
- if (config.jsErrors && driver.getJSErrors) {
2768
- try {
2769
- const jsErrors = await Effect4.runPromise(Effect4.orDie(driver.getJSErrors()));
2770
- if (jsErrors.length > 0) {
2771
- attachments.push(
2772
- writeJsonAttachment(dir, "js-errors.json", `${status}-js-errors`, jsErrors)
2773
- );
2774
- }
2775
- } catch {
2776
- }
2777
- }
2778
- if (config.har && driver.getHAR) {
2779
- try {
2780
- const har = await Effect4.runPromise(Effect4.orDie(driver.getHAR()));
2781
- if (har.log.entries.length > 0) {
2782
- attachments.push(writeJsonAttachment(dir, "network.har", `${status}-network-har`, har));
2783
- }
2784
- } catch {
2785
- }
2786
- }
2787
- if (status === "failed" && driver.getDriverLogs) {
2788
- try {
2789
- const driverLogs = await Effect4.runPromise(Effect4.orDie(driver.getDriverLogs()));
2790
- if (driverLogs.length > 0) {
2791
- attachments.push(
2792
- writeTextAttachment(
2793
- dir,
2794
- "driver-logs.txt",
2795
- `${status}-driver-logs`,
2796
- driverLogs.join("\n")
2797
- )
2798
- );
2799
- }
2800
- } catch {
2801
- }
2802
- }
2803
- return attachments;
2804
- }
2805
- async function captureStepScreenshot(driver, config, flowName, platform, stepIndex, stepName, screenshot) {
2806
- if (!config.screenshot) return void 0;
2807
- try {
2808
- const dir = join3(flowArtifactDir(config, flowName, platform), "steps");
2809
- mkdirSync2(dir, { recursive: true });
2810
- const fileName = `${String(stepIndex).padStart(3, "0")}-${safeName(stepName)}.png`;
2811
- const path = join3(dir, fileName);
2812
- const bytes = screenshot ?? await Effect4.runPromise(Effect4.orDie(driver.takeScreenshot()));
2813
- writeFileSync2(path, bytes);
2814
- return createAttachment(stepName, "image/png", path);
2815
- } catch {
2816
- return void 0;
2817
- }
2818
- }
2819
-
2820
- // src/core/debug-repl.ts
2821
- import * as repl from "repl";
2822
- import { Effect as Effect5 } from "effect";
2823
- var didStartDebugRepl = false;
2824
- function toSuggestedSelectors(root) {
2825
- return flattenElements(root).filter((el) => el.visible !== false && (el.id || el.text || el.accessibilityLabel)).map((el) => ({
2826
- suggestedSelector: el.id ? { testID: el.id } : el.accessibilityLabel ? { accessibilityLabel: el.accessibilityLabel } : el.text ? { text: el.text } : "",
2827
- elementType: el.elementType,
2828
- text: el.text,
2829
- accessibilityLabel: el.accessibilityLabel,
2830
- bounds: el.bounds,
2831
- id: el.id
2832
- }));
2833
- }
2834
- async function runDebugReplOnce(context) {
2835
- if (didStartDebugRepl) {
2836
- return false;
2837
- }
2838
- didStartDebugRepl = true;
2839
- if (!process.stdin.isTTY || !process.stdout.isTTY) {
2840
- console.log("Skipping debug REPL because stdin/stdout is not interactive.");
2841
- return false;
2842
- }
2843
- const hierarchy = async () => context.parseHierarchy(await Effect5.runPromise(context.driver.dumpHierarchy()));
2844
- const selectors = async () => toSuggestedSelectors(await hierarchy());
2845
- console.log("");
2846
- console.log(`Entering debug REPL for failed flow "${context.flowName}" on ${context.platform}.`);
2847
- console.log(
2848
- "Available bindings: app, expect, driver, platform, flowName, error, hierarchy(), selectors(), help()"
2849
- );
2850
- console.log('Use top-level await for async calls, for example: await app.tap({ text: "Login" })');
2851
- const replServer = repl.start({
2852
- prompt: `spana:${context.platform}> `,
2853
- ignoreUndefined: true,
2854
- useGlobal: false
2855
- });
2856
- replServer.context.app = context.app;
2857
- replServer.context.expect = context.expect;
2858
- replServer.context.driver = context.driver;
2859
- replServer.context.platform = context.platform;
2860
- replServer.context.flowName = context.flowName;
2861
- replServer.context.error = context.error;
2862
- replServer.context.hierarchy = hierarchy;
2863
- replServer.context.selectors = selectors;
2864
- replServer.context.help = () => {
2865
- console.log("app Promise-based app API with auto-waiting");
2866
- console.log("expect Assertion helper, e.g. await expect({ text: 'Done' }).toBeVisible()");
2867
- console.log("driver Raw driver service");
2868
- console.log("hierarchy Async helper returning the parsed UI tree");
2869
- console.log("selectors Async helper returning suggested selectors");
2870
- console.log(".exit Leave the REPL");
2871
- };
2872
- await new Promise((resolve) => replServer.on("exit", resolve));
2873
- console.log("");
2874
- return true;
2875
- }
2876
-
2877
- // src/core/step-recorder.ts
2878
- function errorMessage(error) {
2879
- return error instanceof Error ? error.message : String(error);
2880
- }
2881
- function createStepResult(command, durationMs, status, selector, error, attachments) {
2882
- return {
2883
- command,
2884
- selector,
2885
- status,
2886
- durationMs,
2887
- error,
2888
- attachments: attachments && attachments.length > 0 ? attachments : void 0
2889
- };
2890
- }
2891
- function createStepRecorder(driver, artifactConfig, flowName, platform) {
2892
- const steps = [];
2893
- let lastFailureStack;
2894
- return {
2895
- async runStep(command, action, opts) {
2896
- const startedAt = Date.now();
2897
- const callSiteStack = new Error().stack;
2898
- try {
2899
- const result = await action();
2900
- const attachments = [];
2901
- if (opts?.captureScreenshot && artifactConfig.captureSteps) {
2902
- const attachment = await captureStepScreenshot(
2903
- driver,
2904
- artifactConfig,
2905
- flowName,
2906
- platform,
2907
- steps.length + 1,
2908
- command
2909
- );
2910
- if (attachment) attachments.push(attachment);
2911
- }
2912
- steps.push(
2913
- createStepResult(
2914
- command,
2915
- Date.now() - startedAt,
2916
- "passed",
2917
- opts?.selector,
2918
- void 0,
2919
- attachments
2920
- )
2921
- );
2922
- return result;
2923
- } catch (error) {
2924
- lastFailureStack = callSiteStack;
2925
- steps.push(
2926
- createStepResult(
2927
- command,
2928
- Date.now() - startedAt,
2929
- "failed",
2930
- opts?.selector,
2931
- errorMessage(error)
2932
- )
2933
- );
2934
- throw error;
2935
- }
2936
- },
2937
- async runScreenshotStep(command, action, opts) {
2938
- const startedAt = Date.now();
2939
- const callSiteStack = new Error().stack;
2940
- try {
2941
- const screenshot = await action();
2942
- const attachment = await captureStepScreenshot(
2943
- driver,
2944
- artifactConfig,
2945
- flowName,
2946
- platform,
2947
- steps.length + 1,
2948
- opts?.name ?? command,
2949
- screenshot
2950
- );
2951
- steps.push(
2952
- createStepResult(
2953
- command,
2954
- Date.now() - startedAt,
2955
- "passed",
2956
- opts?.selector,
2957
- void 0,
2958
- attachment ? [attachment] : void 0
2959
- )
2960
- );
2961
- return screenshot;
2962
- } catch (error) {
2963
- lastFailureStack = callSiteStack;
2964
- steps.push(
2965
- createStepResult(
2966
- command,
2967
- Date.now() - startedAt,
2968
- "failed",
2969
- opts?.selector,
2970
- errorMessage(error)
2971
- )
2972
- );
2973
- throw error;
2974
- }
2975
- },
2976
- getSteps() {
2977
- return steps;
2978
- },
2979
- getLastFailureStack() {
2980
- return lastFailureStack;
2981
- }
2982
- };
2983
- }
2984
-
2985
- // src/report/classify-error.ts
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
- }
3003
- function selectorHint(selector) {
3004
- if (selector && typeof selector === "object") {
3005
- const s = selector;
3006
- if (s.testID) return `testID="${s.testID}"`;
3007
- if (s.text) return `text="${s.text}"`;
3008
- if (s.accessibilityLabel) return `accessibilityLabel="${s.accessibilityLabel}"`;
3009
- }
3010
- return JSON.stringify(selector);
3011
- }
3012
- function categorizeElementFailure(message) {
3013
- const lower = message.toLowerCase();
3014
- if (lower.includes("not visible") || lower.includes("visible=false")) {
3015
- return "element-not-visible";
3016
- }
3017
- if (lower.includes("off-screen") || lower.includes("zero size")) {
3018
- return "element-off-screen";
3019
- }
3020
- if (lower.includes("disabled") || lower.includes("not interactive")) {
3021
- return "element-not-interactive";
3022
- }
3023
- return "element-not-found";
3024
- }
3025
- function elementSuggestion(category, selector, timeoutMs) {
3026
- switch (category) {
3027
- case "element-not-visible":
3028
- return [
3029
- `Selector ${selector} matched an element, but it is currently hidden.`,
3030
- "Check whether an animation, modal, or loading state is covering it before retrying.",
3031
- "Consider increasing waitTimeout if the element becomes visible after a delay."
3032
- ].join("\n");
3033
- case "element-off-screen":
3034
- return [
3035
- `Selector ${selector} matched an element that is off-screen.`,
3036
- "Use scrollUntilVisible() or scroll to the element before interacting with it.",
3037
- "If the target is above the current viewport, reverse the search direction."
3038
- ].join("\n");
3039
- case "element-not-interactive":
3040
- return [
3041
- `Selector ${selector} matched an element that is disabled or not interactive.`,
3042
- "Wait for the app to enable it, or verify the prerequisite app state first.",
3043
- "Consider increasing waitTimeout if the control becomes enabled after async work completes."
3044
- ].join("\n");
3045
- default:
3046
- return [
3047
- `Selector ${selector} was not found within ${timeoutMs ?? "?"}ms.`,
3048
- "Run `spana selectors` to inspect the current screen and confirm the best selector.",
3049
- "Consider increasing waitTimeout if the element appears after a delay."
3050
- ].join("\n");
3051
- }
3052
- }
3053
- function categorizeDynamic(error, tag, msg) {
3054
- if (tag === "ElementNotFoundError" || tag === "WaitTimeoutError") {
3055
- const sel = selectorHint(error.selector);
3056
- if (msg.includes("scroll(s) toward")) {
3057
- return {
3058
- category: "element-not-found",
3059
- suggestion: [
3060
- `Selector ${sel} stayed off-screen while scrolling.`,
3061
- "Try increasing `maxScrolls` or `timeout`, or reverse the search direction",
3062
- 'if the target is actually above the current viewport (for example `{ direction: "up" }`).'
3063
- ].join("\n")
3064
- };
3065
- }
3066
- if (msg.includes("back action(s)")) {
3067
- return {
3068
- category: "element-not-found",
3069
- suggestion: [
3070
- `Selector ${sel} was not reached while navigating back.`,
3071
- "Try increasing `maxBacks` or `timeout`, or prefer an explicit in-app",
3072
- "back / close control on iOS-style screens instead of relying on system back."
3073
- ].join("\n")
3074
- };
3075
- }
3076
- const category = categorizeElementFailure(msg);
3077
- return {
3078
- category,
3079
- suggestion: elementSuggestion(category, sel, error.timeoutMs)
3080
- };
3081
- }
3082
- if (tag === "TextMismatchError") {
3083
- const e = error;
3084
- return {
3085
- category: "text-mismatch",
3086
- suggestion: [
3087
- `Expected text "${e.expected}" but found "${e.actual ?? "(empty)"}".`,
3088
- "The element exists but its content differs. Check for whitespace, truncation,",
3089
- "or platform-specific text rendering differences."
3090
- ].join("\n")
3091
- };
3092
- }
3093
- if (tag === "DeviceDisconnectedError") {
3094
- const id = error.deviceId ? ` (${error.deviceId})` : "";
3095
- return {
3096
- category: "device-disconnected",
3097
- suggestion: [
3098
- `The device${id} disconnected during the test.`,
3099
- "Check the physical connection or emulator/simulator stability.",
3100
- "Run `spana devices` to verify available devices."
3101
- ].join("\n")
3102
- };
3103
- }
3104
- if (tag === "AppCrashedError") {
3105
- const app = error.appId ? ` (${error.appId})` : "";
3106
- return {
3107
- category: "app-crashed",
3108
- suggestion: [
3109
- `The app${app} crashed during the test.`,
3110
- "Check the device logs for a crash stack trace:",
3111
- " Android: `adb logcat -d | grep FATAL`",
3112
- " iOS: Check Console.app or `log show --predicate 'process == \"your-app\"'`"
3113
- ].join("\n")
3114
- };
3115
- }
3116
- if (tag === "AppNotInstalledError") {
3117
- return {
3118
- category: "app-not-installed",
3119
- suggestion: [
3120
- `App "${error.appId}" is not installed on the device.`,
3121
- "Install it before running tests, or configure `apps.android.appPath`",
3122
- "/ `apps.ios.appPath` in spana.config.ts for auto-install."
3123
- ].join("\n")
3124
- };
3125
- }
3126
- if (tag === "DriverError") {
3127
- return categorizeDynamicDriver(error, msg);
3128
- }
3129
- return void 0;
3130
- }
3131
- function categorizeDynamicDriver(error, msg) {
3132
- for (const rule of driverRules) {
3133
- if (rule.pattern && matchesPattern(msg, rule.pattern)) {
3134
- return {
3135
- category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
3136
- suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
3137
- };
3138
- }
3139
- }
3140
- return {
3141
- category: "driver-error",
3142
- suggestion: error.command ? `Driver command "${error.command}" failed. Check the device connection and driver logs.` : "A low-level driver operation failed. Check the device connection and driver logs."
3143
- };
3144
- }
3145
- var driverRules = [
3146
- {
3147
- pattern: "dismissKeyboard()",
3148
- category: "driver-error",
3149
- suggestion: [
3150
- "Keyboard dismissal failed.",
3151
- 'On Android, try `app.dismissKeyboard({ strategy: "back" })`.',
3152
- "On iOS, prefer tapping a visible Done / Close control or a non-input element."
3153
- ].join("\n")
3154
- },
3155
- {
3156
- pattern: "backUntilVisible()",
3157
- category: "driver-error",
3158
- suggestion: [
3159
- "System back navigation failed before the target screen became visible.",
3160
- "If this route uses app-level navigation, tap the visible back / close control instead.",
3161
- "This is especially common on iOS where a system back button may not exist."
3162
- ].join("\n")
3163
- },
3164
- {
3165
- pattern: "Input text failed",
3166
- category: "driver-error",
3167
- suggestion: [
3168
- "Text input failed at the driver layer.",
3169
- "Make sure the field is focused first, and retry with shorter input chunks if needed.",
3170
- "If the keyboard is in the way, dismiss it before continuing the flow."
3171
- ].join("\n")
3172
- }
3173
- ];
3174
- var tagOnlyRules = [
3175
- {
3176
- tag: "TimeoutError",
3177
- category: "timeout",
3178
- suggestion: [
3179
- "The operation took longer than the allowed timeout.",
3180
- "Try increasing `defaults.waitTimeout` in spana.config.ts,",
3181
- "or set a per-flow timeout: `flow('name', { timeout: 30000 }, ...)`."
3182
- ].join("\n")
3183
- },
3184
- {
3185
- tag: ["ConfigError", "FlowSyntaxError"],
3186
- category: "config-error",
3187
- suggestion: "Run `spana validate-config` to check your configuration."
3188
- }
3189
- ];
3190
- var heuristicRules = [
3191
- {
3192
- pattern: /[Tt]imed out/,
3193
- category: "timeout",
3194
- suggestion: "The operation timed out. Try increasing `defaults.waitTimeout` in spana.config.ts."
3195
- },
3196
- {
3197
- pattern: /not found|not visible|not fillable|covered by/,
3198
- category: (msg) => categorizeElementFailure(msg),
3199
- suggestion: (_error, msg) => {
3200
- if (msg.includes("scroll(s) toward")) {
3201
- return "The target stayed off-screen while scrolling. Increase `maxScrolls` / `timeout`, or reverse the scroll search direction.";
3202
- }
3203
- const category = categorizeElementFailure(msg);
3204
- return elementSuggestion(category, "the target selector", void 0);
3205
- }
3206
- },
3207
- {
3208
- pattern: "dismissKeyboard()",
3209
- category: "driver-error",
3210
- suggestion: 'Keyboard dismissal failed. On Android try `app.dismissKeyboard({ strategy: "back" })`; on iOS prefer an explicit Done / Close control.'
3211
- },
3212
- {
3213
- pattern: /ECONNREFUSED|ECONNRESET|disconnected/,
3214
- category: "device-disconnected",
3215
- suggestion: "The connection was lost. Check the device or emulator/simulator is still running."
3216
- }
3217
- ];
3218
- function matchesPattern(msg, pattern) {
3219
- return typeof pattern === "string" ? msg.includes(pattern) : pattern.test(msg);
3220
- }
3221
- function matchesTag(tag, rule) {
3222
- if (!rule.tag) return true;
3223
- if (Array.isArray(rule.tag)) return tag != null && rule.tag.includes(tag);
3224
- return tag === rule.tag;
3225
- }
3226
- function categorize(error) {
3227
- const tag = error[TAG_KEY];
3228
- const msg = error.message ?? "";
3229
- const dynamic = categorizeDynamic(error, tag, msg);
3230
- if (dynamic) return dynamic;
3231
- for (const rule of tagOnlyRules) {
3232
- if (matchesTag(tag, rule)) {
3233
- return {
3234
- category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
3235
- suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
3236
- };
3237
- }
3238
- }
3239
- for (const rule of heuristicRules) {
3240
- if (rule.pattern && matchesPattern(msg, rule.pattern)) {
3241
- return {
3242
- category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
3243
- suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
3244
- };
3245
- }
3246
- }
3247
- return { category: "unknown" };
3248
- }
3249
- function classifyError(error, opts) {
3250
- const tagged = unwrapTaggedError(error);
3251
- const { category, suggestion } = categorize(tagged);
3252
- const extracted = extractCodeFrame(error.stack, opts?.flowFilePath) ?? extractCodeFrame(opts?.fallbackStack, opts?.flowFilePath);
3253
- return {
3254
- message: tagged.message ?? error.message,
3255
- stack: error.stack,
3256
- category,
3257
- suggestion,
3258
- ...extracted ? { location: extracted.location, codeFrame: extracted.frame } : {}
3259
- };
3260
- }
3261
-
3262
- // src/core/engine.ts
3263
- import { writeFileSync as writeFileSync4 } from "fs";
3264
- import { join as join5 } from "path";
3265
-
3266
- // src/report/failure-bundle.ts
3267
- import { writeFileSync as writeFileSync3, readFileSync as readFileSync3, existsSync as existsSync4 } from "fs";
3268
- import { join as join4, basename } from "path";
3269
- function levenshtein(a, b) {
3270
- const m = a.length;
3271
- const n = b.length;
3272
- const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
3273
- for (let i = 0; i <= m; i++) dp[i][0] = i;
3274
- for (let j = 0; j <= n; j++) dp[0][j] = j;
3275
- for (let i = 1; i <= m; i++) {
3276
- for (let j = 1; j <= n; j++) {
3277
- dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
3278
- }
3279
- }
3280
- return dp[m][n];
3281
- }
3282
- function extractIdentifiers(hierarchyJson) {
3283
- const testIDs = [];
3284
- const texts = [];
3285
- try {
3286
- const root = JSON.parse(hierarchyJson);
3287
- const queue = [root];
3288
- while (queue.length > 0) {
3289
- const node = queue.pop();
3290
- if (!node || typeof node !== "object") continue;
3291
- if (node.testID && typeof node.testID === "string") testIDs.push(node.testID);
3292
- if (node.text && typeof node.text === "string") texts.push(node.text);
3293
- if (Array.isArray(node.children)) {
3294
- for (const child of node.children) queue.push(child);
3295
- }
3296
- }
3297
- } catch {
3298
- }
3299
- return { testIDs, texts };
3300
- }
3301
- function findNearbySelectors(attempted, hierarchyJson) {
3302
- if (!hierarchyJson) return [];
3303
- const { testIDs, texts } = extractIdentifiers(hierarchyJson);
3304
- let target;
3305
- let candidates;
3306
- if (typeof attempted === "string") {
3307
- target = attempted.toLowerCase();
3308
- candidates = [...testIDs, ...texts];
3309
- } else if (attempted && typeof attempted === "object") {
3310
- const sel = attempted;
3311
- if (typeof sel.testID === "string") {
3312
- target = sel.testID.toLowerCase();
3313
- candidates = testIDs;
3314
- } else if (typeof sel.text === "string") {
3315
- target = sel.text.toLowerCase();
3316
- candidates = texts;
3317
- } else if (typeof sel.accessibilityLabel === "string") {
3318
- target = sel.accessibilityLabel.toLowerCase();
3319
- candidates = [...testIDs, ...texts];
3320
- } else {
3321
- return [];
3322
- }
3323
- } else {
3324
- return [];
3325
- }
3326
- const scored = candidates.filter((c) => c !== target).map((c) => {
3327
- const cl = c.toLowerCase();
3328
- const substringMatch = cl.includes(target) || target.includes(cl);
3329
- const dist = levenshtein(target, cl);
3330
- return { value: c, score: substringMatch ? 0 : dist };
3331
- }).filter((s) => s.score <= 5).toSorted((a, b) => a.score - b.score);
3332
- const seen = /* @__PURE__ */ new Set();
3333
- const results = [];
3334
- for (const s of scored) {
3335
- if (!seen.has(s.value)) {
3336
- seen.add(s.value);
3337
- results.push(s.value);
3338
- if (results.length >= 5) break;
3339
- }
3340
- }
3341
- return results;
3342
- }
3343
- function buildArtifactMap(attachments) {
3344
- const map = {};
3345
- if (!attachments) return map;
3346
- for (const att of attachments) {
3347
- const filename = basename(att.path);
3348
- if (filename === "screenshot.png") map.screenshot = filename;
3349
- else if (filename === "hierarchy.json") map.hierarchy = filename;
3350
- else if (filename === "console-logs.json") map.consoleLogs = filename;
3351
- else if (filename === "js-errors.json") map.jsErrors = filename;
3352
- else if (filename === "network.har") map.har = filename;
3353
- else if (filename === "driver-logs.txt") map.driverLogs = filename;
3354
- }
3355
- return map;
3356
- }
3357
- function createFailureBundle(flowName, platform, steps, error, artifactDir, attachments, flowPath) {
3358
- const failedStepIndex = steps.findLastIndex((s) => s.status === "failed");
3359
- const failedStep = failedStepIndex >= 0 ? {
3360
- index: failedStepIndex,
3361
- command: steps[failedStepIndex].command,
3362
- selector: steps[failedStepIndex].selector ?? null,
3363
- durationMs: steps[failedStepIndex].durationMs,
3364
- error: steps[failedStepIndex].error
3365
- } : null;
3366
- const lastPassedIndex = failedStepIndex > 0 ? steps.findLastIndex((s, i) => i < failedStepIndex && s.status === "passed") : -1;
3367
- const lastPassedStep = lastPassedIndex >= 0 ? {
3368
- index: lastPassedIndex,
3369
- command: steps[lastPassedIndex].command,
3370
- selector: steps[lastPassedIndex].selector ?? null,
3371
- durationMs: steps[lastPassedIndex].durationMs
3372
- } : null;
3373
- let selectorContext;
3374
- if (failedStep?.selector && (error.category === "element-not-found" || error.category === "element-not-visible")) {
3375
- const hierarchyPath = join4(artifactDir, "hierarchy.json");
3376
- let hierarchyJson = null;
3377
- if (existsSync4(hierarchyPath)) {
3378
- try {
3379
- hierarchyJson = readFileSync3(hierarchyPath, "utf-8");
3380
- } catch {
3381
- }
3382
- }
3383
- const nearbyAlternatives = findNearbySelectors(failedStep.selector, hierarchyJson);
3384
- selectorContext = {
3385
- attempted: failedStep.selector,
3386
- nearbyAlternatives
3387
- };
3388
- }
3389
- const shellQuote = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
3390
- const flowFile = flowPath ?? `flows/${flowName.replaceAll(" ", "-")}.flow.ts`;
3391
- const reproCommand = `spana test ${shellQuote(flowFile)} --platform ${platform} --grep ${shellQuote(flowName)}`;
3392
- let runtimeDiagnostics;
3393
- const consolePath = join4(artifactDir, "console-logs.json");
3394
- const jsErrPath = join4(artifactDir, "js-errors.json");
3395
- if (existsSync4(consolePath) || existsSync4(jsErrPath)) {
3396
- let consoleErrorCount = 0;
3397
- let consoleWarnCount = 0;
3398
- const recentConsoleErrors = [];
3399
- let jsErrorCount = 0;
3400
- const recentJsErrors = [];
3401
- if (existsSync4(consolePath)) {
3402
- try {
3403
- const logs = JSON.parse(readFileSync3(consolePath, "utf-8"));
3404
- if (Array.isArray(logs)) {
3405
- for (const entry of logs) {
3406
- const lvl = (entry.type ?? entry.level ?? "").toLowerCase();
3407
- const text = entry.text ?? entry.message ?? "";
3408
- if (lvl === "error") {
3409
- consoleErrorCount++;
3410
- if (text) recentConsoleErrors.push(text);
3411
- } else if (lvl === "warn" || lvl === "warning") {
3412
- consoleWarnCount++;
3413
- }
3414
- }
3415
- }
3416
- } catch {
3417
- }
3418
- }
3419
- if (existsSync4(jsErrPath)) {
3420
- try {
3421
- const errs = JSON.parse(readFileSync3(jsErrPath, "utf-8"));
3422
- if (Array.isArray(errs)) {
3423
- jsErrorCount = errs.length;
3424
- for (const e of errs.slice(-5)) {
3425
- const msg = e.message ?? e.text ?? String(e);
3426
- if (msg) recentJsErrors.push(msg);
3427
- }
3428
- }
3429
- } catch {
3430
- }
3431
- }
3432
- if (consoleErrorCount > 0 || consoleWarnCount > 0 || jsErrorCount > 0) {
3433
- runtimeDiagnostics = {
3434
- consoleErrorCount,
3435
- consoleWarnCount,
3436
- recentConsoleErrors: recentConsoleErrors.slice(-5),
3437
- jsErrorCount,
3438
- recentJsErrors
3439
- };
3440
- }
3441
- }
3442
- const bundle = {
3443
- schemaVersion: 1,
3444
- flow: flowName,
3445
- platform,
3446
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3447
- failedStep,
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
- })),
3457
- error: {
3458
- message: error.message,
3459
- category: error.category,
3460
- suggestion: error.suggestion,
3461
- errorCode: error.errorCode,
3462
- ...error.location ? { location: error.location } : {},
3463
- ...error.codeFrame ? { codeFrame: error.codeFrame } : {}
3464
- },
3465
- selectorContext,
3466
- ...runtimeDiagnostics ? { runtimeDiagnostics } : {},
3467
- artifacts: buildArtifactMap(attachments),
3468
- reproCommand,
3469
- durationMs: steps.reduce((sum, s) => sum + s.durationMs, 0)
3470
- };
3471
- return bundle;
3472
- }
3473
- function writeFailureBundle(bundle, artifactDir) {
3474
- const path = join4(artifactDir, "failure-bundle.json");
3475
- writeFileSync3(path, JSON.stringify(bundle, null, 2), "utf-8");
3476
- return path;
3477
- }
3478
-
3479
- // src/core/engine.ts
3480
- function isCdpScreencastCapable(channel) {
3481
- return Boolean(channel) && typeof channel.sendCommand === "function" && typeof channel.onEvent === "function";
3482
- }
3483
- function buildPlaybackStepMarkers(steps) {
3484
- let cursorMs = 0;
3485
- return steps.map((step, index) => {
3486
- const startedAtMs = cursorMs;
3487
- cursorMs += Math.max(1, step.durationMs);
3488
- const sel = step.selector;
3489
- const pt = sel && typeof sel === "object" ? sel["point"] : void 0;
3490
- const tapPoint = pt && typeof pt["x"] === "number" && typeof pt["y"] === "number" ? { x: pt["x"], y: pt["y"] } : void 0;
3491
- return {
3492
- index,
3493
- command: step.command,
3494
- selector: step.selector,
3495
- startedAtMs,
3496
- durationMs: step.durationMs,
3497
- status: step.status,
3498
- error: step.error,
3499
- ...tapPoint ? { tapPoint } : {}
3500
- };
3501
- });
3502
- }
3503
- async function executeFlow(flow, driver, config) {
3504
- const start2 = Date.now();
3505
- const { platform, coordinatorConfig, appId } = config;
3506
- const autoLaunch = flow.config.autoLaunch ?? config.autoLaunch ?? true;
3507
- const timeout = flow.config.timeout ?? config.flowTimeout ?? 6e4;
3508
- const artifactConfig = resolveArtifactConfig(config.artifactConfig, flow.config.artifacts);
3509
- const stepRecorder = createStepRecorder(driver, artifactConfig, flow.name, platform);
3510
- const launchOptions = mergeLaunchOptions(config.launchOptions, flow.config.launchOptions);
3511
- const flowDefaults = flow.config.defaults;
3512
- const mergedCoordinatorConfig = flowDefaults ? {
3513
- ...coordinatorConfig,
3514
- defaults: {
3515
- ...coordinatorConfig.defaults,
3516
- timeout: flowDefaults.waitTimeout ?? coordinatorConfig.defaults?.timeout,
3517
- pollInterval: flowDefaults.pollInterval ?? coordinatorConfig.defaults?.pollInterval,
3518
- settleTimeout: flowDefaults.settleTimeout ?? coordinatorConfig.defaults?.settleTimeout,
3519
- initialPollInterval: flowDefaults.initialPollInterval ?? coordinatorConfig.defaults?.initialPollInterval
3520
- },
3521
- waitForIdleTimeout: flowDefaults.waitForIdleTimeout ?? coordinatorConfig.waitForIdleTimeout,
3522
- typingDelay: flowDefaults.typingDelay ?? coordinatorConfig.typingDelay,
3523
- hierarchyCacheTtl: flowDefaults.hierarchyCacheTtl ?? coordinatorConfig.hierarchyCacheTtl
3524
- } : coordinatorConfig;
3525
- const flowMeta = {
3526
- flowFilePath: flow.sourcePath ?? "",
3527
- flowName: flow.name,
3528
- platform,
3529
- updateBaselines: config.updateBaselines ?? false
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
- });
3540
- const expect = createPromiseExpect(
3541
- driver,
3542
- mergedCoordinatorConfig,
3543
- stepRecorder,
3544
- flowMeta,
3545
- config.visualRegression
3546
- );
3547
- const flowCtx = { app, expect, platform, updateBaselines: flowMeta.updateBaselines };
3548
- const sessionManager = new SessionManager();
3549
- const sessions = createSessions(
3550
- sessionManager,
3551
- async (opts) => {
3552
- const pwDriver = await Effect6.runPromise(
3553
- makePlaywrightDriver({
3554
- browser: opts.browser,
3555
- headless: opts.headless ?? true,
3556
- baseUrl: opts.baseUrl,
3557
- storageState: opts.storageState,
3558
- verboseLogging: opts.verboseLogging
3559
- })
3560
- );
3561
- return pwDriver;
3562
- },
3563
- { parse: (raw) => parseWebHierarchy(raw) }
3564
- );
3565
- flowCtx.sessions = sessions;
3566
- let videoRecorder;
3567
- let recordingFinalized = false;
3568
- const wantRecording = artifactConfig.video !== "off" || artifactConfig.playback;
3569
- const finalizeRecording = async (status, attachments, steps, durationMs) => {
3570
- if (recordingFinalized || !wantRecording) return;
3571
- recordingFinalized = true;
3572
- const keep = artifactConfig.video === "on" || artifactConfig.playback || artifactConfig.video === "retain-on-failure" && status === "failed";
3573
- const fileStem = safeArtifactName(flow.name);
3574
- const outputDir = keep ? flowArtifactDir(artifactConfig, flow.name, platform) : artifactConfig.outputDir;
3575
- let viewport;
3576
- try {
3577
- const info = await Effect6.runPromise(Effect6.orDie(driver.getDeviceInfo()));
3578
- if (info.screenWidth > 0 && info.screenHeight > 0) {
3579
- viewport = { width: info.screenWidth, height: info.screenHeight };
3580
- }
3581
- } catch {
3582
- }
3583
- let stopRes;
3584
- if (videoRecorder) {
3585
- try {
3586
- stopRes = await videoRecorder.stop({
3587
- keep,
3588
- outputDir,
3589
- fileStem,
3590
- steps: buildPlaybackStepMarkers(steps),
3591
- viewport
3592
- });
3593
- } catch {
3594
- }
3595
- }
3596
- if (!keep) return;
3597
- if (stopRes?.videoPath) {
3598
- attachments.push({
3599
- name: "video",
3600
- contentType: stopRes.videoPath.endsWith(".webm") ? "video/webm" : "video/mp4",
3601
- path: stopRes.videoPath
3602
- });
3603
- }
3604
- if (stopRes?.playbackJsonPath) {
3605
- attachments.push({
3606
- name: "playback",
3607
- contentType: "application/json",
3608
- path: stopRes.playbackJsonPath
3609
- });
3610
- return;
3611
- }
3612
- const fallbackTrace = buildPlaybackTraceFromSteps({
3613
- flowName: flow.name,
3614
- platform,
3615
- durationMs,
3616
- steps,
3617
- viewport,
3618
- videoPath: stopRes?.videoPath
3619
- });
3620
- if (fallbackTrace) {
3621
- const playbackPath = join5(outputDir, `${fileStem}-playback.json`);
3622
- writeFileSync4(playbackPath, JSON.stringify(fallbackTrace), "utf8");
3623
- attachments.push({
3624
- name: "playback",
3625
- contentType: "application/json",
3626
- path: playbackPath
3627
- });
3628
- }
3629
- };
3630
- const buildFailureResult = async (error) => {
3631
- const attachments = await captureArtifacts(
3632
- driver,
3633
- artifactConfig,
3634
- flow.name,
3635
- platform,
3636
- "failed"
3637
- );
3638
- const steps = stepRecorder.getSteps();
3639
- const durationMs = Date.now() - start2;
3640
- await finalizeRecording("failed", attachments, steps, durationMs);
3641
- const normalized = error instanceof Error ? error : new Error(String(error));
3642
- return {
3643
- name: flow.name,
3644
- platform,
3645
- status: "failed",
3646
- durationMs,
3647
- error: classifyError(normalized, {
3648
- flowFilePath: flow.sourcePath,
3649
- fallbackStack: stepRecorder.getLastFailureStack?.()
3650
- }),
3651
- attachments,
3652
- steps,
3653
- scenarioSteps: flowCtx.__scenarioSteps
3654
- };
3655
- };
3656
- if (driver.beginFlow) {
3657
- try {
3658
- await Effect6.runPromise(driver.beginFlow(flow.name));
3659
- } catch (error) {
3660
- return buildFailureResult(error);
3661
- }
3662
- }
3663
- if (wantRecording) {
3664
- try {
3665
- if (isCdpScreencastCapable(driver.domChannel)) {
3666
- videoRecorder = await startCdpScreencastRecorder(driver.domChannel, {
3667
- flowName: flow.name,
3668
- platform,
3669
- exportMp4: artifactConfig.video !== "off"
3670
- });
3671
- } else if (artifactConfig.video !== "off" && (platform === "android" || platform === "ios")) {
3672
- const info = await Effect6.runPromise(Effect6.orDie(driver.getDeviceInfo())).catch(
3673
- () => void 0
3674
- );
3675
- if (info?.deviceId) {
3676
- const outDir = flowArtifactDir(artifactConfig, flow.name, platform);
3677
- const videoOut = join5(outDir, `${safeArtifactName(flow.name)}.mp4`);
3678
- videoRecorder = platform === "android" ? startAndroidVideoRecorder(info.deviceId, { outputPath: videoOut }) : startIosSimulatorVideoRecorder(info.deviceId, { outputPath: videoOut });
3679
- }
3680
- }
3681
- } catch {
3682
- }
3683
- }
3684
- if (config.hooks?.beforeEach) {
3685
- try {
3686
- await config.hooks.beforeEach({ app, platform });
3687
- } catch (error) {
3688
- return buildFailureResult(error);
3689
- }
3690
- }
3691
- let result;
3692
- try {
3693
- if (autoLaunch) {
3694
- await app.launch();
3695
- }
3696
- await Promise.race([
3697
- flow.fn(flowCtx),
3698
- new Promise(
3699
- (_, reject) => setTimeout(
3700
- () => reject(new Error(`Flow "${flow.name}" timed out after ${timeout}ms`)),
3701
- timeout
3702
- )
3703
- )
3704
- ]);
3705
- const attachments = await captureArtifacts(
3706
- driver,
3707
- artifactConfig,
3708
- flow.name,
3709
- platform,
3710
- "passed"
3711
- );
3712
- const steps = stepRecorder.getSteps();
3713
- const durationMs = Date.now() - start2;
3714
- await finalizeRecording("passed", attachments, steps, durationMs);
3715
- result = {
3716
- name: flow.name,
3717
- platform,
3718
- status: "passed",
3719
- durationMs,
3720
- attachments,
3721
- steps,
3722
- scenarioSteps: flowCtx.__scenarioSteps
3723
- };
3724
- } catch (error) {
3725
- const attachments = await captureArtifacts(
3726
- driver,
3727
- artifactConfig,
3728
- flow.name,
3729
- platform,
3730
- "failed"
3731
- );
3732
- const steps = stepRecorder.getSteps();
3733
- const durationMs = Date.now() - start2;
3734
- await finalizeRecording("failed", attachments, steps, durationMs);
3735
- const flowError = error instanceof Error ? error : new Error(String(error));
3736
- result = {
3737
- name: flow.name,
3738
- platform,
3739
- status: "failed",
3740
- durationMs,
3741
- error: classifyError(flowError, {
3742
- flowFilePath: flow.sourcePath,
3743
- fallbackStack: stepRecorder.getLastFailureStack?.()
3744
- }),
3745
- attachments,
3746
- steps,
3747
- scenarioSteps: flowCtx.__scenarioSteps
3748
- };
3749
- if (artifactConfig.captureOnFailure && result.error) {
3750
- try {
3751
- const artDir = join5(
3752
- artifactConfig.outputDir,
3753
- `${flow.name.replaceAll(/[^a-zA-Z0-9-_]/g, "_").replaceAll(/_+/g, "_").slice(0, 80) || "artifact"}-${platform}`
3754
- );
3755
- const bundle = createFailureBundle(
3756
- flow.name,
3757
- platform,
3758
- stepRecorder.getSteps(),
3759
- result.error,
3760
- artDir,
3761
- attachments,
3762
- flow.sourcePath
3763
- );
3764
- writeFailureBundle(bundle, artDir);
3765
- } catch {
3766
- }
3767
- }
3768
- if (config.debugOnFailure) {
3769
- await runDebugReplOnce({
3770
- app,
3771
- expect,
3772
- driver,
3773
- error: flowError,
3774
- flowName: flow.name,
3775
- platform,
3776
- parseHierarchy: coordinatorConfig.parse
3777
- });
3778
- }
3779
- }
3780
- for (const cleanup of extraCleanups.toReversed()) {
3781
- try {
3782
- await cleanup();
3783
- } catch {
3784
- }
3785
- }
3786
- try {
3787
- await sessionManager.disconnectAll();
3788
- } catch {
3789
- }
3790
- if (config.hooks?.afterEach) {
3791
- try {
3792
- await config.hooks.afterEach({ app, platform, result });
3793
- } catch (hookError) {
3794
- console.warn(
3795
- `afterEach hook failed: ${hookError instanceof Error ? hookError.message : hookError}`
3796
- );
3797
- }
3798
- }
3799
- return result;
3800
- }
3801
-
3802
- // src/core/parallel.ts
3803
- function orderFlowsLongestFirst(flows, durationHintsMs) {
3804
- if (!durationHintsMs || Object.keys(durationHintsMs).length === 0) {
3805
- return flows;
3806
- }
3807
- return flows.toSorted((a, b) => (durationHintsMs[b.name] ?? 0) - (durationHintsMs[a.name] ?? 0));
3808
- }
3809
- async function runParallel(config) {
3810
- const {
3811
- workers,
3812
- flows: rawFlows,
3813
- onFlowComplete,
3814
- onFlowStart,
3815
- retries = 0,
3816
- retryDelay = 0,
3817
- bail,
3818
- durationHintsMs,
3819
- claimNextFlow
3820
- } = config;
3821
- const flows = orderFlowsLongestFirst(rawFlows, durationHintsMs);
3822
- const start2 = Date.now();
3823
- const results = [];
3824
- let nextFlowIndex = 0;
3825
- let failureCount = 0;
3826
- let bailedOut = false;
3827
- const workerPromises = workers.map(async (worker) => {
3828
- const stats = { flowCount: 0, totalMs: 0 };
3829
- while (true) {
3830
- if (bail !== void 0 && failureCount >= bail) break;
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
- }
3841
- let result;
3842
- let attempts = 0;
3843
- onFlowStart?.(flow.name, worker.name);
3844
- for (let attempt = 0; attempt <= retries; attempt++) {
3845
- if (attempt > 0 && retryDelay > 0) {
3846
- await new Promise((resolve) => setTimeout(resolve, retryDelay));
3847
- }
3848
- result = await executeFlow(flow, worker.driver, worker.engineConfig);
3849
- attempts++;
3850
- if (result.status === "passed") break;
3851
- }
3852
- if (result.status === "passed" && attempts > 1) {
3853
- result.flaky = true;
3854
- }
3855
- result.attempts = attempts;
3856
- results.push(result);
3857
- stats.flowCount++;
3858
- stats.totalMs += result.durationMs;
3859
- if (result.status === "failed") {
3860
- failureCount++;
3861
- }
3862
- onFlowComplete?.(result, worker.name);
3863
- }
3864
- return { workerId: worker.id, stats };
3865
- });
3866
- const workerResults = await Promise.all(workerPromises);
3867
- if (!claimNextFlow && bail !== void 0 && failureCount >= bail) {
3868
- bailedOut = true;
3869
- while (nextFlowIndex < flows.length) {
3870
- const flow = flows[nextFlowIndex++];
3871
- results.push({
3872
- name: flow.name,
3873
- platform: workers[0].engineConfig.platform,
3874
- status: "skipped",
3875
- durationMs: 0,
3876
- attempts: 0
3877
- });
3878
- }
3879
- }
3880
- const workerStats = /* @__PURE__ */ new Map();
3881
- for (const wr of workerResults) {
3882
- workerStats.set(wr.workerId, wr.stats);
3883
- }
3884
- return {
3885
- results,
3886
- totalDurationMs: Date.now() - start2,
3887
- passed: results.filter((r) => r.status === "passed").length,
3888
- failed: results.filter((r) => r.status === "failed").length,
3889
- skipped: results.filter((r) => r.status === "skipped").length,
3890
- flaky: results.filter((r) => r.flaky === true).length,
3891
- bailedOut: bailedOut || void 0,
3892
- workerStats
3893
- };
3894
- }
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
-
4089
2650
  export {
2651
+ resolveBrowserExtensions,
2652
+ applyExtensionChromeArgs,
2653
+ getLoadedExtensions,
2654
+ runOAuthPopupFlow,
4090
2655
  launchDirectCdpBrowser,
4091
2656
  UPLOAD_ATTACH_TIMEOUT_MS,
4092
2657
  makeLightweightCdpDriver,
@@ -4097,24 +2662,6 @@ export {
4097
2662
  buildElectronRuntime,
4098
2663
  buildElectrobunRuntime,
4099
2664
  buildLocalAndroidRuntime,
4100
- buildLocalIOSRuntime,
4101
- formatCodeFrame,
4102
- extractCodeFrame,
4103
- classifyError,
4104
- exportFramesToMp4,
4105
- startCdpScreencastRecorder,
4106
- startAndroidVideoRecorder,
4107
- startIosSimulatorVideoRecorder,
4108
- buildPlaybackTraceFromSteps,
4109
- executeFlow,
4110
- orderFlowsLongestFirst,
4111
- runParallel,
4112
- DEFAULT_MAX_WORKERS_PER_PROCESS,
4113
- startSharedFlowQueueServer,
4114
- createRemoteFlowClaimer,
4115
- planProcessPool,
4116
- partitionFlowsAcrossProcesses,
4117
- writeWorkerProcessReport,
4118
- runMultiProcessPool
2665
+ buildLocalIOSRuntime
4119
2666
  };
4120
- //# sourceMappingURL=chunk-ALPQES3J.js.map
2667
+ //# sourceMappingURL=chunk-3IZMPNE7.js.map