spana-test 0.10.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 (81) hide show
  1. package/dist/agent/index.d.ts +2 -2
  2. package/dist/agent/index.js +10 -7
  3. package/dist/agent-fixture-5C4MCWRD.js +20 -0
  4. package/dist/app-RSDPDTKT.js +10 -0
  5. package/dist/cache-command-PANUAEMZ.js +12 -0
  6. package/dist/{chunk-C2HBFEMQ.js → chunk-26NJXP55.js} +2 -2
  7. package/dist/{chunk-66D3C7NB.js → chunk-3IZMPNE7.js} +504 -2071
  8. package/dist/chunk-3IZMPNE7.js.map +1 -0
  9. package/dist/chunk-4KK4E3N3.js +3587 -0
  10. package/dist/chunk-4KK4E3N3.js.map +1 -0
  11. package/dist/{chunk-6GBAPW6K.js → chunk-4SA7JK5D.js} +15 -11
  12. package/dist/{chunk-6GBAPW6K.js.map → chunk-4SA7JK5D.js.map} +1 -1
  13. package/dist/{chunk-DP7MGXHN.js → chunk-64UZQP7Z.js} +27 -3
  14. package/dist/chunk-64UZQP7Z.js.map +1 -0
  15. package/dist/chunk-6PTUVG6A.js +127 -0
  16. package/dist/chunk-6PTUVG6A.js.map +1 -0
  17. package/dist/chunk-FPQAJNE3.js +2874 -0
  18. package/dist/chunk-FPQAJNE3.js.map +1 -0
  19. package/dist/{chunk-B35G77DN.js → chunk-FXBWACUT.js} +351 -3471
  20. package/dist/chunk-FXBWACUT.js.map +1 -0
  21. package/dist/chunk-OPTNFLBL.js +556 -0
  22. package/dist/chunk-OPTNFLBL.js.map +1 -0
  23. package/dist/chunk-S7MSBZ3F.js +72 -0
  24. package/dist/chunk-S7MSBZ3F.js.map +1 -0
  25. package/dist/chunk-SGZMO456.js +2125 -0
  26. package/dist/chunk-SGZMO456.js.map +1 -0
  27. package/dist/{chunk-Y6KMJJ2T.js → chunk-SIJJVN2D.js} +358 -3
  28. package/dist/chunk-SIJJVN2D.js.map +1 -0
  29. package/dist/{chunk-SF7UYW4I.js → chunk-VUNH4AJD.js} +4 -4
  30. package/dist/{chunk-B473XZOM.js → chunk-WS2TVNMY.js} +18 -1964
  31. package/dist/chunk-WS2TVNMY.js.map +1 -0
  32. package/dist/{chunk-IXON7DMB.js → chunk-WZAQANN6.js} +2 -2
  33. package/dist/{chunk-7QFJ7MDH.js → chunk-XA6LWLZQ.js} +64 -3
  34. package/dist/chunk-XA6LWLZQ.js.map +1 -0
  35. package/dist/cli.js +190 -17
  36. package/dist/cli.js.map +1 -1
  37. package/dist/config-loader-CNGIW2XK.js +9 -0
  38. package/dist/{discover-RLSKEBAX.js → discover-NKDMB4UI.js} +3 -3
  39. package/dist/{doctor-command-QIYBI7ZF.js → doctor-command-6ZVJWCW7.js} +5 -4
  40. package/dist/{doctor-command-QIYBI7ZF.js.map → doctor-command-6ZVJWCW7.js.map} +1 -1
  41. package/dist/{app-xIYd2jde.d.ts → flow-DddAj1xv.d.ts} +960 -356
  42. package/dist/gherkin/steps.d.ts +1 -2
  43. package/dist/index.d.ts +486 -131
  44. package/dist/index.js +474 -275
  45. package/dist/index.js.map +1 -1
  46. package/dist/local-DM3YBSV5.js +31 -0
  47. package/dist/{runner-JID2YWRE.js → runner-WOVZWUQR.js} +2 -2
  48. package/dist/runner-WOVZWUQR.js.map +1 -0
  49. package/dist/{server-UIRGHUYM.js → server-ING5D5ZJ.js} +2 -2
  50. package/dist/server-ING5D5ZJ.js.map +1 -0
  51. package/dist/{server-6KQSTQIG.js → server-JNQ2PLCC.js} +10 -7
  52. package/dist/{server-6KQSTQIG.js.map → server-JNQ2PLCC.js.map} +1 -1
  53. package/dist/session-5TNWVGQQ.js +21 -0
  54. package/dist/session-5TNWVGQQ.js.map +1 -0
  55. package/dist/{session-Bt_mbUWg.d.ts → session-uT8xL03K.d.ts} +5 -1
  56. package/dist/{studio-command-TXQTIWRS.js → studio-command-KK7A3KN6.js} +2 -2
  57. package/dist/{test-command-CCSQPKWU.js → test-command-QGIJBRH7.js} +187 -29
  58. package/dist/test-command-QGIJBRH7.js.map +1 -0
  59. package/dist/{validator-YWNHCU2S.js → validator-WO5IL7IY.js} +3 -3
  60. package/dist/validator-WO5IL7IY.js.map +1 -0
  61. package/package.json +10 -10
  62. package/dist/chunk-66D3C7NB.js.map +0 -1
  63. package/dist/chunk-7QFJ7MDH.js.map +0 -1
  64. package/dist/chunk-B35G77DN.js.map +0 -1
  65. package/dist/chunk-B473XZOM.js.map +0 -1
  66. package/dist/chunk-DP7MGXHN.js.map +0 -1
  67. package/dist/chunk-Y6KMJJ2T.js.map +0 -1
  68. package/dist/config-loader-WLPQ5WVH.js +0 -9
  69. package/dist/flow-CI5parw2.d.ts +0 -90
  70. package/dist/session-BE6U34DA.js +0 -18
  71. package/dist/test-command-CCSQPKWU.js.map +0 -1
  72. /package/dist/{config-loader-WLPQ5WVH.js.map → agent-fixture-5C4MCWRD.js.map} +0 -0
  73. /package/dist/{discover-RLSKEBAX.js.map → app-RSDPDTKT.js.map} +0 -0
  74. /package/dist/{runner-JID2YWRE.js.map → cache-command-PANUAEMZ.js.map} +0 -0
  75. /package/dist/{chunk-C2HBFEMQ.js.map → chunk-26NJXP55.js.map} +0 -0
  76. /package/dist/{chunk-SF7UYW4I.js.map → chunk-VUNH4AJD.js.map} +0 -0
  77. /package/dist/{chunk-IXON7DMB.js.map → chunk-WZAQANN6.js.map} +0 -0
  78. /package/dist/{server-UIRGHUYM.js.map → config-loader-CNGIW2XK.js.map} +0 -0
  79. /package/dist/{session-BE6U34DA.js.map → discover-NKDMB4UI.js.map} +0 -0
  80. /package/dist/{validator-YWNHCU2S.js.map → local-DM3YBSV5.js.map} +0 -0
  81. /package/dist/{studio-command-TXQTIWRS.js.map → studio-command-KK7A3KN6.js.map} +0 -0
@@ -1,30 +1,28 @@
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-B35G77DN.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-B473XZOM.js";
20
+ } from "./chunk-WS2TVNMY.js";
21
+ import {
22
+ adbReverse,
23
+ adbReverseRemove,
24
+ ensureAndroidDevice
25
+ } from "./chunk-2AFWVHQK.js";
28
26
  import {
29
27
  connectPhysicalDevice,
30
28
  ensureAppInstalled,
@@ -44,89 +42,116 @@ import {
44
42
  allocatePort
45
43
  } from "./chunk-JPZCZHL4.js";
46
44
  import {
47
- focusFlows,
48
- getFlowSkip
49
- } from "./chunk-DP7MGXHN.js";
50
- import {
51
- adbReverse,
52
- adbReverseRemove,
53
- ensureAndroidDevice
54
- } 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";
55
52
 
56
- // 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";
57
60
  import { Effect } from "effect";
58
- function createSessions(manager, driverFactory, coordinatorConfig, flowContext) {
59
- const coordConfig = coordinatorConfig ?? { parse: parseWebHierarchy };
60
- return {
61
- async open(opts) {
62
- const existing = manager.all().find((s) => s.name === opts.name);
63
- if (existing) {
64
- throw new Error(`Session "${opts.name}" already exists`);
65
- }
66
- const driver = await driverFactory(opts);
67
- const baseUrl = opts.baseUrl ?? "http://localhost:3000";
68
- await Effect.runPromise(driver.launchApp(baseUrl));
69
- const app = createPromiseApp(driver, baseUrl, coordConfig, void 0, {
70
- platform: "web",
71
- flowContext
72
- });
73
- const expect = createPromiseExpect(driver, coordConfig, void 0, flowContext);
74
- const session = {
75
- name: opts.name,
76
- platform: "web",
77
- app,
78
- expect,
79
- async disconnect() {
80
- await Effect.runPromise(driver.killApp(baseUrl));
81
- manager.remove(opts.name);
82
- }
83
- };
84
- const cleanup = async () => {
85
- await Effect.runPromise(driver.killApp(baseUrl));
86
- };
87
- manager.register(session, cleanup);
88
- return session;
89
- }
90
- };
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}`];
91
95
  }
92
- var SessionManager = class {
93
- sessions = [];
94
- all() {
95
- 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
+ });
96
111
  }
97
- register(session, cleanup) {
98
- 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));
99
134
  }
100
- remove(name) {
101
- 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.`);
102
137
  }
103
- async disconnectAll() {
104
- const errors = [];
105
- for (const entry of [...this.sessions].toReversed()) {
106
- try {
107
- await entry.cleanup();
108
- } catch (err) {
109
- 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
+ });
110
148
  }
111
149
  }
112
- this.sessions = [];
113
- if (errors.length > 0) {
114
- console.warn(
115
- `SessionManager: ${errors.length} error(s) during cleanup:`,
116
- errors.map((e) => e instanceof Error ? e.message : String(e))
117
- );
118
- }
119
150
  }
120
- };
151
+ return { popupTabId, openerTabIndex };
152
+ }
121
153
 
122
154
  // src/drivers/cdp-browser.ts
123
- import { spawn } from "child_process";
124
- import { createHash } from "crypto";
125
- import { existsSync, mkdtempSync, rmSync } from "fs";
126
- import { copyFile, readFile, writeFile } from "fs/promises";
127
- import { tmpdir } from "os";
128
- import { join } from "path";
129
- import { Effect as Effect2 } from "effect";
130
155
  var INSTANT_ANIMATIONS_CDP_SCRIPT = `
131
156
  (() => {
132
157
  const inject = () => {
@@ -149,7 +174,7 @@ function resolveDirectCdpScopeKey(scope) {
149
174
  return `cdp-${cwdHash}`;
150
175
  }
151
176
  function resolveChromiumExecutable(explicit) {
152
- if (explicit && existsSync(explicit)) return explicit;
177
+ if (explicit && existsSync2(explicit)) return explicit;
153
178
  const candidates = process.platform === "darwin" ? [
154
179
  "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
155
180
  "/Applications/Chromium.app/Contents/MacOS/Chromium",
@@ -165,7 +190,7 @@ function resolveChromiumExecutable(explicit) {
165
190
  "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
166
191
  ];
167
192
  for (const path of candidates) {
168
- if (existsSync(path)) return path;
193
+ if (existsSync2(path)) return path;
169
194
  }
170
195
  return explicit ?? "google-chrome";
171
196
  }
@@ -213,7 +238,7 @@ async function launchDirectCdpBrowser(options = {}) {
213
238
  try {
214
239
  const { chromium } = await import("playwright-core");
215
240
  const pwPath = chromium.executablePath();
216
- if (pwPath && existsSync(pwPath)) {
241
+ if (pwPath && existsSync2(pwPath)) {
217
242
  execPath = pwPath;
218
243
  }
219
244
  } catch {
@@ -221,8 +246,8 @@ async function launchDirectCdpBrowser(options = {}) {
221
246
  }
222
247
  execPath = resolveChromiumExecutable(execPath);
223
248
  const port = await allocateFreePort(9350);
224
- const userDataDir = mkdtempSync(join(tmpdir(), "spana-cdp-profile-"));
225
- const chromeArgs = [
249
+ const userDataDir = mkdtempSync(join2(tmpdir(), "spana-cdp-profile-"));
250
+ const baseChromeArgs = [
226
251
  ...options.headless !== false ? ["--headless=new"] : [],
227
252
  `--remote-debugging-port=${port}`,
228
253
  "--remote-debugging-address=127.0.0.1",
@@ -244,6 +269,8 @@ async function launchDirectCdpBrowser(options = {}) {
244
269
  ...options.args ?? [],
245
270
  "about:blank"
246
271
  ];
272
+ const resolvedExts = options.extensions && options.extensions.length > 0 ? resolveBrowserExtensions(options.extensions) : [];
273
+ const chromeArgs = resolvedExts.length > 0 ? applyExtensionChromeArgs(baseChromeArgs, resolvedExts) : baseChromeArgs;
247
274
  const child = spawn(execPath, chromeArgs, {
248
275
  detached: Boolean(options.warmBrowser),
249
276
  stdio: "ignore"
@@ -396,7 +423,7 @@ var RESOURCE_BLOCK_PATTERNS = {
396
423
  stylesheet: ["*.css"]
397
424
  };
398
425
  function makeLightweightCdpDriver(options) {
399
- return Effect2.gen(function* () {
426
+ return Effect.gen(function* () {
400
427
  const isBrowserWs = options.cdpUrl.includes("/devtools/browser/");
401
428
  const useContexts = Boolean(
402
429
  options.useBrowserContexts || options.freshContextPerFlow || isBrowserWs
@@ -405,7 +432,7 @@ function makeLightweightCdpDriver(options) {
405
432
  const httpEndpoint = isWs ? options.cdpUrl.replace(/^ws(s?):\/\//, "http$1://").replace(/\/devtools\/.*$/, "") : options.cdpUrl.replace(/\/+$/, "");
406
433
  let connectWsUrl = isWs ? options.cdpUrl : void 0;
407
434
  if (useContexts && !connectWsUrl) {
408
- connectWsUrl = yield* Effect2.tryPromise({
435
+ connectWsUrl = yield* Effect.tryPromise({
409
436
  try: () => fetchBrowserWsUrl(httpEndpoint, 5e3),
410
437
  catch: (e) => new DriverError({
411
438
  message: `Failed to resolve browser CDP WebSocket at ${options.cdpUrl}: ${e}`
@@ -418,19 +445,20 @@ function makeLightweightCdpDriver(options) {
418
445
  fetchFn: options.fetchFn,
419
446
  createWebSocket: options.createWebSocket
420
447
  });
421
- yield* Effect2.tryPromise({
448
+ yield* Effect.tryPromise({
422
449
  try: () => cdpChannel.connect(),
423
450
  catch: (e) => new DriverError({
424
451
  message: `Failed to connect lightweight CDP browser at ${options.cdpUrl}: ${e}`
425
452
  })
426
453
  });
427
- const width = options.viewport?.width ?? 1280;
428
- const height = options.viewport?.height ?? 720;
454
+ let width = options.viewport?.width ?? 1280;
455
+ let height = options.viewport?.height ?? 720;
429
456
  const label = options.engineLabel ?? "cdp";
430
457
  let activeSlot;
431
458
  let prefetchedSlotPromise;
432
459
  let hasRunFirstFlow = false;
433
460
  let activeAuthenticatorId;
461
+ let dialogHandler = null;
434
462
  const backgroundDisposals = [];
435
463
  const consoleLogs = [];
436
464
  const jsErrors = [];
@@ -444,17 +472,27 @@ function makeLightweightCdpDriver(options) {
444
472
  const pendingDownloadGuids = /* @__PURE__ */ new Map();
445
473
  cdpChannel.onEvent("Browser.downloadWillBegin", (params) => {
446
474
  if (params?.guid && downloadDir) {
447
- 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
+ });
448
481
  }
449
482
  });
450
483
  cdpChannel.onEvent("Browser.downloadProgress", (params) => {
451
484
  if (params?.state === "completed" && params?.guid) {
452
- const filePath = pendingDownloadGuids.get(String(params.guid)) ?? (downloadDir ? join(downloadDir, String(params.guid)) : "");
453
- pendingDownloadGuids.delete(String(params.guid));
454
- 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;
455
493
  const waiter = downloadWaiters.shift();
456
- if (waiter) waiter.resolve(filePath);
457
- else completedDownloads.push(filePath);
494
+ if (waiter) waiter.resolve(entry);
495
+ else completedDownloads.push(entry);
458
496
  }
459
497
  });
460
498
  const loadStorageStateFile = async (path) => {
@@ -561,6 +599,41 @@ function makeLightweightCdpDriver(options) {
561
599
  await cdpChannel.sendCommand("Fetch.enable", { patterns: [{ urlPattern: "*" }] }, sessionId).catch(() => {
562
600
  });
563
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
+ }
564
637
  let authenticatorId;
565
638
  if (options.virtualAuthenticator) {
566
639
  const authOpts = typeof options.virtualAuthenticator === "object" ? options.virtualAuthenticator : void 0;
@@ -699,8 +772,51 @@ function makeLightweightCdpDriver(options) {
699
772
  }
700
773
  });
701
774
  cdpChannel.onEvent("Page.javascriptDialogOpening", (params, sid) => {
702
- const accept = params?.type === "beforeunload";
703
- 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
+ }
704
820
  });
705
821
  });
706
822
  cdpChannel.setFrameOffsetResolver(async (child) => {
@@ -774,7 +890,7 @@ function makeLightweightCdpDriver(options) {
774
890
  });
775
891
  });
776
892
  if (useContexts) {
777
- yield* Effect2.tryPromise({
893
+ yield* Effect.tryPromise({
778
894
  try: () => cdpChannel.sendCommand(
779
895
  "Target.setAutoAttach",
780
896
  {
@@ -787,8 +903,8 @@ function makeLightweightCdpDriver(options) {
787
903
  ).catch(() => {
788
904
  }),
789
905
  catch: () => new DriverError({ message: "Failed to enable Target.setAutoAttach" })
790
- }).pipe(Effect2.catchAll(() => Effect2.void));
791
- activeSlot = yield* Effect2.tryPromise({
906
+ }).pipe(Effect.catchAll(() => Effect.void));
907
+ activeSlot = yield* Effect.tryPromise({
792
908
  try: () => createContextSlot(options.storageState),
793
909
  catch: (e) => new DriverError({ message: `Failed to create direct CDP browser context: ${e}` })
794
910
  });
@@ -829,7 +945,7 @@ function makeLightweightCdpDriver(options) {
829
945
  let coverageSession;
830
946
  const service = {
831
947
  domChannel: cdpChannel,
832
- startJSCoverage: () => Effect2.tryPromise({
948
+ startJSCoverage: () => Effect.tryPromise({
833
949
  try: async () => {
834
950
  const session = activeSlot?.sessionId ?? null;
835
951
  await cdpChannel.sendCommand("Profiler.enable", {}, session);
@@ -848,7 +964,7 @@ function makeLightweightCdpDriver(options) {
848
964
  },
849
965
  catch: (error) => new DriverError({ message: `CDP JavaScript coverage is unavailable: ${error}` })
850
966
  }),
851
- stopJSCoverage: () => Effect2.tryPromise({
967
+ stopJSCoverage: () => Effect.tryPromise({
852
968
  try: async () => {
853
969
  const session = coverageSession;
854
970
  coverageSession = void 0;
@@ -869,10 +985,11 @@ function makeLightweightCdpDriver(options) {
869
985
  },
870
986
  catch: (error) => new DriverError({ message: `CDP JavaScript coverage collection failed: ${error}` })
871
987
  }),
872
- beginFlow: (_flowName) => Effect2.tryPromise({
988
+ beginFlow: (_flowName) => Effect.tryPromise({
873
989
  try: async () => {
874
990
  consoleLogs.length = 0;
875
991
  jsErrors.length = 0;
992
+ dialogHandler = null;
876
993
  cdpChannel.clearChildSessions();
877
994
  if (useContexts && options.freshContextPerFlow && hasRunFirstFlow) {
878
995
  if (options.contextIsolation === "hot-cache" && activeSlot) {
@@ -917,14 +1034,14 @@ function makeLightweightCdpDriver(options) {
917
1034
  },
918
1035
  catch: (e) => new DriverError({ message: `CDP beginFlow failed: ${e}` })
919
1036
  }),
920
- dumpHierarchy: () => Effect2.tryPromise({
1037
+ dumpHierarchy: () => Effect.tryPromise({
921
1038
  try: async () => {
922
1039
  const raw = await cdpChannel.evaluate(CDP_DUMP_HIERARCHY_SCRIPT);
923
1040
  return raw ?? "{}";
924
1041
  },
925
1042
  catch: (e) => new DriverError({ message: `CDP dumpHierarchy failed: ${e}` })
926
1043
  }),
927
- tapAtCoordinate: (x, y) => Effect2.tryPromise({
1044
+ tapAtCoordinate: (x, y) => Effect.tryPromise({
928
1045
  try: async () => {
929
1046
  await Promise.all([
930
1047
  cdpChannel.sendCommand("Input.dispatchMouseEvent", {
@@ -950,7 +1067,7 @@ function makeLightweightCdpDriver(options) {
950
1067
  },
951
1068
  catch: (e) => new DriverError({ message: `CDP tap failed at (${x}, ${y}): ${e}` })
952
1069
  }),
953
- doubleTapAtCoordinate: (x, y) => Effect2.tryPromise({
1070
+ doubleTapAtCoordinate: (x, y) => Effect.tryPromise({
954
1071
  try: async () => {
955
1072
  await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
956
1073
  type: "mousePressed",
@@ -969,7 +1086,7 @@ function makeLightweightCdpDriver(options) {
969
1086
  },
970
1087
  catch: (e) => new DriverError({ message: `CDP doubleTap failed: ${e}` })
971
1088
  }),
972
- longPressAtCoordinate: (x, y, duration) => Effect2.tryPromise({
1089
+ longPressAtCoordinate: (x, y, duration) => Effect.tryPromise({
973
1090
  try: async () => {
974
1091
  await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
975
1092
  type: "mousePressed",
@@ -989,7 +1106,7 @@ function makeLightweightCdpDriver(options) {
989
1106
  },
990
1107
  catch: (e) => new DriverError({ message: `CDP longPress failed: ${e}` })
991
1108
  }),
992
- swipe: (startX, startY, endX, endY) => Effect2.tryPromise({
1109
+ swipe: (startX, startY, endX, endY) => Effect.tryPromise({
993
1110
  try: async () => {
994
1111
  const dx = startX - endX;
995
1112
  const dy = startY - endY;
@@ -997,13 +1114,13 @@ function makeLightweightCdpDriver(options) {
997
1114
  },
998
1115
  catch: (e) => new DriverError({ message: `CDP swipe failed: ${e}` })
999
1116
  }),
1000
- inputText: (text) => Effect2.tryPromise({
1117
+ inputText: (text) => Effect.tryPromise({
1001
1118
  try: async () => {
1002
1119
  await cdpChannel.sendCommand("Input.insertText", { text });
1003
1120
  },
1004
1121
  catch: (e) => new DriverError({ message: `CDP inputText failed: ${e}` })
1005
1122
  }),
1006
- pressKey: (key) => Effect2.tryPromise({
1123
+ pressKey: (key) => Effect.tryPromise({
1007
1124
  try: async () => {
1008
1125
  const desc = parseCdpKeyDescriptor(key);
1009
1126
  await cdpChannel.sendCommand("Input.dispatchKeyEvent", {
@@ -1031,7 +1148,7 @@ function makeLightweightCdpDriver(options) {
1031
1148
  },
1032
1149
  catch: (e) => new DriverError({ message: `CDP pressKey failed: ${e}` })
1033
1150
  }),
1034
- hoverAtCoordinate: (x, y) => Effect2.tryPromise({
1151
+ hoverAtCoordinate: (x, y) => Effect.tryPromise({
1035
1152
  try: async () => {
1036
1153
  await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
1037
1154
  type: "mouseMoved",
@@ -1041,7 +1158,7 @@ function makeLightweightCdpDriver(options) {
1041
1158
  },
1042
1159
  catch: (e) => new DriverError({ message: `CDP hover failed at (${x}, ${y}): ${e}` })
1043
1160
  }),
1044
- reload: (reloadOpts) => Effect2.tryPromise({
1161
+ reload: (reloadOpts) => Effect.tryPromise({
1045
1162
  try: async () => {
1046
1163
  const waitUntil = reloadOpts?.waitUntil ?? options.waitUntil ?? "domcontentloaded";
1047
1164
  const targetSid = activeSlot?.sessionId;
@@ -1057,7 +1174,7 @@ function makeLightweightCdpDriver(options) {
1057
1174
  },
1058
1175
  catch: (e) => new DriverError({ message: `CDP reload failed: ${e}` })
1059
1176
  }),
1060
- getUrl: () => Effect2.tryPromise({
1177
+ getUrl: () => Effect.tryPromise({
1061
1178
  try: async () => {
1062
1179
  const url = await cdpChannel.evaluate(
1063
1180
  "typeof window !== 'undefined' && window.location ? String(window.location.href || '') : ''"
@@ -1066,8 +1183,8 @@ function makeLightweightCdpDriver(options) {
1066
1183
  },
1067
1184
  catch: (e) => new DriverError({ message: `CDP getUrl failed: ${e}` })
1068
1185
  }),
1069
- hideKeyboard: () => Effect2.void,
1070
- takeScreenshot: () => Effect2.tryPromise({
1186
+ hideKeyboard: () => Effect.void,
1187
+ takeScreenshot: () => Effect.tryPromise({
1071
1188
  try: async () => {
1072
1189
  const res = await cdpChannel.sendCommand("Page.captureScreenshot", {
1073
1190
  format: "png"
@@ -1076,7 +1193,7 @@ function makeLightweightCdpDriver(options) {
1076
1193
  },
1077
1194
  catch: (e) => new DriverError({ message: `CDP screenshot failed: ${e}` })
1078
1195
  }),
1079
- getDeviceInfo: () => Effect2.succeed({
1196
+ getDeviceInfo: () => Effect.succeed({
1080
1197
  platform: "web",
1081
1198
  deviceId: `${label}:${options.cdpUrl}`,
1082
1199
  name: `${label} (CDP-direct)`,
@@ -1085,7 +1202,7 @@ function makeLightweightCdpDriver(options) {
1085
1202
  screenHeight: height,
1086
1203
  driverType: "cdp"
1087
1204
  }),
1088
- launchApp: (url, opts) => Effect2.tryPromise({
1205
+ launchApp: (url, opts) => Effect.tryPromise({
1089
1206
  try: async () => {
1090
1207
  if (opts?.clearState) {
1091
1208
  await cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
@@ -1098,11 +1215,11 @@ function makeLightweightCdpDriver(options) {
1098
1215
  },
1099
1216
  catch: (e) => new DriverError({ message: `CDP launchApp failed: ${e}` })
1100
1217
  }),
1101
- stopApp: () => Effect2.tryPromise({
1218
+ stopApp: () => Effect.tryPromise({
1102
1219
  try: () => navigate("about:blank"),
1103
1220
  catch: (e) => new DriverError({ message: `CDP stopApp failed: ${e}` })
1104
1221
  }),
1105
- killApp: () => Effect2.tryPromise({
1222
+ killApp: () => Effect.tryPromise({
1106
1223
  try: async () => {
1107
1224
  const pendingPrefetch = prefetchedSlotPromise;
1108
1225
  prefetchedSlotPromise = void 0;
@@ -1135,7 +1252,7 @@ function makeLightweightCdpDriver(options) {
1135
1252
  },
1136
1253
  catch: (e) => new DriverError({ message: `CDP disconnect failed: ${e}` })
1137
1254
  }),
1138
- clearAppState: () => Effect2.tryPromise({
1255
+ clearAppState: () => Effect.tryPromise({
1139
1256
  try: async () => {
1140
1257
  await cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
1141
1258
  });
@@ -1145,17 +1262,17 @@ function makeLightweightCdpDriver(options) {
1145
1262
  },
1146
1263
  catch: (e) => new DriverError({ message: `CDP clearAppState failed: ${e}` })
1147
1264
  }),
1148
- openLink: (url) => Effect2.tryPromise({
1265
+ openLink: (url) => Effect.tryPromise({
1149
1266
  try: () => navigate(url),
1150
1267
  catch: (e) => new DriverError({ message: `CDP openLink failed: ${e}` })
1151
1268
  }),
1152
- back: () => Effect2.tryPromise({
1269
+ back: () => Effect.tryPromise({
1153
1270
  try: async () => {
1154
1271
  await cdpChannel.evaluate("window.history.back()");
1155
1272
  },
1156
1273
  catch: (e) => new DriverError({ message: `CDP back failed: ${e}` })
1157
1274
  }),
1158
- evaluate: (fn, ...args) => Effect2.tryPromise({
1275
+ evaluate: (fn, ...args) => Effect.tryPromise({
1159
1276
  try: async () => {
1160
1277
  if (typeof fn === "string") {
1161
1278
  return await cdpChannel.evaluate(fn);
@@ -1184,21 +1301,21 @@ function makeLightweightCdpDriver(options) {
1184
1301
  return activeSlot?.browserContextId;
1185
1302
  }
1186
1303
  }),
1187
- mockNetwork: (matcher, response) => Effect2.tryPromise({
1304
+ mockNetwork: (matcher, response) => Effect.tryPromise({
1188
1305
  try: async () => {
1189
1306
  routeRules.push({ kind: "mock", matcher, response });
1190
1307
  await ensureFetchIntercept();
1191
1308
  },
1192
1309
  catch: (e) => new DriverError({ message: `CDP mockNetwork failed: ${e}` })
1193
1310
  }),
1194
- blockNetwork: (matcher) => Effect2.tryPromise({
1311
+ blockNetwork: (matcher) => Effect.tryPromise({
1195
1312
  try: async () => {
1196
1313
  routeRules.push({ kind: "block", matcher });
1197
1314
  await ensureFetchIntercept();
1198
1315
  },
1199
1316
  catch: (e) => new DriverError({ message: `CDP blockNetwork failed: ${e}` })
1200
1317
  }),
1201
- clearNetworkMocks: () => Effect2.tryPromise({
1318
+ clearNetworkMocks: () => Effect.tryPromise({
1202
1319
  try: async () => {
1203
1320
  routeRules.length = 0;
1204
1321
  if (fetchInterceptEnabled) {
@@ -1209,14 +1326,14 @@ function makeLightweightCdpDriver(options) {
1209
1326
  },
1210
1327
  catch: (e) => new DriverError({ message: `CDP clearNetworkMocks failed: ${e}` })
1211
1328
  }),
1212
- saveCookies: (path) => Effect2.tryPromise({
1329
+ saveCookies: (path) => Effect.tryPromise({
1213
1330
  try: async () => {
1214
1331
  const res = await cdpChannel.sendCommand("Network.getCookies");
1215
1332
  await writeFile(path, JSON.stringify(res?.cookies ?? [], null, 2), "utf8");
1216
1333
  },
1217
1334
  catch: (e) => new DriverError({ message: `CDP saveCookies failed: ${e}` })
1218
1335
  }),
1219
- loadCookies: (path) => Effect2.tryPromise({
1336
+ loadCookies: (path) => Effect.tryPromise({
1220
1337
  try: async () => {
1221
1338
  const cookies = JSON.parse(await readFile(path, "utf8"));
1222
1339
  if (Array.isArray(cookies)) {
@@ -1225,7 +1342,7 @@ function makeLightweightCdpDriver(options) {
1225
1342
  },
1226
1343
  catch: (e) => new DriverError({ message: `CDP loadCookies failed: ${e}` })
1227
1344
  }),
1228
- getCookies: (urls) => Effect2.tryPromise({
1345
+ getCookies: (urls) => Effect.tryPromise({
1229
1346
  try: async () => {
1230
1347
  const res = await cdpChannel.sendCommand(
1231
1348
  "Network.getCookies",
@@ -1235,20 +1352,20 @@ function makeLightweightCdpDriver(options) {
1235
1352
  },
1236
1353
  catch: (e) => new DriverError({ message: `CDP getCookies failed: ${e}` })
1237
1354
  }),
1238
- setCookies: (cookies) => Effect2.tryPromise({
1355
+ setCookies: (cookies) => Effect.tryPromise({
1239
1356
  try: async () => {
1240
1357
  if (cookies.length === 0) return;
1241
1358
  await cdpChannel.sendCommand("Network.setCookies", { cookies });
1242
1359
  },
1243
1360
  catch: (e) => new DriverError({ message: `CDP setCookies failed: ${e}` })
1244
1361
  }),
1245
- clearCookies: () => Effect2.tryPromise({
1362
+ clearCookies: () => Effect.tryPromise({
1246
1363
  try: async () => {
1247
1364
  await cdpChannel.sendCommand("Network.clearBrowserCookies");
1248
1365
  },
1249
1366
  catch: (e) => new DriverError({ message: `CDP clearCookies failed: ${e}` })
1250
1367
  }),
1251
- waitForResponse: (matcher, waitOpts) => Effect2.tryPromise({
1368
+ waitForResponse: (matcher, waitOpts) => Effect.tryPromise({
1252
1369
  try: async () => {
1253
1370
  const timeoutMs = waitOpts?.timeout ?? 15e3;
1254
1371
  const slotSessions = () => {
@@ -1278,7 +1395,7 @@ function makeLightweightCdpDriver(options) {
1278
1395
  });
1279
1396
  }
1280
1397
  const requestMethods = /* @__PURE__ */ new Map();
1281
- return await new Promise((resolve, reject) => {
1398
+ return await new Promise((resolve2, reject) => {
1282
1399
  let cleaned = false;
1283
1400
  const cleanup = () => {
1284
1401
  if (cleaned) return;
@@ -1337,16 +1454,16 @@ function makeLightweightCdpDriver(options) {
1337
1454
  const matched = typeof matcher === "function" ? matcher(info) : matchUrl(matcher, info.url);
1338
1455
  if (matched) {
1339
1456
  cleanup();
1340
- resolve(info);
1457
+ resolve2(info);
1341
1458
  }
1342
1459
  });
1343
1460
  });
1344
1461
  },
1345
1462
  catch: (e) => new DriverError({ message: `CDP waitForResponse failed: ${e}` })
1346
1463
  }),
1347
- createIsolatedContext: (ctxOpts) => Effect2.tryPromise({
1464
+ createIsolatedContext: (ctxOpts) => Effect.tryPromise({
1348
1465
  try: async () => {
1349
- const childDriver = await Effect2.runPromise(
1466
+ const childDriver = await Effect.runPromise(
1350
1467
  makeLightweightCdpDriver({
1351
1468
  ...options,
1352
1469
  cdpUrl: connectWsUrl ?? options.cdpUrl,
@@ -1355,19 +1472,19 @@ function makeLightweightCdpDriver(options) {
1355
1472
  })
1356
1473
  );
1357
1474
  if (ctxOpts?.url) {
1358
- await Effect2.runPromise(childDriver.openLink(ctxOpts.url));
1475
+ await Effect.runPromise(childDriver.openLink(ctxOpts.url));
1359
1476
  }
1360
1477
  return {
1361
1478
  driver: childDriver,
1362
1479
  close: async () => {
1363
- await Effect2.runPromise(childDriver.killApp("isolated-context")).catch(() => {
1480
+ await Effect.runPromise(childDriver.killApp("isolated-context")).catch(() => {
1364
1481
  });
1365
1482
  }
1366
1483
  };
1367
1484
  },
1368
1485
  catch: (e) => new DriverError({ message: `CDP createIsolatedContext failed: ${e}` })
1369
1486
  }),
1370
- saveAuthState: (path) => Effect2.tryPromise({
1487
+ saveAuthState: (path) => Effect.tryPromise({
1371
1488
  try: async () => {
1372
1489
  const res = await cdpChannel.sendCommand("Network.getCookies");
1373
1490
  const originState = await cdpChannel.evaluate(
@@ -1390,7 +1507,7 @@ function makeLightweightCdpDriver(options) {
1390
1507
  },
1391
1508
  catch: (e) => new DriverError({ message: `CDP saveAuthState failed: ${e}` })
1392
1509
  }),
1393
- loadAuthState: (path) => Effect2.tryPromise({
1510
+ loadAuthState: (path) => Effect.tryPromise({
1394
1511
  try: async () => {
1395
1512
  if (useContexts) {
1396
1513
  const previousSlot = activeSlot;
@@ -1407,7 +1524,7 @@ function makeLightweightCdpDriver(options) {
1407
1524
  },
1408
1525
  catch: (e) => new DriverError({ message: `CDP loadAuthState failed: ${e}` })
1409
1526
  }),
1410
- enableVirtualAuthenticator: (opts) => Effect2.tryPromise({
1527
+ enableVirtualAuthenticator: (opts) => Effect.tryPromise({
1411
1528
  try: async () => {
1412
1529
  activeAuthenticatorId = await attachVirtualAuthenticatorForSession(
1413
1530
  activeSlot?.sessionId ?? null,
@@ -1417,7 +1534,7 @@ function makeLightweightCdpDriver(options) {
1417
1534
  },
1418
1535
  catch: (e) => new DriverError({ message: `CDP enableVirtualAuthenticator failed: ${e}` })
1419
1536
  }),
1420
- removeVirtualAuthenticator: (authenticatorId) => Effect2.tryPromise({
1537
+ removeVirtualAuthenticator: (authenticatorId) => Effect.tryPromise({
1421
1538
  try: async () => {
1422
1539
  const id = authenticatorId ?? activeAuthenticatorId;
1423
1540
  if (!id) return;
@@ -1428,7 +1545,7 @@ function makeLightweightCdpDriver(options) {
1428
1545
  },
1429
1546
  catch: (e) => new DriverError({ message: `CDP removeVirtualAuthenticator failed: ${e}` })
1430
1547
  }),
1431
- getVirtualCredentials: (authenticatorId) => Effect2.tryPromise({
1548
+ getVirtualCredentials: (authenticatorId) => Effect.tryPromise({
1432
1549
  try: async () => {
1433
1550
  const id = authenticatorId ?? activeAuthenticatorId;
1434
1551
  if (!id) return [];
@@ -1439,7 +1556,7 @@ function makeLightweightCdpDriver(options) {
1439
1556
  },
1440
1557
  catch: (e) => new DriverError({ message: `CDP getVirtualCredentials failed: ${e}` })
1441
1558
  }),
1442
- addVirtualCredential: (credential, authenticatorId) => Effect2.tryPromise({
1559
+ addVirtualCredential: (credential, authenticatorId) => Effect.tryPromise({
1443
1560
  try: async () => {
1444
1561
  let id = authenticatorId ?? activeAuthenticatorId;
1445
1562
  if (!id) {
@@ -1461,7 +1578,7 @@ function makeLightweightCdpDriver(options) {
1461
1578
  },
1462
1579
  catch: (e) => new DriverError({ message: `CDP addVirtualCredential failed: ${e}` })
1463
1580
  }),
1464
- clearVirtualCredentials: (authenticatorId) => Effect2.tryPromise({
1581
+ clearVirtualCredentials: (authenticatorId) => Effect.tryPromise({
1465
1582
  try: async () => {
1466
1583
  const id = authenticatorId ?? activeAuthenticatorId;
1467
1584
  if (!id) return;
@@ -1469,9 +1586,9 @@ function makeLightweightCdpDriver(options) {
1469
1586
  },
1470
1587
  catch: (e) => new DriverError({ message: `CDP clearVirtualCredentials failed: ${e}` })
1471
1588
  }),
1472
- getConsoleLogs: () => Effect2.succeed([...consoleLogs]),
1473
- getJSErrors: () => Effect2.succeed([...jsErrors]),
1474
- setNetworkConditions: (conditions) => Effect2.tryPromise({
1589
+ getConsoleLogs: () => Effect.succeed([...consoleLogs]),
1590
+ getJSErrors: () => Effect.succeed([...jsErrors]),
1591
+ setNetworkConditions: (conditions) => Effect.tryPromise({
1475
1592
  try: async () => {
1476
1593
  const resolved = resolveNetworkConditions(conditions);
1477
1594
  await cdpChannel.sendCommand("Network.enable");
@@ -1484,7 +1601,7 @@ function makeLightweightCdpDriver(options) {
1484
1601
  },
1485
1602
  catch: (e) => new DriverError({ message: `CDP setNetworkConditions failed: ${e}` })
1486
1603
  }),
1487
- uploadFile: (selector, filePath) => Effect2.tryPromise({
1604
+ uploadFile: (selector, filePath) => Effect.tryPromise({
1488
1605
  try: async () => {
1489
1606
  const files = Array.isArray(filePath) ? filePath : [filePath];
1490
1607
  const expr = buildDomFindElementScript(selector);
@@ -1526,10 +1643,10 @@ function makeLightweightCdpDriver(options) {
1526
1643
  },
1527
1644
  catch: (e) => new DriverError({ message: `CDP uploadFile failed: ${e}` })
1528
1645
  }),
1529
- downloadFile: (destPath) => Effect2.tryPromise({
1646
+ downloadFile: (destPath) => Effect.tryPromise({
1530
1647
  try: async () => {
1531
1648
  if (!downloadDir) {
1532
- downloadDir = mkdtempSync(join(tmpdir(), "spana-cdp-dl-"));
1649
+ downloadDir = mkdtempSync(join2(tmpdir(), "spana-cdp-dl-"));
1533
1650
  await cdpChannel.sendCommand(
1534
1651
  "Browser.setDownloadBehavior",
1535
1652
  {
@@ -1541,14 +1658,14 @@ function makeLightweightCdpDriver(options) {
1541
1658
  null
1542
1659
  );
1543
1660
  }
1544
- const downloaded = completedDownloads.shift() ?? await new Promise((resolve, reject) => {
1661
+ const downloaded = completedDownloads.shift() ?? await new Promise((resolve2, reject) => {
1545
1662
  const timer = setTimeout(() => {
1546
1663
  reject(new Error("Timed out waiting for CDP file download"));
1547
1664
  }, 15e3);
1548
1665
  downloadWaiters.push({
1549
- resolve: (fp) => {
1666
+ resolve: (entry) => {
1550
1667
  clearTimeout(timer);
1551
- resolve(fp);
1668
+ resolve2(entry);
1552
1669
  },
1553
1670
  reject: (err) => {
1554
1671
  clearTimeout(timer);
@@ -1556,11 +1673,197 @@ function makeLightweightCdpDriver(options) {
1556
1673
  }
1557
1674
  });
1558
1675
  });
1559
- await copyFile(downloaded, destPath);
1676
+ await copyFile(downloaded.filePath, destPath);
1560
1677
  },
1561
1678
  catch: (e) => new DriverError({ message: `CDP downloadFile failed: ${e}` })
1562
1679
  }),
1563
- 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({
1564
1867
  try: async () => {
1565
1868
  if (!activeSlot) {
1566
1869
  throw new Error("newTab() requires browser-context mode (engine: 'cdp')");
@@ -1594,7 +1897,7 @@ function makeLightweightCdpDriver(options) {
1594
1897
  },
1595
1898
  catch: (e) => new DriverError({ message: `CDP newTab failed: ${e}` })
1596
1899
  }),
1597
- switchToTab: (index) => Effect2.tryPromise({
1900
+ switchToTab: (index) => Effect.tryPromise({
1598
1901
  try: async () => {
1599
1902
  if (!activeSlot || !activeSlot.tabs[index]) {
1600
1903
  throw new Error(`Tab index ${index} is out of range.`);
@@ -1608,7 +1911,7 @@ function makeLightweightCdpDriver(options) {
1608
1911
  },
1609
1912
  catch: (e) => new DriverError({ message: `CDP switchToTab failed: ${e}` })
1610
1913
  }),
1611
- closeTab: () => Effect2.tryPromise({
1914
+ closeTab: () => Effect.tryPromise({
1612
1915
  try: async () => {
1613
1916
  if (!activeSlot) return;
1614
1917
  if (activeSlot.tabs.length <= 1) {
@@ -1627,14 +1930,13 @@ function makeLightweightCdpDriver(options) {
1627
1930
  },
1628
1931
  catch: (e) => new DriverError({ message: `CDP closeTab failed: ${e}` })
1629
1932
  }),
1630
- 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"])
1631
1934
  };
1632
1935
  return service;
1633
1936
  });
1634
1937
  }
1635
1938
 
1636
1939
  // src/runtime/local.ts
1637
- import { Effect as Effect3 } from "effect";
1638
1940
  async function safeCleanup(...fns) {
1639
1941
  for (const fn of fns) {
1640
1942
  try {
@@ -1686,7 +1988,9 @@ function buildEngineConfig(appId, platform, parseFn, config, screenSize) {
1686
1988
  launchOptions: config.launchOptions,
1687
1989
  hooks: config.hooks,
1688
1990
  storybook: platform === "web" ? config.execution?.web?.storybook : void 0,
1689
- visualRegression: config.visualRegression
1991
+ visualRegression: config.visualRegression,
1992
+ replayCache: config.replayCache,
1993
+ agent: config.agent
1690
1994
  };
1691
1995
  }
1692
1996
  function resolveWebEngine(config) {
@@ -1716,6 +2020,7 @@ function speculativelyPrelaunchWebBrowser(config) {
1716
2020
  const cdpBrowserPromise = launchDirectCdpBrowser({
1717
2021
  executablePath: webExecution?.executablePath,
1718
2022
  headless: webExecution?.headless ?? true,
2023
+ extensions: webExecution?.extensions,
1719
2024
  warmBrowser: useWarm2,
1720
2025
  warmBrowserScope: webExecution?.warmBrowserScope ? `${webExecution.warmBrowserScope}-w0` : void 0
1721
2026
  });
@@ -1758,12 +2063,18 @@ async function buildWebRuntime(config, prelaunched) {
1758
2063
  launchedDirectCdp = prelaunched?.cdpBrowserPromise ? await prelaunched.cdpBrowserPromise : await launchDirectCdpBrowser({
1759
2064
  executablePath: webExecution?.executablePath,
1760
2065
  headless: webExecution?.headless ?? true,
2066
+ extensions: webExecution?.extensions,
1761
2067
  warmBrowser: webExecution?.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false,
1762
2068
  warmBrowserScope: webExecution?.warmBrowserScope ? `${webExecution.warmBrowserScope}-w0` : void 0
1763
2069
  });
1764
2070
  targetCdpUrl = launchedDirectCdp.browserWsUrl;
1765
2071
  }
1766
- 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(
1767
2078
  makeLightweightCdpDriver({
1768
2079
  cdpUrl: targetCdpUrl ?? "http://127.0.0.1:9222",
1769
2080
  baseUrl: webUrl,
@@ -1775,11 +2086,12 @@ async function buildWebRuntime(config, prelaunched) {
1775
2086
  instantAnimations: webExecution?.instantAnimations,
1776
2087
  blockResources: webExecution?.blockResources,
1777
2088
  virtualAuthenticator: webExecution?.virtualAuthenticator,
1778
- storageState: webExecution?.storageState
2089
+ storageState: webExecution?.storageState,
2090
+ emulation: cdpEmulation
1779
2091
  })
1780
2092
  );
1781
2093
  } else {
1782
- rawDriver = await Effect3.runPromise(
2094
+ rawDriver = await Effect2.runPromise(
1783
2095
  makePlaywrightDriver({
1784
2096
  browser: webExecution?.browser,
1785
2097
  headless: webExecution?.headless ?? true,
@@ -1803,12 +2115,12 @@ async function buildWebRuntime(config, prelaunched) {
1803
2115
  );
1804
2116
  }
1805
2117
  const driver = bridge ? { ...rawDriver, domChannel: bridge } : rawDriver;
1806
- const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
2118
+ const deviceInfo = await Effect2.runPromise(driver.getDeviceInfo());
1807
2119
  return {
1808
2120
  runtime: {
1809
2121
  driver,
1810
2122
  cleanup: () => safeCleanup(
1811
- () => Effect3.runPromise(driver.killApp("")),
2123
+ () => Effect2.runPromise(driver.killApp("")),
1812
2124
  () => prelaunchedBrowser && prelaunched?.ownsBrowser ? prelaunchedBrowser.close() : Promise.resolve(),
1813
2125
  () => launchedDirectCdp ? launchedDirectCdp.close() : Promise.resolve(),
1814
2126
  () => bridge?.disconnect() ?? Promise.resolve()
@@ -1865,7 +2177,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1865
2177
  const results2 = [];
1866
2178
  for (let i = 0; i < workerCount; i++) {
1867
2179
  const bucket = handles[i % handles.length];
1868
- const driver = await Effect3.runPromise(
2180
+ const driver = await Effect2.runPromise(
1869
2181
  makeLightweightCdpDriver({
1870
2182
  cdpUrl: bucket.cdpUrl,
1871
2183
  baseUrl: webUrl,
@@ -1880,7 +2192,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1880
2192
  storageState: webExecution?.storageState
1881
2193
  })
1882
2194
  );
1883
- const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
2195
+ const deviceInfo = await Effect2.runPromise(driver.getDeviceInfo());
1884
2196
  let cleaned = false;
1885
2197
  results2.push({
1886
2198
  runtime: {
@@ -1888,7 +2200,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1888
2200
  cleanup: () => safeCleanup(async () => {
1889
2201
  if (cleaned) return;
1890
2202
  cleaned = true;
1891
- await Effect3.runPromise(driver.killApp(""));
2203
+ await Effect2.runPromise(driver.killApp(""));
1892
2204
  bucket.remaining -= 1;
1893
2205
  if (bucket.remaining <= 0 && bucket.handle) {
1894
2206
  await bucket.handle.close();
@@ -1961,7 +2273,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1961
2273
  const results = [];
1962
2274
  for (let i = 0; i < workerCount; i++) {
1963
2275
  const bucket = browserBuckets[i % browserBuckets.length];
1964
- const driver = await Effect3.runPromise(
2276
+ const driver = await Effect2.runPromise(
1965
2277
  makePlaywrightDriver({
1966
2278
  browser: webExecution?.browser,
1967
2279
  headless: webExecution?.headless ?? true,
@@ -1980,7 +2292,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1980
2292
  warmBrowserScope: webExecution?.warmBrowserScope
1981
2293
  })
1982
2294
  );
1983
- const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
2295
+ const deviceInfo = await Effect2.runPromise(driver.getDeviceInfo());
1984
2296
  let cleaned = false;
1985
2297
  results.push({
1986
2298
  runtime: {
@@ -1988,7 +2300,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1988
2300
  cleanup: () => safeCleanup(async () => {
1989
2301
  if (cleaned) return;
1990
2302
  cleaned = true;
1991
- await Effect3.runPromise(driver.killApp(""));
2303
+ await Effect2.runPromise(driver.killApp(""));
1992
2304
  bucket.remaining -= 1;
1993
2305
  if (bucket.remaining <= 0 && bucket.owns) {
1994
2306
  await bucket.browser.close();
@@ -2011,7 +2323,7 @@ async function buildWebRuntimePool(config, workerCount, prelaunched) {
2011
2323
  async function buildElectronRuntime(config, resolveFromConfig) {
2012
2324
  const electronCfg = config.apps?.electron ?? {};
2013
2325
  const bridge = await maybeStartBridge(electronCfg.bridge, config.execution?.bridge);
2014
- const driver = await Effect3.runPromise(
2326
+ const driver = await Effect2.runPromise(
2015
2327
  makeElectronDriver({
2016
2328
  entry: electronCfg.entry ? resolveFromConfig(electronCfg.entry) : void 0,
2017
2329
  executablePath: electronCfg.executablePath ? resolveFromConfig(electronCfg.executablePath) : void 0,
@@ -2027,12 +2339,12 @@ async function buildElectronRuntime(config, resolveFromConfig) {
2027
2339
  domChannel: bridge
2028
2340
  })
2029
2341
  );
2030
- const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
2342
+ const deviceInfo = await Effect2.runPromise(driver.getDeviceInfo());
2031
2343
  return {
2032
2344
  runtime: {
2033
2345
  driver,
2034
2346
  cleanup: () => safeCleanup(
2035
- () => Effect3.runPromise(driver.killApp("")),
2347
+ () => Effect2.runPromise(driver.killApp("")),
2036
2348
  () => bridge?.disconnect() ?? Promise.resolve()
2037
2349
  ),
2038
2350
  metadata: {
@@ -2056,7 +2368,7 @@ async function buildElectronRuntime(config, resolveFromConfig) {
2056
2368
  async function buildElectrobunRuntime(config, resolveFromConfig) {
2057
2369
  const electrobunCfg = config.apps?.electrobun ?? {};
2058
2370
  const bridge = await maybeStartBridge(electrobunCfg.bridge, config.execution?.bridge);
2059
- const driver = await Effect3.runPromise(
2371
+ const driver = await Effect2.runPromise(
2060
2372
  makeElectrobunDriver({
2061
2373
  executablePath: electrobunCfg.executablePath ? resolveFromConfig(electrobunCfg.executablePath) : void 0,
2062
2374
  appDir: electrobunCfg.appDir ? resolveFromConfig(electrobunCfg.appDir) : void 0,
@@ -2074,12 +2386,12 @@ async function buildElectrobunRuntime(config, resolveFromConfig) {
2074
2386
  domChannel: bridge
2075
2387
  })
2076
2388
  );
2077
- const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
2389
+ const deviceInfo = await Effect2.runPromise(driver.getDeviceInfo());
2078
2390
  return {
2079
2391
  runtime: {
2080
2392
  driver,
2081
2393
  cleanup: () => safeCleanup(
2082
- () => Effect3.runPromise(driver.killApp("")),
2394
+ () => Effect2.runPromise(driver.killApp("")),
2083
2395
  () => bridge?.disconnect() ?? Promise.resolve()
2084
2396
  ),
2085
2397
  metadata: {
@@ -2141,18 +2453,18 @@ async function buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig)
2141
2453
  warm: warmDaemons?.enabled,
2142
2454
  daemonStateFile: warmDaemons?.stateFile
2143
2455
  });
2144
- const driver = await Effect3.runPromise(
2456
+ const driver = await Effect2.runPromise(
2145
2457
  createUiAutomator2Driver(conn.host, conn.port, device.serial, packageName, {
2146
2458
  domChannel: bridge,
2147
2459
  cdpPort: config.apps?.android?.cdpPort
2148
2460
  })
2149
2461
  );
2150
- const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
2462
+ const deviceInfo = await Effect2.runPromise(driver.getDeviceInfo());
2151
2463
  return {
2152
2464
  runtime: {
2153
2465
  driver,
2154
2466
  cleanup: () => safeCleanup(
2155
- () => Effect3.runPromise(driver.killApp("")),
2467
+ () => Effect2.runPromise(driver.killApp("")),
2156
2468
  () => bridge?.disconnect() ?? Promise.resolve(),
2157
2469
  () => {
2158
2470
  if (reversedBridgePort !== null) {
@@ -2189,7 +2501,7 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
2189
2501
  const bridge = await maybeStartBridge(config.apps?.ios?.bridge, config.execution?.bridge);
2190
2502
  const createIOSRuntime = async (deviceId, conn, simulatorUdid) => {
2191
2503
  const reuseSession = warmDaemons?.enabled && warmDaemons.reuseSession !== false;
2192
- const driver = await Effect3.runPromise(
2504
+ const driver = await Effect2.runPromise(
2193
2505
  createWDADriver(conn.host, conn.port, bundleId, simulatorUdid, snapshotMaxDepth, {
2194
2506
  domChannel: bridge,
2195
2507
  webkitInspectorUrl: config.apps?.ios?.webkitInspectorUrl,
@@ -2199,12 +2511,12 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
2199
2511
  onSessionCreated: reuseSession ? (sessionId) => updateWarmDaemonSession("wda", deviceId, sessionId, bundleId, warmDaemons?.stateFile) : void 0
2200
2512
  })
2201
2513
  );
2202
- const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
2514
+ const deviceInfo = await Effect2.runPromise(driver.getDeviceInfo());
2203
2515
  return {
2204
2516
  runtime: {
2205
2517
  driver,
2206
2518
  cleanup: () => safeCleanup(
2207
- () => Effect3.runPromise(driver.killApp("")),
2519
+ () => Effect2.runPromise(driver.killApp("")),
2208
2520
  () => bridge?.disconnect() ?? Promise.resolve(),
2209
2521
  () => conn.cleanup?.() ?? Promise.resolve()
2210
2522
  ),
@@ -2335,1872 +2647,11 @@ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
2335
2647
  }
2336
2648
  }
2337
2649
 
2338
- // src/report/code-frame.ts
2339
- import { existsSync as existsSync2, readFileSync } from "fs";
2340
- import { fileURLToPath } from "url";
2341
- var INTERNAL_FRAME_PATTERNS = [
2342
- /node_modules\//,
2343
- /^node:/,
2344
- /^bun:/,
2345
- /^internal\//,
2346
- /\/packages\/spana\/(?:src|dist)\/(?!.*\.test\.[jt]sx?$)/,
2347
- /\/spana(?:-test)?\/dist\//
2348
- ];
2349
- function normalizeStackFile(raw) {
2350
- const trimmed = raw.trim();
2351
- if (trimmed.startsWith("file://")) {
2352
- try {
2353
- return fileURLToPath(trimmed);
2354
- } catch {
2355
- return trimmed.replace(/^file:\/\//, "");
2356
- }
2357
- }
2358
- return trimmed;
2359
- }
2360
- function parseStackFrames(stack) {
2361
- const frames = [];
2362
- for (const rawLine of stack.split("\n")) {
2363
- const line = rawLine.trim();
2364
- if (!line.startsWith("at ")) continue;
2365
- const match = line.match(/\((.+):(\d+):(\d+)\)$/) ?? line.match(/^at\s+(.+):(\d+):(\d+)$/);
2366
- if (!match) continue;
2367
- const file = normalizeStackFile(match[1]);
2368
- const lineNum = Number.parseInt(match[2], 10);
2369
- const colNum = Number.parseInt(match[3], 10);
2370
- if (!file || !Number.isFinite(lineNum) || lineNum < 1) continue;
2371
- frames.push({
2372
- file,
2373
- line: lineNum,
2374
- column: Number.isFinite(colNum) && colNum > 0 ? colNum : 1
2375
- });
2376
- }
2377
- return frames;
2378
- }
2379
- function isInternalFrame(file) {
2380
- const normalized = file.replaceAll("\\", "/");
2381
- return INTERNAL_FRAME_PATTERNS.some((re) => re.test(normalized));
2382
- }
2383
- function formatCodeFrame(source, line, column, contextLines = 3) {
2384
- const lines = source.split(/\r?\n/);
2385
- if (line < 1 || line > lines.length) return "";
2386
- const startLine = Math.max(1, line - contextLines);
2387
- const endLine = Math.min(lines.length, line + contextLines);
2388
- const gutterWidth = String(endLine).length;
2389
- const out = [];
2390
- for (let current = startLine; current <= endLine; current++) {
2391
- const marker = current === line ? ">" : " ";
2392
- const num = String(current).padStart(gutterWidth, " ");
2393
- const content = lines[current - 1] ?? "";
2394
- out.push(`${marker} ${num} | ${content}`);
2395
- if (current === line) {
2396
- const caretOffset = Math.max(0, Math.min(column - 1, content.length));
2397
- out.push(` ${" ".repeat(gutterWidth)} | ${" ".repeat(caretOffset)}^`);
2398
- }
2399
- }
2400
- return out.join("\n");
2401
- }
2402
- function extractCodeFrame(stack, preferredFile, contextLines = 3) {
2403
- if (!stack) return void 0;
2404
- const frames = parseStackFrames(stack);
2405
- if (frames.length === 0) return void 0;
2406
- const normalizedPreferred = preferredFile ? normalizeStackFile(preferredFile) : void 0;
2407
- let chosen = normalizedPreferred ? frames.find(
2408
- (f) => (f.file === normalizedPreferred || f.file.endsWith(normalizedPreferred)) && existsSync2(f.file)
2409
- ) : void 0;
2410
- if (!chosen) {
2411
- chosen = frames.find((f) => /\.flow\.[cm]?[jt]sx?$/.test(f.file) && existsSync2(f.file));
2412
- }
2413
- if (!chosen) {
2414
- chosen = frames.find((f) => !isInternalFrame(f.file) && existsSync2(f.file));
2415
- }
2416
- if (!chosen) return void 0;
2417
- try {
2418
- const source = readFileSync(chosen.file, "utf8");
2419
- const frame = formatCodeFrame(source, chosen.line, chosen.column, contextLines);
2420
- if (!frame) return void 0;
2421
- return {
2422
- location: { file: chosen.file, line: chosen.line, column: chosen.column },
2423
- frame
2424
- };
2425
- } catch {
2426
- return void 0;
2427
- }
2428
- }
2429
-
2430
- // src/core/video-recorder.ts
2431
- import { execFileSync, spawn as spawn2 } from "child_process";
2432
- import {
2433
- existsSync as existsSync3,
2434
- mkdirSync,
2435
- mkdtempSync as mkdtempSync2,
2436
- readFileSync as readFileSync2,
2437
- rmSync as rmSync2,
2438
- unlinkSync,
2439
- writeFileSync
2440
- } from "fs";
2441
- import { tmpdir as tmpdir2 } from "os";
2442
- import { join as join2 } from "path";
2443
- function hasFfmpegOnPath() {
2444
- try {
2445
- execFileSync(process.platform === "win32" ? "where" : "which", ["ffmpeg"], {
2446
- stdio: "ignore"
2447
- });
2448
- return true;
2449
- } catch {
2450
- return false;
2451
- }
2452
- }
2453
- async function exportFramesToMp4(frames, outputPath, spawnFn = spawn2) {
2454
- if (frames.length === 0 || !hasFfmpegOnPath()) return void 0;
2455
- const tempDir = mkdtempSync2(join2(tmpdir2(), "spana-vid-"));
2456
- try {
2457
- const ext = frames[0].mimeType === "image/png" ? "png" : "jpg";
2458
- const listLines = [];
2459
- for (let i = 0; i < frames.length; i++) {
2460
- const f = frames[i];
2461
- const framePath = join2(tempDir, `frame-${String(i).padStart(5, "0")}.${ext}`);
2462
- writeFileSync(framePath, Buffer.from(f.dataBase64, "base64"));
2463
- const nextTs = frames[i + 1]?.timestampMs ?? f.timestampMs + 250;
2464
- const durSec = Math.max(0.05, Math.min(2, (nextTs - f.timestampMs) / 1e3));
2465
- listLines.push(`file '${framePath.replaceAll("'", "'\\''")}'`);
2466
- listLines.push(`duration ${durSec.toFixed(3)}`);
2467
- }
2468
- const lastPath = join2(tempDir, `frame-${String(frames.length - 1).padStart(5, "0")}.${ext}`);
2469
- listLines.push(`file '${lastPath.replaceAll("'", "'\\''")}'`);
2470
- const listFile = join2(tempDir, "frames.txt");
2471
- writeFileSync(listFile, listLines.join("\n"), "utf8");
2472
- const ok = await new Promise((resolve) => {
2473
- const child = spawnFn(
2474
- "ffmpeg",
2475
- [
2476
- "-y",
2477
- "-f",
2478
- "concat",
2479
- "-safe",
2480
- "0",
2481
- "-i",
2482
- listFile,
2483
- "-vf",
2484
- "pad=ceil(iw/2)*2:ceil(ih/2)*2",
2485
- "-c:v",
2486
- "libx264",
2487
- "-pix_fmt",
2488
- "yuv420p",
2489
- "-movflags",
2490
- "+faststart",
2491
- outputPath
2492
- ],
2493
- { stdio: "ignore" }
2494
- );
2495
- child.on("error", () => resolve(false));
2496
- child.on("close", (code) => resolve(code === 0));
2497
- });
2498
- return ok && existsSync3(outputPath) ? outputPath : void 0;
2499
- } catch {
2500
- return void 0;
2501
- } finally {
2502
- try {
2503
- rmSync2(tempDir, { recursive: true, force: true });
2504
- } catch {
2505
- }
2506
- }
2507
- }
2508
- async function startCdpScreencastRecorder(cdp, options) {
2509
- const startedAt = Date.now();
2510
- const startedAtIso = new Date(startedAt).toISOString();
2511
- const maxFrames = options.maxFrames ?? 180;
2512
- const frames = [];
2513
- let stopped = false;
2514
- const unsubscribe = cdp.onEvent("Page.screencastFrame", (params) => {
2515
- if (stopped) return;
2516
- const sessionId = params?.sessionId;
2517
- if (sessionId !== void 0) {
2518
- void cdp.sendCommand("Page.screencastFrameAck", { sessionId }).catch(() => {
2519
- });
2520
- }
2521
- if (typeof params?.data === "string" && params.data.length > 0) {
2522
- if (frames.length >= maxFrames) {
2523
- frames.splice(1, 1);
2524
- }
2525
- frames.push({
2526
- timestampMs: Math.max(0, Date.now() - startedAt),
2527
- dataBase64: params.data,
2528
- mimeType: "image/jpeg"
2529
- });
2530
- }
2531
- });
2532
- await cdp.sendCommand("Page.startScreencast", {
2533
- format: "jpeg",
2534
- quality: options.quality ?? 65,
2535
- maxWidth: options.maxWidth ?? 1280,
2536
- maxHeight: options.maxHeight ?? 720,
2537
- everyNthFrame: options.everyNthFrame ?? 2
2538
- }).catch(() => {
2539
- });
2540
- return {
2541
- stop: async (stopOpts) => {
2542
- if (stopped) return { frameCount: frames.length };
2543
- stopped = true;
2544
- unsubscribe();
2545
- await cdp.sendCommand("Page.stopScreencast").catch(() => {
2546
- });
2547
- if (!stopOpts.keep) {
2548
- return { frameCount: 0 };
2549
- }
2550
- if (frames.length === 0) {
2551
- try {
2552
- const snap = await cdp.sendCommand("Page.captureScreenshot", {
2553
- format: "jpeg",
2554
- quality: options.quality ?? 65
2555
- });
2556
- if (typeof snap?.data === "string" && snap.data.length > 0) {
2557
- frames.push({
2558
- timestampMs: Math.max(0, Date.now() - startedAt),
2559
- dataBase64: snap.data,
2560
- mimeType: "image/jpeg"
2561
- });
2562
- }
2563
- } catch {
2564
- }
2565
- }
2566
- if (frames.length === 0) {
2567
- return { frameCount: 0 };
2568
- }
2569
- mkdirSync(stopOpts.outputDir, { recursive: true });
2570
- let videoPath;
2571
- if (options.exportMp4 !== false) {
2572
- const mp4Target = join2(stopOpts.outputDir, `${stopOpts.fileStem}.mp4`);
2573
- videoPath = await exportFramesToMp4(frames, mp4Target, options.spawnFn);
2574
- }
2575
- const trace = {
2576
- version: 1,
2577
- flowName: options.flowName,
2578
- platform: options.platform,
2579
- startedAtIso,
2580
- durationMs: Math.max(1, Date.now() - startedAt),
2581
- viewport: stopOpts.viewport,
2582
- frames,
2583
- steps: stopOpts.steps ?? [],
2584
- ...videoPath ? { videoPath } : {}
2585
- };
2586
- const playbackJsonPath = join2(stopOpts.outputDir, `${stopOpts.fileStem}-playback.json`);
2587
- writeFileSync(playbackJsonPath, JSON.stringify(trace), "utf8");
2588
- return { playbackJsonPath, videoPath, frameCount: frames.length };
2589
- }
2590
- };
2591
- }
2592
- function startAndroidVideoRecorder(serial, options) {
2593
- const spawnFn = options.spawnFn ?? spawn2;
2594
- const execSyncFn = options.execFileSyncFn ?? execFileSync;
2595
- const remotePath = `/sdcard/spana-rec-${Date.now()}-${Math.floor(Math.random() * 1e4)}.mp4`;
2596
- const child = spawnFn(
2597
- "adb",
2598
- ["-s", serial, "shell", "screenrecord", "--time-limit", "180", remotePath],
2599
- { stdio: "ignore" }
2600
- );
2601
- let stopped = false;
2602
- return {
2603
- stop: async ({ keep }) => {
2604
- if (stopped) return { frameCount: 0 };
2605
- stopped = true;
2606
- try {
2607
- child.kill("SIGINT");
2608
- } catch {
2609
- }
2610
- await new Promise((resolve) => {
2611
- const timer = setTimeout(resolve, 1200);
2612
- child.once("close", () => {
2613
- clearTimeout(timer);
2614
- resolve();
2615
- });
2616
- });
2617
- let savedPath;
2618
- if (keep) {
2619
- try {
2620
- execSyncFn("adb", ["-s", serial, "pull", remotePath, options.outputPath], {
2621
- stdio: "ignore"
2622
- });
2623
- if (existsSync3(options.outputPath)) savedPath = options.outputPath;
2624
- } catch {
2625
- }
2626
- }
2627
- try {
2628
- execSyncFn("adb", ["-s", serial, "shell", "rm", "-f", remotePath], { stdio: "ignore" });
2629
- } catch {
2630
- }
2631
- return { videoPath: savedPath, frameCount: savedPath ? 1 : 0 };
2632
- }
2633
- };
2634
- }
2635
- function startIosSimulatorVideoRecorder(udid, options) {
2636
- const spawnFn = options.spawnFn ?? spawn2;
2637
- const child = spawnFn(
2638
- "xcrun",
2639
- ["simctl", "io", udid, "recordVideo", "--codec=h264", "--force", options.outputPath],
2640
- { stdio: "ignore" }
2641
- );
2642
- let stopped = false;
2643
- return {
2644
- stop: async ({ keep }) => {
2645
- if (stopped) return { frameCount: 0 };
2646
- stopped = true;
2647
- try {
2648
- child.kill("SIGINT");
2649
- } catch {
2650
- }
2651
- await new Promise((resolve) => {
2652
- const timer = setTimeout(resolve, 1500);
2653
- child.once("close", () => {
2654
- clearTimeout(timer);
2655
- resolve();
2656
- });
2657
- });
2658
- if (!keep) {
2659
- try {
2660
- if (existsSync3(options.outputPath)) unlinkSync(options.outputPath);
2661
- } catch {
2662
- }
2663
- return { frameCount: 0 };
2664
- }
2665
- return {
2666
- videoPath: existsSync3(options.outputPath) ? options.outputPath : void 0,
2667
- frameCount: existsSync3(options.outputPath) ? 1 : 0
2668
- };
2669
- }
2670
- };
2671
- }
2672
- function buildPlaybackTraceFromSteps(input) {
2673
- const frames = [];
2674
- const markers = [];
2675
- let cursorMs = 0;
2676
- for (let i = 0; i < input.steps.length; i++) {
2677
- const step = input.steps[i];
2678
- const tapPoint = extractTapPointFromStep(step);
2679
- markers.push({
2680
- index: i,
2681
- command: step.command,
2682
- selector: step.selector,
2683
- startedAtMs: cursorMs,
2684
- durationMs: step.durationMs,
2685
- status: step.status,
2686
- error: step.error,
2687
- ...tapPoint ? { tapPoint } : {}
2688
- });
2689
- const img = step.attachments?.find(
2690
- (a) => a.contentType === "image/png" || a.contentType === "image/jpeg"
2691
- );
2692
- if (img && existsSync3(img.path)) {
2693
- try {
2694
- const dataBase64 = readFileSync2(img.path).toString("base64");
2695
- frames.push({
2696
- timestampMs: cursorMs + step.durationMs,
2697
- dataBase64,
2698
- mimeType: img.contentType === "image/jpeg" ? "image/jpeg" : "image/png"
2699
- });
2700
- } catch {
2701
- }
2702
- }
2703
- cursorMs += Math.max(1, step.durationMs);
2704
- }
2705
- if (frames.length === 0 && !input.videoPath) return null;
2706
- return {
2707
- version: 1,
2708
- flowName: input.flowName,
2709
- platform: input.platform,
2710
- startedAtIso: (/* @__PURE__ */ new Date()).toISOString(),
2711
- durationMs: Math.max(1, input.durationMs),
2712
- viewport: input.viewport,
2713
- frames,
2714
- steps: markers,
2715
- ...input.videoPath ? { videoPath: input.videoPath } : {}
2716
- };
2717
- }
2718
- function extractTapPointFromStep(step) {
2719
- const sel = step.selector;
2720
- if (!sel || typeof sel !== "object") return void 0;
2721
- const pt = sel["point"];
2722
- if (pt && typeof pt["x"] === "number" && typeof pt["y"] === "number") {
2723
- return { x: pt["x"], y: pt["y"] };
2724
- }
2725
- return void 0;
2726
- }
2727
-
2728
- // src/core/engine.ts
2729
- import { Effect as Effect6 } from "effect";
2730
-
2731
- // src/core/artifacts.ts
2732
- import { writeFileSync as writeFileSync2, mkdirSync as mkdirSync2 } from "fs";
2733
- import { join as join3 } from "path";
2734
- import { Effect as Effect4 } from "effect";
2735
- var DEFAULT_ARTIFACT_CONFIG = {
2736
- outputDir: "./spana-output",
2737
- captureOnFailure: true,
2738
- captureOnSuccess: false,
2739
- captureSteps: false,
2740
- screenshot: true,
2741
- uiHierarchy: true,
2742
- consoleLogs: true,
2743
- jsErrors: true,
2744
- har: true,
2745
- jsCoverage: false,
2746
- video: "off",
2747
- playback: false
2748
- };
2749
- function safeArtifactName(value) {
2750
- return value.replaceAll(/[^a-zA-Z0-9-_]/g, "_").replaceAll(/_+/g, "_").replaceAll(/^_+|_+$/g, "").slice(0, 80) || "artifact";
2751
- }
2752
- var safeName = safeArtifactName;
2753
- function flowArtifactDir(config, flowName, platform) {
2754
- const dir = join3(config.outputDir, `${safeName(flowName)}-${platform}`);
2755
- mkdirSync2(dir, { recursive: true });
2756
- return dir;
2757
- }
2758
- function createAttachment(name, contentType, path) {
2759
- return { name, contentType, path };
2760
- }
2761
- function writeJsonAttachment(dir, fileName, attachmentName, value) {
2762
- const path = join3(dir, fileName);
2763
- writeFileSync2(path, JSON.stringify(value, null, 2), "utf-8");
2764
- return createAttachment(attachmentName, "application/json", path);
2765
- }
2766
- function writeTextAttachment(dir, fileName, attachmentName, value) {
2767
- const path = join3(dir, fileName);
2768
- writeFileSync2(path, value, "utf-8");
2769
- return createAttachment(attachmentName, "text/plain", path);
2770
- }
2771
- function resolveArtifactConfig(...configs) {
2772
- return configs.reduce(
2773
- (resolved, config) => ({
2774
- ...resolved,
2775
- ...config
2776
- }),
2777
- { ...DEFAULT_ARTIFACT_CONFIG }
2778
- );
2779
- }
2780
- async function captureArtifacts(driver, config, flowName, platform, status) {
2781
- const shouldCapture = status === "failed" && config.captureOnFailure || status === "passed" && config.captureOnSuccess;
2782
- if (!shouldCapture) return [];
2783
- const attachments = [];
2784
- const dir = flowArtifactDir(config, flowName, platform);
2785
- if (config.screenshot) {
2786
- try {
2787
- const screenshot = await Effect4.runPromise(Effect4.orDie(driver.takeScreenshot()));
2788
- const path = join3(dir, "screenshot.png");
2789
- writeFileSync2(path, screenshot);
2790
- attachments.push(createAttachment(`${status}-screenshot`, "image/png", path));
2791
- } catch {
2792
- }
2793
- }
2794
- if (config.uiHierarchy) {
2795
- try {
2796
- const hierarchy = await Effect4.runPromise(Effect4.orDie(driver.dumpHierarchy()));
2797
- const path = join3(dir, "hierarchy.json");
2798
- writeFileSync2(path, hierarchy, "utf-8");
2799
- attachments.push(createAttachment(`${status}-hierarchy`, "application/json", path));
2800
- } catch {
2801
- }
2802
- }
2803
- if (config.consoleLogs && driver.getConsoleLogs) {
2804
- try {
2805
- const consoleLogs = await Effect4.runPromise(Effect4.orDie(driver.getConsoleLogs()));
2806
- if (consoleLogs.length > 0) {
2807
- attachments.push(
2808
- writeJsonAttachment(dir, "console-logs.json", `${status}-console-logs`, consoleLogs)
2809
- );
2810
- }
2811
- } catch {
2812
- }
2813
- }
2814
- if (config.jsErrors && driver.getJSErrors) {
2815
- try {
2816
- const jsErrors = await Effect4.runPromise(Effect4.orDie(driver.getJSErrors()));
2817
- if (jsErrors.length > 0) {
2818
- attachments.push(
2819
- writeJsonAttachment(dir, "js-errors.json", `${status}-js-errors`, jsErrors)
2820
- );
2821
- }
2822
- } catch {
2823
- }
2824
- }
2825
- if (config.har && driver.getHAR) {
2826
- try {
2827
- const har = await Effect4.runPromise(Effect4.orDie(driver.getHAR()));
2828
- if (har.log.entries.length > 0) {
2829
- attachments.push(writeJsonAttachment(dir, "network.har", `${status}-network-har`, har));
2830
- }
2831
- } catch {
2832
- }
2833
- }
2834
- if (status === "failed" && driver.getDriverLogs) {
2835
- try {
2836
- const driverLogs = await Effect4.runPromise(Effect4.orDie(driver.getDriverLogs()));
2837
- if (driverLogs.length > 0) {
2838
- attachments.push(
2839
- writeTextAttachment(
2840
- dir,
2841
- "driver-logs.txt",
2842
- `${status}-driver-logs`,
2843
- driverLogs.join("\n")
2844
- )
2845
- );
2846
- }
2847
- } catch {
2848
- }
2849
- }
2850
- return attachments;
2851
- }
2852
- async function captureStepScreenshot(driver, config, flowName, platform, stepIndex, stepName, screenshot) {
2853
- if (!config.screenshot) return void 0;
2854
- try {
2855
- const dir = join3(flowArtifactDir(config, flowName, platform), "steps");
2856
- mkdirSync2(dir, { recursive: true });
2857
- const fileName = `${String(stepIndex).padStart(3, "0")}-${safeName(stepName)}.png`;
2858
- const path = join3(dir, fileName);
2859
- const bytes = screenshot ?? await Effect4.runPromise(Effect4.orDie(driver.takeScreenshot()));
2860
- writeFileSync2(path, bytes);
2861
- return createAttachment(stepName, "image/png", path);
2862
- } catch {
2863
- return void 0;
2864
- }
2865
- }
2866
-
2867
- // src/core/debug-repl.ts
2868
- import * as repl from "repl";
2869
- import { Effect as Effect5 } from "effect";
2870
- var didStartDebugRepl = false;
2871
- function toSuggestedSelectors(root) {
2872
- return flattenElements(root).filter((el) => el.visible !== false && (el.id || el.text || el.accessibilityLabel)).map((el) => ({
2873
- suggestedSelector: el.id ? { testID: el.id } : el.accessibilityLabel ? { accessibilityLabel: el.accessibilityLabel } : el.text ? { text: el.text } : "",
2874
- elementType: el.elementType,
2875
- text: el.text,
2876
- accessibilityLabel: el.accessibilityLabel,
2877
- bounds: el.bounds,
2878
- id: el.id
2879
- }));
2880
- }
2881
- async function runDebugReplOnce(context) {
2882
- if (didStartDebugRepl) {
2883
- return false;
2884
- }
2885
- didStartDebugRepl = true;
2886
- if (!process.stdin.isTTY || !process.stdout.isTTY) {
2887
- console.log("Skipping debug REPL because stdin/stdout is not interactive.");
2888
- return false;
2889
- }
2890
- const hierarchy = async () => context.parseHierarchy(await Effect5.runPromise(context.driver.dumpHierarchy()));
2891
- const selectors = async () => toSuggestedSelectors(await hierarchy());
2892
- console.log("");
2893
- console.log(`Entering debug REPL for failed flow "${context.flowName}" on ${context.platform}.`);
2894
- console.log(
2895
- "Available bindings: app, expect, driver, platform, flowName, error, hierarchy(), selectors(), help()"
2896
- );
2897
- console.log('Use top-level await for async calls, for example: await app.tap({ text: "Login" })');
2898
- const replServer = repl.start({
2899
- prompt: `spana:${context.platform}> `,
2900
- ignoreUndefined: true,
2901
- useGlobal: false
2902
- });
2903
- replServer.context.app = context.app;
2904
- replServer.context.expect = context.expect;
2905
- replServer.context.driver = context.driver;
2906
- replServer.context.platform = context.platform;
2907
- replServer.context.flowName = context.flowName;
2908
- replServer.context.error = context.error;
2909
- replServer.context.hierarchy = hierarchy;
2910
- replServer.context.selectors = selectors;
2911
- replServer.context.help = () => {
2912
- console.log("app Promise-based app API with auto-waiting");
2913
- console.log("expect Assertion helper, e.g. await expect({ text: 'Done' }).toBeVisible()");
2914
- console.log("driver Raw driver service");
2915
- console.log("hierarchy Async helper returning the parsed UI tree");
2916
- console.log("selectors Async helper returning suggested selectors");
2917
- console.log(".exit Leave the REPL");
2918
- };
2919
- await new Promise((resolve) => replServer.on("exit", resolve));
2920
- console.log("");
2921
- return true;
2922
- }
2923
-
2924
- // src/core/step-recorder.ts
2925
- function errorMessage(error) {
2926
- return error instanceof Error ? error.message : String(error);
2927
- }
2928
- function createStepResult(command, durationMs, status, selector, error, attachments) {
2929
- return {
2930
- command,
2931
- selector,
2932
- status,
2933
- durationMs,
2934
- error,
2935
- attachments: attachments && attachments.length > 0 ? attachments : void 0
2936
- };
2937
- }
2938
- function createStepRecorder(driver, artifactConfig, flowName, platform) {
2939
- const steps = [];
2940
- let lastFailureStack;
2941
- return {
2942
- async runStep(command, action, opts) {
2943
- const startedAt = Date.now();
2944
- const callSiteStack = new Error().stack;
2945
- try {
2946
- const result = await action();
2947
- const attachments = [];
2948
- if (opts?.captureScreenshot && artifactConfig.captureSteps) {
2949
- const attachment = await captureStepScreenshot(
2950
- driver,
2951
- artifactConfig,
2952
- flowName,
2953
- platform,
2954
- steps.length + 1,
2955
- command
2956
- );
2957
- if (attachment) attachments.push(attachment);
2958
- }
2959
- steps.push(
2960
- createStepResult(
2961
- command,
2962
- Date.now() - startedAt,
2963
- "passed",
2964
- opts?.selector,
2965
- void 0,
2966
- attachments
2967
- )
2968
- );
2969
- return result;
2970
- } catch (error) {
2971
- lastFailureStack = callSiteStack;
2972
- steps.push(
2973
- createStepResult(
2974
- command,
2975
- Date.now() - startedAt,
2976
- "failed",
2977
- opts?.selector,
2978
- errorMessage(error)
2979
- )
2980
- );
2981
- throw error;
2982
- }
2983
- },
2984
- async runScreenshotStep(command, action, opts) {
2985
- const startedAt = Date.now();
2986
- const callSiteStack = new Error().stack;
2987
- try {
2988
- const screenshot = await action();
2989
- const attachment = await captureStepScreenshot(
2990
- driver,
2991
- artifactConfig,
2992
- flowName,
2993
- platform,
2994
- steps.length + 1,
2995
- opts?.name ?? command,
2996
- screenshot
2997
- );
2998
- steps.push(
2999
- createStepResult(
3000
- command,
3001
- Date.now() - startedAt,
3002
- "passed",
3003
- opts?.selector,
3004
- void 0,
3005
- attachment ? [attachment] : void 0
3006
- )
3007
- );
3008
- return screenshot;
3009
- } catch (error) {
3010
- lastFailureStack = callSiteStack;
3011
- steps.push(
3012
- createStepResult(
3013
- command,
3014
- Date.now() - startedAt,
3015
- "failed",
3016
- opts?.selector,
3017
- errorMessage(error)
3018
- )
3019
- );
3020
- throw error;
3021
- }
3022
- },
3023
- getSteps() {
3024
- return steps;
3025
- },
3026
- getLastFailureStack() {
3027
- return lastFailureStack;
3028
- }
3029
- };
3030
- }
3031
-
3032
- // src/report/classify-error.ts
3033
- var TAG_KEY = "_tag";
3034
- var FIBER_FAILURE_CAUSE_SYMBOL = /* @__PURE__ */ Symbol.for("effect/Runtime/FiberFailure/Cause");
3035
- function unwrapTaggedError(error) {
3036
- if (!error || typeof error !== "object") return {};
3037
- const obj = error;
3038
- if (typeof obj[TAG_KEY] === "string") {
3039
- return obj;
3040
- }
3041
- const cause = obj[FIBER_FAILURE_CAUSE_SYMBOL];
3042
- if (cause && typeof cause === "object") {
3043
- const inner = cause["error"] ?? cause["defect"];
3044
- if (inner && typeof inner === "object" && typeof inner[TAG_KEY] === "string") {
3045
- return inner;
3046
- }
3047
- }
3048
- return obj;
3049
- }
3050
- function selectorHint(selector) {
3051
- if (selector && typeof selector === "object") {
3052
- const s = selector;
3053
- if (s.testID) return `testID="${s.testID}"`;
3054
- if (s.text) return `text="${s.text}"`;
3055
- if (s.accessibilityLabel) return `accessibilityLabel="${s.accessibilityLabel}"`;
3056
- }
3057
- return JSON.stringify(selector);
3058
- }
3059
- function categorizeElementFailure(message) {
3060
- const lower = message.toLowerCase();
3061
- if (lower.includes("not visible") || lower.includes("visible=false")) {
3062
- return "element-not-visible";
3063
- }
3064
- if (lower.includes("off-screen") || lower.includes("zero size")) {
3065
- return "element-off-screen";
3066
- }
3067
- if (lower.includes("disabled") || lower.includes("not interactive")) {
3068
- return "element-not-interactive";
3069
- }
3070
- return "element-not-found";
3071
- }
3072
- function elementSuggestion(category, selector, timeoutMs) {
3073
- switch (category) {
3074
- case "element-not-visible":
3075
- return [
3076
- `Selector ${selector} matched an element, but it is currently hidden.`,
3077
- "Check whether an animation, modal, or loading state is covering it before retrying.",
3078
- "Consider increasing waitTimeout if the element becomes visible after a delay."
3079
- ].join("\n");
3080
- case "element-off-screen":
3081
- return [
3082
- `Selector ${selector} matched an element that is off-screen.`,
3083
- "Use scrollUntilVisible() or scroll to the element before interacting with it.",
3084
- "If the target is above the current viewport, reverse the search direction."
3085
- ].join("\n");
3086
- case "element-not-interactive":
3087
- return [
3088
- `Selector ${selector} matched an element that is disabled or not interactive.`,
3089
- "Wait for the app to enable it, or verify the prerequisite app state first.",
3090
- "Consider increasing waitTimeout if the control becomes enabled after async work completes."
3091
- ].join("\n");
3092
- default:
3093
- return [
3094
- `Selector ${selector} was not found within ${timeoutMs ?? "?"}ms.`,
3095
- "Run `spana selectors` to inspect the current screen and confirm the best selector.",
3096
- "Consider increasing waitTimeout if the element appears after a delay."
3097
- ].join("\n");
3098
- }
3099
- }
3100
- function categorizeDynamic(error, tag, msg) {
3101
- if (tag === "ElementNotFoundError" || tag === "WaitTimeoutError") {
3102
- const sel = selectorHint(error.selector);
3103
- if (msg.includes("scroll(s) toward")) {
3104
- return {
3105
- category: "element-not-found",
3106
- suggestion: [
3107
- `Selector ${sel} stayed off-screen while scrolling.`,
3108
- "Try increasing `maxScrolls` or `timeout`, or reverse the search direction",
3109
- 'if the target is actually above the current viewport (for example `{ direction: "up" }`).'
3110
- ].join("\n")
3111
- };
3112
- }
3113
- if (msg.includes("back action(s)")) {
3114
- return {
3115
- category: "element-not-found",
3116
- suggestion: [
3117
- `Selector ${sel} was not reached while navigating back.`,
3118
- "Try increasing `maxBacks` or `timeout`, or prefer an explicit in-app",
3119
- "back / close control on iOS-style screens instead of relying on system back."
3120
- ].join("\n")
3121
- };
3122
- }
3123
- const category = categorizeElementFailure(msg);
3124
- return {
3125
- category,
3126
- suggestion: elementSuggestion(category, sel, error.timeoutMs)
3127
- };
3128
- }
3129
- if (tag === "TextMismatchError") {
3130
- const e = error;
3131
- return {
3132
- category: "text-mismatch",
3133
- suggestion: [
3134
- `Expected text "${e.expected}" but found "${e.actual ?? "(empty)"}".`,
3135
- "The element exists but its content differs. Check for whitespace, truncation,",
3136
- "or platform-specific text rendering differences."
3137
- ].join("\n")
3138
- };
3139
- }
3140
- if (tag === "DeviceDisconnectedError") {
3141
- const id = error.deviceId ? ` (${error.deviceId})` : "";
3142
- return {
3143
- category: "device-disconnected",
3144
- suggestion: [
3145
- `The device${id} disconnected during the test.`,
3146
- "Check the physical connection or emulator/simulator stability.",
3147
- "Run `spana devices` to verify available devices."
3148
- ].join("\n")
3149
- };
3150
- }
3151
- if (tag === "AppCrashedError") {
3152
- const app = error.appId ? ` (${error.appId})` : "";
3153
- return {
3154
- category: "app-crashed",
3155
- suggestion: [
3156
- `The app${app} crashed during the test.`,
3157
- "Check the device logs for a crash stack trace:",
3158
- " Android: `adb logcat -d | grep FATAL`",
3159
- " iOS: Check Console.app or `log show --predicate 'process == \"your-app\"'`"
3160
- ].join("\n")
3161
- };
3162
- }
3163
- if (tag === "AppNotInstalledError") {
3164
- return {
3165
- category: "app-not-installed",
3166
- suggestion: [
3167
- `App "${error.appId}" is not installed on the device.`,
3168
- "Install it before running tests, or configure `apps.android.appPath`",
3169
- "/ `apps.ios.appPath` in spana.config.ts for auto-install."
3170
- ].join("\n")
3171
- };
3172
- }
3173
- if (tag === "DriverError") {
3174
- return categorizeDynamicDriver(error, msg);
3175
- }
3176
- return void 0;
3177
- }
3178
- function categorizeDynamicDriver(error, msg) {
3179
- for (const rule of driverRules) {
3180
- if (rule.pattern && matchesPattern(msg, rule.pattern)) {
3181
- return {
3182
- category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
3183
- suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
3184
- };
3185
- }
3186
- }
3187
- return {
3188
- category: "driver-error",
3189
- 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."
3190
- };
3191
- }
3192
- var driverRules = [
3193
- {
3194
- pattern: "dismissKeyboard()",
3195
- category: "driver-error",
3196
- suggestion: [
3197
- "Keyboard dismissal failed.",
3198
- 'On Android, try `app.dismissKeyboard({ strategy: "back" })`.',
3199
- "On iOS, prefer tapping a visible Done / Close control or a non-input element."
3200
- ].join("\n")
3201
- },
3202
- {
3203
- pattern: "backUntilVisible()",
3204
- category: "driver-error",
3205
- suggestion: [
3206
- "System back navigation failed before the target screen became visible.",
3207
- "If this route uses app-level navigation, tap the visible back / close control instead.",
3208
- "This is especially common on iOS where a system back button may not exist."
3209
- ].join("\n")
3210
- },
3211
- {
3212
- pattern: "Input text failed",
3213
- category: "driver-error",
3214
- suggestion: [
3215
- "Text input failed at the driver layer.",
3216
- "Make sure the field is focused first, and retry with shorter input chunks if needed.",
3217
- "If the keyboard is in the way, dismiss it before continuing the flow."
3218
- ].join("\n")
3219
- }
3220
- ];
3221
- var tagOnlyRules = [
3222
- {
3223
- tag: "TimeoutError",
3224
- category: "timeout",
3225
- suggestion: [
3226
- "The operation took longer than the allowed timeout.",
3227
- "Try increasing `defaults.waitTimeout` in spana.config.ts,",
3228
- "or set a per-flow timeout: `flow('name', { timeout: 30000 }, ...)`."
3229
- ].join("\n")
3230
- },
3231
- {
3232
- tag: ["ConfigError", "FlowSyntaxError"],
3233
- category: "config-error",
3234
- suggestion: "Run `spana validate-config` to check your configuration."
3235
- }
3236
- ];
3237
- var heuristicRules = [
3238
- {
3239
- pattern: /[Tt]imed out/,
3240
- category: "timeout",
3241
- suggestion: "The operation timed out. Try increasing `defaults.waitTimeout` in spana.config.ts."
3242
- },
3243
- {
3244
- pattern: /not found|not visible|not fillable|covered by/,
3245
- category: (msg) => categorizeElementFailure(msg),
3246
- suggestion: (_error, msg) => {
3247
- if (msg.includes("scroll(s) toward")) {
3248
- return "The target stayed off-screen while scrolling. Increase `maxScrolls` / `timeout`, or reverse the scroll search direction.";
3249
- }
3250
- const category = categorizeElementFailure(msg);
3251
- return elementSuggestion(category, "the target selector", void 0);
3252
- }
3253
- },
3254
- {
3255
- pattern: "dismissKeyboard()",
3256
- category: "driver-error",
3257
- suggestion: 'Keyboard dismissal failed. On Android try `app.dismissKeyboard({ strategy: "back" })`; on iOS prefer an explicit Done / Close control.'
3258
- },
3259
- {
3260
- pattern: /ECONNREFUSED|ECONNRESET|disconnected/,
3261
- category: "device-disconnected",
3262
- suggestion: "The connection was lost. Check the device or emulator/simulator is still running."
3263
- }
3264
- ];
3265
- function matchesPattern(msg, pattern) {
3266
- return typeof pattern === "string" ? msg.includes(pattern) : pattern.test(msg);
3267
- }
3268
- function matchesTag(tag, rule) {
3269
- if (!rule.tag) return true;
3270
- if (Array.isArray(rule.tag)) return tag != null && rule.tag.includes(tag);
3271
- return tag === rule.tag;
3272
- }
3273
- function categorize(error) {
3274
- const tag = error[TAG_KEY];
3275
- const msg = error.message ?? "";
3276
- const dynamic = categorizeDynamic(error, tag, msg);
3277
- if (dynamic) return dynamic;
3278
- for (const rule of tagOnlyRules) {
3279
- if (matchesTag(tag, rule)) {
3280
- return {
3281
- category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
3282
- suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
3283
- };
3284
- }
3285
- }
3286
- for (const rule of heuristicRules) {
3287
- if (rule.pattern && matchesPattern(msg, rule.pattern)) {
3288
- return {
3289
- category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
3290
- suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
3291
- };
3292
- }
3293
- }
3294
- return { category: "unknown" };
3295
- }
3296
- function classifyError(error, opts) {
3297
- const tagged = unwrapTaggedError(error);
3298
- const { category, suggestion } = categorize(tagged);
3299
- const extracted = extractCodeFrame(error.stack, opts?.flowFilePath) ?? extractCodeFrame(opts?.fallbackStack, opts?.flowFilePath);
3300
- return {
3301
- message: tagged.message ?? error.message,
3302
- stack: error.stack,
3303
- category,
3304
- suggestion,
3305
- ...extracted ? { location: extracted.location, codeFrame: extracted.frame } : {}
3306
- };
3307
- }
3308
-
3309
- // src/core/engine.ts
3310
- import { writeFileSync as writeFileSync4 } from "fs";
3311
- import { join as join5 } from "path";
3312
-
3313
- // src/report/failure-bundle.ts
3314
- import { writeFileSync as writeFileSync3, readFileSync as readFileSync3, existsSync as existsSync4 } from "fs";
3315
- import { join as join4, basename } from "path";
3316
- function levenshtein(a, b) {
3317
- const m = a.length;
3318
- const n = b.length;
3319
- const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
3320
- for (let i = 0; i <= m; i++) dp[i][0] = i;
3321
- for (let j = 0; j <= n; j++) dp[0][j] = j;
3322
- for (let i = 1; i <= m; i++) {
3323
- for (let j = 1; j <= n; j++) {
3324
- 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]);
3325
- }
3326
- }
3327
- return dp[m][n];
3328
- }
3329
- function extractIdentifiers(hierarchyJson) {
3330
- const testIDs = [];
3331
- const texts = [];
3332
- try {
3333
- const root = JSON.parse(hierarchyJson);
3334
- const queue = [root];
3335
- while (queue.length > 0) {
3336
- const node = queue.pop();
3337
- if (!node || typeof node !== "object") continue;
3338
- if (node.testID && typeof node.testID === "string") testIDs.push(node.testID);
3339
- if (node.text && typeof node.text === "string") texts.push(node.text);
3340
- if (Array.isArray(node.children)) {
3341
- for (const child of node.children) queue.push(child);
3342
- }
3343
- }
3344
- } catch {
3345
- }
3346
- return { testIDs, texts };
3347
- }
3348
- function findNearbySelectors(attempted, hierarchyJson) {
3349
- if (!hierarchyJson) return [];
3350
- const { testIDs, texts } = extractIdentifiers(hierarchyJson);
3351
- let target;
3352
- let candidates;
3353
- if (typeof attempted === "string") {
3354
- target = attempted.toLowerCase();
3355
- candidates = [...testIDs, ...texts];
3356
- } else if (attempted && typeof attempted === "object") {
3357
- const sel = attempted;
3358
- if (typeof sel.testID === "string") {
3359
- target = sel.testID.toLowerCase();
3360
- candidates = testIDs;
3361
- } else if (typeof sel.text === "string") {
3362
- target = sel.text.toLowerCase();
3363
- candidates = texts;
3364
- } else if (typeof sel.accessibilityLabel === "string") {
3365
- target = sel.accessibilityLabel.toLowerCase();
3366
- candidates = [...testIDs, ...texts];
3367
- } else {
3368
- return [];
3369
- }
3370
- } else {
3371
- return [];
3372
- }
3373
- const scored = candidates.filter((c) => c !== target).map((c) => {
3374
- const cl = c.toLowerCase();
3375
- const substringMatch = cl.includes(target) || target.includes(cl);
3376
- const dist = levenshtein(target, cl);
3377
- return { value: c, score: substringMatch ? 0 : dist };
3378
- }).filter((s) => s.score <= 5).toSorted((a, b) => a.score - b.score);
3379
- const seen = /* @__PURE__ */ new Set();
3380
- const results = [];
3381
- for (const s of scored) {
3382
- if (!seen.has(s.value)) {
3383
- seen.add(s.value);
3384
- results.push(s.value);
3385
- if (results.length >= 5) break;
3386
- }
3387
- }
3388
- return results;
3389
- }
3390
- function buildArtifactMap(attachments) {
3391
- const map = {};
3392
- if (!attachments) return map;
3393
- for (const att of attachments) {
3394
- const filename = basename(att.path);
3395
- if (filename === "screenshot.png") map.screenshot = filename;
3396
- else if (filename === "hierarchy.json") map.hierarchy = filename;
3397
- else if (filename === "console-logs.json") map.consoleLogs = filename;
3398
- else if (filename === "js-errors.json") map.jsErrors = filename;
3399
- else if (filename === "network.har") map.har = filename;
3400
- else if (filename === "driver-logs.txt") map.driverLogs = filename;
3401
- }
3402
- return map;
3403
- }
3404
- function createFailureBundle(flowName, platform, steps, error, artifactDir, attachments, flowPath) {
3405
- const failedStepIndex = steps.findLastIndex((s) => s.status === "failed");
3406
- const failedStep = failedStepIndex >= 0 ? {
3407
- index: failedStepIndex,
3408
- command: steps[failedStepIndex].command,
3409
- selector: steps[failedStepIndex].selector ?? null,
3410
- durationMs: steps[failedStepIndex].durationMs,
3411
- error: steps[failedStepIndex].error
3412
- } : null;
3413
- const lastPassedIndex = failedStepIndex > 0 ? steps.findLastIndex((s, i) => i < failedStepIndex && s.status === "passed") : -1;
3414
- const lastPassedStep = lastPassedIndex >= 0 ? {
3415
- index: lastPassedIndex,
3416
- command: steps[lastPassedIndex].command,
3417
- selector: steps[lastPassedIndex].selector ?? null,
3418
- durationMs: steps[lastPassedIndex].durationMs
3419
- } : null;
3420
- let selectorContext;
3421
- if (failedStep?.selector && (error.category === "element-not-found" || error.category === "element-not-visible")) {
3422
- const hierarchyPath = join4(artifactDir, "hierarchy.json");
3423
- let hierarchyJson = null;
3424
- if (existsSync4(hierarchyPath)) {
3425
- try {
3426
- hierarchyJson = readFileSync3(hierarchyPath, "utf-8");
3427
- } catch {
3428
- }
3429
- }
3430
- const nearbyAlternatives = findNearbySelectors(failedStep.selector, hierarchyJson);
3431
- selectorContext = {
3432
- attempted: failedStep.selector,
3433
- nearbyAlternatives
3434
- };
3435
- }
3436
- const shellQuote = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
3437
- const flowFile = flowPath ?? `flows/${flowName.replaceAll(" ", "-")}.flow.ts`;
3438
- const reproCommand = `spana test ${shellQuote(flowFile)} --platform ${platform} --grep ${shellQuote(flowName)}`;
3439
- let runtimeDiagnostics;
3440
- const consolePath = join4(artifactDir, "console-logs.json");
3441
- const jsErrPath = join4(artifactDir, "js-errors.json");
3442
- if (existsSync4(consolePath) || existsSync4(jsErrPath)) {
3443
- let consoleErrorCount = 0;
3444
- let consoleWarnCount = 0;
3445
- const recentConsoleErrors = [];
3446
- let jsErrorCount = 0;
3447
- const recentJsErrors = [];
3448
- if (existsSync4(consolePath)) {
3449
- try {
3450
- const logs = JSON.parse(readFileSync3(consolePath, "utf-8"));
3451
- if (Array.isArray(logs)) {
3452
- for (const entry of logs) {
3453
- const lvl = (entry.type ?? entry.level ?? "").toLowerCase();
3454
- const text = entry.text ?? entry.message ?? "";
3455
- if (lvl === "error") {
3456
- consoleErrorCount++;
3457
- if (text) recentConsoleErrors.push(text);
3458
- } else if (lvl === "warn" || lvl === "warning") {
3459
- consoleWarnCount++;
3460
- }
3461
- }
3462
- }
3463
- } catch {
3464
- }
3465
- }
3466
- if (existsSync4(jsErrPath)) {
3467
- try {
3468
- const errs = JSON.parse(readFileSync3(jsErrPath, "utf-8"));
3469
- if (Array.isArray(errs)) {
3470
- jsErrorCount = errs.length;
3471
- for (const e of errs.slice(-5)) {
3472
- const msg = e.message ?? e.text ?? String(e);
3473
- if (msg) recentJsErrors.push(msg);
3474
- }
3475
- }
3476
- } catch {
3477
- }
3478
- }
3479
- if (consoleErrorCount > 0 || consoleWarnCount > 0 || jsErrorCount > 0) {
3480
- runtimeDiagnostics = {
3481
- consoleErrorCount,
3482
- consoleWarnCount,
3483
- recentConsoleErrors: recentConsoleErrors.slice(-5),
3484
- jsErrorCount,
3485
- recentJsErrors
3486
- };
3487
- }
3488
- }
3489
- const bundle = {
3490
- schemaVersion: 1,
3491
- flow: flowName,
3492
- platform,
3493
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3494
- failedStep,
3495
- lastPassedStep,
3496
- steps: steps.map((s, index) => ({
3497
- index,
3498
- command: s.command,
3499
- selector: s.selector ?? null,
3500
- durationMs: s.durationMs,
3501
- status: s.status,
3502
- ...s.error !== void 0 ? { error: s.error } : {}
3503
- })),
3504
- error: {
3505
- message: error.message,
3506
- category: error.category,
3507
- suggestion: error.suggestion,
3508
- errorCode: error.errorCode,
3509
- ...error.location ? { location: error.location } : {},
3510
- ...error.codeFrame ? { codeFrame: error.codeFrame } : {}
3511
- },
3512
- selectorContext,
3513
- ...runtimeDiagnostics ? { runtimeDiagnostics } : {},
3514
- artifacts: buildArtifactMap(attachments),
3515
- reproCommand,
3516
- durationMs: steps.reduce((sum, s) => sum + s.durationMs, 0)
3517
- };
3518
- return bundle;
3519
- }
3520
- function writeFailureBundle(bundle, artifactDir) {
3521
- const path = join4(artifactDir, "failure-bundle.json");
3522
- writeFileSync3(path, JSON.stringify(bundle, null, 2), "utf-8");
3523
- return path;
3524
- }
3525
-
3526
- // src/core/engine.ts
3527
- function isCdpScreencastCapable(channel) {
3528
- return Boolean(channel) && typeof channel.sendCommand === "function" && typeof channel.onEvent === "function";
3529
- }
3530
- function buildPlaybackStepMarkers(steps) {
3531
- let cursorMs = 0;
3532
- return steps.map((step, index) => {
3533
- const startedAtMs = cursorMs;
3534
- cursorMs += Math.max(1, step.durationMs);
3535
- const sel = step.selector;
3536
- const pt = sel && typeof sel === "object" ? sel["point"] : void 0;
3537
- const tapPoint = pt && typeof pt["x"] === "number" && typeof pt["y"] === "number" ? { x: pt["x"], y: pt["y"] } : void 0;
3538
- return {
3539
- index,
3540
- command: step.command,
3541
- selector: step.selector,
3542
- startedAtMs,
3543
- durationMs: step.durationMs,
3544
- status: step.status,
3545
- error: step.error,
3546
- ...tapPoint ? { tapPoint } : {}
3547
- };
3548
- });
3549
- }
3550
- async function executeFlow(flow, driver, config) {
3551
- const start2 = Date.now();
3552
- const { platform, coordinatorConfig, appId } = config;
3553
- const skip = getFlowSkip(flow, platform);
3554
- if (skip) return skip;
3555
- const autoLaunch = flow.config.autoLaunch ?? config.autoLaunch ?? true;
3556
- const timeout = flow.config.timeout ?? config.flowTimeout ?? 6e4;
3557
- const artifactConfig = resolveArtifactConfig(config.artifactConfig, flow.config.artifacts);
3558
- const stepRecorder = createStepRecorder(driver, artifactConfig, flow.name, platform);
3559
- const launchOptions = mergeLaunchOptions(config.launchOptions, flow.config.launchOptions);
3560
- const flowDefaults = flow.config.defaults;
3561
- const mergedCoordinatorConfig = flowDefaults ? {
3562
- ...coordinatorConfig,
3563
- defaults: {
3564
- ...coordinatorConfig.defaults,
3565
- timeout: flowDefaults.waitTimeout ?? coordinatorConfig.defaults?.timeout,
3566
- pollInterval: flowDefaults.pollInterval ?? coordinatorConfig.defaults?.pollInterval,
3567
- settleTimeout: flowDefaults.settleTimeout ?? coordinatorConfig.defaults?.settleTimeout,
3568
- initialPollInterval: flowDefaults.initialPollInterval ?? coordinatorConfig.defaults?.initialPollInterval
3569
- },
3570
- waitForIdleTimeout: flowDefaults.waitForIdleTimeout ?? coordinatorConfig.waitForIdleTimeout,
3571
- typingDelay: flowDefaults.typingDelay ?? coordinatorConfig.typingDelay,
3572
- hierarchyCacheTtl: flowDefaults.hierarchyCacheTtl ?? coordinatorConfig.hierarchyCacheTtl
3573
- } : coordinatorConfig;
3574
- const softFailures = [];
3575
- const aggregateFailures = (hardFailure) => {
3576
- const messages = softFailures.map(
3577
- (error, i) => `${i + 1}. ${error instanceof Error ? error.message : String(error)}`
3578
- );
3579
- return new AggregateError(
3580
- hardFailure ? [hardFailure, ...softFailures] : softFailures,
3581
- `${hardFailure ? `${hardFailure.message}
3582
- ` : ""}${softFailures.length} soft assertion(s) failed:
3583
- ${messages.join("\n")}`,
3584
- { cause: hardFailure ?? softFailures[0] }
3585
- );
3586
- };
3587
- const flowMeta = {
3588
- flowFilePath: flow.sourcePath ?? "",
3589
- flowName: flow.name,
3590
- platform,
3591
- updateBaselines: config.updateBaselines ?? false,
3592
- recordSoftFailure: (error) => {
3593
- softFailures.push(error);
3594
- }
3595
- };
3596
- const extraCleanups = [];
3597
- const app = createPromiseApp(driver, appId, mergedCoordinatorConfig, stepRecorder, {
3598
- platform,
3599
- storybook: config.storybook,
3600
- launchOptions,
3601
- onRegisterCleanup: (fn) => extraCleanups.push(fn),
3602
- flowContext: flowMeta,
3603
- visualRegression: config.visualRegression
3604
- });
3605
- const expect = createPromiseExpect(
3606
- driver,
3607
- mergedCoordinatorConfig,
3608
- stepRecorder,
3609
- flowMeta,
3610
- config.visualRegression
3611
- );
3612
- const flowCtx = { app, expect, platform, updateBaselines: flowMeta.updateBaselines };
3613
- const sessionManager = new SessionManager();
3614
- const sessions = createSessions(
3615
- sessionManager,
3616
- async (opts) => {
3617
- const pwDriver = await Effect6.runPromise(
3618
- makePlaywrightDriver({
3619
- browser: opts.browser,
3620
- headless: opts.headless ?? true,
3621
- baseUrl: opts.baseUrl,
3622
- storageState: opts.storageState,
3623
- verboseLogging: opts.verboseLogging
3624
- })
3625
- );
3626
- return pwDriver;
3627
- },
3628
- { parse: (raw) => parseWebHierarchy(raw) },
3629
- { ...flowMeta, platform: "web" }
3630
- );
3631
- flowCtx.sessions = sessions;
3632
- let videoRecorder;
3633
- let collectingCoverage = false;
3634
- let recordingFinalized = false;
3635
- const wantRecording = artifactConfig.video !== "off" || artifactConfig.playback;
3636
- const captureCoverage = async (attachments, status) => {
3637
- if (!collectingCoverage || !driver.stopJSCoverage) return;
3638
- collectingCoverage = false;
3639
- try {
3640
- const entries = await Effect6.runPromise(driver.stopJSCoverage());
3641
- const path = join5(flowArtifactDir(artifactConfig, flow.name, platform), "js-coverage.json");
3642
- writeFileSync4(path, JSON.stringify(entries), "utf8");
3643
- attachments.push({ name: "js-coverage", contentType: "application/json", path });
3644
- } catch (error) {
3645
- if (status === "passed") throw error;
3646
- console.warn(
3647
- `Failed to capture JavaScript coverage: ${error instanceof Error ? error.message : String(error)}`
3648
- );
3649
- }
3650
- };
3651
- const finalizeRecording = async (status, attachments, steps, durationMs) => {
3652
- if (recordingFinalized || !wantRecording) return;
3653
- recordingFinalized = true;
3654
- const keep = artifactConfig.video === "on" || artifactConfig.playback || artifactConfig.video === "retain-on-failure" && status === "failed";
3655
- const fileStem = safeArtifactName(flow.name);
3656
- const outputDir = keep ? flowArtifactDir(artifactConfig, flow.name, platform) : artifactConfig.outputDir;
3657
- let viewport;
3658
- try {
3659
- const info = await Effect6.runPromise(Effect6.orDie(driver.getDeviceInfo()));
3660
- if (info.screenWidth > 0 && info.screenHeight > 0) {
3661
- viewport = { width: info.screenWidth, height: info.screenHeight };
3662
- }
3663
- } catch {
3664
- }
3665
- let stopRes;
3666
- if (videoRecorder) {
3667
- try {
3668
- stopRes = await videoRecorder.stop({
3669
- keep,
3670
- outputDir,
3671
- fileStem,
3672
- steps: buildPlaybackStepMarkers(steps),
3673
- viewport
3674
- });
3675
- } catch {
3676
- }
3677
- }
3678
- if (!keep) return;
3679
- if (stopRes?.videoPath) {
3680
- attachments.push({
3681
- name: "video",
3682
- contentType: stopRes.videoPath.endsWith(".webm") ? "video/webm" : "video/mp4",
3683
- path: stopRes.videoPath
3684
- });
3685
- }
3686
- if (stopRes?.playbackJsonPath) {
3687
- attachments.push({
3688
- name: "playback",
3689
- contentType: "application/json",
3690
- path: stopRes.playbackJsonPath
3691
- });
3692
- return;
3693
- }
3694
- const fallbackTrace = buildPlaybackTraceFromSteps({
3695
- flowName: flow.name,
3696
- platform,
3697
- durationMs,
3698
- steps,
3699
- viewport,
3700
- videoPath: stopRes?.videoPath
3701
- });
3702
- if (fallbackTrace) {
3703
- const playbackPath = join5(outputDir, `${fileStem}-playback.json`);
3704
- writeFileSync4(playbackPath, JSON.stringify(fallbackTrace), "utf8");
3705
- attachments.push({
3706
- name: "playback",
3707
- contentType: "application/json",
3708
- path: playbackPath
3709
- });
3710
- }
3711
- };
3712
- const buildFailureResult = async (error) => {
3713
- const attachments = await captureArtifacts(
3714
- driver,
3715
- artifactConfig,
3716
- flow.name,
3717
- platform,
3718
- "failed"
3719
- );
3720
- await captureCoverage(attachments, "failed");
3721
- const steps = stepRecorder.getSteps();
3722
- const durationMs = Date.now() - start2;
3723
- await finalizeRecording("failed", attachments, steps, durationMs);
3724
- const normalized = error instanceof Error ? error : new Error(String(error));
3725
- return {
3726
- name: flow.name,
3727
- platform,
3728
- status: "failed",
3729
- durationMs,
3730
- error: classifyError(normalized, {
3731
- flowFilePath: flow.sourcePath,
3732
- fallbackStack: stepRecorder.getLastFailureStack?.()
3733
- }),
3734
- attachments,
3735
- steps,
3736
- scenarioSteps: flowCtx.__scenarioSteps
3737
- };
3738
- };
3739
- if (driver.beginFlow) {
3740
- try {
3741
- await Effect6.runPromise(driver.beginFlow(flow.name));
3742
- } catch (error) {
3743
- return buildFailureResult(error);
3744
- }
3745
- }
3746
- if (artifactConfig.jsCoverage && platform === "web") {
3747
- if (!driver.startJSCoverage || !driver.stopJSCoverage) {
3748
- return buildFailureResult(
3749
- new Error(
3750
- "JavaScript coverage is not supported on web with the current driver; use Chromium with Playwright or direct CDP"
3751
- )
3752
- );
3753
- }
3754
- try {
3755
- await Effect6.runPromise(driver.startJSCoverage());
3756
- collectingCoverage = true;
3757
- } catch (error) {
3758
- return buildFailureResult(error);
3759
- }
3760
- }
3761
- if (wantRecording) {
3762
- try {
3763
- if (isCdpScreencastCapable(driver.domChannel)) {
3764
- videoRecorder = await startCdpScreencastRecorder(driver.domChannel, {
3765
- flowName: flow.name,
3766
- platform,
3767
- exportMp4: artifactConfig.video !== "off"
3768
- });
3769
- } else if (artifactConfig.video !== "off" && (platform === "android" || platform === "ios")) {
3770
- const info = await Effect6.runPromise(Effect6.orDie(driver.getDeviceInfo())).catch(
3771
- () => void 0
3772
- );
3773
- if (info?.deviceId) {
3774
- const outDir = flowArtifactDir(artifactConfig, flow.name, platform);
3775
- const videoOut = join5(outDir, `${safeArtifactName(flow.name)}.mp4`);
3776
- videoRecorder = platform === "android" ? startAndroidVideoRecorder(info.deviceId, { outputPath: videoOut }) : startIosSimulatorVideoRecorder(info.deviceId, { outputPath: videoOut });
3777
- }
3778
- }
3779
- } catch {
3780
- }
3781
- }
3782
- if (config.hooks?.beforeEach) {
3783
- try {
3784
- await config.hooks.beforeEach({ app, platform });
3785
- } catch (error) {
3786
- return buildFailureResult(error);
3787
- }
3788
- }
3789
- let result;
3790
- let softFailureError;
3791
- try {
3792
- if (autoLaunch) {
3793
- await app.launch();
3794
- }
3795
- await Promise.race([
3796
- flow.fn(flowCtx),
3797
- new Promise(
3798
- (_, reject) => setTimeout(
3799
- () => reject(new Error(`Flow "${flow.name}" timed out after ${timeout}ms`)),
3800
- timeout
3801
- )
3802
- )
3803
- ]);
3804
- if (softFailures.length > 0) {
3805
- softFailureError = aggregateFailures();
3806
- throw softFailureError;
3807
- }
3808
- const attachments = await captureArtifacts(
3809
- driver,
3810
- artifactConfig,
3811
- flow.name,
3812
- platform,
3813
- "passed"
3814
- );
3815
- await captureCoverage(attachments, "passed");
3816
- const steps = stepRecorder.getSteps();
3817
- const durationMs = Date.now() - start2;
3818
- await finalizeRecording("passed", attachments, steps, durationMs);
3819
- result = {
3820
- name: flow.name,
3821
- platform,
3822
- status: "passed",
3823
- durationMs,
3824
- attachments,
3825
- steps,
3826
- scenarioSteps: flowCtx.__scenarioSteps
3827
- };
3828
- } catch (error) {
3829
- const attachments = await captureArtifacts(
3830
- driver,
3831
- artifactConfig,
3832
- flow.name,
3833
- platform,
3834
- "failed"
3835
- );
3836
- await captureCoverage(attachments, "failed");
3837
- const steps = stepRecorder.getSteps();
3838
- const durationMs = Date.now() - start2;
3839
- await finalizeRecording("failed", attachments, steps, durationMs);
3840
- const normalized = error instanceof Error ? error : new Error(String(error));
3841
- const flowError = softFailures.length > 0 && error !== softFailureError ? aggregateFailures(normalized) : normalized;
3842
- result = {
3843
- name: flow.name,
3844
- platform,
3845
- status: "failed",
3846
- durationMs,
3847
- error: classifyError(flowError, {
3848
- flowFilePath: flow.sourcePath,
3849
- fallbackStack: stepRecorder.getLastFailureStack?.()
3850
- }),
3851
- attachments,
3852
- steps,
3853
- scenarioSteps: flowCtx.__scenarioSteps
3854
- };
3855
- if (artifactConfig.captureOnFailure && result.error) {
3856
- try {
3857
- const artDir = join5(
3858
- artifactConfig.outputDir,
3859
- `${flow.name.replaceAll(/[^a-zA-Z0-9-_]/g, "_").replaceAll(/_+/g, "_").slice(0, 80) || "artifact"}-${platform}`
3860
- );
3861
- const bundle = createFailureBundle(
3862
- flow.name,
3863
- platform,
3864
- stepRecorder.getSteps(),
3865
- result.error,
3866
- artDir,
3867
- attachments,
3868
- flow.sourcePath
3869
- );
3870
- writeFailureBundle(bundle, artDir);
3871
- } catch {
3872
- }
3873
- }
3874
- if (config.debugOnFailure) {
3875
- await runDebugReplOnce({
3876
- app,
3877
- expect,
3878
- driver,
3879
- error: flowError,
3880
- flowName: flow.name,
3881
- platform,
3882
- parseHierarchy: coordinatorConfig.parse
3883
- });
3884
- }
3885
- }
3886
- for (const cleanup of extraCleanups.toReversed()) {
3887
- try {
3888
- await cleanup();
3889
- } catch {
3890
- }
3891
- }
3892
- try {
3893
- await sessionManager.disconnectAll();
3894
- } catch {
3895
- }
3896
- if (config.hooks?.afterEach) {
3897
- try {
3898
- await config.hooks.afterEach({ app, platform, result });
3899
- } catch (hookError) {
3900
- console.warn(
3901
- `afterEach hook failed: ${hookError instanceof Error ? hookError.message : hookError}`
3902
- );
3903
- }
3904
- }
3905
- return result;
3906
- }
3907
-
3908
- // src/core/parallel.ts
3909
- function orderFlowsLongestFirst(flows, durationHintsMs) {
3910
- if (!durationHintsMs || Object.keys(durationHintsMs).length === 0) {
3911
- return flows;
3912
- }
3913
- return flows.toSorted((a, b) => (durationHintsMs[b.name] ?? 0) - (durationHintsMs[a.name] ?? 0));
3914
- }
3915
- async function runParallel(config) {
3916
- const {
3917
- workers,
3918
- flows: rawFlows,
3919
- onFlowComplete,
3920
- onFlowStart,
3921
- retries = 0,
3922
- retryDelay = 0,
3923
- bail,
3924
- durationHintsMs,
3925
- claimNextFlow
3926
- } = config;
3927
- const flows = orderFlowsLongestFirst(focusFlows(rawFlows), durationHintsMs);
3928
- const start2 = Date.now();
3929
- const results = [];
3930
- let nextFlowIndex = 0;
3931
- let failureCount = 0;
3932
- let bailedOut = false;
3933
- const workerPromises = workers.map(async (worker) => {
3934
- const stats = { flowCount: 0, totalMs: 0 };
3935
- while (true) {
3936
- if (bail !== void 0 && failureCount >= bail) break;
3937
- let flow;
3938
- if (claimNextFlow) {
3939
- const claimed = await claimNextFlow();
3940
- if (!claimed) break;
3941
- flow = claimed;
3942
- } else {
3943
- const flowIdx = nextFlowIndex++;
3944
- if (flowIdx >= flows.length) break;
3945
- flow = flows[flowIdx];
3946
- }
3947
- const skip = getFlowSkip(flow, worker.engineConfig.platform);
3948
- if (skip) {
3949
- results.push(skip);
3950
- onFlowComplete?.(skip, worker.name);
3951
- continue;
3952
- }
3953
- const flowRetries = flow.config.retries ?? retries;
3954
- onFlowStart?.(flow.name, worker.name);
3955
- let result = await executeFlow(flow, worker.driver, worker.engineConfig);
3956
- let attempts = 1;
3957
- while (result.status === "failed" && attempts <= flowRetries) {
3958
- if (retryDelay > 0) {
3959
- await new Promise((resolve) => setTimeout(resolve, retryDelay));
3960
- }
3961
- result = await executeFlow(flow, worker.driver, worker.engineConfig);
3962
- attempts++;
3963
- }
3964
- if (result.status === "passed" && attempts > 1) {
3965
- result.flaky = true;
3966
- }
3967
- result.attempts = attempts;
3968
- results.push(result);
3969
- stats.flowCount++;
3970
- stats.totalMs += result.durationMs;
3971
- if (result.status === "failed") {
3972
- failureCount++;
3973
- }
3974
- onFlowComplete?.(result, worker.name);
3975
- }
3976
- return { workerId: worker.id, stats };
3977
- });
3978
- const workerResults = await Promise.all(workerPromises);
3979
- if (!claimNextFlow && bail !== void 0 && failureCount >= bail) {
3980
- bailedOut = true;
3981
- while (nextFlowIndex < flows.length) {
3982
- const flow = flows[nextFlowIndex++];
3983
- results.push(
3984
- getFlowSkip(flow, workers[0].engineConfig.platform) ?? {
3985
- name: flow.name,
3986
- platform: workers[0].engineConfig.platform,
3987
- status: "skipped",
3988
- durationMs: 0,
3989
- attempts: 0
3990
- }
3991
- );
3992
- }
3993
- }
3994
- const workerStats = /* @__PURE__ */ new Map();
3995
- for (const wr of workerResults) {
3996
- workerStats.set(wr.workerId, wr.stats);
3997
- }
3998
- return {
3999
- results,
4000
- totalDurationMs: Date.now() - start2,
4001
- passed: results.filter((r) => r.status === "passed").length,
4002
- failed: results.filter((r) => r.status === "failed").length,
4003
- skipped: results.filter((r) => r.status === "skipped").length,
4004
- flaky: results.filter((r) => r.flaky === true).length,
4005
- bailedOut: bailedOut || void 0,
4006
- workerStats
4007
- };
4008
- }
4009
-
4010
- // src/core/worker-pool.ts
4011
- import { spawn as spawn3 } from "child_process";
4012
- import { mkdir, readFile as readFile2, unlink, writeFile as writeFile2 } from "fs/promises";
4013
- import { createServer } from "http";
4014
- import { dirname } from "path";
4015
- var DEFAULT_MAX_WORKERS_PER_PROCESS = 8;
4016
- async function startSharedFlowQueueServer(orderedFlowNames) {
4017
- const queue = [...orderedFlowNames];
4018
- let cursor = 0;
4019
- const server = createServer((req, res) => {
4020
- if (req.url === "/claim" && (req.method === "POST" || req.method === "GET")) {
4021
- const flowName = cursor < queue.length ? queue[cursor++] : null;
4022
- const body = JSON.stringify({ flowName });
4023
- res.writeHead(200, { "content-type": "application/json" });
4024
- res.end(body);
4025
- return;
4026
- }
4027
- res.writeHead(404);
4028
- res.end();
4029
- });
4030
- await new Promise((resolve, reject) => {
4031
- server.once("error", reject);
4032
- server.listen(0, "127.0.0.1", () => resolve());
4033
- });
4034
- const addr = server.address();
4035
- const url = `http://127.0.0.1:${addr.port}`;
4036
- return {
4037
- url,
4038
- remaining: () => Math.max(0, queue.length - cursor),
4039
- close: () => new Promise((resolve) => {
4040
- server.close(() => resolve());
4041
- })
4042
- };
4043
- }
4044
- function createRemoteFlowClaimer(queueUrl) {
4045
- const endpoint = `${queueUrl.replace(/\/+$/, "")}/claim`;
4046
- return async () => {
4047
- const res = await fetch(endpoint, { method: "POST" });
4048
- if (!res.ok) return null;
4049
- const data = await res.json();
4050
- return typeof data.flowName === "string" ? data.flowName : null;
4051
- };
4052
- }
4053
- function planProcessPool(totalWorkers, maxWorkersPerProcess = DEFAULT_MAX_WORKERS_PER_PROCESS, explicitProcesses) {
4054
- const safeTotal = Math.max(1, Math.floor(totalWorkers));
4055
- const safeMax = Math.max(1, Math.floor(maxWorkersPerProcess));
4056
- const processCount = explicitProcesses !== void 0 && explicitProcesses >= 1 ? Math.min(Math.floor(explicitProcesses), safeTotal) : safeTotal <= safeMax ? 1 : Math.ceil(safeTotal / safeMax);
4057
- if (processCount <= 1) {
4058
- return {
4059
- totalWorkers: safeTotal,
4060
- maxWorkersPerProcess: safeMax,
4061
- processCount: 1,
4062
- workersPerProcess: [safeTotal]
4063
- };
4064
- }
4065
- const base = Math.floor(safeTotal / processCount);
4066
- const remainder = safeTotal % processCount;
4067
- const workersPerProcess = Array.from(
4068
- { length: processCount },
4069
- (_v, i) => base + (i < remainder ? 1 : 0)
4070
- );
4071
- return {
4072
- totalWorkers: safeTotal,
4073
- maxWorkersPerProcess: safeMax,
4074
- processCount,
4075
- workersPerProcess
4076
- };
4077
- }
4078
- function partitionFlowsAcrossProcesses(items, processCount, options) {
4079
- const count = Math.max(1, Math.min(Math.floor(processCount), Math.max(1, items.length)));
4080
- if (count === 1 || items.length === 0) {
4081
- return items.length === 0 ? [] : [items];
4082
- }
4083
- const hints = options?.durationHintsMs;
4084
- const getName = options?.getName;
4085
- const known = hints ? Object.values(hints).filter((v) => typeof v === "number" && v > 0) : [];
4086
- const defaultWeight = known.length > 0 ? known.reduce((a, b) => a + b, 0) / known.length : 1e3;
4087
- const indexed = items.map((item, idx) => ({
4088
- item,
4089
- idx,
4090
- weight: hints && getName ? hints[getName(item)] ?? defaultWeight : 1e3
4091
- }));
4092
- const ordered = hints && getName && Object.keys(hints).length > 0 ? indexed.toSorted((a, b) => b.weight - a.weight || a.idx - b.idx) : indexed;
4093
- const loads = Array.from({ length: count }, () => 0);
4094
- const buckets = Array.from({ length: count }, () => []);
4095
- for (const entry of ordered) {
4096
- let best = 0;
4097
- for (let i = 1; i < count; i++) {
4098
- if (loads[i] < loads[best]) best = i;
4099
- }
4100
- loads[best] = loads[best] + entry.weight;
4101
- buckets[best].push({ item: entry.item, idx: entry.idx });
4102
- }
4103
- return buckets.map((bucket) => bucket.toSorted((a, b) => a.idx - b.idx).map((e) => e.item)).filter((b) => b.length > 0);
4104
- }
4105
- async function writeWorkerProcessReport(results, env = process.env) {
4106
- const reportPath = env["SPANA_WORKER_REPORT_PATH"];
4107
- if (!reportPath) return null;
4108
- await mkdir(dirname(reportPath), { recursive: true });
4109
- await writeFile2(reportPath, JSON.stringify({ results }, null, 2), "utf8");
4110
- return reportPath;
4111
- }
4112
- async function defaultReadJsonReport(reportJsonPath) {
4113
- let content;
4114
- try {
4115
- content = await readFile2(reportJsonPath, "utf8");
4116
- } catch {
4117
- return [];
4118
- }
4119
- const raw = JSON.parse(content);
4120
- return Array.isArray(raw.results) ? raw.results : [];
4121
- }
4122
- async function runMultiProcessPool(options) {
4123
- const plan = planProcessPool(
4124
- options.totalWorkers,
4125
- options.maxWorkersPerProcess,
4126
- options.processes
4127
- );
4128
- const spawnFn = options.spawnFn ?? spawn3;
4129
- const readReport = options.readReportFn ?? defaultReadJsonReport;
4130
- const shouldCleanup = options.cleanupReportFiles !== false;
4131
- const startedAt = Date.now();
4132
- const processResults = await Promise.all(
4133
- plan.workersPerProcess.map(async (workerCount, shardIdx) => {
4134
- const shardStart = Date.now();
4135
- const spec = options.buildShardCommand(shardIdx + 1, plan.processCount, workerCount);
4136
- let exitCode = null;
4137
- let spawnError;
4138
- try {
4139
- exitCode = await new Promise((resolve, reject) => {
4140
- const child = spawnFn(spec.command, spec.args, {
4141
- env: { ...process.env, ...spec.env },
4142
- stdio: "inherit"
4143
- });
4144
- child.on("error", reject);
4145
- child.on("close", (code) => resolve(code));
4146
- });
4147
- } catch (err) {
4148
- spawnError = err instanceof Error ? err.message : String(err);
4149
- }
4150
- let shardResults = [];
4151
- try {
4152
- shardResults = await readReport(spec.reportJsonPath);
4153
- } catch (err) {
4154
- if (!spawnError) {
4155
- spawnError = `Failed to parse shard ${shardIdx + 1} report: ${err instanceof Error ? err.message : String(err)}`;
4156
- }
4157
- }
4158
- if (shouldCleanup) {
4159
- try {
4160
- await unlink(spec.reportJsonPath);
4161
- } catch {
4162
- }
4163
- }
4164
- if (exitCode !== 0 && shardResults.length === 0) {
4165
- shardResults.push({
4166
- name: `worker-process-${shardIdx + 1}`,
4167
- platform: "web",
4168
- status: "failed",
4169
- durationMs: Date.now() - shardStart,
4170
- error: {
4171
- category: "driver-error",
4172
- message: spawnError ?? `Worker process ${shardIdx + 1} exited with code ${exitCode ?? "unknown"}`
4173
- }
4174
- });
4175
- }
4176
- return {
4177
- shardIndex: shardIdx + 1,
4178
- workerCount,
4179
- exitCode,
4180
- durationMs: Date.now() - shardStart,
4181
- results: shardResults,
4182
- ...spawnError ? { error: spawnError } : {}
4183
- };
4184
- })
4185
- );
4186
- const results = processResults.flatMap((p) => p.results);
4187
- const passed = results.filter((r) => r.status === "passed").length;
4188
- const failed = results.filter((r) => r.status === "failed").length;
4189
- const skipped = results.filter((r) => r.status === "skipped").length;
4190
- const flaky = results.filter((r) => r.flaky).length;
4191
- return {
4192
- results,
4193
- totalDurationMs: Date.now() - startedAt,
4194
- passed,
4195
- failed,
4196
- skipped,
4197
- flaky,
4198
- processCount: plan.processCount,
4199
- processResults
4200
- };
4201
- }
4202
-
4203
2650
  export {
2651
+ resolveBrowserExtensions,
2652
+ applyExtensionChromeArgs,
2653
+ getLoadedExtensions,
2654
+ runOAuthPopupFlow,
4204
2655
  launchDirectCdpBrowser,
4205
2656
  UPLOAD_ATTACH_TIMEOUT_MS,
4206
2657
  makeLightweightCdpDriver,
@@ -4211,24 +2662,6 @@ export {
4211
2662
  buildElectronRuntime,
4212
2663
  buildElectrobunRuntime,
4213
2664
  buildLocalAndroidRuntime,
4214
- buildLocalIOSRuntime,
4215
- formatCodeFrame,
4216
- extractCodeFrame,
4217
- classifyError,
4218
- exportFramesToMp4,
4219
- startCdpScreencastRecorder,
4220
- startAndroidVideoRecorder,
4221
- startIosSimulatorVideoRecorder,
4222
- buildPlaybackTraceFromSteps,
4223
- executeFlow,
4224
- orderFlowsLongestFirst,
4225
- runParallel,
4226
- DEFAULT_MAX_WORKERS_PER_PROCESS,
4227
- startSharedFlowQueueServer,
4228
- createRemoteFlowClaimer,
4229
- planProcessPool,
4230
- partitionFlowsAcrossProcesses,
4231
- writeWorkerProcessReport,
4232
- runMultiProcessPool
2665
+ buildLocalIOSRuntime
4233
2666
  };
4234
- //# sourceMappingURL=chunk-66D3C7NB.js.map
2667
+ //# sourceMappingURL=chunk-3IZMPNE7.js.map