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
@@ -0,0 +1,2874 @@
1
+ import {
2
+ createFlowAgent
3
+ } from "./chunk-OPTNFLBL.js";
4
+ import {
5
+ makePlaywrightDriver,
6
+ parseWebHierarchy
7
+ } from "./chunk-FXBWACUT.js";
8
+ import {
9
+ focusFlows,
10
+ getFlowSkip
11
+ } from "./chunk-64UZQP7Z.js";
12
+ import {
13
+ createPromiseApp,
14
+ createPromiseExpect,
15
+ flattenElements
16
+ } from "./chunk-4KK4E3N3.js";
17
+ import {
18
+ mergeLaunchOptions
19
+ } from "./chunk-6PTUVG6A.js";
20
+
21
+ // src/core/session-manager.ts
22
+ import { Effect } from "effect";
23
+ function createSessions(manager, driverFactory, coordinatorConfig, flowContext) {
24
+ const coordConfig = coordinatorConfig ?? { parse: parseWebHierarchy };
25
+ return {
26
+ async open(opts) {
27
+ const existing = manager.all().find((s) => s.name === opts.name);
28
+ if (existing) {
29
+ throw new Error(`Session "${opts.name}" already exists`);
30
+ }
31
+ const driver = await driverFactory(opts);
32
+ const baseUrl = opts.baseUrl ?? "http://localhost:3000";
33
+ await Effect.runPromise(driver.launchApp(baseUrl));
34
+ const app = createPromiseApp(driver, baseUrl, coordConfig, void 0, {
35
+ platform: "web",
36
+ flowContext
37
+ });
38
+ const expect = createPromiseExpect(driver, coordConfig, void 0, flowContext);
39
+ const session = {
40
+ name: opts.name,
41
+ platform: "web",
42
+ app,
43
+ expect,
44
+ async disconnect() {
45
+ await Effect.runPromise(driver.killApp(baseUrl));
46
+ manager.remove(opts.name);
47
+ }
48
+ };
49
+ const cleanup = async () => {
50
+ await Effect.runPromise(driver.killApp(baseUrl));
51
+ };
52
+ manager.register(session, cleanup);
53
+ return session;
54
+ }
55
+ };
56
+ }
57
+ var SessionManager = class {
58
+ sessions = [];
59
+ all() {
60
+ return this.sessions.map((s) => s.session);
61
+ }
62
+ register(session, cleanup) {
63
+ this.sessions.push({ session, cleanup });
64
+ }
65
+ remove(name) {
66
+ this.sessions = this.sessions.filter((s) => s.session.name !== name);
67
+ }
68
+ async disconnectAll() {
69
+ const errors = [];
70
+ for (const entry of [...this.sessions].toReversed()) {
71
+ try {
72
+ await entry.cleanup();
73
+ } catch (err) {
74
+ errors.push(err);
75
+ }
76
+ }
77
+ this.sessions = [];
78
+ if (errors.length > 0) {
79
+ console.warn(
80
+ `SessionManager: ${errors.length} error(s) during cleanup:`,
81
+ errors.map((e) => e instanceof Error ? e.message : String(e))
82
+ );
83
+ }
84
+ }
85
+ };
86
+
87
+ // src/api/suite.ts
88
+ import { AsyncLocalStorage } from "async_hooks";
89
+ var activeStepRecorderStorage = new AsyncLocalStorage();
90
+ function withActiveStepRecorder(recorder, fn) {
91
+ return activeStepRecorderStorage.run(recorder, fn);
92
+ }
93
+ async function step(name, fn) {
94
+ const recorder = activeStepRecorderStorage.getStore();
95
+ if (!recorder) {
96
+ return fn();
97
+ }
98
+ return recorder.runStep(`step(${name})`, fn, { captureScreenshot: false });
99
+ }
100
+ function mergeFlowConfigs(parent, child) {
101
+ const mergedTags = parent.tags || child.tags ? Array.from(/* @__PURE__ */ new Set([...parent.tags ?? [], ...child.tags ?? []])) : void 0;
102
+ return {
103
+ ...parent,
104
+ ...child,
105
+ ...mergedTags ? { tags: mergedTags } : {},
106
+ ...parent.defaults || child.defaults ? { defaults: { ...parent.defaults, ...child.defaults } } : {},
107
+ ...parent.artifacts || child.artifacts ? { artifacts: { ...parent.artifacts, ...child.artifacts } } : {}
108
+ };
109
+ }
110
+ function suite(name, configOrDefine, maybeDefine) {
111
+ const suiteConfig = typeof configOrDefine === "function" ? {} : configOrDefine;
112
+ const define = typeof configOrDefine === "function" ? configOrDefine : maybeDefine;
113
+ const {
114
+ beforeAll: cfgBeforeAll,
115
+ beforeEach: cfgBeforeEach,
116
+ afterEach: cfgAfterEach,
117
+ afterAll: cfgAfterAll,
118
+ ...baseFlowConfig
119
+ } = suiteConfig;
120
+ const beforeAllHooks = cfgBeforeAll ? [cfgBeforeAll] : [];
121
+ const beforeEachHooks = cfgBeforeEach ? [cfgBeforeEach] : [];
122
+ const afterEachHooks = cfgAfterEach ? [cfgAfterEach] : [];
123
+ const afterAllHooks = cfgAfterAll ? [cfgAfterAll] : [];
124
+ const rawFlows = [];
125
+ const registerFlow = (flowName, configOrFn, maybeFn, modifier) => {
126
+ const childCfg = typeof configOrFn === "function" ? {} : configOrFn;
127
+ const fn = typeof configOrFn === "function" ? configOrFn : maybeFn;
128
+ const mergedCfg = mergeFlowConfigs(baseFlowConfig, {
129
+ ...childCfg,
130
+ ...modifier ? { [modifier]: childCfg[modifier] ?? true } : {}
131
+ });
132
+ rawFlows.push({
133
+ name: `${name} > ${flowName}`,
134
+ config: mergedCfg,
135
+ fn
136
+ });
137
+ };
138
+ const builder = {
139
+ flow(flowName, a, b) {
140
+ registerFlow(flowName, a, b);
141
+ },
142
+ skip(flowName, a, b) {
143
+ registerFlow(flowName, a, b, "skip");
144
+ },
145
+ only(flowName, a, b) {
146
+ registerFlow(flowName, a, b, "only");
147
+ },
148
+ fixme(flowName, a, b) {
149
+ registerFlow(flowName, a, b, "fixme");
150
+ },
151
+ beforeAll(fn) {
152
+ beforeAllHooks.push(fn);
153
+ },
154
+ beforeEach(fn) {
155
+ beforeEachHooks.push(fn);
156
+ },
157
+ afterEach(fn) {
158
+ afterEachHooks.push(fn);
159
+ },
160
+ afterAll(fn) {
161
+ afterAllHooks.push(fn);
162
+ },
163
+ suite(nestedName, a, b) {
164
+ const nestedFlows = typeof a === "function" ? suite(nestedName, a) : suite(nestedName, a, b);
165
+ for (const nf of nestedFlows) {
166
+ rawFlows.push({
167
+ ...nf,
168
+ name: `${name} > ${nf.name}`,
169
+ config: mergeFlowConfigs(baseFlowConfig, nf.config)
170
+ });
171
+ }
172
+ }
173
+ };
174
+ define(builder);
175
+ let ranBeforeAll = false;
176
+ let completedCount = 0;
177
+ const totalRunnable = rawFlows.filter((f) => !f.config.skip && !f.config.fixme).length;
178
+ return rawFlows.map((entry) => {
179
+ const innerFn = entry.fn;
180
+ const wrappedFn = async (ctx) => {
181
+ if (!ranBeforeAll && beforeAllHooks.length > 0) {
182
+ ranBeforeAll = true;
183
+ for (const hook of beforeAllHooks) {
184
+ await hook(ctx);
185
+ }
186
+ }
187
+ for (const hook of beforeEachHooks) {
188
+ await hook(ctx);
189
+ }
190
+ let flowError;
191
+ let threw = false;
192
+ try {
193
+ await innerFn(ctx);
194
+ } catch (err) {
195
+ threw = true;
196
+ flowError = err;
197
+ } finally {
198
+ for (const hook of afterEachHooks) {
199
+ await hook(ctx);
200
+ }
201
+ completedCount += 1;
202
+ if (completedCount >= Math.max(1, totalRunnable) && afterAllHooks.length > 0) {
203
+ for (const hook of afterAllHooks) {
204
+ await hook(ctx);
205
+ }
206
+ }
207
+ }
208
+ if (threw) throw flowError;
209
+ };
210
+ return {
211
+ ...entry,
212
+ fn: wrappedFn
213
+ };
214
+ });
215
+ }
216
+
217
+ // src/core/trace-viewer.ts
218
+ import { mkdirSync, readFileSync, writeFileSync } from "fs";
219
+ import { join } from "path";
220
+ function readAttachmentDataUrl(path, contentType) {
221
+ try {
222
+ const bytes = readFileSync(path);
223
+ return `data:${contentType};base64,${bytes.toString("base64")}`;
224
+ } catch {
225
+ return void 0;
226
+ }
227
+ }
228
+ function buildRichFlowTrace(input) {
229
+ const inline = input.inlineScreenshots !== false;
230
+ let cursorMs = 0;
231
+ const steps = input.steps.map((step2, index) => {
232
+ const startedAtMs = cursorMs;
233
+ cursorMs += Math.max(0, step2.durationMs);
234
+ let screenshotDataUrl;
235
+ const imgAttachment = step2.attachments?.find((a) => a.contentType.startsWith("image/"));
236
+ if (imgAttachment) {
237
+ screenshotDataUrl = inline ? readAttachmentDataUrl(imgAttachment.path, imgAttachment.contentType) : imgAttachment.path;
238
+ }
239
+ return {
240
+ index,
241
+ command: step2.command,
242
+ status: step2.status,
243
+ startedAtMs,
244
+ durationMs: step2.durationMs,
245
+ ...step2.selector !== void 0 ? { selector: step2.selector } : {},
246
+ ...step2.error ? { error: step2.error } : {},
247
+ ...screenshotDataUrl ? { screenshotDataUrl } : {}
248
+ };
249
+ });
250
+ const network = [];
251
+ if (input.liveNetwork && input.liveNetwork.length > 0) {
252
+ for (const ev of input.liveNetwork) {
253
+ network.push({
254
+ url: ev.url,
255
+ method: ev.method,
256
+ status: ev.status,
257
+ durationMs: ev.durationMs,
258
+ failed: ev.failed,
259
+ errorText: ev.errorText,
260
+ resourceType: ev.resourceType
261
+ });
262
+ }
263
+ } else if (input.har?.log?.entries?.length) {
264
+ for (const entry of input.har.log.entries) {
265
+ network.push({
266
+ url: entry.request.url,
267
+ method: entry.request.method,
268
+ status: entry.response.status,
269
+ durationMs: entry.time,
270
+ failed: entry.response.status === 0 || Boolean(entry._failureText),
271
+ errorText: entry._failureText,
272
+ resourceType: entry._resourceType
273
+ });
274
+ }
275
+ }
276
+ return {
277
+ schemaVersion: 1,
278
+ flowName: input.flowName,
279
+ platform: input.platform,
280
+ status: input.status,
281
+ startedAt: input.startedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
282
+ durationMs: input.durationMs,
283
+ ...input.viewport ? { viewport: input.viewport } : {},
284
+ steps,
285
+ consoleLogs: input.consoleLogs ?? [],
286
+ jsErrors: input.jsErrors ?? [],
287
+ network,
288
+ ...input.domSnapshot ? { domSnapshot: input.domSnapshot } : {},
289
+ ...input.ariaSnapshot ? { ariaSnapshot: input.ariaSnapshot } : {},
290
+ ...input.error ? { error: input.error } : {}
291
+ };
292
+ }
293
+ function escapeJsonForHtmlScript(value) {
294
+ return JSON.stringify(value).replaceAll("<", "\\u003c").replaceAll(">", "\\u003e").replaceAll("&", "\\u0026").replaceAll("\u2028", "\\u2028").replaceAll("\u2029", "\\u2029");
295
+ }
296
+ function escapeHtml(value) {
297
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
298
+ }
299
+ function renderTraceViewerHtml(trace) {
300
+ const payload = escapeJsonForHtmlScript(trace);
301
+ const title = escapeHtml(`${trace.flowName} (${trace.platform}) \u2014 Spana Trace Viewer`);
302
+ return `<!DOCTYPE html>
303
+ <html lang="en">
304
+ <head>
305
+ <meta charset="utf-8" />
306
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
307
+ <title>${title}</title>
308
+ <style>
309
+ :root { color-scheme: dark; --bg: #0d1117; --panel: #161b22; --border: #30363d; --fg: #e6edf3; --muted: #8b949e; --pass: #3fb950; --fail: #f85149; --accent: #58a6ff; }
310
+ * { box-sizing: border-box; }
311
+ body { margin: 0; font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; background: var(--bg); color: var(--fg); height: 100vh; display: flex; flex-direction: column; }
312
+ header { display: flex; align-items: center; gap: 12px; padding: 10px 16px; border-bottom: 1px solid var(--border); background: var(--panel); }
313
+ .badge { padding: 2px 8px; border-radius: 999px; font-size: 12px; font-weight: 600; text-transform: uppercase; }
314
+ .badge.passed { background: rgba(63,185,80,0.18); color: var(--pass); }
315
+ .badge.failed { background: rgba(248,81,73,0.18); color: var(--fail); }
316
+ .meta { color: var(--muted); font-size: 13px; margin-left: auto; }
317
+ main { flex: 1; display: grid; grid-template-columns: 320px 1fr 380px; min-height: 0; }
318
+ .col { border-right: 1px solid var(--border); display: flex; flex-direction: column; min-height: 0; }
319
+ .col:last-child { border-right: none; }
320
+ .col-title { padding: 8px 12px; font-size: 12px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.04em; color: var(--muted); border-bottom: 1px solid var(--border); background: var(--panel); }
321
+ .scroll { overflow: auto; flex: 1; }
322
+ .step { padding: 8px 12px; border-bottom: 1px solid var(--border); cursor: pointer; font-size: 13px; display: flex; align-items: baseline; gap: 8px; }
323
+ .step:hover { background: rgba(88,166,255,0.08); }
324
+ .step.active { background: rgba(88,166,255,0.18); border-left: 3px solid var(--accent); padding-left: 9px; }
325
+ .step-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }
326
+ .step-dot.passed { background: var(--pass); }
327
+ .step-dot.failed { background: var(--fail); }
328
+ .step-dur { margin-left: auto; color: var(--muted); font-size: 11px; font-family: ui-monospace, monospace; }
329
+ .stage { padding: 16px; display: flex; flex-direction: column; gap: 12px; align-items: center; justify-content: flex-start; }
330
+ .stage img { max-width: 100%; border: 1px solid var(--border); border-radius: 6px; background: #000; }
331
+ .empty { color: var(--muted); font-size: 13px; padding: 24px; text-align: center; }
332
+ .tabs { display: flex; border-bottom: 1px solid var(--border); background: var(--panel); }
333
+ .tab { padding: 8px 12px; font-size: 12px; border: none; background: transparent; color: var(--muted); cursor: pointer; border-bottom: 2px solid transparent; }
334
+ .tab.active { color: var(--fg); border-bottom-color: var(--accent); }
335
+ pre { margin: 0; padding: 12px; font-size: 12px; font-family: ui-monospace, monospace; white-space: pre-wrap; word-break: break-word; }
336
+ table { width: 100%; border-collapse: collapse; font-size: 12px; }
337
+ th, td { padding: 6px 8px; border-bottom: 1px solid var(--border); text-align: left; }
338
+ th { color: var(--muted); font-weight: 600; position: sticky; top: 0; background: var(--panel); }
339
+ .err-box { background: rgba(248,81,73,0.12); border: 1px solid var(--fail); color: #ffb4ae; padding: 10px 12px; border-radius: 6px; font-family: ui-monospace, monospace; font-size: 12px; width: 100%; }
340
+ </style>
341
+ </head>
342
+ <body>
343
+ <header>
344
+ <strong>Spana Trace Viewer</strong>
345
+ <span class="badge ${trace.status}">${trace.status}</span>
346
+ <span>${escapeHtml(trace.flowName)}</span>
347
+ <span class="meta">${escapeHtml(trace.platform)} \xB7 ${trace.durationMs}ms \xB7 ${trace.steps.length} steps</span>
348
+ </header>
349
+ <main>
350
+ <section class="col">
351
+ <div class="col-title">Actions (${trace.steps.length})</div>
352
+ <div id="steps" class="scroll"></div>
353
+ </section>
354
+ <section class="col">
355
+ <div class="col-title">Snapshot &amp; Details</div>
356
+ <div id="stage" class="scroll stage"></div>
357
+ </section>
358
+ <section class="col">
359
+ <div class="tabs">
360
+ <button class="tab active" data-tab="network">Network (${trace.network.length})</button>
361
+ <button class="tab" data-tab="console">Console (${trace.consoleLogs.length})</button>
362
+ <button class="tab" data-tab="errors">Errors (${trace.jsErrors.length})</button>
363
+ <button class="tab" data-tab="dom">DOM / ARIA</button>
364
+ </div>
365
+ <div id="inspector" class="scroll"></div>
366
+ </section>
367
+ </main>
368
+ <script>
369
+ const TRACE = ${payload};
370
+ let selectedIdx = TRACE.steps.findIndex((s) => s.status === "failed");
371
+ if (selectedIdx < 0) selectedIdx = Math.max(0, TRACE.steps.length - 1);
372
+ let activeTab = "network";
373
+
374
+ function renderSteps() {
375
+ const el = document.getElementById("steps");
376
+ el.innerHTML = "";
377
+ TRACE.steps.forEach((step, i) => {
378
+ const row = document.createElement("div");
379
+ row.className = "step" + (i === selectedIdx ? " active" : "");
380
+ row.innerHTML = '<span class="step-dot ' + step.status + '"></span><span>' + (i + 1) + '. ' + step.command + '</span><span class="step-dur">' + step.durationMs + 'ms</span>';
381
+ row.onclick = () => { selectedIdx = i; renderSteps(); renderStage(); };
382
+ el.appendChild(row);
383
+ });
384
+ }
385
+
386
+ function renderStage() {
387
+ const stage = document.getElementById("stage");
388
+ const step = TRACE.steps[selectedIdx];
389
+ stage.innerHTML = "";
390
+ if (TRACE.error) {
391
+ const err = document.createElement("div");
392
+ err.className = "err-box";
393
+ err.textContent = TRACE.error.message;
394
+ stage.appendChild(err);
395
+ }
396
+ if (!step) {
397
+ stage.innerHTML += '<div class="empty">No recorded steps.</div>';
398
+ return;
399
+ }
400
+ if (step.screenshotDataUrl) {
401
+ const img = document.createElement("img");
402
+ img.src = step.screenshotDataUrl;
403
+ img.alt = step.command;
404
+ stage.appendChild(img);
405
+ } else {
406
+ const note = document.createElement("div");
407
+ note.className = "empty";
408
+ note.textContent = "No screenshot captured for step: " + step.command;
409
+ stage.appendChild(note);
410
+ }
411
+ const meta = document.createElement("pre");
412
+ meta.style.width = "100%";
413
+ meta.textContent = JSON.stringify({ command: step.command, status: step.status, startedAtMs: step.startedAtMs, durationMs: step.durationMs, selector: step.selector, error: step.error }, null, 2);
414
+ stage.appendChild(meta);
415
+ }
416
+
417
+ function renderInspector() {
418
+ const box = document.getElementById("inspector");
419
+ if (activeTab === "network") {
420
+ if (!TRACE.network.length) { box.innerHTML = '<div class="empty">No network requests captured.</div>'; return; }
421
+ let html = '<table><thead><tr><th>Method</th><th>Status</th><th>Time</th><th>URL</th></tr></thead><tbody>';
422
+ for (const req of TRACE.network) {
423
+ html += '<tr><td>' + req.method + '</td><td>' + (req.failed ? 'ERR' : (req.status ?? '-')) + '</td><td>' + (req.durationMs ?? 0) + 'ms</td><td>' + req.url + '</td></tr>';
424
+ }
425
+ box.innerHTML = html + '</tbody></table>';
426
+ } else if (activeTab === "console") {
427
+ if (!TRACE.consoleLogs.length) { box.innerHTML = '<div class="empty">No console logs.</div>'; return; }
428
+ const pre = document.createElement("pre");
429
+ pre.textContent = TRACE.consoleLogs.map((l) => '[' + l.type + '] ' + l.text).join("\\n");
430
+ box.innerHTML = "";
431
+ box.appendChild(pre);
432
+ } else if (activeTab === "errors") {
433
+ if (!TRACE.jsErrors.length) { box.innerHTML = '<div class="empty">No JS errors.</div>'; return; }
434
+ const pre = document.createElement("pre");
435
+ pre.textContent = TRACE.jsErrors.map((e) => e.name + ': ' + e.message).join("\\n\\n");
436
+ box.innerHTML = "";
437
+ box.appendChild(pre);
438
+ } else {
439
+ const pre = document.createElement("pre");
440
+ pre.textContent = [TRACE.ariaSnapshot ? "=== ARIA SNAPSHOT ===\\n" + TRACE.ariaSnapshot : "", TRACE.domSnapshot ? "=== DOM SNAPSHOT ===\\n" + TRACE.domSnapshot.slice(0, 20000) : ""].filter(Boolean).join("\\n\\n") || "No DOM/ARIA snapshot captured.";
441
+ box.innerHTML = "";
442
+ box.appendChild(pre);
443
+ }
444
+ }
445
+
446
+ document.querySelectorAll(".tab").forEach((btn) => {
447
+ btn.onclick = () => {
448
+ document.querySelectorAll(".tab").forEach((b) => b.classList.remove("active"));
449
+ btn.classList.add("active");
450
+ activeTab = btn.dataset.tab;
451
+ renderInspector();
452
+ };
453
+ });
454
+
455
+ renderSteps();
456
+ renderStage();
457
+ renderInspector();
458
+ </script>
459
+ </body>
460
+ </html>`;
461
+ }
462
+ function writeRichTraceBundle(trace, outputDir) {
463
+ mkdirSync(outputDir, { recursive: true });
464
+ const traceJsonPath = join(outputDir, "trace.json");
465
+ const traceViewerHtmlPath = join(outputDir, "trace-viewer.html");
466
+ writeFileSync(traceJsonPath, JSON.stringify(trace, null, 2), "utf8");
467
+ writeFileSync(traceViewerHtmlPath, renderTraceViewerHtml(trace), "utf8");
468
+ return { traceJsonPath, traceViewerHtmlPath };
469
+ }
470
+
471
+ // src/diagnostics/native-logs.ts
472
+ import { execFile } from "child_process";
473
+ import { existsSync, readdirSync, readFileSync as readFileSync2, statSync } from "fs";
474
+ import { homedir } from "os";
475
+ import { join as join2 } from "path";
476
+ function defaultExecFile(cmd, args, opts) {
477
+ return new Promise((resolve, reject) => {
478
+ execFile(cmd, args, opts, (err, stdout, stderr) => {
479
+ if (err) {
480
+ reject(err);
481
+ return;
482
+ }
483
+ resolve({ stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
484
+ });
485
+ });
486
+ }
487
+ async function captureAndroidLogcat(deviceId, opts = {}) {
488
+ const maxLines = Math.max(10, opts.maxLines ?? 400);
489
+ const timeout = opts.timeoutMs ?? 5e3;
490
+ const run = opts.execFileFn ?? defaultExecFile;
491
+ const args = [
492
+ ...deviceId ? ["-s", deviceId] : [],
493
+ "logcat",
494
+ "-d",
495
+ "-t",
496
+ String(maxLines),
497
+ "-v",
498
+ "time"
499
+ ];
500
+ try {
501
+ const { stdout } = await run("adb", args, {
502
+ timeout,
503
+ maxBuffer: 4 * 1024 * 1024
504
+ });
505
+ const lines = stdout.split(/\r?\n/);
506
+ const filtered = opts.filter ? lines.filter((line) => line.toLowerCase().includes(opts.filter.toLowerCase())) : lines;
507
+ const joined = filtered.join("\n").trim();
508
+ return joined.length > 0 ? joined : null;
509
+ } catch {
510
+ return null;
511
+ }
512
+ }
513
+ function captureIosSimulatorCrashLogs(opts) {
514
+ const dir = opts?.reportsDir ?? join2(homedir(), "Library", "Logs", "DiagnosticReports");
515
+ if (!existsSync(dir)) return [];
516
+ const maxFiles = Math.max(1, opts?.maxFiles ?? 5);
517
+ const sinceMs = opts?.sinceMs ?? Date.now() - 10 * 60 * 1e3;
518
+ const needle = opts?.bundleOrAppName?.toLowerCase();
519
+ try {
520
+ const candidates = readdirSync(dir).filter((name) => name.endsWith(".ips") || name.endsWith(".crash")).filter((name) => !needle ? true : name.toLowerCase().includes(needle)).map((name) => {
521
+ const filePath = join2(dir, name);
522
+ const st = statSync(filePath);
523
+ return { name, filePath, mtimeMs: st.mtimeMs };
524
+ }).filter((item) => item.mtimeMs >= sinceMs).toSorted((a, b) => b.mtimeMs - a.mtimeMs).slice(0, maxFiles);
525
+ return candidates.map((item) => {
526
+ let preview = "";
527
+ try {
528
+ preview = readFileSync2(item.filePath, "utf8").slice(0, 4e3);
529
+ } catch {
530
+ preview = "(unreadable)";
531
+ }
532
+ return {
533
+ fileName: item.name,
534
+ filePath: item.filePath,
535
+ modifiedAt: new Date(item.mtimeMs).toISOString(),
536
+ preview
537
+ };
538
+ });
539
+ } catch {
540
+ return [];
541
+ }
542
+ }
543
+
544
+ // src/report/code-frame.ts
545
+ import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
546
+ import { fileURLToPath } from "url";
547
+ var INTERNAL_FRAME_PATTERNS = [
548
+ /node_modules\//,
549
+ /^node:/,
550
+ /^bun:/,
551
+ /^internal\//,
552
+ /\/packages\/spana\/(?:src|dist)\/(?!.*\.test\.[jt]sx?$)/,
553
+ /\/spana(?:-test)?\/dist\//
554
+ ];
555
+ function normalizeStackFile(raw) {
556
+ const trimmed = raw.trim();
557
+ if (trimmed.startsWith("file://")) {
558
+ try {
559
+ return fileURLToPath(trimmed);
560
+ } catch {
561
+ return trimmed.replace(/^file:\/\//, "");
562
+ }
563
+ }
564
+ return trimmed;
565
+ }
566
+ function parseStackFrames(stack) {
567
+ const frames = [];
568
+ for (const rawLine of stack.split("\n")) {
569
+ const line = rawLine.trim();
570
+ if (!line.startsWith("at ")) continue;
571
+ const match = line.match(/\((.+):(\d+):(\d+)\)$/) ?? line.match(/^at\s+(.+):(\d+):(\d+)$/);
572
+ if (!match) continue;
573
+ const file = normalizeStackFile(match[1]);
574
+ const lineNum = Number.parseInt(match[2], 10);
575
+ const colNum = Number.parseInt(match[3], 10);
576
+ if (!file || !Number.isFinite(lineNum) || lineNum < 1) continue;
577
+ frames.push({
578
+ file,
579
+ line: lineNum,
580
+ column: Number.isFinite(colNum) && colNum > 0 ? colNum : 1
581
+ });
582
+ }
583
+ return frames;
584
+ }
585
+ function isInternalFrame(file) {
586
+ const normalized = file.replaceAll("\\", "/");
587
+ return INTERNAL_FRAME_PATTERNS.some((re) => re.test(normalized));
588
+ }
589
+ function formatCodeFrame(source, line, column, contextLines = 3) {
590
+ const lines = source.split(/\r?\n/);
591
+ if (line < 1 || line > lines.length) return "";
592
+ const startLine = Math.max(1, line - contextLines);
593
+ const endLine = Math.min(lines.length, line + contextLines);
594
+ const gutterWidth = String(endLine).length;
595
+ const out = [];
596
+ for (let current = startLine; current <= endLine; current++) {
597
+ const marker = current === line ? ">" : " ";
598
+ const num = String(current).padStart(gutterWidth, " ");
599
+ const content = lines[current - 1] ?? "";
600
+ out.push(`${marker} ${num} | ${content}`);
601
+ if (current === line) {
602
+ const caretOffset = Math.max(0, Math.min(column - 1, content.length));
603
+ out.push(` ${" ".repeat(gutterWidth)} | ${" ".repeat(caretOffset)}^`);
604
+ }
605
+ }
606
+ return out.join("\n");
607
+ }
608
+ function extractCodeFrame(stack, preferredFile, contextLines = 3) {
609
+ if (!stack) return void 0;
610
+ const frames = parseStackFrames(stack);
611
+ if (frames.length === 0) return void 0;
612
+ const normalizedPreferred = preferredFile ? normalizeStackFile(preferredFile) : void 0;
613
+ let chosen = normalizedPreferred ? frames.find(
614
+ (f) => (f.file === normalizedPreferred || f.file.endsWith(normalizedPreferred)) && existsSync2(f.file)
615
+ ) : void 0;
616
+ if (!chosen) {
617
+ chosen = frames.find((f) => /\.flow\.[cm]?[jt]sx?$/.test(f.file) && existsSync2(f.file));
618
+ }
619
+ if (!chosen) {
620
+ chosen = frames.find((f) => !isInternalFrame(f.file) && existsSync2(f.file));
621
+ }
622
+ if (!chosen) return void 0;
623
+ try {
624
+ const source = readFileSync3(chosen.file, "utf8");
625
+ const frame = formatCodeFrame(source, chosen.line, chosen.column, contextLines);
626
+ if (!frame) return void 0;
627
+ return {
628
+ location: { file: chosen.file, line: chosen.line, column: chosen.column },
629
+ frame
630
+ };
631
+ } catch {
632
+ return void 0;
633
+ }
634
+ }
635
+
636
+ // src/core/video-recorder.ts
637
+ import { execFileSync, spawn } from "child_process";
638
+ import {
639
+ existsSync as existsSync3,
640
+ mkdirSync as mkdirSync2,
641
+ mkdtempSync,
642
+ readFileSync as readFileSync4,
643
+ rmSync,
644
+ unlinkSync,
645
+ writeFileSync as writeFileSync2
646
+ } from "fs";
647
+ import { tmpdir } from "os";
648
+ import { join as join3 } from "path";
649
+ function hasFfmpegOnPath() {
650
+ try {
651
+ execFileSync(process.platform === "win32" ? "where" : "which", ["ffmpeg"], {
652
+ stdio: "ignore"
653
+ });
654
+ return true;
655
+ } catch {
656
+ return false;
657
+ }
658
+ }
659
+ async function exportFramesToMp4(frames, outputPath, spawnFn = spawn) {
660
+ if (frames.length === 0 || !hasFfmpegOnPath()) return void 0;
661
+ const tempDir = mkdtempSync(join3(tmpdir(), "spana-vid-"));
662
+ try {
663
+ const ext = frames[0].mimeType === "image/png" ? "png" : "jpg";
664
+ const listLines = [];
665
+ for (let i = 0; i < frames.length; i++) {
666
+ const f = frames[i];
667
+ const framePath = join3(tempDir, `frame-${String(i).padStart(5, "0")}.${ext}`);
668
+ writeFileSync2(framePath, Buffer.from(f.dataBase64, "base64"));
669
+ const nextTs = frames[i + 1]?.timestampMs ?? f.timestampMs + 250;
670
+ const durSec = Math.max(0.05, Math.min(2, (nextTs - f.timestampMs) / 1e3));
671
+ listLines.push(`file '${framePath.replaceAll("'", "'\\''")}'`);
672
+ listLines.push(`duration ${durSec.toFixed(3)}`);
673
+ }
674
+ const lastPath = join3(tempDir, `frame-${String(frames.length - 1).padStart(5, "0")}.${ext}`);
675
+ listLines.push(`file '${lastPath.replaceAll("'", "'\\''")}'`);
676
+ const listFile = join3(tempDir, "frames.txt");
677
+ writeFileSync2(listFile, listLines.join("\n"), "utf8");
678
+ const ok = await new Promise((resolve) => {
679
+ const child = spawnFn(
680
+ "ffmpeg",
681
+ [
682
+ "-y",
683
+ "-f",
684
+ "concat",
685
+ "-safe",
686
+ "0",
687
+ "-i",
688
+ listFile,
689
+ "-vf",
690
+ "pad=ceil(iw/2)*2:ceil(ih/2)*2",
691
+ "-c:v",
692
+ "libx264",
693
+ "-pix_fmt",
694
+ "yuv420p",
695
+ "-movflags",
696
+ "+faststart",
697
+ outputPath
698
+ ],
699
+ { stdio: "ignore" }
700
+ );
701
+ child.on("error", () => resolve(false));
702
+ child.on("close", (code) => resolve(code === 0));
703
+ });
704
+ return ok && existsSync3(outputPath) ? outputPath : void 0;
705
+ } catch {
706
+ return void 0;
707
+ } finally {
708
+ try {
709
+ rmSync(tempDir, { recursive: true, force: true });
710
+ } catch {
711
+ }
712
+ }
713
+ }
714
+ async function startCdpScreencastRecorder(cdp, options) {
715
+ const startedAt = Date.now();
716
+ const startedAtIso = new Date(startedAt).toISOString();
717
+ const maxFrames = options.maxFrames ?? 180;
718
+ const frames = [];
719
+ let stopped = false;
720
+ const unsubscribe = cdp.onEvent("Page.screencastFrame", (params) => {
721
+ if (stopped) return;
722
+ const sessionId = params?.sessionId;
723
+ if (sessionId !== void 0) {
724
+ void cdp.sendCommand("Page.screencastFrameAck", { sessionId }).catch(() => {
725
+ });
726
+ }
727
+ if (typeof params?.data === "string" && params.data.length > 0) {
728
+ if (frames.length >= maxFrames) {
729
+ frames.splice(1, 1);
730
+ }
731
+ frames.push({
732
+ timestampMs: Math.max(0, Date.now() - startedAt),
733
+ dataBase64: params.data,
734
+ mimeType: "image/jpeg"
735
+ });
736
+ }
737
+ });
738
+ await cdp.sendCommand("Page.startScreencast", {
739
+ format: "jpeg",
740
+ quality: options.quality ?? 65,
741
+ maxWidth: options.maxWidth ?? 1280,
742
+ maxHeight: options.maxHeight ?? 720,
743
+ everyNthFrame: options.everyNthFrame ?? 2
744
+ }).catch(() => {
745
+ });
746
+ return {
747
+ stop: async (stopOpts) => {
748
+ if (stopped) return { frameCount: frames.length };
749
+ stopped = true;
750
+ unsubscribe();
751
+ await cdp.sendCommand("Page.stopScreencast").catch(() => {
752
+ });
753
+ if (!stopOpts.keep) {
754
+ return { frameCount: 0 };
755
+ }
756
+ if (frames.length === 0) {
757
+ try {
758
+ const snap = await cdp.sendCommand("Page.captureScreenshot", {
759
+ format: "jpeg",
760
+ quality: options.quality ?? 65
761
+ });
762
+ if (typeof snap?.data === "string" && snap.data.length > 0) {
763
+ frames.push({
764
+ timestampMs: Math.max(0, Date.now() - startedAt),
765
+ dataBase64: snap.data,
766
+ mimeType: "image/jpeg"
767
+ });
768
+ }
769
+ } catch {
770
+ }
771
+ }
772
+ if (frames.length === 0) {
773
+ return { frameCount: 0 };
774
+ }
775
+ mkdirSync2(stopOpts.outputDir, { recursive: true });
776
+ let videoPath;
777
+ if (options.exportMp4 !== false) {
778
+ const mp4Target = join3(stopOpts.outputDir, `${stopOpts.fileStem}.mp4`);
779
+ videoPath = await exportFramesToMp4(frames, mp4Target, options.spawnFn);
780
+ }
781
+ const trace = {
782
+ version: 1,
783
+ flowName: options.flowName,
784
+ platform: options.platform,
785
+ startedAtIso,
786
+ durationMs: Math.max(1, Date.now() - startedAt),
787
+ viewport: stopOpts.viewport,
788
+ frames,
789
+ steps: stopOpts.steps ?? [],
790
+ ...videoPath ? { videoPath } : {}
791
+ };
792
+ const playbackJsonPath = join3(stopOpts.outputDir, `${stopOpts.fileStem}-playback.json`);
793
+ writeFileSync2(playbackJsonPath, JSON.stringify(trace), "utf8");
794
+ return { playbackJsonPath, videoPath, frameCount: frames.length };
795
+ }
796
+ };
797
+ }
798
+ function startAndroidVideoRecorder(serial, options) {
799
+ const spawnFn = options.spawnFn ?? spawn;
800
+ const execSyncFn = options.execFileSyncFn ?? execFileSync;
801
+ const remotePath = `/sdcard/spana-rec-${Date.now()}-${Math.floor(Math.random() * 1e4)}.mp4`;
802
+ const child = spawnFn(
803
+ "adb",
804
+ ["-s", serial, "shell", "screenrecord", "--time-limit", "180", remotePath],
805
+ { stdio: "ignore" }
806
+ );
807
+ let stopped = false;
808
+ return {
809
+ stop: async ({ keep }) => {
810
+ if (stopped) return { frameCount: 0 };
811
+ stopped = true;
812
+ try {
813
+ child.kill("SIGINT");
814
+ } catch {
815
+ }
816
+ await new Promise((resolve) => {
817
+ const timer = setTimeout(resolve, 1200);
818
+ child.once("close", () => {
819
+ clearTimeout(timer);
820
+ resolve();
821
+ });
822
+ });
823
+ let savedPath;
824
+ if (keep) {
825
+ try {
826
+ execSyncFn("adb", ["-s", serial, "pull", remotePath, options.outputPath], {
827
+ stdio: "ignore"
828
+ });
829
+ if (existsSync3(options.outputPath)) savedPath = options.outputPath;
830
+ } catch {
831
+ }
832
+ }
833
+ try {
834
+ execSyncFn("adb", ["-s", serial, "shell", "rm", "-f", remotePath], { stdio: "ignore" });
835
+ } catch {
836
+ }
837
+ return { videoPath: savedPath, frameCount: savedPath ? 1 : 0 };
838
+ }
839
+ };
840
+ }
841
+ function startIosSimulatorVideoRecorder(udid, options) {
842
+ const spawnFn = options.spawnFn ?? spawn;
843
+ const child = spawnFn(
844
+ "xcrun",
845
+ ["simctl", "io", udid, "recordVideo", "--codec=h264", "--force", options.outputPath],
846
+ { stdio: "ignore" }
847
+ );
848
+ let stopped = false;
849
+ return {
850
+ stop: async ({ keep }) => {
851
+ if (stopped) return { frameCount: 0 };
852
+ stopped = true;
853
+ try {
854
+ child.kill("SIGINT");
855
+ } catch {
856
+ }
857
+ await new Promise((resolve) => {
858
+ const timer = setTimeout(resolve, 1500);
859
+ child.once("close", () => {
860
+ clearTimeout(timer);
861
+ resolve();
862
+ });
863
+ });
864
+ if (!keep) {
865
+ try {
866
+ if (existsSync3(options.outputPath)) unlinkSync(options.outputPath);
867
+ } catch {
868
+ }
869
+ return { frameCount: 0 };
870
+ }
871
+ return {
872
+ videoPath: existsSync3(options.outputPath) ? options.outputPath : void 0,
873
+ frameCount: existsSync3(options.outputPath) ? 1 : 0
874
+ };
875
+ }
876
+ };
877
+ }
878
+ function buildPlaybackTraceFromSteps(input) {
879
+ const frames = [];
880
+ const markers = [];
881
+ let cursorMs = 0;
882
+ for (let i = 0; i < input.steps.length; i++) {
883
+ const step2 = input.steps[i];
884
+ const tapPoint = extractTapPointFromStep(step2);
885
+ markers.push({
886
+ index: i,
887
+ command: step2.command,
888
+ selector: step2.selector,
889
+ startedAtMs: cursorMs,
890
+ durationMs: step2.durationMs,
891
+ status: step2.status,
892
+ error: step2.error,
893
+ ...tapPoint ? { tapPoint } : {}
894
+ });
895
+ const img = step2.attachments?.find(
896
+ (a) => a.contentType === "image/png" || a.contentType === "image/jpeg"
897
+ );
898
+ if (img && existsSync3(img.path)) {
899
+ try {
900
+ const dataBase64 = readFileSync4(img.path).toString("base64");
901
+ frames.push({
902
+ timestampMs: cursorMs + step2.durationMs,
903
+ dataBase64,
904
+ mimeType: img.contentType === "image/jpeg" ? "image/jpeg" : "image/png"
905
+ });
906
+ } catch {
907
+ }
908
+ }
909
+ cursorMs += Math.max(1, step2.durationMs);
910
+ }
911
+ if (frames.length === 0 && !input.videoPath) return null;
912
+ return {
913
+ version: 1,
914
+ flowName: input.flowName,
915
+ platform: input.platform,
916
+ startedAtIso: (/* @__PURE__ */ new Date()).toISOString(),
917
+ durationMs: Math.max(1, input.durationMs),
918
+ viewport: input.viewport,
919
+ frames,
920
+ steps: markers,
921
+ ...input.videoPath ? { videoPath: input.videoPath } : {}
922
+ };
923
+ }
924
+ function extractTapPointFromStep(step2) {
925
+ const sel = step2.selector;
926
+ if (!sel || typeof sel !== "object") return void 0;
927
+ const pt = sel["point"];
928
+ if (pt && typeof pt["x"] === "number" && typeof pt["y"] === "number") {
929
+ return { x: pt["x"], y: pt["y"] };
930
+ }
931
+ return void 0;
932
+ }
933
+
934
+ // src/core/engine.ts
935
+ import { Effect as Effect4 } from "effect";
936
+
937
+ // src/core/artifacts.ts
938
+ import { writeFileSync as writeFileSync3, mkdirSync as mkdirSync3 } from "fs";
939
+ import { join as join4 } from "path";
940
+ import { Effect as Effect2 } from "effect";
941
+ var DEFAULT_ARTIFACT_CONFIG = {
942
+ outputDir: "./spana-output",
943
+ captureOnFailure: true,
944
+ captureOnSuccess: false,
945
+ captureSteps: false,
946
+ screenshot: true,
947
+ uiHierarchy: true,
948
+ consoleLogs: true,
949
+ jsErrors: true,
950
+ har: true,
951
+ jsCoverage: false,
952
+ video: "off",
953
+ playback: false,
954
+ trace: false,
955
+ nativeLogs: false
956
+ };
957
+ function safeArtifactName(value) {
958
+ return value.replaceAll(/[^a-zA-Z0-9-_]/g, "_").replaceAll(/_+/g, "_").replaceAll(/^_+|_+$/g, "").slice(0, 80) || "artifact";
959
+ }
960
+ var safeName = safeArtifactName;
961
+ function flowArtifactDir(config, flowName, platform) {
962
+ const dir = join4(config.outputDir, `${safeName(flowName)}-${platform}`);
963
+ mkdirSync3(dir, { recursive: true });
964
+ return dir;
965
+ }
966
+ function createAttachment(name, contentType, path) {
967
+ return { name, contentType, path };
968
+ }
969
+ function writeJsonAttachment(dir, fileName, attachmentName, value) {
970
+ const path = join4(dir, fileName);
971
+ writeFileSync3(path, JSON.stringify(value, null, 2), "utf-8");
972
+ return createAttachment(attachmentName, "application/json", path);
973
+ }
974
+ function writeTextAttachment(dir, fileName, attachmentName, value) {
975
+ const path = join4(dir, fileName);
976
+ writeFileSync3(path, value, "utf-8");
977
+ return createAttachment(attachmentName, "text/plain", path);
978
+ }
979
+ function resolveArtifactConfig(...configs) {
980
+ return configs.reduce(
981
+ (resolved, config) => ({
982
+ ...resolved,
983
+ ...config
984
+ }),
985
+ { ...DEFAULT_ARTIFACT_CONFIG }
986
+ );
987
+ }
988
+ async function captureArtifacts(driver, config, flowName, platform, status) {
989
+ const shouldCapture = status === "failed" && config.captureOnFailure || status === "passed" && config.captureOnSuccess;
990
+ if (!shouldCapture) return [];
991
+ const attachments = [];
992
+ const dir = flowArtifactDir(config, flowName, platform);
993
+ if (config.screenshot) {
994
+ try {
995
+ const screenshot = await Effect2.runPromise(Effect2.orDie(driver.takeScreenshot()));
996
+ const path = join4(dir, "screenshot.png");
997
+ writeFileSync3(path, screenshot);
998
+ attachments.push(createAttachment(`${status}-screenshot`, "image/png", path));
999
+ } catch {
1000
+ }
1001
+ }
1002
+ if (config.uiHierarchy) {
1003
+ try {
1004
+ const hierarchy = await Effect2.runPromise(Effect2.orDie(driver.dumpHierarchy()));
1005
+ const path = join4(dir, "hierarchy.json");
1006
+ writeFileSync3(path, hierarchy, "utf-8");
1007
+ attachments.push(createAttachment(`${status}-hierarchy`, "application/json", path));
1008
+ } catch {
1009
+ }
1010
+ }
1011
+ if (config.consoleLogs && driver.getConsoleLogs) {
1012
+ try {
1013
+ const consoleLogs = await Effect2.runPromise(Effect2.orDie(driver.getConsoleLogs()));
1014
+ if (consoleLogs.length > 0) {
1015
+ attachments.push(
1016
+ writeJsonAttachment(dir, "console-logs.json", `${status}-console-logs`, consoleLogs)
1017
+ );
1018
+ }
1019
+ } catch {
1020
+ }
1021
+ }
1022
+ if (config.jsErrors && driver.getJSErrors) {
1023
+ try {
1024
+ const jsErrors = await Effect2.runPromise(Effect2.orDie(driver.getJSErrors()));
1025
+ if (jsErrors.length > 0) {
1026
+ attachments.push(
1027
+ writeJsonAttachment(dir, "js-errors.json", `${status}-js-errors`, jsErrors)
1028
+ );
1029
+ }
1030
+ } catch {
1031
+ }
1032
+ }
1033
+ if (config.har && driver.getHAR) {
1034
+ try {
1035
+ const har = await Effect2.runPromise(Effect2.orDie(driver.getHAR()));
1036
+ if (har.log.entries.length > 0) {
1037
+ attachments.push(writeJsonAttachment(dir, "network.har", `${status}-network-har`, har));
1038
+ }
1039
+ } catch {
1040
+ }
1041
+ }
1042
+ if (status === "failed" && driver.getDriverLogs) {
1043
+ try {
1044
+ const driverLogs = await Effect2.runPromise(Effect2.orDie(driver.getDriverLogs()));
1045
+ if (driverLogs.length > 0) {
1046
+ attachments.push(
1047
+ writeTextAttachment(
1048
+ dir,
1049
+ "driver-logs.txt",
1050
+ `${status}-driver-logs`,
1051
+ driverLogs.join("\n")
1052
+ )
1053
+ );
1054
+ }
1055
+ } catch {
1056
+ }
1057
+ }
1058
+ if (status === "failed" && config.nativeLogs) {
1059
+ if (platform === "android") {
1060
+ try {
1061
+ const info = await Effect2.runPromise(Effect2.orDie(driver.getDeviceInfo())).catch(
1062
+ () => null
1063
+ );
1064
+ const logcat = await captureAndroidLogcat(info?.deviceId);
1065
+ if (logcat) {
1066
+ attachments.push(
1067
+ writeTextAttachment(dir, "android-logcat.txt", "android-logcat", logcat)
1068
+ );
1069
+ }
1070
+ } catch {
1071
+ }
1072
+ } else if (platform === "ios") {
1073
+ try {
1074
+ const crashes = captureIosSimulatorCrashLogs({ maxFiles: 3 });
1075
+ if (crashes.length > 0) {
1076
+ attachments.push(
1077
+ writeJsonAttachment(dir, "ios-crash-logs.json", "ios-crash-logs", crashes)
1078
+ );
1079
+ }
1080
+ } catch {
1081
+ }
1082
+ }
1083
+ }
1084
+ return attachments;
1085
+ }
1086
+ async function captureStepScreenshot(driver, config, flowName, platform, stepIndex, stepName, screenshot) {
1087
+ if (!config.screenshot) return void 0;
1088
+ try {
1089
+ const dir = join4(flowArtifactDir(config, flowName, platform), "steps");
1090
+ mkdirSync3(dir, { recursive: true });
1091
+ const fileName = `${String(stepIndex).padStart(3, "0")}-${safeName(stepName)}.png`;
1092
+ const path = join4(dir, fileName);
1093
+ const bytes = screenshot ?? await Effect2.runPromise(Effect2.orDie(driver.takeScreenshot()));
1094
+ writeFileSync3(path, bytes);
1095
+ return createAttachment(stepName, "image/png", path);
1096
+ } catch {
1097
+ return void 0;
1098
+ }
1099
+ }
1100
+
1101
+ // src/core/debug-repl.ts
1102
+ import * as repl from "repl";
1103
+ import { Effect as Effect3 } from "effect";
1104
+ var didStartDebugRepl = false;
1105
+ function toSuggestedSelectors(root) {
1106
+ return flattenElements(root).filter((el) => el.visible !== false && (el.id || el.text || el.accessibilityLabel)).map((el) => ({
1107
+ suggestedSelector: el.id ? { testID: el.id } : el.accessibilityLabel ? { accessibilityLabel: el.accessibilityLabel } : el.text ? { text: el.text } : "",
1108
+ elementType: el.elementType,
1109
+ text: el.text,
1110
+ accessibilityLabel: el.accessibilityLabel,
1111
+ bounds: el.bounds,
1112
+ id: el.id
1113
+ }));
1114
+ }
1115
+ async function runDebugReplOnce(context) {
1116
+ if (didStartDebugRepl) {
1117
+ return false;
1118
+ }
1119
+ didStartDebugRepl = true;
1120
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
1121
+ console.log("Skipping debug REPL because stdin/stdout is not interactive.");
1122
+ return false;
1123
+ }
1124
+ const hierarchy = async () => context.parseHierarchy(await Effect3.runPromise(context.driver.dumpHierarchy()));
1125
+ const selectors = async () => toSuggestedSelectors(await hierarchy());
1126
+ console.log("");
1127
+ console.log(`Entering debug REPL for failed flow "${context.flowName}" on ${context.platform}.`);
1128
+ console.log(
1129
+ "Available bindings: app, expect, driver, platform, flowName, error, hierarchy(), selectors(), help()"
1130
+ );
1131
+ console.log('Use top-level await for async calls, for example: await app.tap({ text: "Login" })');
1132
+ const replServer = repl.start({
1133
+ prompt: `spana:${context.platform}> `,
1134
+ ignoreUndefined: true,
1135
+ useGlobal: false
1136
+ });
1137
+ replServer.context.app = context.app;
1138
+ replServer.context.expect = context.expect;
1139
+ replServer.context.driver = context.driver;
1140
+ replServer.context.platform = context.platform;
1141
+ replServer.context.flowName = context.flowName;
1142
+ replServer.context.error = context.error;
1143
+ replServer.context.hierarchy = hierarchy;
1144
+ replServer.context.selectors = selectors;
1145
+ replServer.context.help = () => {
1146
+ console.log("app Promise-based app API with auto-waiting");
1147
+ console.log("expect Assertion helper, e.g. await expect({ text: 'Done' }).toBeVisible()");
1148
+ console.log("driver Raw driver service");
1149
+ console.log("hierarchy Async helper returning the parsed UI tree");
1150
+ console.log("selectors Async helper returning suggested selectors");
1151
+ console.log(".exit Leave the REPL");
1152
+ };
1153
+ await new Promise((resolve) => replServer.on("exit", resolve));
1154
+ console.log("");
1155
+ return true;
1156
+ }
1157
+
1158
+ // src/core/step-recorder.ts
1159
+ function errorMessage(error) {
1160
+ return error instanceof Error ? error.message : String(error);
1161
+ }
1162
+ function createStepResult(command, durationMs, status, selector, error, attachments) {
1163
+ return {
1164
+ command,
1165
+ selector,
1166
+ status,
1167
+ durationMs,
1168
+ error,
1169
+ attachments: attachments && attachments.length > 0 ? attachments : void 0
1170
+ };
1171
+ }
1172
+ function createStepRecorder(driver, artifactConfig, flowName, platform) {
1173
+ const steps = [];
1174
+ let lastFailureStack;
1175
+ return {
1176
+ async runStep(command, action, opts) {
1177
+ const startedAt = Date.now();
1178
+ const callSiteStack = new Error().stack;
1179
+ try {
1180
+ const result = await action();
1181
+ const attachments = [];
1182
+ if (opts?.captureScreenshot && artifactConfig.captureSteps) {
1183
+ const attachment = await captureStepScreenshot(
1184
+ driver,
1185
+ artifactConfig,
1186
+ flowName,
1187
+ platform,
1188
+ steps.length + 1,
1189
+ command
1190
+ );
1191
+ if (attachment) attachments.push(attachment);
1192
+ }
1193
+ steps.push(
1194
+ createStepResult(
1195
+ command,
1196
+ Date.now() - startedAt,
1197
+ "passed",
1198
+ opts?.selector,
1199
+ void 0,
1200
+ attachments
1201
+ )
1202
+ );
1203
+ return result;
1204
+ } catch (error) {
1205
+ lastFailureStack = callSiteStack;
1206
+ steps.push(
1207
+ createStepResult(
1208
+ command,
1209
+ Date.now() - startedAt,
1210
+ "failed",
1211
+ opts?.selector,
1212
+ errorMessage(error)
1213
+ )
1214
+ );
1215
+ throw error;
1216
+ }
1217
+ },
1218
+ async runScreenshotStep(command, action, opts) {
1219
+ const startedAt = Date.now();
1220
+ const callSiteStack = new Error().stack;
1221
+ try {
1222
+ const screenshot = await action();
1223
+ const attachment = await captureStepScreenshot(
1224
+ driver,
1225
+ artifactConfig,
1226
+ flowName,
1227
+ platform,
1228
+ steps.length + 1,
1229
+ opts?.name ?? command,
1230
+ screenshot
1231
+ );
1232
+ steps.push(
1233
+ createStepResult(
1234
+ command,
1235
+ Date.now() - startedAt,
1236
+ "passed",
1237
+ opts?.selector,
1238
+ void 0,
1239
+ attachment ? [attachment] : void 0
1240
+ )
1241
+ );
1242
+ return screenshot;
1243
+ } catch (error) {
1244
+ lastFailureStack = callSiteStack;
1245
+ steps.push(
1246
+ createStepResult(
1247
+ command,
1248
+ Date.now() - startedAt,
1249
+ "failed",
1250
+ opts?.selector,
1251
+ errorMessage(error)
1252
+ )
1253
+ );
1254
+ throw error;
1255
+ }
1256
+ },
1257
+ getSteps() {
1258
+ return steps;
1259
+ },
1260
+ getLastFailureStack() {
1261
+ return lastFailureStack;
1262
+ }
1263
+ };
1264
+ }
1265
+
1266
+ // src/report/classify-error.ts
1267
+ var TAG_KEY = "_tag";
1268
+ var FIBER_FAILURE_CAUSE_SYMBOL = /* @__PURE__ */ Symbol.for("effect/Runtime/FiberFailure/Cause");
1269
+ function unwrapTaggedError(error) {
1270
+ if (!error || typeof error !== "object") return {};
1271
+ const obj = error;
1272
+ if (typeof obj[TAG_KEY] === "string") {
1273
+ return obj;
1274
+ }
1275
+ const cause = obj[FIBER_FAILURE_CAUSE_SYMBOL];
1276
+ if (cause && typeof cause === "object") {
1277
+ const inner = cause["error"] ?? cause["defect"];
1278
+ if (inner && typeof inner === "object" && typeof inner[TAG_KEY] === "string") {
1279
+ return inner;
1280
+ }
1281
+ }
1282
+ return obj;
1283
+ }
1284
+ function selectorHint(selector) {
1285
+ if (selector && typeof selector === "object") {
1286
+ const s = selector;
1287
+ if (s.testID) return `testID="${s.testID}"`;
1288
+ if (s.text) return `text="${s.text}"`;
1289
+ if (s.accessibilityLabel) return `accessibilityLabel="${s.accessibilityLabel}"`;
1290
+ }
1291
+ return JSON.stringify(selector);
1292
+ }
1293
+ function categorizeElementFailure(message) {
1294
+ const lower = message.toLowerCase();
1295
+ if (lower.includes("not visible") || lower.includes("visible=false")) {
1296
+ return "element-not-visible";
1297
+ }
1298
+ if (lower.includes("off-screen") || lower.includes("zero size")) {
1299
+ return "element-off-screen";
1300
+ }
1301
+ if (lower.includes("disabled") || lower.includes("not interactive")) {
1302
+ return "element-not-interactive";
1303
+ }
1304
+ return "element-not-found";
1305
+ }
1306
+ function elementSuggestion(category, selector, timeoutMs) {
1307
+ switch (category) {
1308
+ case "element-not-visible":
1309
+ return [
1310
+ `Selector ${selector} matched an element, but it is currently hidden.`,
1311
+ "Check whether an animation, modal, or loading state is covering it before retrying.",
1312
+ "Consider increasing waitTimeout if the element becomes visible after a delay."
1313
+ ].join("\n");
1314
+ case "element-off-screen":
1315
+ return [
1316
+ `Selector ${selector} matched an element that is off-screen.`,
1317
+ "Use scrollUntilVisible() or scroll to the element before interacting with it.",
1318
+ "If the target is above the current viewport, reverse the search direction."
1319
+ ].join("\n");
1320
+ case "element-not-interactive":
1321
+ return [
1322
+ `Selector ${selector} matched an element that is disabled or not interactive.`,
1323
+ "Wait for the app to enable it, or verify the prerequisite app state first.",
1324
+ "Consider increasing waitTimeout if the control becomes enabled after async work completes."
1325
+ ].join("\n");
1326
+ default:
1327
+ return [
1328
+ `Selector ${selector} was not found within ${timeoutMs ?? "?"}ms.`,
1329
+ "Run `spana selectors` to inspect the current screen and confirm the best selector.",
1330
+ "Consider increasing waitTimeout if the element appears after a delay."
1331
+ ].join("\n");
1332
+ }
1333
+ }
1334
+ function categorizeDynamic(error, tag, msg) {
1335
+ if (tag === "ElementNotFoundError" || tag === "WaitTimeoutError") {
1336
+ const sel = selectorHint(error.selector);
1337
+ if (msg.includes("scroll(s) toward")) {
1338
+ return {
1339
+ category: "element-not-found",
1340
+ suggestion: [
1341
+ `Selector ${sel} stayed off-screen while scrolling.`,
1342
+ "Try increasing `maxScrolls` or `timeout`, or reverse the search direction",
1343
+ 'if the target is actually above the current viewport (for example `{ direction: "up" }`).'
1344
+ ].join("\n")
1345
+ };
1346
+ }
1347
+ if (msg.includes("back action(s)")) {
1348
+ return {
1349
+ category: "element-not-found",
1350
+ suggestion: [
1351
+ `Selector ${sel} was not reached while navigating back.`,
1352
+ "Try increasing `maxBacks` or `timeout`, or prefer an explicit in-app",
1353
+ "back / close control on iOS-style screens instead of relying on system back."
1354
+ ].join("\n")
1355
+ };
1356
+ }
1357
+ const category = categorizeElementFailure(msg);
1358
+ return {
1359
+ category,
1360
+ suggestion: elementSuggestion(category, sel, error.timeoutMs)
1361
+ };
1362
+ }
1363
+ if (tag === "TextMismatchError") {
1364
+ const e = error;
1365
+ return {
1366
+ category: "text-mismatch",
1367
+ suggestion: [
1368
+ `Expected text "${e.expected}" but found "${e.actual ?? "(empty)"}".`,
1369
+ "The element exists but its content differs. Check for whitespace, truncation,",
1370
+ "or platform-specific text rendering differences."
1371
+ ].join("\n")
1372
+ };
1373
+ }
1374
+ if (tag === "DeviceDisconnectedError") {
1375
+ const id = error.deviceId ? ` (${error.deviceId})` : "";
1376
+ return {
1377
+ category: "device-disconnected",
1378
+ suggestion: [
1379
+ `The device${id} disconnected during the test.`,
1380
+ "Check the physical connection or emulator/simulator stability.",
1381
+ "Run `spana devices` to verify available devices."
1382
+ ].join("\n")
1383
+ };
1384
+ }
1385
+ if (tag === "AppCrashedError") {
1386
+ const app = error.appId ? ` (${error.appId})` : "";
1387
+ return {
1388
+ category: "app-crashed",
1389
+ suggestion: [
1390
+ `The app${app} crashed during the test.`,
1391
+ "Check the device logs for a crash stack trace:",
1392
+ " Android: `adb logcat -d | grep FATAL`",
1393
+ " iOS: Check Console.app or `log show --predicate 'process == \"your-app\"'`"
1394
+ ].join("\n")
1395
+ };
1396
+ }
1397
+ if (tag === "AppNotInstalledError") {
1398
+ return {
1399
+ category: "app-not-installed",
1400
+ suggestion: [
1401
+ `App "${error.appId}" is not installed on the device.`,
1402
+ "Install it before running tests, or configure `apps.android.appPath`",
1403
+ "/ `apps.ios.appPath` in spana.config.ts for auto-install."
1404
+ ].join("\n")
1405
+ };
1406
+ }
1407
+ if (tag === "DriverError") {
1408
+ return categorizeDynamicDriver(error, msg);
1409
+ }
1410
+ return void 0;
1411
+ }
1412
+ function categorizeDynamicDriver(error, msg) {
1413
+ for (const rule of driverRules) {
1414
+ if (rule.pattern && matchesPattern(msg, rule.pattern)) {
1415
+ return {
1416
+ category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
1417
+ suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
1418
+ };
1419
+ }
1420
+ }
1421
+ return {
1422
+ category: "driver-error",
1423
+ 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."
1424
+ };
1425
+ }
1426
+ var driverRules = [
1427
+ {
1428
+ pattern: "dismissKeyboard()",
1429
+ category: "driver-error",
1430
+ suggestion: [
1431
+ "Keyboard dismissal failed.",
1432
+ 'On Android, try `app.dismissKeyboard({ strategy: "back" })`.',
1433
+ "On iOS, prefer tapping a visible Done / Close control or a non-input element."
1434
+ ].join("\n")
1435
+ },
1436
+ {
1437
+ pattern: "backUntilVisible()",
1438
+ category: "driver-error",
1439
+ suggestion: [
1440
+ "System back navigation failed before the target screen became visible.",
1441
+ "If this route uses app-level navigation, tap the visible back / close control instead.",
1442
+ "This is especially common on iOS where a system back button may not exist."
1443
+ ].join("\n")
1444
+ },
1445
+ {
1446
+ pattern: "Input text failed",
1447
+ category: "driver-error",
1448
+ suggestion: [
1449
+ "Text input failed at the driver layer.",
1450
+ "Make sure the field is focused first, and retry with shorter input chunks if needed.",
1451
+ "If the keyboard is in the way, dismiss it before continuing the flow."
1452
+ ].join("\n")
1453
+ }
1454
+ ];
1455
+ var tagOnlyRules = [
1456
+ {
1457
+ tag: "TimeoutError",
1458
+ category: "timeout",
1459
+ suggestion: [
1460
+ "The operation took longer than the allowed timeout.",
1461
+ "Try increasing `defaults.waitTimeout` in spana.config.ts,",
1462
+ "or set a per-flow timeout: `flow('name', { timeout: 30000 }, ...)`."
1463
+ ].join("\n")
1464
+ },
1465
+ {
1466
+ tag: ["ConfigError", "FlowSyntaxError"],
1467
+ category: "config-error",
1468
+ suggestion: "Run `spana validate-config` to check your configuration."
1469
+ }
1470
+ ];
1471
+ var heuristicRules = [
1472
+ {
1473
+ pattern: /[Tt]imed out/,
1474
+ category: "timeout",
1475
+ suggestion: "The operation timed out. Try increasing `defaults.waitTimeout` in spana.config.ts."
1476
+ },
1477
+ {
1478
+ pattern: /not found|not visible|not fillable|covered by/,
1479
+ category: (msg) => categorizeElementFailure(msg),
1480
+ suggestion: (_error, msg) => {
1481
+ if (msg.includes("scroll(s) toward")) {
1482
+ return "The target stayed off-screen while scrolling. Increase `maxScrolls` / `timeout`, or reverse the scroll search direction.";
1483
+ }
1484
+ const category = categorizeElementFailure(msg);
1485
+ return elementSuggestion(category, "the target selector", void 0);
1486
+ }
1487
+ },
1488
+ {
1489
+ pattern: "dismissKeyboard()",
1490
+ category: "driver-error",
1491
+ suggestion: 'Keyboard dismissal failed. On Android try `app.dismissKeyboard({ strategy: "back" })`; on iOS prefer an explicit Done / Close control.'
1492
+ },
1493
+ {
1494
+ pattern: /ECONNREFUSED|ECONNRESET|disconnected/,
1495
+ category: "device-disconnected",
1496
+ suggestion: "The connection was lost. Check the device or emulator/simulator is still running."
1497
+ }
1498
+ ];
1499
+ function matchesPattern(msg, pattern) {
1500
+ return typeof pattern === "string" ? msg.includes(pattern) : pattern.test(msg);
1501
+ }
1502
+ function matchesTag(tag, rule) {
1503
+ if (!rule.tag) return true;
1504
+ if (Array.isArray(rule.tag)) return tag != null && rule.tag.includes(tag);
1505
+ return tag === rule.tag;
1506
+ }
1507
+ function categorize(error) {
1508
+ const tag = error[TAG_KEY];
1509
+ const msg = error.message ?? "";
1510
+ const dynamic = categorizeDynamic(error, tag, msg);
1511
+ if (dynamic) return dynamic;
1512
+ for (const rule of tagOnlyRules) {
1513
+ if (matchesTag(tag, rule)) {
1514
+ return {
1515
+ category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
1516
+ suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
1517
+ };
1518
+ }
1519
+ }
1520
+ for (const rule of heuristicRules) {
1521
+ if (rule.pattern && matchesPattern(msg, rule.pattern)) {
1522
+ return {
1523
+ category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
1524
+ suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
1525
+ };
1526
+ }
1527
+ }
1528
+ return { category: "unknown" };
1529
+ }
1530
+ function classifyError(error, opts) {
1531
+ const tagged = unwrapTaggedError(error);
1532
+ const { category, suggestion } = categorize(tagged);
1533
+ const extracted = extractCodeFrame(error.stack, opts?.flowFilePath) ?? extractCodeFrame(opts?.fallbackStack, opts?.flowFilePath);
1534
+ return {
1535
+ message: tagged.message ?? error.message,
1536
+ stack: error.stack,
1537
+ category,
1538
+ suggestion,
1539
+ ...extracted ? { location: extracted.location, codeFrame: extracted.frame } : {}
1540
+ };
1541
+ }
1542
+
1543
+ // src/core/engine.ts
1544
+ import { writeFileSync as writeFileSync5 } from "fs";
1545
+ import { join as join6 } from "path";
1546
+
1547
+ // src/report/failure-bundle.ts
1548
+ import { writeFileSync as writeFileSync4, readFileSync as readFileSync5, existsSync as existsSync4 } from "fs";
1549
+ import { join as join5, basename } from "path";
1550
+ function levenshtein(a, b) {
1551
+ const m = a.length;
1552
+ const n = b.length;
1553
+ const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
1554
+ for (let i = 0; i <= m; i++) dp[i][0] = i;
1555
+ for (let j = 0; j <= n; j++) dp[0][j] = j;
1556
+ for (let i = 1; i <= m; i++) {
1557
+ for (let j = 1; j <= n; j++) {
1558
+ 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]);
1559
+ }
1560
+ }
1561
+ return dp[m][n];
1562
+ }
1563
+ function extractIdentifiers(hierarchyJson) {
1564
+ const testIDs = [];
1565
+ const texts = [];
1566
+ try {
1567
+ const root = JSON.parse(hierarchyJson);
1568
+ const queue = [root];
1569
+ while (queue.length > 0) {
1570
+ const node = queue.pop();
1571
+ if (!node || typeof node !== "object") continue;
1572
+ if (node.testID && typeof node.testID === "string") testIDs.push(node.testID);
1573
+ if (node.text && typeof node.text === "string") texts.push(node.text);
1574
+ if (Array.isArray(node.children)) {
1575
+ for (const child of node.children) queue.push(child);
1576
+ }
1577
+ }
1578
+ } catch {
1579
+ }
1580
+ return { testIDs, texts };
1581
+ }
1582
+ function findNearbySelectors(attempted, hierarchyJson) {
1583
+ if (!hierarchyJson) return [];
1584
+ const { testIDs, texts } = extractIdentifiers(hierarchyJson);
1585
+ let target;
1586
+ let candidates;
1587
+ if (typeof attempted === "string") {
1588
+ target = attempted.toLowerCase();
1589
+ candidates = [...testIDs, ...texts];
1590
+ } else if (attempted && typeof attempted === "object") {
1591
+ const sel = attempted;
1592
+ if (typeof sel.testID === "string") {
1593
+ target = sel.testID.toLowerCase();
1594
+ candidates = testIDs;
1595
+ } else if (typeof sel.text === "string") {
1596
+ target = sel.text.toLowerCase();
1597
+ candidates = texts;
1598
+ } else if (typeof sel.accessibilityLabel === "string") {
1599
+ target = sel.accessibilityLabel.toLowerCase();
1600
+ candidates = [...testIDs, ...texts];
1601
+ } else {
1602
+ return [];
1603
+ }
1604
+ } else {
1605
+ return [];
1606
+ }
1607
+ const scored = candidates.filter((c) => c !== target).map((c) => {
1608
+ const cl = c.toLowerCase();
1609
+ const substringMatch = cl.includes(target) || target.includes(cl);
1610
+ const dist = levenshtein(target, cl);
1611
+ return { value: c, score: substringMatch ? 0 : dist };
1612
+ }).filter((s) => s.score <= 5).toSorted((a, b) => a.score - b.score);
1613
+ const seen = /* @__PURE__ */ new Set();
1614
+ const results = [];
1615
+ for (const s of scored) {
1616
+ if (!seen.has(s.value)) {
1617
+ seen.add(s.value);
1618
+ results.push(s.value);
1619
+ if (results.length >= 5) break;
1620
+ }
1621
+ }
1622
+ return results;
1623
+ }
1624
+ function buildArtifactMap(attachments) {
1625
+ const map = {};
1626
+ if (!attachments) return map;
1627
+ for (const att of attachments) {
1628
+ const filename = basename(att.path);
1629
+ if (filename === "screenshot.png") map.screenshot = filename;
1630
+ else if (filename === "hierarchy.json") map.hierarchy = filename;
1631
+ else if (filename === "console-logs.json") map.consoleLogs = filename;
1632
+ else if (filename === "js-errors.json") map.jsErrors = filename;
1633
+ else if (filename === "network.har") map.har = filename;
1634
+ else if (filename === "driver-logs.txt") map.driverLogs = filename;
1635
+ }
1636
+ return map;
1637
+ }
1638
+ function createFailureBundle(flowName, platform, steps, error, artifactDir, attachments, flowPath) {
1639
+ const failedStepIndex = steps.findLastIndex((s) => s.status === "failed");
1640
+ const failedStep = failedStepIndex >= 0 ? {
1641
+ index: failedStepIndex,
1642
+ command: steps[failedStepIndex].command,
1643
+ selector: steps[failedStepIndex].selector ?? null,
1644
+ durationMs: steps[failedStepIndex].durationMs,
1645
+ error: steps[failedStepIndex].error
1646
+ } : null;
1647
+ const lastPassedIndex = failedStepIndex > 0 ? steps.findLastIndex((s, i) => i < failedStepIndex && s.status === "passed") : -1;
1648
+ const lastPassedStep = lastPassedIndex >= 0 ? {
1649
+ index: lastPassedIndex,
1650
+ command: steps[lastPassedIndex].command,
1651
+ selector: steps[lastPassedIndex].selector ?? null,
1652
+ durationMs: steps[lastPassedIndex].durationMs
1653
+ } : null;
1654
+ let selectorContext;
1655
+ if (failedStep?.selector && (error.category === "element-not-found" || error.category === "element-not-visible")) {
1656
+ const hierarchyPath = join5(artifactDir, "hierarchy.json");
1657
+ let hierarchyJson = null;
1658
+ if (existsSync4(hierarchyPath)) {
1659
+ try {
1660
+ hierarchyJson = readFileSync5(hierarchyPath, "utf-8");
1661
+ } catch {
1662
+ }
1663
+ }
1664
+ const nearbyAlternatives = findNearbySelectors(failedStep.selector, hierarchyJson);
1665
+ selectorContext = {
1666
+ attempted: failedStep.selector,
1667
+ nearbyAlternatives
1668
+ };
1669
+ }
1670
+ const shellQuote = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
1671
+ const flowFile = flowPath ?? `flows/${flowName.replaceAll(" ", "-")}.flow.ts`;
1672
+ const reproCommand = `spana test ${shellQuote(flowFile)} --platform ${platform} --grep ${shellQuote(flowName)}`;
1673
+ let runtimeDiagnostics;
1674
+ const consolePath = join5(artifactDir, "console-logs.json");
1675
+ const jsErrPath = join5(artifactDir, "js-errors.json");
1676
+ if (existsSync4(consolePath) || existsSync4(jsErrPath)) {
1677
+ let consoleErrorCount = 0;
1678
+ let consoleWarnCount = 0;
1679
+ const recentConsoleErrors = [];
1680
+ let jsErrorCount = 0;
1681
+ const recentJsErrors = [];
1682
+ if (existsSync4(consolePath)) {
1683
+ try {
1684
+ const logs = JSON.parse(readFileSync5(consolePath, "utf-8"));
1685
+ if (Array.isArray(logs)) {
1686
+ for (const entry of logs) {
1687
+ const lvl = (entry.type ?? entry.level ?? "").toLowerCase();
1688
+ const text = entry.text ?? entry.message ?? "";
1689
+ if (lvl === "error") {
1690
+ consoleErrorCount++;
1691
+ if (text) recentConsoleErrors.push(text);
1692
+ } else if (lvl === "warn" || lvl === "warning") {
1693
+ consoleWarnCount++;
1694
+ }
1695
+ }
1696
+ }
1697
+ } catch {
1698
+ }
1699
+ }
1700
+ if (existsSync4(jsErrPath)) {
1701
+ try {
1702
+ const errs = JSON.parse(readFileSync5(jsErrPath, "utf-8"));
1703
+ if (Array.isArray(errs)) {
1704
+ jsErrorCount = errs.length;
1705
+ for (const e of errs.slice(-5)) {
1706
+ const msg = e.message ?? e.text ?? String(e);
1707
+ if (msg) recentJsErrors.push(msg);
1708
+ }
1709
+ }
1710
+ } catch {
1711
+ }
1712
+ }
1713
+ if (consoleErrorCount > 0 || consoleWarnCount > 0 || jsErrorCount > 0) {
1714
+ runtimeDiagnostics = {
1715
+ consoleErrorCount,
1716
+ consoleWarnCount,
1717
+ recentConsoleErrors: recentConsoleErrors.slice(-5),
1718
+ jsErrorCount,
1719
+ recentJsErrors
1720
+ };
1721
+ }
1722
+ }
1723
+ const bundle = {
1724
+ schemaVersion: 1,
1725
+ flow: flowName,
1726
+ platform,
1727
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1728
+ failedStep,
1729
+ lastPassedStep,
1730
+ steps: steps.map((s, index) => ({
1731
+ index,
1732
+ command: s.command,
1733
+ selector: s.selector ?? null,
1734
+ durationMs: s.durationMs,
1735
+ status: s.status,
1736
+ ...s.error !== void 0 ? { error: s.error } : {}
1737
+ })),
1738
+ error: {
1739
+ message: error.message,
1740
+ category: error.category,
1741
+ suggestion: error.suggestion,
1742
+ errorCode: error.errorCode,
1743
+ ...error.location ? { location: error.location } : {},
1744
+ ...error.codeFrame ? { codeFrame: error.codeFrame } : {}
1745
+ },
1746
+ selectorContext,
1747
+ ...runtimeDiagnostics ? { runtimeDiagnostics } : {},
1748
+ artifacts: buildArtifactMap(attachments),
1749
+ reproCommand,
1750
+ durationMs: steps.reduce((sum, s) => sum + s.durationMs, 0)
1751
+ };
1752
+ return bundle;
1753
+ }
1754
+ function writeFailureBundle(bundle, artifactDir) {
1755
+ const path = join5(artifactDir, "failure-bundle.json");
1756
+ writeFileSync4(path, JSON.stringify(bundle, null, 2), "utf-8");
1757
+ return path;
1758
+ }
1759
+
1760
+ // src/core/engine.ts
1761
+ function isCdpScreencastCapable(channel) {
1762
+ return Boolean(channel) && typeof channel.sendCommand === "function" && typeof channel.onEvent === "function";
1763
+ }
1764
+ function buildPlaybackStepMarkers(steps) {
1765
+ let cursorMs = 0;
1766
+ return steps.map((step2, index) => {
1767
+ const startedAtMs = cursorMs;
1768
+ cursorMs += Math.max(1, step2.durationMs);
1769
+ const sel = step2.selector;
1770
+ const pt = sel && typeof sel === "object" ? sel["point"] : void 0;
1771
+ const tapPoint = pt && typeof pt["x"] === "number" && typeof pt["y"] === "number" ? { x: pt["x"], y: pt["y"] } : void 0;
1772
+ return {
1773
+ index,
1774
+ command: step2.command,
1775
+ selector: step2.selector,
1776
+ startedAtMs,
1777
+ durationMs: step2.durationMs,
1778
+ status: step2.status,
1779
+ error: step2.error,
1780
+ ...tapPoint ? { tapPoint } : {}
1781
+ };
1782
+ });
1783
+ }
1784
+ async function executeFlow(flow, driver, config) {
1785
+ const start2 = Date.now();
1786
+ const { platform, coordinatorConfig, appId } = config;
1787
+ const skip = getFlowSkip(flow, platform);
1788
+ if (skip) return skip;
1789
+ const autoLaunch = flow.config.autoLaunch ?? config.autoLaunch ?? true;
1790
+ const timeout = flow.config.timeout ?? config.flowTimeout ?? 6e4;
1791
+ const artifactConfig = resolveArtifactConfig(config.artifactConfig, flow.config.artifacts);
1792
+ const stepRecorder = createStepRecorder(driver, artifactConfig, flow.name, platform);
1793
+ const launchOptions = mergeLaunchOptions(config.launchOptions, flow.config.launchOptions);
1794
+ const flowDefaults = flow.config.defaults;
1795
+ const mergedCoordinatorConfig = flowDefaults ? {
1796
+ ...coordinatorConfig,
1797
+ defaults: {
1798
+ ...coordinatorConfig.defaults,
1799
+ timeout: flowDefaults.waitTimeout ?? coordinatorConfig.defaults?.timeout,
1800
+ pollInterval: flowDefaults.pollInterval ?? coordinatorConfig.defaults?.pollInterval,
1801
+ settleTimeout: flowDefaults.settleTimeout ?? coordinatorConfig.defaults?.settleTimeout,
1802
+ initialPollInterval: flowDefaults.initialPollInterval ?? coordinatorConfig.defaults?.initialPollInterval
1803
+ },
1804
+ waitForIdleTimeout: flowDefaults.waitForIdleTimeout ?? coordinatorConfig.waitForIdleTimeout,
1805
+ typingDelay: flowDefaults.typingDelay ?? coordinatorConfig.typingDelay,
1806
+ hierarchyCacheTtl: flowDefaults.hierarchyCacheTtl ?? coordinatorConfig.hierarchyCacheTtl
1807
+ } : coordinatorConfig;
1808
+ const softFailures = [];
1809
+ const aggregateFailures = (hardFailure) => {
1810
+ const messages = softFailures.map(
1811
+ (error, i) => `${i + 1}. ${error instanceof Error ? error.message : String(error)}`
1812
+ );
1813
+ return new AggregateError(
1814
+ hardFailure ? [hardFailure, ...softFailures] : softFailures,
1815
+ `${hardFailure ? `${hardFailure.message}
1816
+ ` : ""}${softFailures.length} soft assertion(s) failed:
1817
+ ${messages.join("\n")}`,
1818
+ { cause: hardFailure ?? softFailures[0] }
1819
+ );
1820
+ };
1821
+ const flowMeta = {
1822
+ flowFilePath: flow.sourcePath ?? "",
1823
+ flowName: flow.name,
1824
+ platform,
1825
+ updateBaselines: config.updateBaselines ?? false,
1826
+ recordSoftFailure: (error) => {
1827
+ softFailures.push(error);
1828
+ }
1829
+ };
1830
+ const extraCleanups = [];
1831
+ const app = createPromiseApp(driver, appId, mergedCoordinatorConfig, stepRecorder, {
1832
+ platform,
1833
+ storybook: config.storybook,
1834
+ launchOptions,
1835
+ onRegisterCleanup: (fn) => extraCleanups.push(fn),
1836
+ flowContext: flowMeta,
1837
+ visualRegression: config.visualRegression
1838
+ });
1839
+ const expect = createPromiseExpect(
1840
+ driver,
1841
+ mergedCoordinatorConfig,
1842
+ stepRecorder,
1843
+ flowMeta,
1844
+ config.visualRegression
1845
+ );
1846
+ const agent = createFlowAgent({
1847
+ flowName: flow.name,
1848
+ platform,
1849
+ app,
1850
+ cacheDir: config.replayCache?.dir,
1851
+ cacheMode: config.strictCache ? "strict" : config.replayCache?.mode,
1852
+ provider: config.agent
1853
+ });
1854
+ const flowCtx = {
1855
+ app,
1856
+ expect,
1857
+ platform,
1858
+ agent,
1859
+ step,
1860
+ updateBaselines: flowMeta.updateBaselines
1861
+ };
1862
+ const sessionManager = new SessionManager();
1863
+ const sessions = createSessions(
1864
+ sessionManager,
1865
+ async (opts) => {
1866
+ const pwDriver = await Effect4.runPromise(
1867
+ makePlaywrightDriver({
1868
+ browser: opts.browser,
1869
+ headless: opts.headless ?? true,
1870
+ baseUrl: opts.baseUrl,
1871
+ storageState: opts.storageState,
1872
+ verboseLogging: opts.verboseLogging
1873
+ })
1874
+ );
1875
+ return pwDriver;
1876
+ },
1877
+ { parse: (raw) => parseWebHierarchy(raw) },
1878
+ { ...flowMeta, platform: "web" }
1879
+ );
1880
+ flowCtx.sessions = sessions;
1881
+ let videoRecorder;
1882
+ let collectingCoverage = false;
1883
+ let recordingFinalized = false;
1884
+ const wantRecording = artifactConfig.video !== "off" || artifactConfig.playback;
1885
+ const captureCoverage = async (attachments, status) => {
1886
+ if (!collectingCoverage || !driver.stopJSCoverage) return;
1887
+ collectingCoverage = false;
1888
+ try {
1889
+ const entries = await Effect4.runPromise(driver.stopJSCoverage());
1890
+ const path = join6(flowArtifactDir(artifactConfig, flow.name, platform), "js-coverage.json");
1891
+ writeFileSync5(path, JSON.stringify(entries), "utf8");
1892
+ attachments.push({ name: "js-coverage", contentType: "application/json", path });
1893
+ } catch (error) {
1894
+ if (status === "passed") throw error;
1895
+ console.warn(
1896
+ `Failed to capture JavaScript coverage: ${error instanceof Error ? error.message : String(error)}`
1897
+ );
1898
+ }
1899
+ };
1900
+ const finalizeRecording = async (status, attachments, steps, durationMs) => {
1901
+ if (recordingFinalized || !wantRecording) return;
1902
+ recordingFinalized = true;
1903
+ const keep = artifactConfig.video === "on" || artifactConfig.playback || artifactConfig.video === "retain-on-failure" && status === "failed";
1904
+ const fileStem = safeArtifactName(flow.name);
1905
+ const outputDir = keep ? flowArtifactDir(artifactConfig, flow.name, platform) : artifactConfig.outputDir;
1906
+ let viewport;
1907
+ try {
1908
+ const info = await Effect4.runPromise(Effect4.orDie(driver.getDeviceInfo()));
1909
+ if (info.screenWidth > 0 && info.screenHeight > 0) {
1910
+ viewport = { width: info.screenWidth, height: info.screenHeight };
1911
+ }
1912
+ } catch {
1913
+ }
1914
+ let stopRes;
1915
+ if (videoRecorder) {
1916
+ try {
1917
+ stopRes = await videoRecorder.stop({
1918
+ keep,
1919
+ outputDir,
1920
+ fileStem,
1921
+ steps: buildPlaybackStepMarkers(steps),
1922
+ viewport
1923
+ });
1924
+ } catch {
1925
+ }
1926
+ }
1927
+ if (!keep) return;
1928
+ if (stopRes?.videoPath) {
1929
+ attachments.push({
1930
+ name: "video",
1931
+ contentType: stopRes.videoPath.endsWith(".webm") ? "video/webm" : "video/mp4",
1932
+ path: stopRes.videoPath
1933
+ });
1934
+ }
1935
+ if (stopRes?.playbackJsonPath) {
1936
+ attachments.push({
1937
+ name: "playback",
1938
+ contentType: "application/json",
1939
+ path: stopRes.playbackJsonPath
1940
+ });
1941
+ return;
1942
+ }
1943
+ const fallbackTrace = buildPlaybackTraceFromSteps({
1944
+ flowName: flow.name,
1945
+ platform,
1946
+ durationMs,
1947
+ steps,
1948
+ viewport,
1949
+ videoPath: stopRes?.videoPath
1950
+ });
1951
+ if (fallbackTrace) {
1952
+ const playbackPath = join6(outputDir, `${fileStem}-playback.json`);
1953
+ writeFileSync5(playbackPath, JSON.stringify(fallbackTrace), "utf8");
1954
+ attachments.push({
1955
+ name: "playback",
1956
+ contentType: "application/json",
1957
+ path: playbackPath
1958
+ });
1959
+ }
1960
+ };
1961
+ const writeRichTraceIfEnabled = async (status, attachments, steps, durationMs, error) => {
1962
+ if (!artifactConfig.trace) return;
1963
+ try {
1964
+ const outDir = flowArtifactDir(artifactConfig, flow.name, platform);
1965
+ const [consoleLogs, jsErrors, har, domSnapshot] = await Promise.all([
1966
+ driver.getConsoleLogs ? Effect4.runPromise(Effect4.orDie(driver.getConsoleLogs())).catch(() => []) : Promise.resolve([]),
1967
+ driver.getJSErrors ? Effect4.runPromise(Effect4.orDie(driver.getJSErrors())).catch(() => []) : Promise.resolve([]),
1968
+ driver.getHAR ? Effect4.runPromise(Effect4.orDie(driver.getHAR())).catch(() => void 0) : Promise.resolve(void 0),
1969
+ driver.dumpHierarchy ? Effect4.runPromise(Effect4.orDie(driver.dumpHierarchy())).catch(() => void 0) : Promise.resolve(void 0)
1970
+ ]);
1971
+ const richTrace = buildRichFlowTrace({
1972
+ flowName: flow.name,
1973
+ platform,
1974
+ status,
1975
+ durationMs,
1976
+ steps,
1977
+ consoleLogs,
1978
+ jsErrors,
1979
+ har,
1980
+ domSnapshot,
1981
+ error
1982
+ });
1983
+ const { traceJsonPath, traceViewerHtmlPath } = writeRichTraceBundle(richTrace, outDir);
1984
+ attachments.push(
1985
+ { name: "trace-json", contentType: "application/json", path: traceJsonPath },
1986
+ { name: "trace-viewer", contentType: "text/html", path: traceViewerHtmlPath }
1987
+ );
1988
+ } catch {
1989
+ }
1990
+ };
1991
+ const buildFailureResult = async (error) => {
1992
+ const attachments = await captureArtifacts(
1993
+ driver,
1994
+ artifactConfig,
1995
+ flow.name,
1996
+ platform,
1997
+ "failed"
1998
+ );
1999
+ await captureCoverage(attachments, "failed");
2000
+ const steps = stepRecorder.getSteps();
2001
+ const durationMs = Date.now() - start2;
2002
+ await finalizeRecording("failed", attachments, steps, durationMs);
2003
+ const normalized = error instanceof Error ? error : new Error(String(error));
2004
+ return {
2005
+ name: flow.name,
2006
+ platform,
2007
+ status: "failed",
2008
+ durationMs,
2009
+ error: classifyError(normalized, {
2010
+ flowFilePath: flow.sourcePath,
2011
+ fallbackStack: stepRecorder.getLastFailureStack?.()
2012
+ }),
2013
+ attachments,
2014
+ steps,
2015
+ scenarioSteps: flowCtx.__scenarioSteps
2016
+ };
2017
+ };
2018
+ if (driver.beginFlow) {
2019
+ try {
2020
+ await Effect4.runPromise(driver.beginFlow(flow.name));
2021
+ } catch (error) {
2022
+ return buildFailureResult(error);
2023
+ }
2024
+ }
2025
+ if (artifactConfig.jsCoverage && platform === "web") {
2026
+ if (!driver.startJSCoverage || !driver.stopJSCoverage) {
2027
+ return buildFailureResult(
2028
+ new Error(
2029
+ "JavaScript coverage is not supported on web with the current driver; use Chromium with Playwright or direct CDP"
2030
+ )
2031
+ );
2032
+ }
2033
+ try {
2034
+ await Effect4.runPromise(driver.startJSCoverage());
2035
+ collectingCoverage = true;
2036
+ } catch (error) {
2037
+ return buildFailureResult(error);
2038
+ }
2039
+ }
2040
+ if (wantRecording) {
2041
+ try {
2042
+ if (isCdpScreencastCapable(driver.domChannel)) {
2043
+ videoRecorder = await startCdpScreencastRecorder(driver.domChannel, {
2044
+ flowName: flow.name,
2045
+ platform,
2046
+ exportMp4: artifactConfig.video !== "off"
2047
+ });
2048
+ } else if (artifactConfig.video !== "off" && (platform === "android" || platform === "ios")) {
2049
+ const info = await Effect4.runPromise(Effect4.orDie(driver.getDeviceInfo())).catch(
2050
+ () => void 0
2051
+ );
2052
+ if (info?.deviceId) {
2053
+ const outDir = flowArtifactDir(artifactConfig, flow.name, platform);
2054
+ const videoOut = join6(outDir, `${safeArtifactName(flow.name)}.mp4`);
2055
+ videoRecorder = platform === "android" ? startAndroidVideoRecorder(info.deviceId, { outputPath: videoOut }) : startIosSimulatorVideoRecorder(info.deviceId, { outputPath: videoOut });
2056
+ }
2057
+ }
2058
+ } catch {
2059
+ }
2060
+ }
2061
+ if (config.hooks?.beforeEach) {
2062
+ try {
2063
+ await config.hooks.beforeEach({ app, platform });
2064
+ } catch (error) {
2065
+ return buildFailureResult(error);
2066
+ }
2067
+ }
2068
+ let result;
2069
+ let softFailureError;
2070
+ try {
2071
+ if (autoLaunch) {
2072
+ await app.launch();
2073
+ }
2074
+ await Promise.race([
2075
+ withActiveStepRecorder(stepRecorder, () => flow.fn(flowCtx)),
2076
+ new Promise(
2077
+ (_, reject) => setTimeout(
2078
+ () => reject(new Error(`Flow "${flow.name}" timed out after ${timeout}ms`)),
2079
+ timeout
2080
+ )
2081
+ )
2082
+ ]);
2083
+ if (softFailures.length > 0) {
2084
+ softFailureError = aggregateFailures();
2085
+ throw softFailureError;
2086
+ }
2087
+ agent.finalize(true);
2088
+ const attachments = await captureArtifacts(
2089
+ driver,
2090
+ artifactConfig,
2091
+ flow.name,
2092
+ platform,
2093
+ "passed"
2094
+ );
2095
+ await captureCoverage(attachments, "passed");
2096
+ const steps = stepRecorder.getSteps();
2097
+ const durationMs = Date.now() - start2;
2098
+ await finalizeRecording("passed", attachments, steps, durationMs);
2099
+ await writeRichTraceIfEnabled("passed", attachments, steps, durationMs);
2100
+ result = {
2101
+ name: flow.name,
2102
+ platform,
2103
+ status: "passed",
2104
+ durationMs,
2105
+ attachments,
2106
+ steps,
2107
+ scenarioSteps: flowCtx.__scenarioSteps
2108
+ };
2109
+ } catch (error) {
2110
+ agent.finalize(false);
2111
+ const attachments = await captureArtifacts(
2112
+ driver,
2113
+ artifactConfig,
2114
+ flow.name,
2115
+ platform,
2116
+ "failed"
2117
+ );
2118
+ await captureCoverage(attachments, "failed");
2119
+ const steps = stepRecorder.getSteps();
2120
+ const durationMs = Date.now() - start2;
2121
+ await finalizeRecording("failed", attachments, steps, durationMs);
2122
+ const normalized = error instanceof Error ? error : new Error(String(error));
2123
+ const flowError = softFailures.length > 0 && error !== softFailureError ? aggregateFailures(normalized) : normalized;
2124
+ await writeRichTraceIfEnabled("failed", attachments, steps, durationMs, {
2125
+ message: flowError.message,
2126
+ stack: flowError.stack
2127
+ });
2128
+ result = {
2129
+ name: flow.name,
2130
+ platform,
2131
+ status: "failed",
2132
+ durationMs,
2133
+ error: classifyError(flowError, {
2134
+ flowFilePath: flow.sourcePath,
2135
+ fallbackStack: stepRecorder.getLastFailureStack?.()
2136
+ }),
2137
+ attachments,
2138
+ steps,
2139
+ scenarioSteps: flowCtx.__scenarioSteps
2140
+ };
2141
+ if (artifactConfig.captureOnFailure && result.error) {
2142
+ try {
2143
+ const artDir = join6(
2144
+ artifactConfig.outputDir,
2145
+ `${flow.name.replaceAll(/[^a-zA-Z0-9-_]/g, "_").replaceAll(/_+/g, "_").slice(0, 80) || "artifact"}-${platform}`
2146
+ );
2147
+ const bundle = createFailureBundle(
2148
+ flow.name,
2149
+ platform,
2150
+ stepRecorder.getSteps(),
2151
+ result.error,
2152
+ artDir,
2153
+ attachments,
2154
+ flow.sourcePath
2155
+ );
2156
+ writeFailureBundle(bundle, artDir);
2157
+ } catch {
2158
+ }
2159
+ }
2160
+ if (config.debugOnFailure) {
2161
+ await runDebugReplOnce({
2162
+ app,
2163
+ expect,
2164
+ driver,
2165
+ error: flowError,
2166
+ flowName: flow.name,
2167
+ platform,
2168
+ parseHierarchy: coordinatorConfig.parse
2169
+ });
2170
+ }
2171
+ }
2172
+ for (const cleanup of extraCleanups.toReversed()) {
2173
+ try {
2174
+ await cleanup();
2175
+ } catch {
2176
+ }
2177
+ }
2178
+ try {
2179
+ await sessionManager.disconnectAll();
2180
+ } catch {
2181
+ }
2182
+ if (config.hooks?.afterEach) {
2183
+ try {
2184
+ await config.hooks.afterEach({ app, platform, result });
2185
+ } catch (hookError) {
2186
+ console.warn(
2187
+ `afterEach hook failed: ${hookError instanceof Error ? hookError.message : hookError}`
2188
+ );
2189
+ }
2190
+ }
2191
+ return result;
2192
+ }
2193
+
2194
+ // src/core/parallel.ts
2195
+ function orderFlowsLongestFirst(flows, durationHintsMs) {
2196
+ if (!durationHintsMs || Object.keys(durationHintsMs).length === 0) {
2197
+ return flows;
2198
+ }
2199
+ return flows.toSorted((a, b) => (durationHintsMs[b.name] ?? 0) - (durationHintsMs[a.name] ?? 0));
2200
+ }
2201
+ async function runParallel(config) {
2202
+ const {
2203
+ workers,
2204
+ flows: rawFlows,
2205
+ onFlowComplete,
2206
+ onFlowStart,
2207
+ retries = 0,
2208
+ retryDelay = 0,
2209
+ bail,
2210
+ durationHintsMs,
2211
+ claimNextFlow
2212
+ } = config;
2213
+ const flows = orderFlowsLongestFirst(focusFlows(rawFlows), durationHintsMs);
2214
+ const start2 = Date.now();
2215
+ const results = [];
2216
+ let nextFlowIndex = 0;
2217
+ let failureCount = 0;
2218
+ let bailedOut = false;
2219
+ const workerPromises = workers.map(async (worker) => {
2220
+ const stats = { flowCount: 0, totalMs: 0 };
2221
+ while (true) {
2222
+ if (bail !== void 0 && failureCount >= bail) break;
2223
+ let flow;
2224
+ if (claimNextFlow) {
2225
+ const claimed = await claimNextFlow();
2226
+ if (!claimed) break;
2227
+ flow = claimed;
2228
+ } else {
2229
+ const flowIdx = nextFlowIndex++;
2230
+ if (flowIdx >= flows.length) break;
2231
+ flow = flows[flowIdx];
2232
+ }
2233
+ const skip = getFlowSkip(flow, worker.engineConfig.platform);
2234
+ if (skip) {
2235
+ results.push(skip);
2236
+ onFlowComplete?.(skip, worker.name);
2237
+ continue;
2238
+ }
2239
+ const flowRetries = flow.config.retries ?? retries;
2240
+ onFlowStart?.(flow.name, worker.name);
2241
+ let result = await executeFlow(flow, worker.driver, worker.engineConfig);
2242
+ let attempts = 1;
2243
+ while (result.status === "failed" && attempts <= flowRetries) {
2244
+ if (retryDelay > 0) {
2245
+ await new Promise((resolve) => setTimeout(resolve, retryDelay));
2246
+ }
2247
+ result = await executeFlow(flow, worker.driver, worker.engineConfig);
2248
+ attempts++;
2249
+ }
2250
+ if (result.status === "passed" && attempts > 1) {
2251
+ result.flaky = true;
2252
+ }
2253
+ result.attempts = attempts;
2254
+ results.push(result);
2255
+ stats.flowCount++;
2256
+ stats.totalMs += result.durationMs;
2257
+ if (result.status === "failed") {
2258
+ failureCount++;
2259
+ }
2260
+ onFlowComplete?.(result, worker.name);
2261
+ }
2262
+ return { workerId: worker.id, stats };
2263
+ });
2264
+ const workerResults = await Promise.all(workerPromises);
2265
+ if (!claimNextFlow && bail !== void 0 && failureCount >= bail) {
2266
+ bailedOut = true;
2267
+ while (nextFlowIndex < flows.length) {
2268
+ const flow = flows[nextFlowIndex++];
2269
+ results.push(
2270
+ getFlowSkip(flow, workers[0].engineConfig.platform) ?? {
2271
+ name: flow.name,
2272
+ platform: workers[0].engineConfig.platform,
2273
+ status: "skipped",
2274
+ durationMs: 0,
2275
+ attempts: 0
2276
+ }
2277
+ );
2278
+ }
2279
+ }
2280
+ const workerStats = /* @__PURE__ */ new Map();
2281
+ for (const wr of workerResults) {
2282
+ workerStats.set(wr.workerId, wr.stats);
2283
+ }
2284
+ return {
2285
+ results,
2286
+ totalDurationMs: Date.now() - start2,
2287
+ passed: results.filter((r) => r.status === "passed").length,
2288
+ failed: results.filter((r) => r.status === "failed").length,
2289
+ skipped: results.filter((r) => r.status === "skipped").length,
2290
+ flaky: results.filter((r) => r.flaky === true).length,
2291
+ bailedOut: bailedOut || void 0,
2292
+ workerStats
2293
+ };
2294
+ }
2295
+
2296
+ // src/core/worker-pool.ts
2297
+ import { spawn as spawn2 } from "child_process";
2298
+ import { mkdir, readFile, unlink, writeFile } from "fs/promises";
2299
+ import { createServer } from "http";
2300
+ import { dirname } from "path";
2301
+ var DEFAULT_MAX_WORKERS_PER_PROCESS = 8;
2302
+ async function startSharedFlowQueueServer(orderedFlowNames) {
2303
+ const queue = [...orderedFlowNames];
2304
+ let cursor = 0;
2305
+ const server = createServer((req, res) => {
2306
+ if (req.url === "/claim" && (req.method === "POST" || req.method === "GET")) {
2307
+ const flowName = cursor < queue.length ? queue[cursor++] : null;
2308
+ const body = JSON.stringify({ flowName });
2309
+ res.writeHead(200, { "content-type": "application/json" });
2310
+ res.end(body);
2311
+ return;
2312
+ }
2313
+ res.writeHead(404);
2314
+ res.end();
2315
+ });
2316
+ await new Promise((resolve, reject) => {
2317
+ server.once("error", reject);
2318
+ server.listen(0, "127.0.0.1", () => resolve());
2319
+ });
2320
+ const addr = server.address();
2321
+ const url = `http://127.0.0.1:${addr.port}`;
2322
+ return {
2323
+ url,
2324
+ remaining: () => Math.max(0, queue.length - cursor),
2325
+ close: () => new Promise((resolve) => {
2326
+ server.close(() => resolve());
2327
+ })
2328
+ };
2329
+ }
2330
+ function createRemoteFlowClaimer(queueUrl) {
2331
+ const endpoint = `${queueUrl.replace(/\/+$/, "")}/claim`;
2332
+ return async () => {
2333
+ const res = await fetch(endpoint, { method: "POST" });
2334
+ if (!res.ok) return null;
2335
+ const data = await res.json();
2336
+ return typeof data.flowName === "string" ? data.flowName : null;
2337
+ };
2338
+ }
2339
+ function planProcessPool(totalWorkers, maxWorkersPerProcess = DEFAULT_MAX_WORKERS_PER_PROCESS, explicitProcesses) {
2340
+ const safeTotal = Math.max(1, Math.floor(totalWorkers));
2341
+ const safeMax = Math.max(1, Math.floor(maxWorkersPerProcess));
2342
+ const processCount = explicitProcesses !== void 0 && explicitProcesses >= 1 ? Math.min(Math.floor(explicitProcesses), safeTotal) : safeTotal <= safeMax ? 1 : Math.ceil(safeTotal / safeMax);
2343
+ if (processCount <= 1) {
2344
+ return {
2345
+ totalWorkers: safeTotal,
2346
+ maxWorkersPerProcess: safeMax,
2347
+ processCount: 1,
2348
+ workersPerProcess: [safeTotal]
2349
+ };
2350
+ }
2351
+ const base = Math.floor(safeTotal / processCount);
2352
+ const remainder = safeTotal % processCount;
2353
+ const workersPerProcess = Array.from(
2354
+ { length: processCount },
2355
+ (_v, i) => base + (i < remainder ? 1 : 0)
2356
+ );
2357
+ return {
2358
+ totalWorkers: safeTotal,
2359
+ maxWorkersPerProcess: safeMax,
2360
+ processCount,
2361
+ workersPerProcess
2362
+ };
2363
+ }
2364
+ function partitionFlowsAcrossProcesses(items, processCount, options) {
2365
+ const count = Math.max(1, Math.min(Math.floor(processCount), Math.max(1, items.length)));
2366
+ if (count === 1 || items.length === 0) {
2367
+ return items.length === 0 ? [] : [items];
2368
+ }
2369
+ const hints = options?.durationHintsMs;
2370
+ const getName = options?.getName;
2371
+ const known = hints ? Object.values(hints).filter((v) => typeof v === "number" && v > 0) : [];
2372
+ const defaultWeight = known.length > 0 ? known.reduce((a, b) => a + b, 0) / known.length : 1e3;
2373
+ const indexed = items.map((item, idx) => ({
2374
+ item,
2375
+ idx,
2376
+ weight: hints && getName ? hints[getName(item)] ?? defaultWeight : 1e3
2377
+ }));
2378
+ const ordered = hints && getName && Object.keys(hints).length > 0 ? indexed.toSorted((a, b) => b.weight - a.weight || a.idx - b.idx) : indexed;
2379
+ const loads = Array.from({ length: count }, () => 0);
2380
+ const buckets = Array.from({ length: count }, () => []);
2381
+ for (const entry of ordered) {
2382
+ let best = 0;
2383
+ for (let i = 1; i < count; i++) {
2384
+ if (loads[i] < loads[best]) best = i;
2385
+ }
2386
+ loads[best] = loads[best] + entry.weight;
2387
+ buckets[best].push({ item: entry.item, idx: entry.idx });
2388
+ }
2389
+ return buckets.map((bucket) => bucket.toSorted((a, b) => a.idx - b.idx).map((e) => e.item)).filter((b) => b.length > 0);
2390
+ }
2391
+ async function writeWorkerProcessReport(results, env = process.env) {
2392
+ const reportPath = env["SPANA_WORKER_REPORT_PATH"];
2393
+ if (!reportPath) return null;
2394
+ await mkdir(dirname(reportPath), { recursive: true });
2395
+ await writeFile(reportPath, JSON.stringify({ results }, null, 2), "utf8");
2396
+ return reportPath;
2397
+ }
2398
+ async function defaultReadJsonReport(reportJsonPath) {
2399
+ let content;
2400
+ try {
2401
+ content = await readFile(reportJsonPath, "utf8");
2402
+ } catch {
2403
+ return [];
2404
+ }
2405
+ const raw = JSON.parse(content);
2406
+ return Array.isArray(raw.results) ? raw.results : [];
2407
+ }
2408
+ async function runMultiProcessPool(options) {
2409
+ const plan = planProcessPool(
2410
+ options.totalWorkers,
2411
+ options.maxWorkersPerProcess,
2412
+ options.processes
2413
+ );
2414
+ const spawnFn = options.spawnFn ?? spawn2;
2415
+ const readReport = options.readReportFn ?? defaultReadJsonReport;
2416
+ const shouldCleanup = options.cleanupReportFiles !== false;
2417
+ const startedAt = Date.now();
2418
+ const processResults = await Promise.all(
2419
+ plan.workersPerProcess.map(async (workerCount, shardIdx) => {
2420
+ const shardStart = Date.now();
2421
+ const spec = options.buildShardCommand(shardIdx + 1, plan.processCount, workerCount);
2422
+ let exitCode = null;
2423
+ let spawnError;
2424
+ try {
2425
+ exitCode = await new Promise((resolve, reject) => {
2426
+ const child = spawnFn(spec.command, spec.args, {
2427
+ env: { ...process.env, ...spec.env },
2428
+ stdio: "inherit"
2429
+ });
2430
+ child.on("error", reject);
2431
+ child.on("close", (code) => resolve(code));
2432
+ });
2433
+ } catch (err) {
2434
+ spawnError = err instanceof Error ? err.message : String(err);
2435
+ }
2436
+ let shardResults = [];
2437
+ try {
2438
+ shardResults = await readReport(spec.reportJsonPath);
2439
+ } catch (err) {
2440
+ if (!spawnError) {
2441
+ spawnError = `Failed to parse shard ${shardIdx + 1} report: ${err instanceof Error ? err.message : String(err)}`;
2442
+ }
2443
+ }
2444
+ if (shouldCleanup) {
2445
+ try {
2446
+ await unlink(spec.reportJsonPath);
2447
+ } catch {
2448
+ }
2449
+ }
2450
+ if (exitCode !== 0 && shardResults.length === 0) {
2451
+ shardResults.push({
2452
+ name: `worker-process-${shardIdx + 1}`,
2453
+ platform: "web",
2454
+ status: "failed",
2455
+ durationMs: Date.now() - shardStart,
2456
+ error: {
2457
+ category: "driver-error",
2458
+ message: spawnError ?? `Worker process ${shardIdx + 1} exited with code ${exitCode ?? "unknown"}`
2459
+ }
2460
+ });
2461
+ }
2462
+ return {
2463
+ shardIndex: shardIdx + 1,
2464
+ workerCount,
2465
+ exitCode,
2466
+ durationMs: Date.now() - shardStart,
2467
+ results: shardResults,
2468
+ ...spawnError ? { error: spawnError } : {}
2469
+ };
2470
+ })
2471
+ );
2472
+ const results = processResults.flatMap((p) => p.results);
2473
+ const passed = results.filter((r) => r.status === "passed").length;
2474
+ const failed = results.filter((r) => r.status === "failed").length;
2475
+ const skipped = results.filter((r) => r.status === "skipped").length;
2476
+ const flaky = results.filter((r) => r.flaky).length;
2477
+ return {
2478
+ results,
2479
+ totalDurationMs: Date.now() - startedAt,
2480
+ passed,
2481
+ failed,
2482
+ skipped,
2483
+ flaky,
2484
+ processCount: plan.processCount,
2485
+ processResults
2486
+ };
2487
+ }
2488
+
2489
+ // src/runtime/web-server.ts
2490
+ import { spawn as spawn3 } from "child_process";
2491
+ import { createConnection } from "net";
2492
+ async function isTcpPortOpen(port, host = "127.0.0.1", timeoutMs = 400) {
2493
+ return new Promise((resolve) => {
2494
+ const socket = createConnection({ host, port });
2495
+ let settled = false;
2496
+ const finish = (ok) => {
2497
+ if (settled) return;
2498
+ settled = true;
2499
+ socket.destroy();
2500
+ resolve(ok);
2501
+ };
2502
+ socket.setTimeout(timeoutMs, () => finish(false));
2503
+ socket.once("connect", () => finish(true));
2504
+ socket.once("error", () => finish(false));
2505
+ });
2506
+ }
2507
+ async function isHttpUrlReady(url, timeoutMs = 1e3) {
2508
+ try {
2509
+ const res = await fetch(url, {
2510
+ method: "GET",
2511
+ redirect: "follow",
2512
+ signal: AbortSignal.timeout(timeoutMs)
2513
+ });
2514
+ return res.status >= 200 && res.status < 400;
2515
+ } catch {
2516
+ return false;
2517
+ }
2518
+ }
2519
+ async function checkServerReady(config) {
2520
+ if (config.url) {
2521
+ return isHttpUrlReady(config.url);
2522
+ }
2523
+ if (typeof config.port === "number" && config.port > 0) {
2524
+ return isTcpPortOpen(config.port);
2525
+ }
2526
+ return false;
2527
+ }
2528
+ function killProcessTree(child, signal) {
2529
+ const pid = child.pid;
2530
+ if (!pid || pid === process.pid) return;
2531
+ try {
2532
+ if (process.platform !== "win32") {
2533
+ process.kill(-pid, signal);
2534
+ return;
2535
+ }
2536
+ } catch {
2537
+ }
2538
+ try {
2539
+ child.kill(signal);
2540
+ } catch {
2541
+ }
2542
+ }
2543
+ async function stopChildProcess(child, gracefulMs) {
2544
+ if (child.exitCode !== null || child.signalCode !== null) return;
2545
+ await new Promise((resolve) => {
2546
+ let done = false;
2547
+ const finish = () => {
2548
+ if (done) return;
2549
+ done = true;
2550
+ clearTimeout(timer);
2551
+ resolve();
2552
+ };
2553
+ child.once("exit", finish);
2554
+ child.once("close", finish);
2555
+ killProcessTree(child, "SIGTERM");
2556
+ const timer = setTimeout(() => {
2557
+ killProcessTree(child, "SIGKILL");
2558
+ finish();
2559
+ }, gracefulMs);
2560
+ timer.unref?.();
2561
+ });
2562
+ }
2563
+ async function startWebServer(config, opts = {}) {
2564
+ if (!config.command || config.command.trim().length === 0) {
2565
+ throw new Error("webServer.command must be a non-empty string.");
2566
+ }
2567
+ const isCI = opts.isCI ?? Boolean(process.env["CI"]);
2568
+ const reuse = config.reuseExistingServer ?? !isCI;
2569
+ const timeoutMs = config.timeout ?? 6e4;
2570
+ const pollIntervalMs = opts.pollIntervalMs ?? 150;
2571
+ const gracefulShutdownMs = config.gracefulShutdownMs ?? 3e3;
2572
+ const targetUrl = config.url ?? (config.port ? `http://127.0.0.1:${config.port}` : void 0);
2573
+ if (reuse && (config.url || config.port)) {
2574
+ const alreadyUp = await checkServerReady(config);
2575
+ if (alreadyUp) {
2576
+ return {
2577
+ config,
2578
+ url: targetUrl,
2579
+ port: config.port,
2580
+ reused: true,
2581
+ stop: async () => {
2582
+ }
2583
+ };
2584
+ }
2585
+ }
2586
+ const outputTail = [];
2587
+ const pushOutput = (chunk) => {
2588
+ const text = chunk.toString();
2589
+ outputTail.push(text);
2590
+ if (outputTail.length > 40) outputTail.shift();
2591
+ };
2592
+ const stdoutMode = config.stdout ?? "pipe";
2593
+ const stderrMode = config.stderr ?? "pipe";
2594
+ const child = spawn3(config.command, {
2595
+ cwd: config.cwd ?? opts.cwd ?? process.cwd(),
2596
+ env: { ...process.env, ...config.env },
2597
+ shell: true,
2598
+ detached: process.platform !== "win32",
2599
+ stdio: ["ignore", stdoutMode, stderrMode]
2600
+ });
2601
+ if (stdoutMode === "pipe" && child.stdout) {
2602
+ child.stdout.on("data", pushOutput);
2603
+ }
2604
+ if (stderrMode === "pipe" && child.stderr) {
2605
+ child.stderr.on("data", pushOutput);
2606
+ }
2607
+ let exitedEarly = null;
2608
+ let spawnError = null;
2609
+ child.once("error", (err) => {
2610
+ spawnError = err;
2611
+ });
2612
+ child.once("exit", (code, signal) => {
2613
+ exitedEarly = { code, signal };
2614
+ });
2615
+ if (!config.url && !config.port) {
2616
+ await new Promise((r) => setTimeout(r, Math.min(300, timeoutMs)));
2617
+ if (spawnError) {
2618
+ throw new Error(`webServer failed to spawn "${config.command}": ${String(spawnError)}`);
2619
+ }
2620
+ if (exitedEarly !== null) {
2621
+ const info = exitedEarly;
2622
+ throw new Error(
2623
+ `webServer "${config.command}" exited immediately (code=${info.code}, signal=${info.signal}).
2624
+ ${outputTail.join("")}`
2625
+ );
2626
+ }
2627
+ return {
2628
+ config,
2629
+ reused: false,
2630
+ pid: child.pid,
2631
+ stop: () => stopChildProcess(child, gracefulShutdownMs)
2632
+ };
2633
+ }
2634
+ const deadline = Date.now() + timeoutMs;
2635
+ while (Date.now() < deadline) {
2636
+ if (spawnError) {
2637
+ throw new Error(`webServer failed to spawn "${config.command}": ${String(spawnError)}`);
2638
+ }
2639
+ if (exitedEarly !== null) {
2640
+ const info = exitedEarly;
2641
+ throw new Error(
2642
+ `webServer "${config.command}" exited before ${targetUrl} became ready (code=${info.code}, signal=${info.signal}).
2643
+ ${outputTail.join("")}`
2644
+ );
2645
+ }
2646
+ if (await checkServerReady(config)) {
2647
+ return {
2648
+ config,
2649
+ url: targetUrl,
2650
+ port: config.port,
2651
+ reused: false,
2652
+ pid: child.pid,
2653
+ stop: () => stopChildProcess(child, gracefulShutdownMs)
2654
+ };
2655
+ }
2656
+ await new Promise((r) => setTimeout(r, pollIntervalMs));
2657
+ }
2658
+ await stopChildProcess(child, gracefulShutdownMs);
2659
+ throw new Error(
2660
+ `Timed out after ${timeoutMs}ms waiting for webServer "${config.command}" at ${targetUrl}.
2661
+ ${outputTail.join("")}`
2662
+ );
2663
+ }
2664
+ async function startWebServers(input, opts = {}) {
2665
+ if (!input) {
2666
+ return { servers: [], stopAll: async () => {
2667
+ } };
2668
+ }
2669
+ const configs = Array.isArray(input) ? input : [input];
2670
+ const started = [];
2671
+ try {
2672
+ for (const cfg of configs) {
2673
+ const handle = await startWebServer(cfg, opts);
2674
+ started.push(handle);
2675
+ }
2676
+ } catch (err) {
2677
+ for (const handle of started.toReversed()) {
2678
+ await handle.stop().catch(() => {
2679
+ });
2680
+ }
2681
+ throw err;
2682
+ }
2683
+ return {
2684
+ servers: started,
2685
+ stopAll: async () => {
2686
+ for (const handle of started.toReversed()) {
2687
+ await handle.stop().catch(() => {
2688
+ });
2689
+ }
2690
+ }
2691
+ };
2692
+ }
2693
+
2694
+ // src/core/projects.ts
2695
+ function globToRegExp(pattern) {
2696
+ const escaped = pattern.replaceAll(/[.+^${}()|[\]\\]/g, "\\$&").replaceAll("**/", "\0GLOBSTAR_SLASH\0").replaceAll("**", "\0GLOBSTAR\0").replaceAll("*", "[^/]*").replaceAll("?", ".").replaceAll("\0GLOBSTAR_SLASH\0", "(?:.*/)?").replaceAll("\0GLOBSTAR\0", ".*");
2697
+ return new RegExp(`(?:^|/)${escaped}$`, "i");
2698
+ }
2699
+ function matchesPattern2(target, pattern) {
2700
+ const normalized = target.replaceAll("\\", "/");
2701
+ if (pattern instanceof RegExp) return pattern.test(normalized);
2702
+ if (pattern.includes("*") || pattern.includes("?")) {
2703
+ return globToRegExp(pattern).test(normalized);
2704
+ }
2705
+ return normalized.toLowerCase().includes(pattern.toLowerCase());
2706
+ }
2707
+ function filterFlowsForProject(flows, project) {
2708
+ return flows.filter((flowDef) => {
2709
+ const candidatePath = flowDef.sourcePath ?? flowDef.name;
2710
+ if (project.testMatch && project.testMatch.length > 0) {
2711
+ if (!project.testMatch.some((p) => matchesPattern2(candidatePath, p))) {
2712
+ return false;
2713
+ }
2714
+ }
2715
+ if (project.testIgnore && project.testIgnore.length > 0) {
2716
+ if (project.testIgnore.some((p) => matchesPattern2(candidatePath, p))) {
2717
+ return false;
2718
+ }
2719
+ }
2720
+ if (project.tags && project.tags.length > 0) {
2721
+ const flowTags = flowDef.config.tags ?? [];
2722
+ if (!project.tags.some((t) => flowTags.includes(t))) {
2723
+ return false;
2724
+ }
2725
+ }
2726
+ if (project.grep) {
2727
+ if (!flowDef.name.toLowerCase().includes(project.grep.toLowerCase())) {
2728
+ return false;
2729
+ }
2730
+ }
2731
+ if (project.platform && flowDef.config.platforms && flowDef.config.platforms.length > 0) {
2732
+ if (!flowDef.config.platforms.includes(project.platform)) {
2733
+ return false;
2734
+ }
2735
+ }
2736
+ return true;
2737
+ });
2738
+ }
2739
+ function resolveProjectExecutionPlan(projects, selectedNames) {
2740
+ const byName = /* @__PURE__ */ new Map();
2741
+ for (const proj of projects) {
2742
+ if (!proj.name || proj.name.trim().length === 0) {
2743
+ throw new Error("Project name must be a non-empty string.");
2744
+ }
2745
+ if (byName.has(proj.name)) {
2746
+ throw new Error(`Duplicate project name "${proj.name}" in spana config.`);
2747
+ }
2748
+ byName.set(proj.name, proj);
2749
+ }
2750
+ for (const proj of projects) {
2751
+ for (const dep of proj.dependencies ?? []) {
2752
+ if (!byName.has(dep)) {
2753
+ throw new Error(`Project "${proj.name}" depends on unknown project "${dep}".`);
2754
+ }
2755
+ }
2756
+ if (proj.teardown && !byName.has(proj.teardown)) {
2757
+ throw new Error(
2758
+ `Project "${proj.name}" references unknown teardown project "${proj.teardown}".`
2759
+ );
2760
+ }
2761
+ }
2762
+ const teardownNames = /* @__PURE__ */ new Set();
2763
+ for (const proj of projects) {
2764
+ if (proj.teardown) teardownNames.add(proj.teardown);
2765
+ }
2766
+ const activeNames = /* @__PURE__ */ new Set();
2767
+ if (selectedNames && selectedNames.length > 0) {
2768
+ const queue = [...selectedNames];
2769
+ while (queue.length > 0) {
2770
+ const name = queue.shift();
2771
+ const proj = byName.get(name);
2772
+ if (!proj) {
2773
+ const available = projects.map((p) => p.name).join(", ");
2774
+ throw new Error(
2775
+ `Unknown --project "${name}". Available projects: ${available || "(none)"}.`
2776
+ );
2777
+ }
2778
+ if (activeNames.has(name)) continue;
2779
+ activeNames.add(name);
2780
+ for (const dep of proj.dependencies ?? []) {
2781
+ if (!activeNames.has(dep)) queue.push(dep);
2782
+ }
2783
+ }
2784
+ } else {
2785
+ for (const proj of projects) {
2786
+ if (!teardownNames.has(proj.name)) {
2787
+ activeNames.add(proj.name);
2788
+ }
2789
+ }
2790
+ }
2791
+ const inDegree = /* @__PURE__ */ new Map();
2792
+ const dependents = /* @__PURE__ */ new Map();
2793
+ for (const name of activeNames) {
2794
+ inDegree.set(name, 0);
2795
+ dependents.set(name, []);
2796
+ }
2797
+ for (const name of activeNames) {
2798
+ const proj = byName.get(name);
2799
+ for (const dep of proj.dependencies ?? []) {
2800
+ if (!activeNames.has(dep)) continue;
2801
+ inDegree.set(name, (inDegree.get(name) ?? 0) + 1);
2802
+ dependents.get(dep).push(name);
2803
+ }
2804
+ }
2805
+ const waves = [];
2806
+ const ordered = [];
2807
+ let ready = [...activeNames].filter((name) => (inDegree.get(name) ?? 0) === 0);
2808
+ while (ready.length > 0) {
2809
+ const waveProjects = ready.map((name) => byName.get(name));
2810
+ waves.push(waveProjects);
2811
+ ordered.push(...waveProjects);
2812
+ const nextReady = [];
2813
+ for (const name of ready) {
2814
+ for (const child of dependents.get(name) ?? []) {
2815
+ const remaining = (inDegree.get(child) ?? 1) - 1;
2816
+ inDegree.set(child, remaining);
2817
+ if (remaining === 0) {
2818
+ nextReady.push(child);
2819
+ }
2820
+ }
2821
+ }
2822
+ ready = nextReady;
2823
+ }
2824
+ if (ordered.length !== activeNames.size) {
2825
+ const stuck = [...activeNames].filter((n) => !ordered.some((p) => p.name === n));
2826
+ throw new Error(`Circular project dependency detected involving: ${stuck.join(", ")}.`);
2827
+ }
2828
+ const teardowns = [];
2829
+ const seenTeardowns = /* @__PURE__ */ new Set();
2830
+ for (const proj of ordered) {
2831
+ if (proj.teardown && !seenTeardowns.has(proj.teardown)) {
2832
+ seenTeardowns.add(proj.teardown);
2833
+ teardowns.push(byName.get(proj.teardown));
2834
+ }
2835
+ }
2836
+ return { waves, ordered, teardowns };
2837
+ }
2838
+
2839
+ export {
2840
+ withActiveStepRecorder,
2841
+ step,
2842
+ suite,
2843
+ buildRichFlowTrace,
2844
+ renderTraceViewerHtml,
2845
+ writeRichTraceBundle,
2846
+ captureAndroidLogcat,
2847
+ captureIosSimulatorCrashLogs,
2848
+ formatCodeFrame,
2849
+ extractCodeFrame,
2850
+ classifyError,
2851
+ exportFramesToMp4,
2852
+ startCdpScreencastRecorder,
2853
+ startAndroidVideoRecorder,
2854
+ startIosSimulatorVideoRecorder,
2855
+ buildPlaybackTraceFromSteps,
2856
+ executeFlow,
2857
+ orderFlowsLongestFirst,
2858
+ runParallel,
2859
+ DEFAULT_MAX_WORKERS_PER_PROCESS,
2860
+ startSharedFlowQueueServer,
2861
+ createRemoteFlowClaimer,
2862
+ planProcessPool,
2863
+ partitionFlowsAcrossProcesses,
2864
+ writeWorkerProcessReport,
2865
+ runMultiProcessPool,
2866
+ isTcpPortOpen,
2867
+ isHttpUrlReady,
2868
+ checkServerReady,
2869
+ startWebServer,
2870
+ startWebServers,
2871
+ filterFlowsForProject,
2872
+ resolveProjectExecutionPlan
2873
+ };
2874
+ //# sourceMappingURL=chunk-FPQAJNE3.js.map