spana-test 0.0.2 → 0.2.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 (124) hide show
  1. package/.agents/skills/spana-testing/SKILL.md +304 -0
  2. package/README.md +308 -88
  3. package/dist/agent/index.d.ts +110 -0
  4. package/dist/agent/index.js +25 -0
  5. package/dist/allure-PTTVORQ6.js +124 -0
  6. package/dist/allure-PTTVORQ6.js.map +1 -0
  7. package/dist/android-PAPJJWVN.js +34 -0
  8. package/dist/android-PAPJJWVN.js.map +1 -0
  9. package/dist/chunk-3FSZNKEF.js +62 -0
  10. package/dist/chunk-3FSZNKEF.js.map +1 -0
  11. package/dist/chunk-3YR4GUGE.js +249 -0
  12. package/dist/chunk-3YR4GUGE.js.map +1 -0
  13. package/dist/{discover-XIRJTZ7Z.js → chunk-AEKDFFPJ.js} +12 -5
  14. package/dist/{discover-XIRJTZ7Z.js.map → chunk-AEKDFFPJ.js.map} +1 -1
  15. package/dist/chunk-BF37W5EG.js +125 -0
  16. package/dist/chunk-BF37W5EG.js.map +1 -0
  17. package/dist/chunk-DGUM43GV.js +11 -0
  18. package/dist/chunk-DGUM43GV.js.map +1 -0
  19. package/dist/chunk-EXLUY7KT.js +21 -0
  20. package/dist/chunk-EXLUY7KT.js.map +1 -0
  21. package/dist/chunk-FNDOEMOL.js +62 -0
  22. package/dist/chunk-FNDOEMOL.js.map +1 -0
  23. package/dist/{chunk-CYEDLQJ4.js → chunk-GZK22EIE.js} +76 -102
  24. package/dist/chunk-GZK22EIE.js.map +1 -0
  25. package/dist/chunk-HWFDXIXR.js +183 -0
  26. package/dist/chunk-HWFDXIXR.js.map +1 -0
  27. package/dist/chunk-IJIASIX5.js +314 -0
  28. package/dist/chunk-IJIASIX5.js.map +1 -0
  29. package/dist/chunk-KJPHH2TW.js +168 -0
  30. package/dist/chunk-KJPHH2TW.js.map +1 -0
  31. package/dist/chunk-L7MFJF46.js +137 -0
  32. package/dist/chunk-L7MFJF46.js.map +1 -0
  33. package/dist/chunk-MRH7SK52.js +134 -0
  34. package/dist/chunk-MRH7SK52.js.map +1 -0
  35. package/dist/chunk-P7JQRLP4.js +114 -0
  36. package/dist/chunk-P7JQRLP4.js.map +1 -0
  37. package/dist/chunk-S2XNAKSO.js +1087 -0
  38. package/dist/chunk-S2XNAKSO.js.map +1 -0
  39. package/dist/chunk-S4R4OR7T.js +358 -0
  40. package/dist/chunk-S4R4OR7T.js.map +1 -0
  41. package/dist/chunk-SFBRFB2N.js +277 -0
  42. package/dist/chunk-SFBRFB2N.js.map +1 -0
  43. package/dist/chunk-VNYF5BHX.js +494 -0
  44. package/dist/chunk-VNYF5BHX.js.map +1 -0
  45. package/dist/chunk-WBU34APM.js +38 -0
  46. package/dist/chunk-WBU34APM.js.map +1 -0
  47. package/dist/chunk-WQ4GXUUE.js +2402 -0
  48. package/dist/chunk-WQ4GXUUE.js.map +1 -0
  49. package/dist/chunk-YBZCOQXJ.js +311 -0
  50. package/dist/chunk-YBZCOQXJ.js.map +1 -0
  51. package/dist/cli.js +428 -34
  52. package/dist/cli.js.map +1 -1
  53. package/dist/compiler-74VGKZO6.js +312 -0
  54. package/dist/compiler-74VGKZO6.js.map +1 -0
  55. package/dist/config-loader-BJJ3IJJ7.js +9 -0
  56. package/dist/config-loader-BJJ3IJJ7.js.map +1 -0
  57. package/dist/console-XWKUTP3D.js +164 -0
  58. package/dist/console-XWKUTP3D.js.map +1 -0
  59. package/dist/coordinator-BbUjvvnX.d.ts +383 -0
  60. package/dist/discover-KZKXHZZA.js +14 -0
  61. package/dist/discover-KZKXHZZA.js.map +1 -0
  62. package/dist/doctor-command-T2UX5RV5.js +732 -0
  63. package/dist/doctor-command-T2UX5RV5.js.map +1 -0
  64. package/dist/element-DZ0HyJ3C.d.ts +25 -0
  65. package/dist/flow-BUC9Mf8W.d.ts +128 -0
  66. package/dist/gherkin/steps.d.ts +32 -0
  67. package/dist/gherkin/steps.js +39 -0
  68. package/dist/gherkin/steps.js.map +1 -0
  69. package/dist/{html-GRB34S6X.js → html-GE6Q4DCG.js} +76 -22
  70. package/dist/html-GE6Q4DCG.js.map +1 -0
  71. package/dist/index.d.ts +159 -144
  72. package/dist/index.js +39 -165
  73. package/dist/index.js.map +1 -1
  74. package/dist/init-command-GVMRXIMY.js +121 -0
  75. package/dist/init-command-GVMRXIMY.js.map +1 -0
  76. package/dist/init-flow-command-R76AXF4Z.js +34 -0
  77. package/dist/init-flow-command-R76AXF4Z.js.map +1 -0
  78. package/dist/installer-YZJ4DV3F.js +22 -0
  79. package/dist/installer-YZJ4DV3F.js.map +1 -0
  80. package/dist/ios-ZW6XVNLG.js +50 -0
  81. package/dist/ios-ZW6XVNLG.js.map +1 -0
  82. package/dist/json-KS67BZYU.js +39 -0
  83. package/dist/json-KS67BZYU.js.map +1 -0
  84. package/dist/{junit-NAGZJOGQ.js → junit-HLC62MK6.js} +15 -4
  85. package/dist/junit-HLC62MK6.js.map +1 -0
  86. package/dist/provider-A57C3MU6.js +12 -0
  87. package/dist/provider-A57C3MU6.js.map +1 -0
  88. package/dist/redact-U72BUBBR.js +77 -0
  89. package/dist/redact-U72BUBBR.js.map +1 -0
  90. package/dist/runner-UXNHVVGG.js +20 -0
  91. package/dist/runner-UXNHVVGG.js.map +1 -0
  92. package/dist/server-W7OA3DDN.js +530 -0
  93. package/dist/server-W7OA3DDN.js.map +1 -0
  94. package/dist/session-TMNOKYLG.js +17 -0
  95. package/dist/session-TMNOKYLG.js.map +1 -0
  96. package/dist/studio-command-6VHTHDUK.js +24 -0
  97. package/dist/studio-command-6VHTHDUK.js.map +1 -0
  98. package/dist/test-command-AHMOZLV4.js +2852 -0
  99. package/dist/test-command-AHMOZLV4.js.map +1 -0
  100. package/dist/validator-35624P7S.js +20 -0
  101. package/dist/validator-35624P7S.js.map +1 -0
  102. package/package.json +41 -4
  103. package/studio-dist/assets/index-DC6DIXfl.js +188 -0
  104. package/studio-dist/assets/index-DDKsnBwD.css +1 -0
  105. package/studio-dist/index.html +13 -0
  106. package/dist/chunk-CYEDLQJ4.js.map +0 -1
  107. package/dist/chunk-PVNNKPBW.js +0 -64
  108. package/dist/chunk-PVNNKPBW.js.map +0 -1
  109. package/dist/chunk-VZZH66U5.js +0 -1781
  110. package/dist/chunk-VZZH66U5.js.map +0 -1
  111. package/dist/console-GPV3M3PC.js +0 -71
  112. package/dist/console-GPV3M3PC.js.map +0 -1
  113. package/dist/html-GRB34S6X.js.map +0 -1
  114. package/dist/json-FK2NSRGC.js +0 -20
  115. package/dist/json-FK2NSRGC.js.map +0 -1
  116. package/dist/junit-NAGZJOGQ.js.map +0 -1
  117. package/dist/runner-LBQUCG3K.js +0 -12
  118. package/dist/session-U7VP5J2C.js +0 -122
  119. package/dist/session-U7VP5J2C.js.map +0 -1
  120. package/dist/test-command-WPYLJYIK.js +0 -636
  121. package/dist/test-command-WPYLJYIK.js.map +0 -1
  122. package/dist/validator-J4YSBB66.js +0 -33
  123. package/dist/validator-J4YSBB66.js.map +0 -1
  124. /package/dist/{runner-LBQUCG3K.js.map → agent/index.js.map} +0 -0
@@ -0,0 +1,2852 @@
1
+ import {
2
+ collectDiagnosticSections
3
+ } from "./chunk-KJPHH2TW.js";
4
+ import {
5
+ resolveCapabilities
6
+ } from "./chunk-EXLUY7KT.js";
7
+ import {
8
+ loadConfig
9
+ } from "./chunk-P7JQRLP4.js";
10
+ import {
11
+ createPromiseApp,
12
+ createPromiseExpect
13
+ } from "./chunk-YBZCOQXJ.js";
14
+ import "./chunk-L7MFJF46.js";
15
+ import {
16
+ createUiAutomator2Driver,
17
+ createWDADriver,
18
+ makePlaywrightDriver,
19
+ parseAndroidHierarchy,
20
+ parseIOSHierarchy,
21
+ parseWebHierarchy
22
+ } from "./chunk-WQ4GXUUE.js";
23
+ import {
24
+ setupUiAutomator2
25
+ } from "./chunk-BF37W5EG.js";
26
+ import {
27
+ applyShard,
28
+ discoverFlows,
29
+ discoverStepFiles,
30
+ filterFlows,
31
+ loadStepFiles,
32
+ loadTestSource
33
+ } from "./chunk-MRH7SK52.js";
34
+ import {
35
+ DriverError,
36
+ flattenElements,
37
+ splitGraphemes,
38
+ withBufferedDriverLogs
39
+ } from "./chunk-S2XNAKSO.js";
40
+ import {
41
+ failureCategoryToDocsUrl,
42
+ failureCategoryToErrorCode
43
+ } from "./chunk-FNDOEMOL.js";
44
+ import {
45
+ createCloudProviderHelper,
46
+ detectProvider
47
+ } from "./chunk-VNYF5BHX.js";
48
+ import {
49
+ ensureAndroidDevice
50
+ } from "./chunk-GZK22EIE.js";
51
+ import {
52
+ connectPhysicalDevice,
53
+ ensureAppInstalled,
54
+ ensureIOSSimulator,
55
+ firstIOSPhysicalDevice
56
+ } from "./chunk-SFBRFB2N.js";
57
+ import {
58
+ allocatePort,
59
+ setupWDA
60
+ } from "./chunk-3YR4GUGE.js";
61
+ import "./chunk-DGUM43GV.js";
62
+
63
+ // src/cli/test-command.ts
64
+ import { resolve as resolve3, dirname as dirname3 } from "path";
65
+
66
+ // src/core/engine.ts
67
+ import { Effect as Effect3 } from "effect";
68
+
69
+ // src/core/artifacts.ts
70
+ import { writeFileSync, mkdirSync } from "fs";
71
+ import { join } from "path";
72
+ import { Effect } from "effect";
73
+ var DEFAULT_ARTIFACT_CONFIG = {
74
+ outputDir: "./spana-output",
75
+ captureOnFailure: true,
76
+ captureOnSuccess: false,
77
+ captureSteps: false,
78
+ screenshot: true,
79
+ uiHierarchy: true,
80
+ consoleLogs: true,
81
+ jsErrors: true,
82
+ har: true
83
+ };
84
+ function safeName(value) {
85
+ return value.replaceAll(/[^a-zA-Z0-9-_]/g, "_").replaceAll(/_+/g, "_").replaceAll(/^_+|_+$/g, "").slice(0, 80) || "artifact";
86
+ }
87
+ function flowArtifactDir(config, flowName, platform) {
88
+ const dir = join(config.outputDir, `${safeName(flowName)}-${platform}`);
89
+ mkdirSync(dir, { recursive: true });
90
+ return dir;
91
+ }
92
+ function createAttachment(name, contentType, path) {
93
+ return { name, contentType, path };
94
+ }
95
+ function writeJsonAttachment(dir, fileName, attachmentName, value) {
96
+ const path = join(dir, fileName);
97
+ writeFileSync(path, JSON.stringify(value, null, 2), "utf-8");
98
+ return createAttachment(attachmentName, "application/json", path);
99
+ }
100
+ function writeTextAttachment(dir, fileName, attachmentName, value) {
101
+ const path = join(dir, fileName);
102
+ writeFileSync(path, value, "utf-8");
103
+ return createAttachment(attachmentName, "text/plain", path);
104
+ }
105
+ function resolveArtifactConfig(...configs) {
106
+ return configs.reduce(
107
+ (resolved, config) => ({
108
+ ...resolved,
109
+ ...config
110
+ }),
111
+ { ...DEFAULT_ARTIFACT_CONFIG }
112
+ );
113
+ }
114
+ async function captureArtifacts(driver, config, flowName, platform, status) {
115
+ const shouldCapture = status === "failed" && config.captureOnFailure || status === "passed" && config.captureOnSuccess;
116
+ if (!shouldCapture) return [];
117
+ const attachments = [];
118
+ const dir = flowArtifactDir(config, flowName, platform);
119
+ if (config.screenshot) {
120
+ try {
121
+ const screenshot = await Effect.runPromise(Effect.orDie(driver.takeScreenshot()));
122
+ const path = join(dir, "screenshot.png");
123
+ writeFileSync(path, screenshot);
124
+ attachments.push(createAttachment(`${status}-screenshot`, "image/png", path));
125
+ } catch {
126
+ }
127
+ }
128
+ if (config.uiHierarchy) {
129
+ try {
130
+ const hierarchy = await Effect.runPromise(Effect.orDie(driver.dumpHierarchy()));
131
+ const path = join(dir, "hierarchy.json");
132
+ writeFileSync(path, hierarchy, "utf-8");
133
+ attachments.push(createAttachment(`${status}-hierarchy`, "application/json", path));
134
+ } catch {
135
+ }
136
+ }
137
+ if (config.consoleLogs && driver.getConsoleLogs) {
138
+ try {
139
+ const consoleLogs = await Effect.runPromise(Effect.orDie(driver.getConsoleLogs()));
140
+ if (consoleLogs.length > 0) {
141
+ attachments.push(
142
+ writeJsonAttachment(dir, "console-logs.json", `${status}-console-logs`, consoleLogs)
143
+ );
144
+ }
145
+ } catch {
146
+ }
147
+ }
148
+ if (config.jsErrors && driver.getJSErrors) {
149
+ try {
150
+ const jsErrors = await Effect.runPromise(Effect.orDie(driver.getJSErrors()));
151
+ if (jsErrors.length > 0) {
152
+ attachments.push(
153
+ writeJsonAttachment(dir, "js-errors.json", `${status}-js-errors`, jsErrors)
154
+ );
155
+ }
156
+ } catch {
157
+ }
158
+ }
159
+ if (config.har && driver.getHAR) {
160
+ try {
161
+ const har = await Effect.runPromise(Effect.orDie(driver.getHAR()));
162
+ if (har.log.entries.length > 0) {
163
+ attachments.push(writeJsonAttachment(dir, "network.har", `${status}-network-har`, har));
164
+ }
165
+ } catch {
166
+ }
167
+ }
168
+ if (status === "failed" && driver.getDriverLogs) {
169
+ try {
170
+ const driverLogs = await Effect.runPromise(Effect.orDie(driver.getDriverLogs()));
171
+ if (driverLogs.length > 0) {
172
+ attachments.push(
173
+ writeTextAttachment(
174
+ dir,
175
+ "driver-logs.txt",
176
+ `${status}-driver-logs`,
177
+ driverLogs.join("\n")
178
+ )
179
+ );
180
+ }
181
+ } catch {
182
+ }
183
+ }
184
+ return attachments;
185
+ }
186
+ async function captureStepScreenshot(driver, config, flowName, platform, stepIndex, stepName, screenshot) {
187
+ if (!config.screenshot) return void 0;
188
+ try {
189
+ const dir = join(flowArtifactDir(config, flowName, platform), "steps");
190
+ mkdirSync(dir, { recursive: true });
191
+ const fileName = `${String(stepIndex).padStart(3, "0")}-${safeName(stepName)}.png`;
192
+ const path = join(dir, fileName);
193
+ const bytes = screenshot ?? await Effect.runPromise(Effect.orDie(driver.takeScreenshot()));
194
+ writeFileSync(path, bytes);
195
+ return createAttachment(stepName, "image/png", path);
196
+ } catch {
197
+ return void 0;
198
+ }
199
+ }
200
+
201
+ // src/core/debug-repl.ts
202
+ import * as repl from "repl";
203
+ import { Effect as Effect2 } from "effect";
204
+ var didStartDebugRepl = false;
205
+ function toSuggestedSelectors(root) {
206
+ return flattenElements(root).filter((el) => el.visible !== false && (el.id || el.text || el.accessibilityLabel)).map((el) => ({
207
+ suggestedSelector: el.id ? { testID: el.id } : el.accessibilityLabel ? { accessibilityLabel: el.accessibilityLabel } : el.text ? { text: el.text } : "",
208
+ elementType: el.elementType,
209
+ text: el.text,
210
+ accessibilityLabel: el.accessibilityLabel,
211
+ bounds: el.bounds,
212
+ id: el.id
213
+ }));
214
+ }
215
+ async function runDebugReplOnce(context) {
216
+ if (didStartDebugRepl) {
217
+ return false;
218
+ }
219
+ didStartDebugRepl = true;
220
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
221
+ console.log("Skipping debug REPL because stdin/stdout is not interactive.");
222
+ return false;
223
+ }
224
+ const hierarchy = async () => context.parseHierarchy(await Effect2.runPromise(context.driver.dumpHierarchy()));
225
+ const selectors = async () => toSuggestedSelectors(await hierarchy());
226
+ console.log("");
227
+ console.log(`Entering debug REPL for failed flow "${context.flowName}" on ${context.platform}.`);
228
+ console.log(
229
+ "Available bindings: app, expect, driver, platform, flowName, error, hierarchy(), selectors(), help()"
230
+ );
231
+ console.log('Use top-level await for async calls, for example: await app.tap({ text: "Login" })');
232
+ const replServer = repl.start({
233
+ prompt: `spana:${context.platform}> `,
234
+ ignoreUndefined: true,
235
+ useGlobal: false
236
+ });
237
+ replServer.context.app = context.app;
238
+ replServer.context.expect = context.expect;
239
+ replServer.context.driver = context.driver;
240
+ replServer.context.platform = context.platform;
241
+ replServer.context.flowName = context.flowName;
242
+ replServer.context.error = context.error;
243
+ replServer.context.hierarchy = hierarchy;
244
+ replServer.context.selectors = selectors;
245
+ replServer.context.help = () => {
246
+ console.log("app Promise-based app API with auto-waiting");
247
+ console.log("expect Assertion helper, e.g. await expect({ text: 'Done' }).toBeVisible()");
248
+ console.log("driver Raw driver service");
249
+ console.log("hierarchy Async helper returning the parsed UI tree");
250
+ console.log("selectors Async helper returning suggested selectors");
251
+ console.log(".exit Leave the REPL");
252
+ };
253
+ await new Promise((resolve4) => replServer.on("exit", resolve4));
254
+ console.log("");
255
+ return true;
256
+ }
257
+
258
+ // src/core/step-recorder.ts
259
+ function errorMessage(error) {
260
+ return error instanceof Error ? error.message : String(error);
261
+ }
262
+ function createStepResult(command, durationMs, status, selector, error, attachments) {
263
+ return {
264
+ command,
265
+ selector,
266
+ status,
267
+ durationMs,
268
+ error,
269
+ attachments: attachments && attachments.length > 0 ? attachments : void 0
270
+ };
271
+ }
272
+ function createStepRecorder(driver, artifactConfig, flowName, platform) {
273
+ const steps = [];
274
+ return {
275
+ async runStep(command, action, opts) {
276
+ const startedAt = Date.now();
277
+ try {
278
+ const result = await action();
279
+ const attachments = [];
280
+ if (opts?.captureScreenshot && artifactConfig.captureSteps) {
281
+ const attachment = await captureStepScreenshot(
282
+ driver,
283
+ artifactConfig,
284
+ flowName,
285
+ platform,
286
+ steps.length + 1,
287
+ command
288
+ );
289
+ if (attachment) attachments.push(attachment);
290
+ }
291
+ steps.push(
292
+ createStepResult(
293
+ command,
294
+ Date.now() - startedAt,
295
+ "passed",
296
+ opts?.selector,
297
+ void 0,
298
+ attachments
299
+ )
300
+ );
301
+ return result;
302
+ } catch (error) {
303
+ steps.push(
304
+ createStepResult(
305
+ command,
306
+ Date.now() - startedAt,
307
+ "failed",
308
+ opts?.selector,
309
+ errorMessage(error)
310
+ )
311
+ );
312
+ throw error;
313
+ }
314
+ },
315
+ async runScreenshotStep(command, action, opts) {
316
+ const startedAt = Date.now();
317
+ try {
318
+ const screenshot = await action();
319
+ const attachment = await captureStepScreenshot(
320
+ driver,
321
+ artifactConfig,
322
+ flowName,
323
+ platform,
324
+ steps.length + 1,
325
+ opts?.name ?? command,
326
+ screenshot
327
+ );
328
+ steps.push(
329
+ createStepResult(
330
+ command,
331
+ Date.now() - startedAt,
332
+ "passed",
333
+ opts?.selector,
334
+ void 0,
335
+ attachment ? [attachment] : void 0
336
+ )
337
+ );
338
+ return screenshot;
339
+ } catch (error) {
340
+ steps.push(
341
+ createStepResult(
342
+ command,
343
+ Date.now() - startedAt,
344
+ "failed",
345
+ opts?.selector,
346
+ errorMessage(error)
347
+ )
348
+ );
349
+ throw error;
350
+ }
351
+ },
352
+ getSteps() {
353
+ return steps;
354
+ }
355
+ };
356
+ }
357
+
358
+ // src/report/classify-error.ts
359
+ var TAG_KEY = "_tag";
360
+ function selectorHint(selector) {
361
+ if (selector && typeof selector === "object") {
362
+ const s = selector;
363
+ if (s.testID) return `testID="${s.testID}"`;
364
+ if (s.text) return `text="${s.text}"`;
365
+ if (s.accessibilityLabel) return `accessibilityLabel="${s.accessibilityLabel}"`;
366
+ }
367
+ return JSON.stringify(selector);
368
+ }
369
+ function categorizeElementFailure(message) {
370
+ const lower = message.toLowerCase();
371
+ if (lower.includes("not visible") || lower.includes("visible=false")) {
372
+ return "element-not-visible";
373
+ }
374
+ if (lower.includes("off-screen") || lower.includes("zero size")) {
375
+ return "element-off-screen";
376
+ }
377
+ if (lower.includes("disabled") || lower.includes("not interactive")) {
378
+ return "element-not-interactive";
379
+ }
380
+ return "element-not-found";
381
+ }
382
+ function elementSuggestion(category, selector, timeoutMs) {
383
+ switch (category) {
384
+ case "element-not-visible":
385
+ return [
386
+ `Selector ${selector} matched an element, but it is currently hidden.`,
387
+ "Check whether an animation, modal, or loading state is covering it before retrying.",
388
+ "Consider increasing waitTimeout if the element becomes visible after a delay."
389
+ ].join("\n");
390
+ case "element-off-screen":
391
+ return [
392
+ `Selector ${selector} matched an element that is off-screen.`,
393
+ "Use scrollUntilVisible() or scroll to the element before interacting with it.",
394
+ "If the target is above the current viewport, reverse the search direction."
395
+ ].join("\n");
396
+ case "element-not-interactive":
397
+ return [
398
+ `Selector ${selector} matched an element that is disabled or not interactive.`,
399
+ "Wait for the app to enable it, or verify the prerequisite app state first.",
400
+ "Consider increasing waitTimeout if the control becomes enabled after async work completes."
401
+ ].join("\n");
402
+ default:
403
+ return [
404
+ `Selector ${selector} was not found within ${timeoutMs ?? "?"}ms.`,
405
+ "Run `spana selectors` to inspect the current screen and confirm the best selector.",
406
+ "Consider increasing waitTimeout if the element appears after a delay."
407
+ ].join("\n");
408
+ }
409
+ }
410
+ function categorizeDynamic(error, tag, msg) {
411
+ if (tag === "ElementNotFoundError" || tag === "WaitTimeoutError") {
412
+ const sel = selectorHint(error.selector);
413
+ if (msg.includes("scroll(s) toward")) {
414
+ return {
415
+ category: "element-not-found",
416
+ suggestion: [
417
+ `Selector ${sel} stayed off-screen while scrolling.`,
418
+ "Try increasing `maxScrolls` or `timeout`, or reverse the search direction",
419
+ 'if the target is actually above the current viewport (for example `{ direction: "up" }`).'
420
+ ].join("\n")
421
+ };
422
+ }
423
+ if (msg.includes("back action(s)")) {
424
+ return {
425
+ category: "element-not-found",
426
+ suggestion: [
427
+ `Selector ${sel} was not reached while navigating back.`,
428
+ "Try increasing `maxBacks` or `timeout`, or prefer an explicit in-app",
429
+ "back / close control on iOS-style screens instead of relying on system back."
430
+ ].join("\n")
431
+ };
432
+ }
433
+ const category = categorizeElementFailure(msg);
434
+ return {
435
+ category,
436
+ suggestion: elementSuggestion(category, sel, error.timeoutMs)
437
+ };
438
+ }
439
+ if (tag === "TextMismatchError") {
440
+ const e = error;
441
+ return {
442
+ category: "text-mismatch",
443
+ suggestion: [
444
+ `Expected text "${e.expected}" but found "${e.actual ?? "(empty)"}".`,
445
+ "The element exists but its content differs. Check for whitespace, truncation,",
446
+ "or platform-specific text rendering differences."
447
+ ].join("\n")
448
+ };
449
+ }
450
+ if (tag === "DeviceDisconnectedError") {
451
+ const id = error.deviceId ? ` (${error.deviceId})` : "";
452
+ return {
453
+ category: "device-disconnected",
454
+ suggestion: [
455
+ `The device${id} disconnected during the test.`,
456
+ "Check the physical connection or emulator/simulator stability.",
457
+ "Run `spana devices` to verify available devices."
458
+ ].join("\n")
459
+ };
460
+ }
461
+ if (tag === "AppCrashedError") {
462
+ const app = error.appId ? ` (${error.appId})` : "";
463
+ return {
464
+ category: "app-crashed",
465
+ suggestion: [
466
+ `The app${app} crashed during the test.`,
467
+ "Check the device logs for a crash stack trace:",
468
+ " Android: `adb logcat -d | grep FATAL`",
469
+ " iOS: Check Console.app or `log show --predicate 'process == \"your-app\"'`"
470
+ ].join("\n")
471
+ };
472
+ }
473
+ if (tag === "AppNotInstalledError") {
474
+ return {
475
+ category: "app-not-installed",
476
+ suggestion: [
477
+ `App "${error.appId}" is not installed on the device.`,
478
+ "Install it before running tests, or configure `apps.android.appPath`",
479
+ "/ `apps.ios.appPath` in spana.config.ts for auto-install."
480
+ ].join("\n")
481
+ };
482
+ }
483
+ if (tag === "DriverError") {
484
+ return categorizeDynamicDriver(error, msg);
485
+ }
486
+ return void 0;
487
+ }
488
+ function categorizeDynamicDriver(error, msg) {
489
+ for (const rule of driverRules) {
490
+ if (rule.pattern && matchesPattern(msg, rule.pattern)) {
491
+ return {
492
+ category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
493
+ suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
494
+ };
495
+ }
496
+ }
497
+ return {
498
+ category: "driver-error",
499
+ 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."
500
+ };
501
+ }
502
+ var driverRules = [
503
+ {
504
+ pattern: "dismissKeyboard()",
505
+ category: "driver-error",
506
+ suggestion: [
507
+ "Keyboard dismissal failed.",
508
+ 'On Android, try `app.dismissKeyboard({ strategy: "back" })`.',
509
+ "On iOS, prefer tapping a visible Done / Close control or a non-input element."
510
+ ].join("\n")
511
+ },
512
+ {
513
+ pattern: "backUntilVisible()",
514
+ category: "driver-error",
515
+ suggestion: [
516
+ "System back navigation failed before the target screen became visible.",
517
+ "If this route uses app-level navigation, tap the visible back / close control instead.",
518
+ "This is especially common on iOS where a system back button may not exist."
519
+ ].join("\n")
520
+ },
521
+ {
522
+ pattern: "Input text failed",
523
+ category: "driver-error",
524
+ suggestion: [
525
+ "Text input failed at the driver layer.",
526
+ "Make sure the field is focused first, and retry with shorter input chunks if needed.",
527
+ "If the keyboard is in the way, dismiss it before continuing the flow."
528
+ ].join("\n")
529
+ }
530
+ ];
531
+ var tagOnlyRules = [
532
+ {
533
+ tag: "TimeoutError",
534
+ category: "timeout",
535
+ suggestion: [
536
+ "The operation took longer than the allowed timeout.",
537
+ "Try increasing `defaults.waitTimeout` in spana.config.ts,",
538
+ "or set a per-flow timeout: `flow('name', { timeout: 30000 }, ...)`."
539
+ ].join("\n")
540
+ },
541
+ {
542
+ tag: ["ConfigError", "FlowSyntaxError"],
543
+ category: "config-error",
544
+ suggestion: "Run `spana validate-config` to check your configuration."
545
+ }
546
+ ];
547
+ var heuristicRules = [
548
+ {
549
+ pattern: /[Tt]imed out/,
550
+ category: "timeout",
551
+ suggestion: "The operation timed out. Try increasing `defaults.waitTimeout` in spana.config.ts."
552
+ },
553
+ {
554
+ pattern: /not found|not visible/,
555
+ category: (msg) => categorizeElementFailure(msg),
556
+ suggestion: (_error, msg) => {
557
+ if (msg.includes("scroll(s) toward")) {
558
+ return "The target stayed off-screen while scrolling. Increase `maxScrolls` / `timeout`, or reverse the scroll search direction.";
559
+ }
560
+ const category = categorizeElementFailure(msg);
561
+ return elementSuggestion(category, "the target selector", void 0);
562
+ }
563
+ },
564
+ {
565
+ pattern: "dismissKeyboard()",
566
+ category: "driver-error",
567
+ suggestion: 'Keyboard dismissal failed. On Android try `app.dismissKeyboard({ strategy: "back" })`; on iOS prefer an explicit Done / Close control.'
568
+ },
569
+ {
570
+ pattern: /ECONNREFUSED|ECONNRESET|disconnected/,
571
+ category: "device-disconnected",
572
+ suggestion: "The connection was lost. Check the device or emulator/simulator is still running."
573
+ }
574
+ ];
575
+ function matchesPattern(msg, pattern) {
576
+ return typeof pattern === "string" ? msg.includes(pattern) : pattern.test(msg);
577
+ }
578
+ function matchesTag(tag, rule) {
579
+ if (!rule.tag) return true;
580
+ if (Array.isArray(rule.tag)) return tag != null && rule.tag.includes(tag);
581
+ return tag === rule.tag;
582
+ }
583
+ function categorize(error) {
584
+ const tag = error[TAG_KEY];
585
+ const msg = error.message ?? "";
586
+ const dynamic = categorizeDynamic(error, tag, msg);
587
+ if (dynamic) return dynamic;
588
+ for (const rule of tagOnlyRules) {
589
+ if (matchesTag(tag, rule)) {
590
+ return {
591
+ category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
592
+ suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
593
+ };
594
+ }
595
+ }
596
+ for (const rule of heuristicRules) {
597
+ if (rule.pattern && matchesPattern(msg, rule.pattern)) {
598
+ return {
599
+ category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
600
+ suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
601
+ };
602
+ }
603
+ }
604
+ return { category: "unknown" };
605
+ }
606
+ function classifyError(error) {
607
+ const tagged = error;
608
+ const { category, suggestion } = categorize(tagged);
609
+ return {
610
+ message: error.message,
611
+ stack: error.stack,
612
+ category,
613
+ errorCode: failureCategoryToErrorCode(category),
614
+ suggestion,
615
+ suggestedFix: suggestion,
616
+ docsUrl: failureCategoryToDocsUrl(category)
617
+ };
618
+ }
619
+
620
+ // src/core/engine.ts
621
+ async function executeFlow(flow, driver, config) {
622
+ const start2 = Date.now();
623
+ const { platform, coordinatorConfig, appId } = config;
624
+ const autoLaunch = flow.config.autoLaunch ?? config.autoLaunch ?? true;
625
+ const timeout = flow.config.timeout ?? config.flowTimeout ?? 6e4;
626
+ const artifactConfig = resolveArtifactConfig(config.artifactConfig, flow.config.artifacts);
627
+ const stepRecorder = createStepRecorder(driver, artifactConfig, flow.name, platform);
628
+ const flowDefaults = flow.config.defaults;
629
+ const mergedCoordinatorConfig = flowDefaults ? {
630
+ ...coordinatorConfig,
631
+ defaults: {
632
+ ...coordinatorConfig.defaults,
633
+ timeout: flowDefaults.waitTimeout ?? coordinatorConfig.defaults?.timeout,
634
+ pollInterval: flowDefaults.pollInterval ?? coordinatorConfig.defaults?.pollInterval,
635
+ settleTimeout: flowDefaults.settleTimeout ?? coordinatorConfig.defaults?.settleTimeout,
636
+ initialPollInterval: flowDefaults.initialPollInterval ?? coordinatorConfig.defaults?.initialPollInterval
637
+ },
638
+ waitForIdleTimeout: flowDefaults.waitForIdleTimeout ?? coordinatorConfig.waitForIdleTimeout,
639
+ typingDelay: flowDefaults.typingDelay ?? coordinatorConfig.typingDelay,
640
+ hierarchyCacheTtl: flowDefaults.hierarchyCacheTtl ?? coordinatorConfig.hierarchyCacheTtl
641
+ } : coordinatorConfig;
642
+ const app = createPromiseApp(driver, appId, mergedCoordinatorConfig, stepRecorder);
643
+ const expect = createPromiseExpect(driver, mergedCoordinatorConfig, stepRecorder);
644
+ const flowCtx = { app, expect, platform };
645
+ const buildFailureResult = async (error) => {
646
+ const attachments = await captureArtifacts(driver, artifactConfig, flow.name, platform, "failed");
647
+ const normalized = error instanceof Error ? error : new Error(String(error));
648
+ return {
649
+ name: flow.name,
650
+ platform,
651
+ status: "failed",
652
+ durationMs: Date.now() - start2,
653
+ error: classifyError(normalized),
654
+ attachments,
655
+ steps: stepRecorder.getSteps(),
656
+ scenarioSteps: flowCtx.__scenarioSteps
657
+ };
658
+ };
659
+ if (driver.beginFlow) {
660
+ try {
661
+ await Effect3.runPromise(driver.beginFlow(flow.name));
662
+ } catch (error) {
663
+ return buildFailureResult(error);
664
+ }
665
+ }
666
+ if (config.hooks?.beforeEach) {
667
+ try {
668
+ await config.hooks.beforeEach({ app, platform });
669
+ } catch (error) {
670
+ return buildFailureResult(error);
671
+ }
672
+ }
673
+ let result;
674
+ try {
675
+ if (autoLaunch) {
676
+ await app.launch(config.launchOptions);
677
+ }
678
+ await Promise.race([
679
+ flow.fn(flowCtx),
680
+ new Promise(
681
+ (_, reject) => setTimeout(
682
+ () => reject(new Error(`Flow "${flow.name}" timed out after ${timeout}ms`)),
683
+ timeout
684
+ )
685
+ )
686
+ ]);
687
+ const attachments = await captureArtifacts(
688
+ driver,
689
+ artifactConfig,
690
+ flow.name,
691
+ platform,
692
+ "passed"
693
+ );
694
+ result = {
695
+ name: flow.name,
696
+ platform,
697
+ status: "passed",
698
+ durationMs: Date.now() - start2,
699
+ attachments,
700
+ steps: stepRecorder.getSteps(),
701
+ scenarioSteps: flowCtx.__scenarioSteps
702
+ };
703
+ } catch (error) {
704
+ const attachments = await captureArtifacts(
705
+ driver,
706
+ artifactConfig,
707
+ flow.name,
708
+ platform,
709
+ "failed"
710
+ );
711
+ const flowError = error instanceof Error ? error : new Error(String(error));
712
+ result = {
713
+ name: flow.name,
714
+ platform,
715
+ status: "failed",
716
+ durationMs: Date.now() - start2,
717
+ error: classifyError(flowError),
718
+ attachments,
719
+ steps: stepRecorder.getSteps(),
720
+ scenarioSteps: flowCtx.__scenarioSteps
721
+ };
722
+ if (config.debugOnFailure) {
723
+ await runDebugReplOnce({
724
+ app,
725
+ expect,
726
+ driver,
727
+ error: flowError,
728
+ flowName: flow.name,
729
+ platform,
730
+ parseHierarchy: coordinatorConfig.parse
731
+ });
732
+ }
733
+ }
734
+ if (config.hooks?.afterEach) {
735
+ try {
736
+ await config.hooks.afterEach({ app, platform, result });
737
+ } catch (hookError) {
738
+ console.warn(
739
+ `afterEach hook failed: ${hookError instanceof Error ? hookError.message : hookError}`
740
+ );
741
+ }
742
+ }
743
+ return result;
744
+ }
745
+
746
+ // src/core/parallel.ts
747
+ async function runParallel(config) {
748
+ const { workers, flows, onFlowComplete, onFlowStart, retries = 0, retryDelay = 0, bail } = config;
749
+ const start2 = Date.now();
750
+ const results = [];
751
+ let nextFlowIndex = 0;
752
+ let failureCount = 0;
753
+ let bailedOut = false;
754
+ const workerPromises = workers.map(async (worker) => {
755
+ const stats = { flowCount: 0, totalMs: 0 };
756
+ while (true) {
757
+ if (bail !== void 0 && failureCount >= bail) break;
758
+ const flowIdx = nextFlowIndex++;
759
+ if (flowIdx >= flows.length) break;
760
+ const flow = flows[flowIdx];
761
+ let result;
762
+ let attempts = 0;
763
+ onFlowStart?.(flow.name, worker.name);
764
+ for (let attempt = 0; attempt <= retries; attempt++) {
765
+ if (attempt > 0 && retryDelay > 0) {
766
+ await new Promise((resolve4) => setTimeout(resolve4, retryDelay));
767
+ }
768
+ result = await executeFlow(flow, worker.driver, worker.engineConfig);
769
+ attempts++;
770
+ if (result.status === "passed") break;
771
+ }
772
+ if (result.status === "passed" && attempts > 1) {
773
+ result.flaky = true;
774
+ }
775
+ result.attempts = attempts;
776
+ results.push(result);
777
+ stats.flowCount++;
778
+ stats.totalMs += result.durationMs;
779
+ if (result.status === "failed") {
780
+ failureCount++;
781
+ }
782
+ onFlowComplete?.(result, worker.name);
783
+ }
784
+ return { workerId: worker.id, stats };
785
+ });
786
+ const workerResults = await Promise.all(workerPromises);
787
+ if (bail !== void 0 && failureCount >= bail) {
788
+ bailedOut = true;
789
+ while (nextFlowIndex < flows.length) {
790
+ const flow = flows[nextFlowIndex++];
791
+ results.push({
792
+ name: flow.name,
793
+ platform: workers[0].engineConfig.platform,
794
+ status: "skipped",
795
+ durationMs: 0,
796
+ attempts: 0
797
+ });
798
+ }
799
+ }
800
+ const workerStats = /* @__PURE__ */ new Map();
801
+ for (const wr of workerResults) {
802
+ workerStats.set(wr.workerId, wr.stats);
803
+ }
804
+ return {
805
+ results,
806
+ totalDurationMs: Date.now() - start2,
807
+ passed: results.filter((r) => r.status === "passed").length,
808
+ failed: results.filter((r) => r.status === "failed").length,
809
+ skipped: results.filter((r) => r.status === "skipped").length,
810
+ flaky: results.filter((r) => r.flaky === true).length,
811
+ bailedOut: bailedOut || void 0,
812
+ workerStats
813
+ };
814
+ }
815
+
816
+ // src/core/orchestrator.ts
817
+ async function sleep(ms) {
818
+ if (ms <= 0) return;
819
+ return new Promise((resolve4) => setTimeout(resolve4, ms));
820
+ }
821
+ async function runPlatform(flows, platformConfig, options, shouldBail, noteFailure) {
822
+ const { platform, driver, engineConfig } = platformConfig;
823
+ const retries = options?.retries ?? 0;
824
+ const retryDelay = options?.retryDelay ?? 0;
825
+ const results = [];
826
+ const platformFlows = flows.filter((f) => {
827
+ const fp = f.config.platforms;
828
+ return !fp || fp.includes(platform);
829
+ });
830
+ if (shouldBail()) {
831
+ for (const flow of platformFlows) {
832
+ results.push({ name: flow.name, platform, status: "skipped", durationMs: 0 });
833
+ }
834
+ return { results };
835
+ }
836
+ const hooks = engineConfig.hooks;
837
+ if (hooks?.beforeAll) {
838
+ try {
839
+ await hooks.beforeAll({ app: void 0, platform });
840
+ } catch (error) {
841
+ for (const flow of platformFlows) {
842
+ results.push({
843
+ name: flow.name,
844
+ platform,
845
+ status: "failed",
846
+ durationMs: 0,
847
+ error: classifyError(error instanceof Error ? error : new Error(String(error)))
848
+ });
849
+ }
850
+ noteFailure(platformFlows.length);
851
+ return { results };
852
+ }
853
+ }
854
+ if (platformConfig.additionalWorkers && platformConfig.additionalWorkers.length > 0) {
855
+ const allWorkers = [
856
+ {
857
+ id: `${platform}-primary`,
858
+ name: platform,
859
+ driver,
860
+ engineConfig
861
+ },
862
+ ...platformConfig.additionalWorkers
863
+ ];
864
+ const parallelResult = await runParallel({
865
+ workers: allWorkers,
866
+ flows: platformFlows,
867
+ retries: options?.retries ?? 0,
868
+ retryDelay: options?.retryDelay ?? 0,
869
+ bail: options?.bail,
870
+ onFlowStart: (name, workerName) => {
871
+ options?.onFlowStart?.(name, platform, workerName);
872
+ },
873
+ onFlowComplete: (result, workerName) => {
874
+ const resultWithWorker = { ...result, workerName };
875
+ options?.onResult?.(resultWithWorker);
876
+ if (result.status === "failed") noteFailure();
877
+ }
878
+ });
879
+ if (hooks?.afterAll) {
880
+ try {
881
+ await hooks.afterAll({
882
+ app: void 0,
883
+ platform,
884
+ summary: { results: parallelResult.results }
885
+ });
886
+ } catch (hookError) {
887
+ console.warn(
888
+ `afterAll hook failed: ${hookError instanceof Error ? hookError.message : hookError}`
889
+ );
890
+ }
891
+ }
892
+ return { results: parallelResult.results, workerStats: parallelResult.workerStats };
893
+ }
894
+ for (let index = 0; index < platformFlows.length; index++) {
895
+ const flow = platformFlows[index];
896
+ if (shouldBail()) {
897
+ for (const skippedFlow of platformFlows.slice(index)) {
898
+ results.push({ name: skippedFlow.name, platform, status: "skipped", durationMs: 0 });
899
+ }
900
+ break;
901
+ }
902
+ options?.onFlowStart?.(flow.name, platform);
903
+ let result = await executeFlow(flow, driver, engineConfig);
904
+ let attempts = 1;
905
+ if (result.status === "failed" && retries > 0) {
906
+ for (let retry = 0; retry < retries; retry++) {
907
+ if (shouldBail()) break;
908
+ await sleep(retryDelay);
909
+ const retryResult = await executeFlow(flow, driver, engineConfig);
910
+ attempts++;
911
+ if (retryResult.status === "passed") {
912
+ result = { ...retryResult, flaky: true, attempts };
913
+ break;
914
+ }
915
+ result = { ...retryResult, attempts };
916
+ }
917
+ if (result.status === "failed") {
918
+ result = { ...result, attempts };
919
+ }
920
+ }
921
+ results.push(result);
922
+ options?.onResult?.(result);
923
+ if (result.status === "failed") {
924
+ noteFailure();
925
+ }
926
+ }
927
+ if (hooks?.afterAll) {
928
+ try {
929
+ await hooks.afterAll({ app: void 0, platform, summary: { results } });
930
+ } catch (hookError) {
931
+ console.warn(
932
+ `afterAll hook failed: ${hookError instanceof Error ? hookError.message : hookError}`
933
+ );
934
+ }
935
+ }
936
+ return { results };
937
+ }
938
+ async function orchestrate(flows, platforms, options) {
939
+ const start2 = Date.now();
940
+ const bail = options?.bail;
941
+ let failureCount = 0;
942
+ let bailedOut = false;
943
+ const shouldBail = () => {
944
+ if (bail !== void 0 && failureCount >= bail) {
945
+ bailedOut = true;
946
+ return true;
947
+ }
948
+ return false;
949
+ };
950
+ const noteFailure = (count = 1) => {
951
+ failureCount += count;
952
+ };
953
+ let platformResults;
954
+ if (options?.parallelPlatforms && platforms.length > 1) {
955
+ platformResults = await Promise.all(
956
+ platforms.map((pc) => runPlatform(flows, pc, options, shouldBail, noteFailure))
957
+ );
958
+ } else {
959
+ platformResults = [];
960
+ for (const pc of platforms) {
961
+ const pr = await runPlatform(flows, pc, options, shouldBail, noteFailure);
962
+ platformResults.push(pr);
963
+ }
964
+ }
965
+ const allResults = platformResults.flatMap((pr) => pr.results);
966
+ const allWorkerStats = /* @__PURE__ */ new Map();
967
+ for (const pr of platformResults) {
968
+ if (pr.workerStats) {
969
+ for (const [id, stats] of pr.workerStats) {
970
+ allWorkerStats.set(id, stats);
971
+ }
972
+ }
973
+ }
974
+ return {
975
+ results: allResults,
976
+ totalDurationMs: Date.now() - start2,
977
+ passed: allResults.filter((r) => r.status === "passed").length,
978
+ failed: allResults.filter((r) => r.status === "failed").length,
979
+ skipped: allResults.filter((r) => r.status === "skipped").length,
980
+ flaky: allResults.filter((r) => r.flaky).length,
981
+ bailedOut,
982
+ bailLimit: bail,
983
+ workerStats: allWorkerStats.size > 0 ? allWorkerStats : void 0
984
+ };
985
+ }
986
+
987
+ // src/runtime/local.ts
988
+ import { Effect as Effect4 } from "effect";
989
+ async function safeCleanup(...fns) {
990
+ for (const fn of fns) {
991
+ try {
992
+ await fn();
993
+ } catch {
994
+ }
995
+ }
996
+ }
997
+ function buildEngineConfig(appId, platform, parseFn, config) {
998
+ return {
999
+ appId,
1000
+ platform,
1001
+ coordinatorConfig: {
1002
+ parse: parseFn,
1003
+ defaults: {
1004
+ timeout: config.defaults?.waitTimeout,
1005
+ pollInterval: config.defaults?.pollInterval
1006
+ },
1007
+ waitForIdleTimeout: config.defaults?.waitForIdleTimeout,
1008
+ typingDelay: config.defaults?.typingDelay
1009
+ },
1010
+ autoLaunch: true,
1011
+ flowTimeout: config.defaults?.waitTimeout ? config.defaults.waitTimeout * 10 : 6e4,
1012
+ artifactConfig: config.artifacts,
1013
+ launchOptions: config.launchOptions,
1014
+ hooks: config.hooks
1015
+ };
1016
+ }
1017
+ async function buildWebRuntime(config) {
1018
+ const webUrl = config.apps?.web?.url ?? "http://localhost:3000";
1019
+ const webExecution = config.execution?.web;
1020
+ const rawDriver = await Effect4.runPromise(
1021
+ makePlaywrightDriver({
1022
+ browser: webExecution?.browser,
1023
+ headless: webExecution?.headless ?? true,
1024
+ baseUrl: webUrl,
1025
+ storageState: webExecution?.storageState,
1026
+ verboseLogging: webExecution?.verboseLogging
1027
+ })
1028
+ );
1029
+ const driver = withBufferedDriverLogs(rawDriver);
1030
+ return {
1031
+ runtime: {
1032
+ driver,
1033
+ cleanup: () => safeCleanup(() => Effect4.runPromise(driver.killApp(""))),
1034
+ metadata: {
1035
+ platform: "web",
1036
+ mode: "local"
1037
+ }
1038
+ },
1039
+ engineConfig: buildEngineConfig(webUrl, "web", parseWebHierarchy, config)
1040
+ };
1041
+ }
1042
+ async function buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig) {
1043
+ const device = targetDevice?.platform === "android" ? {
1044
+ serial: targetDevice.id,
1045
+ state: "device",
1046
+ type: targetDevice.type
1047
+ } : ensureAndroidDevice();
1048
+ if (!device) {
1049
+ console.log("No Android device/emulator available. Skipping android platform.");
1050
+ return null;
1051
+ }
1052
+ const packageName = config.apps?.android?.packageName ?? "";
1053
+ const androidAppPath = config.apps?.android?.appPath;
1054
+ if (androidAppPath && packageName) {
1055
+ try {
1056
+ const { adbShell, adbInstall } = await import("./android-PAPJJWVN.js");
1057
+ const output = adbShell(device.serial, `pm list packages ${packageName}`);
1058
+ if (!output.includes(packageName)) {
1059
+ console.log(`Installing ${packageName} on Android device...`);
1060
+ adbInstall(device.serial, resolveFromConfig(androidAppPath));
1061
+ }
1062
+ } catch {
1063
+ console.log(`Installing ${packageName} on Android device...`);
1064
+ const { adbInstall } = await import("./android-PAPJJWVN.js");
1065
+ adbInstall(device.serial, resolveFromConfig(androidAppPath));
1066
+ }
1067
+ }
1068
+ const hostPort = allocatePort(8200);
1069
+ try {
1070
+ const conn = await setupUiAutomator2(device.serial, hostPort);
1071
+ const rawDriver = await Effect4.runPromise(
1072
+ createUiAutomator2Driver(conn.host, conn.port, device.serial, packageName)
1073
+ );
1074
+ const driver = withBufferedDriverLogs(rawDriver);
1075
+ return {
1076
+ runtime: {
1077
+ driver,
1078
+ cleanup: () => safeCleanup(
1079
+ () => Effect4.runPromise(driver.killApp("")),
1080
+ () => conn.cleanup?.() ?? Promise.resolve()
1081
+ ),
1082
+ metadata: {
1083
+ platform: "android",
1084
+ mode: "local",
1085
+ deviceId: device.serial
1086
+ }
1087
+ },
1088
+ engineConfig: buildEngineConfig(packageName, "android", parseAndroidHierarchy, config)
1089
+ };
1090
+ } catch (e) {
1091
+ console.log(`Android setup failed on ${device.serial}: ${e instanceof Error ? e.message : e}`);
1092
+ return null;
1093
+ }
1094
+ }
1095
+ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
1096
+ const bundleId = config.apps?.ios?.bundleId ?? "";
1097
+ const iosAppPath = config.apps?.ios?.appPath;
1098
+ if (targetDevice?.platform === "ios" && targetDevice.type === "simulator") {
1099
+ if (iosAppPath && bundleId) {
1100
+ ensureAppInstalled({
1101
+ udid: targetDevice.id,
1102
+ bundleId,
1103
+ appPath: resolveFromConfig(iosAppPath),
1104
+ isPhysicalDevice: false
1105
+ });
1106
+ }
1107
+ const wdaPort2 = allocatePort(8100);
1108
+ try {
1109
+ const conn = await setupWDA(targetDevice.id, wdaPort2);
1110
+ const rawDriver = await Effect4.runPromise(
1111
+ createWDADriver(conn.host, conn.port, bundleId, targetDevice.id)
1112
+ );
1113
+ const driver = withBufferedDriverLogs(rawDriver);
1114
+ return {
1115
+ runtime: {
1116
+ driver,
1117
+ cleanup: () => safeCleanup(
1118
+ () => Effect4.runPromise(driver.killApp("")),
1119
+ () => conn.cleanup?.() ?? Promise.resolve()
1120
+ ),
1121
+ metadata: {
1122
+ platform: "ios",
1123
+ mode: "local",
1124
+ deviceId: targetDevice.id
1125
+ }
1126
+ },
1127
+ engineConfig: buildEngineConfig(bundleId, "ios", parseIOSHierarchy, config)
1128
+ };
1129
+ } catch (e) {
1130
+ console.log(
1131
+ `iOS setup failed for device ${targetDevice.id}: ${e instanceof Error ? e.message : e}`
1132
+ );
1133
+ return null;
1134
+ }
1135
+ }
1136
+ const physicalDevice = firstIOSPhysicalDevice();
1137
+ const signing = config.apps?.ios?.signing;
1138
+ if (physicalDevice) {
1139
+ let conn;
1140
+ try {
1141
+ console.log(`Found physical iOS device: ${physicalDevice.name} (${physicalDevice.udid})`);
1142
+ if (iosAppPath && bundleId) {
1143
+ ensureAppInstalled({
1144
+ udid: physicalDevice.udid,
1145
+ bundleId,
1146
+ appPath: resolveFromConfig(iosAppPath),
1147
+ isPhysicalDevice: true
1148
+ });
1149
+ }
1150
+ if (signing?.teamId) {
1151
+ const { setupWDAForDevice } = await import("./installer-YZJ4DV3F.js");
1152
+ const wdaPort2 = allocatePort(8100);
1153
+ conn = await setupWDAForDevice(
1154
+ physicalDevice.udid,
1155
+ wdaPort2,
1156
+ signing.teamId,
1157
+ signing.signingIdentity
1158
+ );
1159
+ } else {
1160
+ conn = connectPhysicalDevice(physicalDevice.udid);
1161
+ }
1162
+ const activeConn = conn;
1163
+ const rawDriver = await Effect4.runPromise(
1164
+ createWDADriver(activeConn.host, activeConn.port, bundleId)
1165
+ );
1166
+ const driver = withBufferedDriverLogs(rawDriver);
1167
+ return {
1168
+ runtime: {
1169
+ driver,
1170
+ cleanup: () => safeCleanup(
1171
+ () => Effect4.runPromise(driver.killApp("")),
1172
+ () => activeConn.cleanup?.() ?? Promise.resolve()
1173
+ ),
1174
+ metadata: {
1175
+ platform: "ios",
1176
+ mode: "local",
1177
+ deviceId: physicalDevice.udid
1178
+ }
1179
+ },
1180
+ engineConfig: buildEngineConfig(bundleId, "ios", parseIOSHierarchy, config)
1181
+ };
1182
+ } catch (e) {
1183
+ if (conn?.cleanup) {
1184
+ try {
1185
+ await conn.cleanup();
1186
+ } catch (cleanupError) {
1187
+ console.warn(
1188
+ `Failed to clean up physical device tunnel: ${cleanupError instanceof Error ? cleanupError.message : cleanupError}`
1189
+ );
1190
+ }
1191
+ }
1192
+ console.log(
1193
+ `Physical device setup failed (${physicalDevice.name}): ${e instanceof Error ? e.message : e}. Falling back to simulator.`
1194
+ );
1195
+ }
1196
+ }
1197
+ const simulator = ensureIOSSimulator(bundleId);
1198
+ if (!simulator) {
1199
+ console.log("No iOS simulator or physical device available. Skipping ios platform.");
1200
+ return null;
1201
+ }
1202
+ if (iosAppPath && bundleId) {
1203
+ ensureAppInstalled({
1204
+ udid: simulator.udid,
1205
+ bundleId,
1206
+ appPath: resolveFromConfig(iosAppPath),
1207
+ isPhysicalDevice: false
1208
+ });
1209
+ }
1210
+ const wdaPort = allocatePort(8100);
1211
+ try {
1212
+ const conn = await setupWDA(simulator.udid, wdaPort);
1213
+ const rawDriver = await Effect4.runPromise(
1214
+ createWDADriver(conn.host, conn.port, bundleId, simulator.udid)
1215
+ );
1216
+ const driver = withBufferedDriverLogs(rawDriver);
1217
+ return {
1218
+ runtime: {
1219
+ driver,
1220
+ cleanup: () => safeCleanup(
1221
+ () => Effect4.runPromise(driver.killApp("")),
1222
+ () => conn.cleanup?.() ?? Promise.resolve()
1223
+ ),
1224
+ metadata: {
1225
+ platform: "ios",
1226
+ mode: "local",
1227
+ deviceId: simulator.udid
1228
+ }
1229
+ },
1230
+ engineConfig: buildEngineConfig(bundleId, "ios", parseIOSHierarchy, config)
1231
+ };
1232
+ } catch (e) {
1233
+ console.log(`iOS setup failed on ${simulator.name}: ${e instanceof Error ? e.message : e}`);
1234
+ return null;
1235
+ }
1236
+ }
1237
+
1238
+ // src/runtime/appium.ts
1239
+ import { Effect as Effect7 } from "effect";
1240
+
1241
+ // src/drivers/appium/client.ts
1242
+ var AppiumClient = class {
1243
+ baseUrl;
1244
+ sessionId = null;
1245
+ sessionCaps = {};
1246
+ constructor(serverUrl) {
1247
+ this.baseUrl = serverUrl.replace(/\/+$/, "");
1248
+ }
1249
+ // ---------------------------------------------------------------------------
1250
+ // HTTP helpers
1251
+ // ---------------------------------------------------------------------------
1252
+ async request(method, path, body) {
1253
+ const url = `${this.baseUrl}${path}`;
1254
+ const init = {
1255
+ method,
1256
+ headers: { "Content-Type": "application/json" }
1257
+ };
1258
+ if (body !== void 0) {
1259
+ init.body = JSON.stringify(body);
1260
+ }
1261
+ const res = await fetch(url, init);
1262
+ const text = await res.text();
1263
+ let parsed;
1264
+ try {
1265
+ parsed = JSON.parse(text);
1266
+ } catch {
1267
+ throw new Error(`Appium: failed to parse response: ${text}`);
1268
+ }
1269
+ if (!res.ok) {
1270
+ const val = parsed.value;
1271
+ const msg = val?.message ?? val?.error ?? text;
1272
+ throw new Error(`Appium ${method} ${path} -> ${res.status}: ${msg}`);
1273
+ }
1274
+ if (parsed.value !== null && typeof parsed.value === "object" && "error" in parsed.value) {
1275
+ const val = parsed.value;
1276
+ throw new Error(`Appium error: ${val.message ?? val.error}`);
1277
+ }
1278
+ return parsed.value;
1279
+ }
1280
+ sessionPath(suffix) {
1281
+ if (this.sessionId === null) {
1282
+ throw new Error("Appium: no active session");
1283
+ }
1284
+ return `/session/${this.sessionId}${suffix}`;
1285
+ }
1286
+ // ---------------------------------------------------------------------------
1287
+ // Session management
1288
+ // ---------------------------------------------------------------------------
1289
+ async createSession(capabilities) {
1290
+ const body = {
1291
+ capabilities: {
1292
+ alwaysMatch: capabilities
1293
+ }
1294
+ };
1295
+ const res = await fetch(`${this.baseUrl}/session`, {
1296
+ method: "POST",
1297
+ headers: { "Content-Type": "application/json" },
1298
+ body: JSON.stringify(body)
1299
+ });
1300
+ const text = await res.text();
1301
+ let parsed;
1302
+ try {
1303
+ parsed = JSON.parse(text);
1304
+ } catch {
1305
+ throw new Error(`Appium: failed to parse session response: ${text}`);
1306
+ }
1307
+ if (!res.ok) {
1308
+ const val = parsed["value"];
1309
+ throw new Error(`Appium: failed to create session: ${val?.message ?? text}`);
1310
+ }
1311
+ const value = parsed["value"];
1312
+ const sessionId = value?.["sessionId"] ?? parsed["sessionId"];
1313
+ if (!sessionId) {
1314
+ throw new Error("Appium: no sessionId in session response");
1315
+ }
1316
+ this.sessionId = sessionId;
1317
+ this.sessionCaps = value?.["capabilities"] ?? {};
1318
+ return sessionId;
1319
+ }
1320
+ async deleteSession() {
1321
+ if (this.sessionId === null) return;
1322
+ const path = `/session/${this.sessionId}`;
1323
+ this.sessionId = null;
1324
+ this.sessionCaps = {};
1325
+ await fetch(`${this.baseUrl}${path}`, { method: "DELETE" });
1326
+ }
1327
+ getSessionId() {
1328
+ return this.sessionId;
1329
+ }
1330
+ getSessionCaps() {
1331
+ return this.sessionCaps;
1332
+ }
1333
+ // ---------------------------------------------------------------------------
1334
+ // WebView / hybrid context switching
1335
+ // ---------------------------------------------------------------------------
1336
+ async getContexts() {
1337
+ return this.request("GET", this.sessionPath("/contexts"));
1338
+ }
1339
+ async getCurrentContext() {
1340
+ return this.request("GET", this.sessionPath("/context"));
1341
+ }
1342
+ async setContext(contextId) {
1343
+ await this.request("POST", this.sessionPath("/context"), { name: contextId });
1344
+ }
1345
+ // ---------------------------------------------------------------------------
1346
+ // Scripting (execute in current context — works in WebView contexts)
1347
+ // ---------------------------------------------------------------------------
1348
+ async executeScript(script, args = []) {
1349
+ return this.request("POST", this.sessionPath("/execute/sync"), { script, args });
1350
+ }
1351
+ };
1352
+
1353
+ // src/drivers/appium/android.ts
1354
+ import { Effect as Effect5 } from "effect";
1355
+ function createAppiumAndroidDriver(client) {
1356
+ const service = {
1357
+ // -----------------------------------------------------------------------
1358
+ // Hierarchy
1359
+ // -----------------------------------------------------------------------
1360
+ dumpHierarchy: () => Effect5.tryPromise({
1361
+ try: () => client.request("GET", client.sessionPath("/source")),
1362
+ catch: (e) => new DriverError({ message: `Failed to get page source: ${e}` })
1363
+ }),
1364
+ // -----------------------------------------------------------------------
1365
+ // Coordinate-level actions
1366
+ // -----------------------------------------------------------------------
1367
+ tapAtCoordinate: (x, y) => Effect5.tryPromise({
1368
+ try: () => client.request("POST", client.sessionPath("/appium/gestures/click"), {
1369
+ offset: { x, y }
1370
+ }),
1371
+ catch: (e) => new DriverError({ message: `Tap failed: ${e}` })
1372
+ }),
1373
+ doubleTapAtCoordinate: (x, y) => Effect5.tryPromise({
1374
+ try: () => client.request("POST", client.sessionPath("/appium/gestures/double_click"), {
1375
+ offset: { x, y }
1376
+ }),
1377
+ catch: (e) => new DriverError({ message: `Double tap failed: ${e}` })
1378
+ }),
1379
+ longPressAtCoordinate: (x, y, duration) => Effect5.tryPromise({
1380
+ try: () => client.request("POST", client.sessionPath("/appium/gestures/long_click"), {
1381
+ offset: { x, y },
1382
+ duration
1383
+ }),
1384
+ catch: (e) => new DriverError({ message: `Long press failed: ${e}` })
1385
+ }),
1386
+ swipe: (sx, sy, ex, ey, dur) => Effect5.tryPromise({
1387
+ try: () => client.request("POST", client.sessionPath("/actions"), {
1388
+ actions: [
1389
+ {
1390
+ type: "pointer",
1391
+ id: "finger1",
1392
+ parameters: { pointerType: "touch" },
1393
+ actions: [
1394
+ { type: "pointerMove", duration: 0, x: sx, y: sy },
1395
+ { type: "pointerDown", button: 0 },
1396
+ { type: "pointerMove", duration: dur, x: ex, y: ey },
1397
+ { type: "pointerUp", button: 0 }
1398
+ ]
1399
+ }
1400
+ ]
1401
+ }),
1402
+ catch: (e) => new DriverError({ message: `Swipe failed: ${e}` })
1403
+ }),
1404
+ // -----------------------------------------------------------------------
1405
+ // Text input
1406
+ // -----------------------------------------------------------------------
1407
+ inputText: (text) => Effect5.tryPromise({
1408
+ try: () => {
1409
+ const keyActions = [];
1410
+ for (const segment of splitGraphemes(text)) {
1411
+ keyActions.push({ type: "keyDown", value: segment });
1412
+ keyActions.push({ type: "keyUp", value: segment });
1413
+ }
1414
+ return client.request("POST", client.sessionPath("/actions"), {
1415
+ actions: [
1416
+ {
1417
+ type: "key",
1418
+ id: "keyboard",
1419
+ actions: keyActions
1420
+ }
1421
+ ]
1422
+ });
1423
+ },
1424
+ catch: (e) => new DriverError({ message: `Input text failed: ${e}` })
1425
+ }),
1426
+ pressKey: (key) => Effect5.tryPromise({
1427
+ try: () => client.request("POST", client.sessionPath("/appium/device/press_keycode"), {
1428
+ keycode: parseInt(key, 10) || 0
1429
+ }),
1430
+ catch: (e) => new DriverError({ message: `Press key failed: ${e}` })
1431
+ }),
1432
+ hideKeyboard: () => Effect5.tryPromise({
1433
+ try: () => client.request("POST", client.sessionPath("/appium/device/hide_keyboard")),
1434
+ catch: (e) => new DriverError({ message: `Hide keyboard failed: ${e}` })
1435
+ }),
1436
+ // -----------------------------------------------------------------------
1437
+ // Queries
1438
+ // -----------------------------------------------------------------------
1439
+ takeScreenshot: () => Effect5.tryPromise({
1440
+ try: async () => {
1441
+ const base64 = await client.request("GET", client.sessionPath("/screenshot"));
1442
+ return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
1443
+ },
1444
+ catch: (e) => new DriverError({ message: `Screenshot failed: ${e}` })
1445
+ }),
1446
+ getDeviceInfo: () => Effect5.tryPromise({
1447
+ try: async () => {
1448
+ const size = await client.request(
1449
+ "GET",
1450
+ client.sessionPath("/window/size")
1451
+ );
1452
+ const caps = client.getSessionCaps();
1453
+ return {
1454
+ platform: "android",
1455
+ deviceId: client.getSessionId() ?? "appium",
1456
+ name: caps["deviceName"] ?? "Android Device (Appium)",
1457
+ isEmulator: false,
1458
+ screenWidth: size.width,
1459
+ screenHeight: size.height,
1460
+ driverType: "appium"
1461
+ };
1462
+ },
1463
+ catch: (e) => new DriverError({ message: `Get device info failed: ${e}` })
1464
+ }),
1465
+ // -----------------------------------------------------------------------
1466
+ // App lifecycle
1467
+ // -----------------------------------------------------------------------
1468
+ launchApp: (bundleId, opts) => Effect5.tryPromise({
1469
+ try: async () => {
1470
+ if (opts?.clearState) {
1471
+ try {
1472
+ await client.request("POST", client.sessionPath("/appium/device/terminate_app"), {
1473
+ appId: bundleId
1474
+ });
1475
+ } catch {
1476
+ }
1477
+ await client.request("POST", client.sessionPath("/appium/execute_mobile/clearApp"), {
1478
+ appId: bundleId
1479
+ });
1480
+ await client.request("POST", client.sessionPath("/appium/device/activate_app"), {
1481
+ appId: bundleId
1482
+ });
1483
+ } else {
1484
+ await client.request("POST", client.sessionPath("/appium/device/activate_app"), {
1485
+ appId: bundleId
1486
+ });
1487
+ }
1488
+ if (opts?.clearKeychain) {
1489
+ console.warn("clearKeychain is not supported on Android, skipping.");
1490
+ }
1491
+ if (opts?.launchArguments && Object.keys(opts.launchArguments).length > 0) {
1492
+ throw new DriverError({
1493
+ message: "launchArguments are not supported in Appium Android mode. Remove launchArguments from your config or use local mode."
1494
+ });
1495
+ }
1496
+ if (opts?.deepLink) {
1497
+ await client.request("POST", client.sessionPath("/url"), {
1498
+ url: opts.deepLink
1499
+ });
1500
+ }
1501
+ },
1502
+ catch: (e) => new DriverError({ message: `Launch app failed: ${e}` })
1503
+ }),
1504
+ stopApp: (bundleId) => Effect5.tryPromise({
1505
+ try: () => client.request("POST", client.sessionPath("/appium/device/terminate_app"), {
1506
+ appId: bundleId
1507
+ }),
1508
+ catch: (e) => new DriverError({ message: `Stop app failed: ${e}` })
1509
+ }),
1510
+ killApp: (bundleId) => Effect5.tryPromise({
1511
+ try: () => client.request("POST", client.sessionPath("/appium/device/terminate_app"), {
1512
+ appId: bundleId
1513
+ }),
1514
+ catch: (e) => new DriverError({ message: `Kill app failed: ${e}` })
1515
+ }),
1516
+ clearAppState: (bundleId) => Effect5.tryPromise({
1517
+ try: async () => {
1518
+ try {
1519
+ await client.request("POST", client.sessionPath("/appium/device/terminate_app"), {
1520
+ appId: bundleId
1521
+ });
1522
+ } catch {
1523
+ }
1524
+ await client.request("POST", client.sessionPath("/appium/execute_mobile/clearApp"), {
1525
+ appId: bundleId
1526
+ });
1527
+ },
1528
+ catch: (e) => new DriverError({ message: `Clear app state failed: ${e}` })
1529
+ }),
1530
+ // -----------------------------------------------------------------------
1531
+ // Navigation
1532
+ // -----------------------------------------------------------------------
1533
+ openLink: (url) => Effect5.tryPromise({
1534
+ try: () => client.request("POST", client.sessionPath("/url"), { url }),
1535
+ catch: (e) => new DriverError({ message: `Open link failed: ${e}` })
1536
+ }),
1537
+ back: () => Effect5.tryPromise({
1538
+ try: () => client.request("POST", client.sessionPath("/back")),
1539
+ catch: (e) => new DriverError({ message: `Back failed: ${e}` })
1540
+ }),
1541
+ // -----------------------------------------------------------------------
1542
+ // Scripting (works when switched to a WebView context)
1543
+ // -----------------------------------------------------------------------
1544
+ evaluate: (script, ...args) => Effect5.tryPromise({
1545
+ try: () => client.executeScript(
1546
+ typeof script === "function" ? `return (${script})(...arguments)` : script,
1547
+ args
1548
+ ),
1549
+ catch: (e) => new DriverError({ message: `evaluate() failed: ${e}` })
1550
+ }),
1551
+ // -----------------------------------------------------------------------
1552
+ // WebView / hybrid context switching
1553
+ // -----------------------------------------------------------------------
1554
+ getContexts: () => Effect5.tryPromise({
1555
+ try: () => client.getContexts(),
1556
+ catch: (e) => new DriverError({ message: `getContexts failed: ${e}` })
1557
+ }),
1558
+ getCurrentContext: () => Effect5.tryPromise({
1559
+ try: () => client.getCurrentContext(),
1560
+ catch: (e) => new DriverError({ message: `getCurrentContext failed: ${e}` })
1561
+ }),
1562
+ setContext: (contextId) => Effect5.tryPromise({
1563
+ try: () => client.setContext(contextId),
1564
+ catch: (e) => new DriverError({ message: `setContext failed: ${e}` })
1565
+ })
1566
+ };
1567
+ return Effect5.succeed(service);
1568
+ }
1569
+
1570
+ // src/drivers/appium/ios.ts
1571
+ import { Effect as Effect6 } from "effect";
1572
+ function createAppiumIOSDriver(client) {
1573
+ const service = {
1574
+ // -----------------------------------------------------------------------
1575
+ // Hierarchy
1576
+ // -----------------------------------------------------------------------
1577
+ dumpHierarchy: () => Effect6.tryPromise({
1578
+ try: () => client.request("GET", client.sessionPath("/source")),
1579
+ catch: (e) => new DriverError({ message: `Failed to get page source: ${e}` })
1580
+ }),
1581
+ // -----------------------------------------------------------------------
1582
+ // Coordinate-level actions (W3C touch pointer actions for iOS)
1583
+ // -----------------------------------------------------------------------
1584
+ tapAtCoordinate: (x, y) => Effect6.tryPromise({
1585
+ try: () => client.request("POST", client.sessionPath("/actions"), {
1586
+ actions: [
1587
+ {
1588
+ type: "pointer",
1589
+ id: "finger1",
1590
+ parameters: { pointerType: "touch" },
1591
+ actions: [
1592
+ { type: "pointerMove", duration: 0, x, y },
1593
+ { type: "pointerDown", button: 0 },
1594
+ { type: "pointerUp", button: 0 }
1595
+ ]
1596
+ }
1597
+ ]
1598
+ }),
1599
+ catch: (e) => new DriverError({ message: `Tap failed: ${e}` })
1600
+ }),
1601
+ doubleTapAtCoordinate: (x, y) => Effect6.tryPromise({
1602
+ try: () => client.request("POST", client.sessionPath("/actions"), {
1603
+ actions: [
1604
+ {
1605
+ type: "pointer",
1606
+ id: "finger1",
1607
+ parameters: { pointerType: "touch" },
1608
+ actions: [
1609
+ { type: "pointerMove", duration: 0, x, y },
1610
+ { type: "pointerDown", button: 0 },
1611
+ { type: "pointerUp", button: 0 },
1612
+ { type: "pause", duration: 40 },
1613
+ { type: "pointerDown", button: 0 },
1614
+ { type: "pointerUp", button: 0 }
1615
+ ]
1616
+ }
1617
+ ]
1618
+ }),
1619
+ catch: (e) => new DriverError({ message: `Double tap failed: ${e}` })
1620
+ }),
1621
+ longPressAtCoordinate: (x, y, duration) => Effect6.tryPromise({
1622
+ try: () => client.request("POST", client.sessionPath("/actions"), {
1623
+ actions: [
1624
+ {
1625
+ type: "pointer",
1626
+ id: "finger1",
1627
+ parameters: { pointerType: "touch" },
1628
+ actions: [
1629
+ { type: "pointerMove", duration: 0, x, y },
1630
+ { type: "pointerDown", button: 0 },
1631
+ { type: "pause", duration },
1632
+ { type: "pointerUp", button: 0 }
1633
+ ]
1634
+ }
1635
+ ]
1636
+ }),
1637
+ catch: (e) => new DriverError({ message: `Long press failed: ${e}` })
1638
+ }),
1639
+ swipe: (sx, sy, ex, ey, dur) => Effect6.tryPromise({
1640
+ try: () => client.request("POST", client.sessionPath("/actions"), {
1641
+ actions: [
1642
+ {
1643
+ type: "pointer",
1644
+ id: "finger1",
1645
+ parameters: { pointerType: "touch" },
1646
+ actions: [
1647
+ { type: "pointerMove", duration: 0, x: sx, y: sy },
1648
+ { type: "pointerDown", button: 0 },
1649
+ { type: "pointerMove", duration: dur, x: ex, y: ey },
1650
+ { type: "pointerUp", button: 0 }
1651
+ ]
1652
+ }
1653
+ ]
1654
+ }),
1655
+ catch: (e) => new DriverError({ message: `Swipe failed: ${e}` })
1656
+ }),
1657
+ // -----------------------------------------------------------------------
1658
+ // Text input
1659
+ // -----------------------------------------------------------------------
1660
+ inputText: (text) => Effect6.tryPromise({
1661
+ try: () => {
1662
+ const keyActions = [];
1663
+ for (const segment of splitGraphemes(text)) {
1664
+ keyActions.push({ type: "keyDown", value: segment });
1665
+ keyActions.push({ type: "keyUp", value: segment });
1666
+ }
1667
+ return client.request("POST", client.sessionPath("/actions"), {
1668
+ actions: [
1669
+ {
1670
+ type: "key",
1671
+ id: "keyboard",
1672
+ actions: keyActions
1673
+ }
1674
+ ]
1675
+ });
1676
+ },
1677
+ catch: (e) => new DriverError({ message: `Input text failed: ${e}` })
1678
+ }),
1679
+ pressKey: (key) => Effect6.tryPromise({
1680
+ try: () => client.request("POST", client.sessionPath("/actions"), {
1681
+ actions: [
1682
+ {
1683
+ type: "key",
1684
+ id: "keyboard",
1685
+ actions: [
1686
+ { type: "keyDown", value: key },
1687
+ { type: "keyUp", value: key }
1688
+ ]
1689
+ }
1690
+ ]
1691
+ }),
1692
+ catch: (e) => new DriverError({ message: `Press key failed: ${e}` })
1693
+ }),
1694
+ hideKeyboard: () => Effect6.tryPromise({
1695
+ try: () => client.request("POST", client.sessionPath("/appium/device/hide_keyboard")),
1696
+ catch: (e) => new DriverError({ message: `Hide keyboard failed: ${e}` })
1697
+ }),
1698
+ // -----------------------------------------------------------------------
1699
+ // Queries
1700
+ // -----------------------------------------------------------------------
1701
+ takeScreenshot: () => Effect6.tryPromise({
1702
+ try: async () => {
1703
+ const base64 = await client.request("GET", client.sessionPath("/screenshot"));
1704
+ return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
1705
+ },
1706
+ catch: (e) => new DriverError({ message: `Screenshot failed: ${e}` })
1707
+ }),
1708
+ getDeviceInfo: () => Effect6.tryPromise({
1709
+ try: async () => {
1710
+ const size = await client.request(
1711
+ "GET",
1712
+ client.sessionPath("/window/size")
1713
+ );
1714
+ const caps = client.getSessionCaps();
1715
+ return {
1716
+ platform: "ios",
1717
+ deviceId: client.getSessionId() ?? "appium",
1718
+ name: caps["deviceName"] ?? "iOS Device (Appium)",
1719
+ isEmulator: false,
1720
+ screenWidth: size.width,
1721
+ screenHeight: size.height,
1722
+ driverType: "appium"
1723
+ };
1724
+ },
1725
+ catch: (e) => new DriverError({ message: `Get device info failed: ${e}` })
1726
+ }),
1727
+ // -----------------------------------------------------------------------
1728
+ // App lifecycle
1729
+ // -----------------------------------------------------------------------
1730
+ launchApp: (bundleId, opts) => Effect6.tryPromise({
1731
+ try: async () => {
1732
+ if (opts?.clearState) {
1733
+ try {
1734
+ await client.request("POST", client.sessionPath("/appium/device/terminate_app"), {
1735
+ appId: bundleId
1736
+ });
1737
+ } catch {
1738
+ }
1739
+ await client.request("POST", client.sessionPath("/appium/execute_mobile/clearApp"), {
1740
+ appId: bundleId
1741
+ });
1742
+ await client.request("POST", client.sessionPath("/appium/device/activate_app"), {
1743
+ appId: bundleId
1744
+ });
1745
+ } else {
1746
+ await client.request("POST", client.sessionPath("/appium/device/activate_app"), {
1747
+ appId: bundleId
1748
+ });
1749
+ }
1750
+ if (opts?.clearKeychain) {
1751
+ console.warn(
1752
+ "clearKeychain is not available via Appium on iOS. Use local mode with xcrun simctl for keychain operations."
1753
+ );
1754
+ }
1755
+ if (opts?.launchArguments && Object.keys(opts.launchArguments).length > 0) {
1756
+ throw new DriverError({
1757
+ message: "launchArguments are not supported in Appium iOS mode. Remove launchArguments from your config or use local mode."
1758
+ });
1759
+ }
1760
+ if (opts?.deepLink) {
1761
+ await client.request("POST", client.sessionPath("/url"), {
1762
+ url: opts.deepLink
1763
+ });
1764
+ }
1765
+ },
1766
+ catch: (e) => new DriverError({ message: `Launch app failed: ${e}` })
1767
+ }),
1768
+ stopApp: (bundleId) => Effect6.tryPromise({
1769
+ try: () => client.request("POST", client.sessionPath("/appium/device/terminate_app"), {
1770
+ appId: bundleId
1771
+ }),
1772
+ catch: (e) => new DriverError({ message: `Stop app failed: ${e}` })
1773
+ }),
1774
+ killApp: (bundleId) => Effect6.tryPromise({
1775
+ try: () => client.request("POST", client.sessionPath("/appium/device/terminate_app"), {
1776
+ appId: bundleId
1777
+ }),
1778
+ catch: (e) => new DriverError({ message: `Kill app failed: ${e}` })
1779
+ }),
1780
+ clearAppState: (bundleId) => Effect6.tryPromise({
1781
+ try: async () => {
1782
+ try {
1783
+ await client.request("POST", client.sessionPath("/appium/device/terminate_app"), {
1784
+ appId: bundleId
1785
+ });
1786
+ } catch {
1787
+ }
1788
+ await client.request("POST", client.sessionPath("/appium/execute_mobile/clearApp"), {
1789
+ appId: bundleId
1790
+ });
1791
+ },
1792
+ catch: (e) => new DriverError({
1793
+ message: `Clear app state failed: ${e}. Note: clearApp may not be available on all iOS Appium providers. If this persists, consider using terminate + uninstall + install instead.`
1794
+ })
1795
+ }),
1796
+ // -----------------------------------------------------------------------
1797
+ // Navigation
1798
+ // -----------------------------------------------------------------------
1799
+ openLink: (url) => Effect6.tryPromise({
1800
+ try: () => client.request("POST", client.sessionPath("/url"), { url }),
1801
+ catch: (e) => new DriverError({ message: `Open link failed: ${e}` })
1802
+ }),
1803
+ back: () => Effect6.fail(
1804
+ new DriverError({
1805
+ message: "back() is not supported on iOS. Use navigation within the app or swipe gestures."
1806
+ })
1807
+ ),
1808
+ // -----------------------------------------------------------------------
1809
+ // Scripting (works when switched to a WebView context)
1810
+ // -----------------------------------------------------------------------
1811
+ evaluate: (script, ...args) => Effect6.tryPromise({
1812
+ try: () => client.executeScript(
1813
+ typeof script === "function" ? `return (${script})(...arguments)` : script,
1814
+ args
1815
+ ),
1816
+ catch: (e) => new DriverError({ message: `evaluate() failed: ${e}` })
1817
+ }),
1818
+ // -----------------------------------------------------------------------
1819
+ // WebView / hybrid context switching
1820
+ // -----------------------------------------------------------------------
1821
+ getContexts: () => Effect6.tryPromise({
1822
+ try: () => client.getContexts(),
1823
+ catch: (e) => new DriverError({ message: `getContexts failed: ${e}` })
1824
+ }),
1825
+ getCurrentContext: () => Effect6.tryPromise({
1826
+ try: () => client.getCurrentContext(),
1827
+ catch: (e) => new DriverError({ message: `getCurrentContext failed: ${e}` })
1828
+ }),
1829
+ setContext: (contextId) => Effect6.tryPromise({
1830
+ try: () => client.setContext(contextId),
1831
+ catch: (e) => new DriverError({ message: `setContext failed: ${e}` })
1832
+ })
1833
+ };
1834
+ return Effect6.succeed(service);
1835
+ }
1836
+
1837
+ // src/runtime/appium.ts
1838
+ async function buildAppiumAndroidRuntime(config, appiumUrl, caps) {
1839
+ const client = new AppiumClient(appiumUrl);
1840
+ await client.createSession({
1841
+ platformName: "Android",
1842
+ ...caps
1843
+ });
1844
+ const rawDriver = await Effect7.runPromise(createAppiumAndroidDriver(client));
1845
+ const driver = withBufferedDriverLogs(rawDriver);
1846
+ const sessionId = client.getSessionId() ?? void 0;
1847
+ const sessionCaps = client.getSessionCaps();
1848
+ const detectedProvider = detectProvider(appiumUrl);
1849
+ const providerName = detectedProvider?.name();
1850
+ return {
1851
+ runtime: {
1852
+ driver,
1853
+ cleanup: async () => {
1854
+ try {
1855
+ await client.deleteSession();
1856
+ } catch {
1857
+ }
1858
+ },
1859
+ metadata: {
1860
+ platform: "android",
1861
+ mode: "appium",
1862
+ sessionId,
1863
+ sessionCaps,
1864
+ provider: providerName
1865
+ }
1866
+ },
1867
+ engineConfig: {
1868
+ appId: caps["appium:appPackage"] ?? "",
1869
+ platform: "android",
1870
+ coordinatorConfig: {
1871
+ parse: parseAndroidHierarchy,
1872
+ defaults: {
1873
+ timeout: config.defaults?.waitTimeout,
1874
+ pollInterval: config.defaults?.pollInterval
1875
+ },
1876
+ waitForIdleTimeout: config.defaults?.waitForIdleTimeout,
1877
+ typingDelay: config.defaults?.typingDelay
1878
+ },
1879
+ autoLaunch: false,
1880
+ // Appium manages app lifecycle
1881
+ flowTimeout: config.defaults?.waitTimeout ? config.defaults.waitTimeout * 10 : 6e4,
1882
+ artifactConfig: config.artifacts,
1883
+ launchOptions: config.launchOptions,
1884
+ hooks: config.hooks
1885
+ }
1886
+ };
1887
+ }
1888
+ async function buildAppiumIOSRuntime(config, appiumUrl, caps) {
1889
+ const client = new AppiumClient(appiumUrl);
1890
+ await client.createSession({
1891
+ platformName: "iOS",
1892
+ "appium:automationName": "XCUITest",
1893
+ ...caps
1894
+ });
1895
+ const rawDriver = await Effect7.runPromise(createAppiumIOSDriver(client));
1896
+ const driver = withBufferedDriverLogs(rawDriver);
1897
+ const sessionId = client.getSessionId() ?? void 0;
1898
+ const sessionCaps = client.getSessionCaps();
1899
+ const detectedProvider = detectProvider(appiumUrl);
1900
+ const providerName = detectedProvider?.name();
1901
+ return {
1902
+ runtime: {
1903
+ driver,
1904
+ cleanup: async () => {
1905
+ try {
1906
+ await client.deleteSession();
1907
+ } catch {
1908
+ }
1909
+ },
1910
+ metadata: {
1911
+ platform: "ios",
1912
+ mode: "appium",
1913
+ sessionId,
1914
+ sessionCaps,
1915
+ provider: providerName
1916
+ }
1917
+ },
1918
+ engineConfig: {
1919
+ appId: caps["appium:bundleId"] ?? "",
1920
+ platform: "ios",
1921
+ coordinatorConfig: {
1922
+ parse: parseIOSHierarchy,
1923
+ defaults: {
1924
+ timeout: config.defaults?.waitTimeout,
1925
+ pollInterval: config.defaults?.pollInterval
1926
+ },
1927
+ waitForIdleTimeout: config.defaults?.waitForIdleTimeout,
1928
+ typingDelay: config.defaults?.typingDelay
1929
+ },
1930
+ autoLaunch: false,
1931
+ // Appium manages app lifecycle
1932
+ flowTimeout: config.defaults?.waitTimeout ? config.defaults.waitTimeout * 10 : 6e4,
1933
+ artifactConfig: config.artifacts,
1934
+ launchOptions: config.launchOptions,
1935
+ hooks: config.hooks
1936
+ }
1937
+ };
1938
+ }
1939
+
1940
+ // src/cli/iteration.ts
1941
+ import { execFileSync } from "child_process";
1942
+ import { mkdir, readFile, writeFile } from "fs/promises";
1943
+ import { dirname, join as join2, resolve } from "path";
1944
+ var LAST_RUN_STATE_SCHEMA_VERSION = 1;
1945
+ function createLastRunStatePath(outputDir) {
1946
+ return join2(outputDir, ".spana", "last-run.json");
1947
+ }
1948
+ function buildLastRunState(options) {
1949
+ const flows = options.results.map((result) => ({
1950
+ name: result.name,
1951
+ platform: result.platform,
1952
+ status: result.status,
1953
+ sourcePath: options.sourcePathsByFlowName.get(result.name)
1954
+ }));
1955
+ const failedFlowNames = flows.filter((flow) => flow.status === "failed").map((flow) => flow.name);
1956
+ const failedSourcePaths = [
1957
+ ...new Set(
1958
+ flows.filter((flow) => flow.status === "failed").map((flow) => flow.sourcePath).filter((value) => Boolean(value))
1959
+ )
1960
+ ];
1961
+ return {
1962
+ schemaVersion: LAST_RUN_STATE_SCHEMA_VERSION,
1963
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1964
+ flowDir: resolve(options.flowDir),
1965
+ platforms: [...new Set(options.platforms)],
1966
+ failedFlowNames,
1967
+ failedSourcePaths,
1968
+ flows
1969
+ };
1970
+ }
1971
+ function parseLastRunState(raw, filePath) {
1972
+ const parsed = JSON.parse(raw);
1973
+ if (parsed.schemaVersion !== LAST_RUN_STATE_SCHEMA_VERSION) {
1974
+ throw new Error(
1975
+ `Unsupported last run state schema in ${filePath}. Delete the file and rerun Spana.`
1976
+ );
1977
+ }
1978
+ if (!Array.isArray(parsed.flows) || !Array.isArray(parsed.failedFlowNames)) {
1979
+ throw new Error(`Invalid last run state file at ${filePath}. Delete the file and rerun Spana.`);
1980
+ }
1981
+ return {
1982
+ schemaVersion: LAST_RUN_STATE_SCHEMA_VERSION,
1983
+ updatedAt: typeof parsed.updatedAt === "string" ? parsed.updatedAt : (/* @__PURE__ */ new Date(0)).toISOString(),
1984
+ flowDir: typeof parsed.flowDir === "string" ? parsed.flowDir : "",
1985
+ platforms: Array.isArray(parsed.platforms) ? parsed.platforms : [],
1986
+ failedFlowNames: parsed.failedFlowNames.filter(
1987
+ (value) => typeof value === "string"
1988
+ ),
1989
+ failedSourcePaths: Array.isArray(parsed.failedSourcePaths) ? parsed.failedSourcePaths.filter((value) => typeof value === "string") : [],
1990
+ flows: parsed.flows.filter(
1991
+ (value) => typeof value === "object" && value !== null && typeof value.name === "string" && typeof value.platform === "string" && typeof value.status === "string"
1992
+ ).map((value) => ({
1993
+ name: value.name,
1994
+ platform: value.platform,
1995
+ status: value.status,
1996
+ sourcePath: typeof value.sourcePath === "string" ? value.sourcePath : void 0
1997
+ }))
1998
+ };
1999
+ }
2000
+ async function readLastRunState(filePath) {
2001
+ try {
2002
+ const raw = await readFile(filePath, "utf8");
2003
+ return parseLastRunState(raw, filePath);
2004
+ } catch (error) {
2005
+ if (error.code === "ENOENT") {
2006
+ return null;
2007
+ }
2008
+ throw error;
2009
+ }
2010
+ }
2011
+ async function writeLastRunState(filePath, state) {
2012
+ await mkdir(dirname(filePath), { recursive: true });
2013
+ await writeFile(filePath, `${JSON.stringify(state, null, 2)}
2014
+ `, "utf8");
2015
+ }
2016
+ function parseGitPathList(output, cwd) {
2017
+ return output.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).map((line) => resolve(cwd, line));
2018
+ }
2019
+ function getGitChangedFiles(cwd = process.cwd()) {
2020
+ try {
2021
+ const tracked = execFileSync("git", ["diff", "--name-only", "--relative", "HEAD"], {
2022
+ cwd,
2023
+ encoding: "utf8"
2024
+ });
2025
+ const untracked = execFileSync("git", ["ls-files", "--others", "--exclude-standard"], {
2026
+ cwd,
2027
+ encoding: "utf8"
2028
+ });
2029
+ return [.../* @__PURE__ */ new Set([...parseGitPathList(tracked, cwd), ...parseGitPathList(untracked, cwd)])];
2030
+ } catch (error) {
2031
+ const message = error instanceof Error ? error.message : String(error);
2032
+ throw new Error(
2033
+ `Failed to read changed files from git. Make sure git is installed and the project is in a git repository. ${message}`,
2034
+ { cause: error }
2035
+ );
2036
+ }
2037
+ }
2038
+ function selectChangedFlowPaths(options) {
2039
+ const flowPaths = options.flowPaths.map((path) => resolve(path));
2040
+ const changedFiles = new Set(options.changedFiles.map((path) => resolve(path)));
2041
+ const stepPaths = new Set((options.stepPaths ?? []).map((path) => resolve(path)));
2042
+ const configPath = options.configPath ? resolve(options.configPath) : void 0;
2043
+ if (configPath && changedFiles.has(configPath)) {
2044
+ return {
2045
+ mode: "all",
2046
+ reason: "Config changed; running the full filtered flow set.",
2047
+ flowPaths
2048
+ };
2049
+ }
2050
+ const changedFlowPaths = flowPaths.filter((path) => changedFiles.has(path));
2051
+ if (changedFlowPaths.length > 0) {
2052
+ return {
2053
+ mode: "targeted",
2054
+ reason: "Detected changed flow files.",
2055
+ flowPaths: changedFlowPaths
2056
+ };
2057
+ }
2058
+ const hasChangedStepFiles = [...stepPaths].some((path) => changedFiles.has(path));
2059
+ if (hasChangedStepFiles) {
2060
+ const featureFlowPaths = flowPaths.filter((path) => path.endsWith(".feature"));
2061
+ if (featureFlowPaths.length > 0) {
2062
+ return {
2063
+ mode: "targeted",
2064
+ reason: "Detected changed step definition files; rerunning feature files.",
2065
+ flowPaths: featureFlowPaths
2066
+ };
2067
+ }
2068
+ return {
2069
+ mode: "none",
2070
+ reason: "Step definition files changed, but no .feature flows were discovered.",
2071
+ flowPaths: []
2072
+ };
2073
+ }
2074
+ return {
2075
+ mode: "none",
2076
+ reason: "No changed flow files were detected.",
2077
+ flowPaths: []
2078
+ };
2079
+ }
2080
+
2081
+ // src/cli/watch-mode.ts
2082
+ import { readdir, stat } from "fs/promises";
2083
+ import { dirname as dirname2, extname, resolve as resolve2 } from "path";
2084
+ var IGNORED_DIRECTORIES = /* @__PURE__ */ new Set([".git", "node_modules", "spana-output", "dist", "coverage"]);
2085
+ var WATCHABLE_EXTENSIONS = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".json", ".feature"]);
2086
+ var defaultWatchDependencies = {
2087
+ sleep: (ms) => new Promise((resolveDelay) => setTimeout(resolveDelay, ms)),
2088
+ snapshotRoots: snapshotWatchRoots
2089
+ };
2090
+ function collectWatchRoots(flowPathOrDir, configPath) {
2091
+ const roots = /* @__PURE__ */ new Set();
2092
+ const resolvedFlowPath = resolve2(flowPathOrDir);
2093
+ roots.add(resolvedFlowPath);
2094
+ if (configPath) {
2095
+ roots.add(resolve2(configPath));
2096
+ }
2097
+ return [...roots];
2098
+ }
2099
+ function shouldTrackFile(filePath) {
2100
+ return WATCHABLE_EXTENSIONS.has(extname(filePath));
2101
+ }
2102
+ async function snapshotPath(path, snapshot) {
2103
+ const stats = await stat(path).catch(() => null);
2104
+ if (!stats) {
2105
+ return;
2106
+ }
2107
+ if (stats.isDirectory()) {
2108
+ const entries = await readdir(path, { withFileTypes: true });
2109
+ for (const entry of entries) {
2110
+ if (entry.isDirectory() && IGNORED_DIRECTORIES.has(entry.name)) {
2111
+ continue;
2112
+ }
2113
+ await snapshotPath(resolve2(path, entry.name), snapshot);
2114
+ }
2115
+ return;
2116
+ }
2117
+ if (!shouldTrackFile(path)) {
2118
+ return;
2119
+ }
2120
+ snapshot.set(path, `${stats.mtimeMs}:${stats.size}`);
2121
+ }
2122
+ async function snapshotWatchRoots(roots) {
2123
+ const snapshot = /* @__PURE__ */ new Map();
2124
+ for (const root of roots.map((path) => resolve2(path))) {
2125
+ const stats = await stat(root).catch(() => null);
2126
+ if (!stats) {
2127
+ const parent = dirname2(root);
2128
+ const parentStats = await stat(parent).catch(() => null);
2129
+ if (parentStats?.isDirectory()) {
2130
+ await snapshotPath(parent, snapshot);
2131
+ }
2132
+ continue;
2133
+ }
2134
+ await snapshotPath(root, snapshot);
2135
+ }
2136
+ return snapshot;
2137
+ }
2138
+ function diffSnapshots(previous, next) {
2139
+ const changed = /* @__PURE__ */ new Set();
2140
+ for (const [path, signature] of previous) {
2141
+ if (next.get(path) !== signature) {
2142
+ changed.add(path);
2143
+ }
2144
+ }
2145
+ for (const path of next.keys()) {
2146
+ if (!previous.has(path)) {
2147
+ changed.add(path);
2148
+ }
2149
+ }
2150
+ return [...changed].toSorted();
2151
+ }
2152
+ async function runWatchLoop(options, dependencies = defaultWatchDependencies) {
2153
+ let previousSnapshot = await dependencies.snapshotRoots(options.roots);
2154
+ while (true) {
2155
+ await dependencies.sleep(options.intervalMs ?? 500);
2156
+ const nextSnapshot = await dependencies.snapshotRoots(options.roots);
2157
+ const changedPaths = diffSnapshots(previousSnapshot, nextSnapshot);
2158
+ if (changedPaths.length === 0) {
2159
+ continue;
2160
+ }
2161
+ previousSnapshot = nextSnapshot;
2162
+ await options.onChange(changedPaths);
2163
+ }
2164
+ }
2165
+
2166
+ // src/cli/test-command.ts
2167
+ function validateOptions(opts) {
2168
+ if (opts.driver && opts.driver !== "local" && opts.driver !== "appium") {
2169
+ return `Unknown --driver value "${opts.driver}". Use "local" or "appium".`;
2170
+ }
2171
+ if (opts.shard) {
2172
+ const { current, total } = opts.shard;
2173
+ if (!Number.isInteger(current) || !Number.isInteger(total) || current < 1 || total < 1 || current > total) {
2174
+ return "Invalid shard config. Use { current, total } with 1 <= current <= total.";
2175
+ }
2176
+ }
2177
+ if (opts.bail !== void 0 && (!Number.isInteger(opts.bail) || opts.bail < 1)) {
2178
+ return "Invalid bail config. Use a positive integer.";
2179
+ }
2180
+ if (opts.parallel && opts.device) {
2181
+ return "Cannot use --parallel with --device. Remove --device to auto-discover all devices.";
2182
+ }
2183
+ if (opts.devices && opts.device) {
2184
+ return "Cannot use --devices with --device. Use --devices for multi-device selection.";
2185
+ }
2186
+ if (opts.device && opts.workers) {
2187
+ return "Cannot use --workers with --device. --device targets a single device.";
2188
+ }
2189
+ if (opts.watch && opts.validateConfigOnly) {
2190
+ return "Cannot use --watch with --validate-config.";
2191
+ }
2192
+ return null;
2193
+ }
2194
+ async function loadFlowsWithSources(flowPaths) {
2195
+ const loadedFlows = [];
2196
+ for (const sourcePath of flowPaths) {
2197
+ const loaded = await loadTestSource(sourcePath);
2198
+ for (const flow of loaded) {
2199
+ loadedFlows.push({ sourcePath, flow });
2200
+ }
2201
+ }
2202
+ return loadedFlows;
2203
+ }
2204
+ function filterLoadedFlows(loadedFlows, options) {
2205
+ const filteredFlows = filterFlows(
2206
+ loadedFlows.map((loaded) => loaded.flow),
2207
+ options
2208
+ );
2209
+ const allowedFlows = new Set(filteredFlows);
2210
+ return loadedFlows.filter((loaded) => allowedFlows.has(loaded.flow));
2211
+ }
2212
+ async function buildParallelPlatformConfigs(platforms, opts, config, runtimes, resolveFromConfig) {
2213
+ const { discoverDevices, findDeviceById } = await import("./discover-KZKXHZZA.js");
2214
+ let allDevices;
2215
+ if (opts.devices) {
2216
+ allDevices = [];
2217
+ for (const id of opts.devices) {
2218
+ const found = findDeviceById(id);
2219
+ if (found) {
2220
+ allDevices.push(found);
2221
+ } else {
2222
+ console.log(`Warning: Device "${id}" not found, skipping.`);
2223
+ }
2224
+ }
2225
+ if (opts.platforms.length === 0) {
2226
+ const inferredPlatforms = [...new Set(allDevices.map((d) => d.platform))];
2227
+ platforms.length = 0;
2228
+ platforms.push(...inferredPlatforms);
2229
+ }
2230
+ } else {
2231
+ allDevices = discoverDevices(platforms);
2232
+ }
2233
+ const maxWorkers = opts.workers ?? config.defaults?.workers;
2234
+ const platformConfigs = [];
2235
+ for (const platform of platforms) {
2236
+ let platformDevices = allDevices.filter((d) => d.platform === platform);
2237
+ if (maxWorkers && platformDevices.length > maxWorkers) {
2238
+ platformDevices = platformDevices.slice(0, maxWorkers);
2239
+ }
2240
+ if (platform === "web") {
2241
+ const webWorkers = maxWorkers ?? 1;
2242
+ if (webWorkers > 1) {
2243
+ const primaryResult = await buildWebRuntime(config);
2244
+ runtimes.push(primaryResult.runtime);
2245
+ const additionalWorkers = [];
2246
+ for (let i = 1; i < webWorkers; i++) {
2247
+ const result = await buildWebRuntime(config);
2248
+ runtimes.push(result.runtime);
2249
+ additionalWorkers.push({
2250
+ id: `web-context-${i + 1}`,
2251
+ name: `Chromium #${i + 1}`,
2252
+ driver: result.runtime.driver,
2253
+ engineConfig: { ...result.engineConfig, debugOnFailure: opts.debugOnFailure }
2254
+ });
2255
+ }
2256
+ platformConfigs.push({
2257
+ platform,
2258
+ driver: primaryResult.runtime.driver,
2259
+ engineConfig: { ...primaryResult.engineConfig, debugOnFailure: opts.debugOnFailure },
2260
+ additionalWorkers: additionalWorkers.length > 0 ? additionalWorkers : void 0
2261
+ });
2262
+ } else {
2263
+ const result = await buildWebRuntime(config);
2264
+ runtimes.push(result.runtime);
2265
+ platformConfigs.push({
2266
+ platform,
2267
+ driver: result.runtime.driver,
2268
+ engineConfig: { ...result.engineConfig, debugOnFailure: opts.debugOnFailure }
2269
+ });
2270
+ }
2271
+ } else if (platformDevices.length === 0) {
2272
+ console.log(`No ${platform} devices found. Skipping ${platform} platform.`);
2273
+ } else {
2274
+ if (platformDevices.length === 1) {
2275
+ console.log(
2276
+ `\u2139 Only 1 ${platform} device found \u2014 connect more devices for parallel execution.`
2277
+ );
2278
+ }
2279
+ const builder = platform === "android" ? buildLocalAndroidRuntime : buildLocalIOSRuntime;
2280
+ const primaryResult = await builder(config, platformDevices[0], resolveFromConfig);
2281
+ if (!primaryResult) continue;
2282
+ runtimes.push(primaryResult.runtime);
2283
+ const additionalWorkers = [];
2284
+ for (const device of platformDevices.slice(1)) {
2285
+ try {
2286
+ const result = await builder(config, device, resolveFromConfig);
2287
+ if (result) {
2288
+ runtimes.push(result.runtime);
2289
+ additionalWorkers.push({
2290
+ id: device.id,
2291
+ name: device.name,
2292
+ driver: result.runtime.driver,
2293
+ engineConfig: { ...result.engineConfig, debugOnFailure: opts.debugOnFailure }
2294
+ });
2295
+ }
2296
+ } catch (err) {
2297
+ console.log(
2298
+ `Warning: Failed to set up ${platform} device ${device.name}: ${err instanceof Error ? err.message : err}`
2299
+ );
2300
+ }
2301
+ }
2302
+ platformConfigs.push({
2303
+ platform,
2304
+ driver: primaryResult.runtime.driver,
2305
+ engineConfig: { ...primaryResult.engineConfig, debugOnFailure: opts.debugOnFailure },
2306
+ additionalWorkers: additionalWorkers.length > 0 ? additionalWorkers : void 0
2307
+ });
2308
+ }
2309
+ }
2310
+ return platformConfigs;
2311
+ }
2312
+ async function buildSerialPlatformConfigs(platforms, opts, config, runtimes, executionMode, appiumUrl, baseAppiumCaps, cloudHelper, targetDevice, resolveFromConfig) {
2313
+ const platformConfigs = [];
2314
+ for (const platform of platforms) {
2315
+ if (executionMode === "appium" && (platform === "android" || platform === "ios")) {
2316
+ const builder = platform === "android" ? buildAppiumAndroidRuntime : buildAppiumIOSRuntime;
2317
+ const preparedCaps = await cloudHelper.prepareCapabilities(
2318
+ platform,
2319
+ { ...baseAppiumCaps },
2320
+ platform === "android" ? config.apps?.android : config.apps?.ios
2321
+ );
2322
+ const result = await builder(config, appiumUrl, preparedCaps);
2323
+ runtimes.push(result.runtime);
2324
+ platformConfigs.push({
2325
+ platform,
2326
+ driver: result.runtime.driver,
2327
+ engineConfig: { ...result.engineConfig, debugOnFailure: opts.debugOnFailure }
2328
+ });
2329
+ } else if (platform === "web") {
2330
+ const result = await buildWebRuntime(config);
2331
+ runtimes.push(result.runtime);
2332
+ platformConfigs.push({
2333
+ platform,
2334
+ driver: result.runtime.driver,
2335
+ engineConfig: { ...result.engineConfig, debugOnFailure: opts.debugOnFailure }
2336
+ });
2337
+ } else if (platform === "android") {
2338
+ const result = await buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig);
2339
+ if (!result) continue;
2340
+ runtimes.push(result.runtime);
2341
+ platformConfigs.push({
2342
+ platform,
2343
+ driver: result.runtime.driver,
2344
+ engineConfig: { ...result.engineConfig, debugOnFailure: opts.debugOnFailure }
2345
+ });
2346
+ } else if (platform === "ios") {
2347
+ const result = await buildLocalIOSRuntime(config, targetDevice, resolveFromConfig);
2348
+ if (!result) continue;
2349
+ runtimes.push(result.runtime);
2350
+ platformConfigs.push({
2351
+ platform,
2352
+ driver: result.runtime.driver,
2353
+ engineConfig: { ...result.engineConfig, debugOnFailure: opts.debugOnFailure }
2354
+ });
2355
+ }
2356
+ }
2357
+ return platformConfigs;
2358
+ }
2359
+ var BUILTIN_REPORTERS = /* @__PURE__ */ new Set(["console", "json", "junit", "html", "allure"]);
2360
+ async function loadCustomReporter(modulePath, configDir) {
2361
+ const resolvedPath = modulePath.startsWith(".") ? resolve3(configDir, modulePath) : modulePath;
2362
+ let mod;
2363
+ try {
2364
+ mod = await import(resolvedPath);
2365
+ } catch (err) {
2366
+ throw new Error(
2367
+ `Failed to load custom reporter from "${modulePath}" (resolved: ${resolvedPath}): ${err instanceof Error ? err.message : err}`,
2368
+ { cause: err }
2369
+ );
2370
+ }
2371
+ const exported = mod.default;
2372
+ if (!exported) {
2373
+ throw new Error(
2374
+ `Custom reporter "${modulePath}" has no default export. Export a Reporter object or a (options) => Reporter factory function.`
2375
+ );
2376
+ }
2377
+ if (typeof exported === "function") {
2378
+ return exported({ outputDir: configDir });
2379
+ }
2380
+ if (typeof exported === "object") {
2381
+ return exported;
2382
+ }
2383
+ throw new Error(
2384
+ `Custom reporter "${modulePath}" default export must be a Reporter object or factory function, got ${typeof exported}.`
2385
+ );
2386
+ }
2387
+ async function setupReporters(reporterNames, config, resolveFromConfig, appiumUrl, opts) {
2388
+ const { createRedactor, registerUrlSecrets } = await import("./redact-U72BUBBR.js");
2389
+ const redactor = createRedactor();
2390
+ if (appiumUrl) registerUrlSecrets(redactor, appiumUrl);
2391
+ const { createConsoleReporter } = await import("./console-XWKUTP3D.js");
2392
+ const { createJsonReporter } = await import("./json-KS67BZYU.js");
2393
+ const { createJUnitReporter } = await import("./junit-HLC62MK6.js");
2394
+ const { createHtmlReporter } = await import("./html-GE6Q4DCG.js");
2395
+ const { createAllureReporter } = await import("./allure-PTTVORQ6.js");
2396
+ const resolvedOutputDir = config.artifacts?.outputDir ?? resolveFromConfig("./spana-output");
2397
+ const reporters = [];
2398
+ for (const name of reporterNames.split(",")) {
2399
+ const trimmed = name.trim();
2400
+ if (!trimmed) continue;
2401
+ if (BUILTIN_REPORTERS.has(trimmed)) {
2402
+ switch (trimmed) {
2403
+ case "json":
2404
+ reporters.push(createJsonReporter());
2405
+ break;
2406
+ case "junit":
2407
+ reporters.push(createJUnitReporter(resolvedOutputDir));
2408
+ break;
2409
+ case "html":
2410
+ reporters.push(createHtmlReporter(resolvedOutputDir));
2411
+ break;
2412
+ case "allure":
2413
+ reporters.push(createAllureReporter());
2414
+ break;
2415
+ default:
2416
+ reporters.push(createConsoleReporter({ quiet: opts.quiet }));
2417
+ break;
2418
+ }
2419
+ } else {
2420
+ const configDir = resolve3(resolveFromConfig("."));
2421
+ try {
2422
+ const custom = await loadCustomReporter(trimmed, configDir);
2423
+ reporters.push(custom);
2424
+ } catch (err) {
2425
+ console.log(err instanceof Error ? err.message : String(err));
2426
+ throw err;
2427
+ }
2428
+ }
2429
+ }
2430
+ return { redactor, reporters };
2431
+ }
2432
+ async function runTestCommandOnce(opts) {
2433
+ const validationError = validateOptions(opts);
2434
+ if (validationError) {
2435
+ console.log(validationError);
2436
+ return { success: false, watchRoots: [] };
2437
+ }
2438
+ let config = {};
2439
+ let loadedConfigPath;
2440
+ try {
2441
+ const loaded = await loadConfig({ configPath: opts.configPath, allowMissing: true });
2442
+ config = loaded.config;
2443
+ loadedConfigPath = loaded.configPath;
2444
+ } catch (error) {
2445
+ console.log(error instanceof Error ? error.message : String(error));
2446
+ return { success: false, watchRoots: [] };
2447
+ }
2448
+ const configDir = dirname3(loadedConfigPath ?? resolve3("spana.config.ts"));
2449
+ if (opts.validateConfigOnly) {
2450
+ if (!loadedConfigPath) {
2451
+ console.log("No config file found to validate.");
2452
+ return { success: false, watchRoots: [] };
2453
+ }
2454
+ console.log(`\u2713 Config valid (${loadedConfigPath})`);
2455
+ return { success: true, watchRoots: [] };
2456
+ }
2457
+ const resolveFromConfig = (p) => resolve3(configDir, p);
2458
+ if (config.artifacts?.outputDir) {
2459
+ config.artifacts.outputDir = resolveFromConfig(config.artifacts.outputDir);
2460
+ }
2461
+ const executionMode = opts.driver ?? (opts.appiumUrl ? "appium" : void 0) ?? config.execution?.mode ?? "local";
2462
+ if (opts.capsJson) {
2463
+ try {
2464
+ JSON.parse(opts.capsJson);
2465
+ } catch {
2466
+ console.log("Invalid JSON in --caps-json flag.");
2467
+ return { success: false, watchRoots: [] };
2468
+ }
2469
+ }
2470
+ if (executionMode === "appium") {
2471
+ const appiumUrl = opts.appiumUrl ?? config.execution?.appium?.serverUrl;
2472
+ if (!appiumUrl) {
2473
+ console.log(
2474
+ "Appium mode requires a server URL. Set --appium-url or execution.appium.serverUrl in config."
2475
+ );
2476
+ return { success: false, watchRoots: [] };
2477
+ }
2478
+ if (opts.device) {
2479
+ console.log(
2480
+ "Cannot use --device with appium mode. Use --caps or --caps-json to set device capabilities."
2481
+ );
2482
+ return { success: false, watchRoots: [] };
2483
+ }
2484
+ }
2485
+ const platforms = opts.platforms.length > 0 ? opts.platforms : config.platforms && config.platforms.length > 0 ? config.platforms : ["web"];
2486
+ let targetDevice = null;
2487
+ if (opts.device) {
2488
+ const { findDeviceById } = await import("./discover-KZKXHZZA.js");
2489
+ targetDevice = findDeviceById(opts.device);
2490
+ if (!targetDevice) {
2491
+ const { discoverDevices } = await import("./discover-KZKXHZZA.js");
2492
+ const available = discoverDevices(["web", "android", "ios"]);
2493
+ console.log(`Device "${opts.device}" not found. Available devices:`);
2494
+ for (const d of available) {
2495
+ console.log(` ${d.id.padEnd(30)} ${d.platform.padEnd(8)} ${d.type}`);
2496
+ }
2497
+ return {
2498
+ success: false,
2499
+ watchRoots: collectWatchRoots(resolveFromConfig(config.flowDir ?? "./flows"), loadedConfigPath)
2500
+ };
2501
+ }
2502
+ if (opts.platforms.length === 0) {
2503
+ platforms.length = 0;
2504
+ platforms.push(targetDevice.platform);
2505
+ }
2506
+ if (!platforms.includes(targetDevice.platform)) {
2507
+ console.log(
2508
+ `Device "${opts.device}" is ${targetDevice.platform}, but --platform ${platforms.join(",")} was specified.`
2509
+ );
2510
+ return {
2511
+ success: false,
2512
+ watchRoots: collectWatchRoots(resolveFromConfig(config.flowDir ?? "./flows"), loadedConfigPath)
2513
+ };
2514
+ }
2515
+ }
2516
+ const reporterNames = opts.reporter?.trim() ? opts.reporter : config.reporters && config.reporters.length > 0 ? config.reporters.join(",") : "console";
2517
+ const flowDir = opts.flowPath ?? resolveFromConfig(config.flowDir ?? "./flows");
2518
+ const watchRoots = collectWatchRoots(flowDir, loadedConfigPath);
2519
+ let flowPaths = await discoverFlows(flowDir);
2520
+ if (flowPaths.length === 0) {
2521
+ console.log("No flow files found.");
2522
+ return { success: true, watchRoots };
2523
+ }
2524
+ let stepPaths = [];
2525
+ const hasFeatureFiles = flowPaths.some((p) => p.endsWith(".feature"));
2526
+ if (hasFeatureFiles) {
2527
+ const { stat: statPath } = await import("fs/promises");
2528
+ const { dirname: dirnameDyn } = await import("path");
2529
+ const flowDirStats = await statPath(flowDir).catch(() => null);
2530
+ const stepSearchDir = flowDirStats?.isDirectory() ? flowDir : dirnameDyn(flowDir);
2531
+ stepPaths = await discoverStepFiles(stepSearchDir);
2532
+ }
2533
+ if (opts.changed) {
2534
+ let changedFiles;
2535
+ try {
2536
+ changedFiles = getGitChangedFiles(process.cwd());
2537
+ } catch (error) {
2538
+ console.log(error instanceof Error ? error.message : String(error));
2539
+ return { success: false, watchRoots };
2540
+ }
2541
+ const selection = selectChangedFlowPaths({
2542
+ flowPaths,
2543
+ changedFiles,
2544
+ stepPaths,
2545
+ configPath: loadedConfigPath
2546
+ });
2547
+ if (selection.mode === "none") {
2548
+ console.log(selection.reason);
2549
+ return { success: true, watchRoots };
2550
+ }
2551
+ if (selection.mode === "targeted") {
2552
+ flowPaths = selection.flowPaths;
2553
+ console.log(selection.reason);
2554
+ } else {
2555
+ console.log(selection.reason);
2556
+ }
2557
+ }
2558
+ if (flowPaths.length === 0) {
2559
+ console.log("No flow files found.");
2560
+ return { success: true, watchRoots };
2561
+ }
2562
+ if (flowPaths.some((path) => path.endsWith(".feature")) && stepPaths.length > 0) {
2563
+ await loadStepFiles(stepPaths);
2564
+ }
2565
+ const loadedFlows = await loadFlowsWithSources(flowPaths);
2566
+ let filteredFlows = filterLoadedFlows(loadedFlows, {
2567
+ tags: opts.tags,
2568
+ grep: opts.grep,
2569
+ platforms
2570
+ });
2571
+ if (opts.lastFailed) {
2572
+ const outputDir = config.artifacts?.outputDir ?? resolveFromConfig("./spana-output");
2573
+ const lastRunStatePath = createLastRunStatePath(outputDir);
2574
+ const state = await readLastRunState(lastRunStatePath);
2575
+ if (!state) {
2576
+ console.log("No previous Spana run state found. Run `spana test` once before using --last-failed.");
2577
+ return { success: true, watchRoots };
2578
+ }
2579
+ if (state.failedFlowNames.length === 0) {
2580
+ console.log("No failed flows were recorded in the last Spana run.");
2581
+ return { success: true, watchRoots };
2582
+ }
2583
+ const failedFlowNames = new Set(state.failedFlowNames);
2584
+ filteredFlows = filteredFlows.filter((loaded) => failedFlowNames.has(loaded.flow.name));
2585
+ if (filteredFlows.length === 0) {
2586
+ console.log("No last-failed flows match the current filters.");
2587
+ return { success: true, watchRoots };
2588
+ }
2589
+ console.log(`Rerunning ${filteredFlows.length} flow(s) from the last failed run.`);
2590
+ }
2591
+ const selectedLoadedFlows = applyShard(filteredFlows, opts.shard);
2592
+ const selectedFlows = selectedLoadedFlows.map((loaded) => loaded.flow);
2593
+ if (filteredFlows.length === 0) {
2594
+ console.log("No flows match the given filters.");
2595
+ return { success: true, watchRoots };
2596
+ }
2597
+ if (selectedFlows.length === 0) {
2598
+ console.log(`No flows assigned to shard ${opts.shard.current}/${opts.shard.total}.`);
2599
+ return { success: true, watchRoots };
2600
+ }
2601
+ if (opts.shard) {
2602
+ console.log(
2603
+ `Running shard ${opts.shard.current}/${opts.shard.total} (${selectedFlows.length}/${filteredFlows.length} flow(s))...`
2604
+ );
2605
+ }
2606
+ console.log(`Running ${selectedFlows.length} flow(s) on ${platforms.join(", ")}...
2607
+ `);
2608
+ const runtimes = [];
2609
+ const platformConfigs = [];
2610
+ const runCleanups = [];
2611
+ const handleSignal = () => {
2612
+ for (const cleanup of runCleanups) {
2613
+ try {
2614
+ void cleanup();
2615
+ } catch {
2616
+ }
2617
+ }
2618
+ for (const rt of runtimes) {
2619
+ try {
2620
+ void rt.cleanup();
2621
+ } catch {
2622
+ }
2623
+ }
2624
+ process.exit(1);
2625
+ };
2626
+ process.on("SIGINT", handleSignal);
2627
+ process.on("SIGTERM", handleSignal);
2628
+ try {
2629
+ const appiumUrl = opts.appiumUrl ?? config.execution?.appium?.serverUrl;
2630
+ const appiumConfig = config.execution?.appium ?? {};
2631
+ const shouldReportToProvider = !opts.noProviderReporting && appiumConfig.reportToProvider !== false;
2632
+ const cloudHelper = executionMode === "appium" && appiumUrl ? await createCloudProviderHelper(appiumUrl, appiumConfig) : void 0;
2633
+ const baseAppiumCaps = executionMode === "appium" && appiumUrl ? await resolveCapabilities(appiumConfig, {
2634
+ capsPath: opts.capsPath,
2635
+ capsJson: opts.capsJson
2636
+ }) : void 0;
2637
+ if (cloudHelper) {
2638
+ runCleanups.push(() => cloudHelper.cleanup());
2639
+ }
2640
+ if (opts.parallel || opts.workers || opts.devices) {
2641
+ platformConfigs.push(
2642
+ ...await buildParallelPlatformConfigs(
2643
+ platforms,
2644
+ opts,
2645
+ config,
2646
+ runtimes,
2647
+ resolveFromConfig
2648
+ )
2649
+ );
2650
+ } else {
2651
+ platformConfigs.push(
2652
+ ...await buildSerialPlatformConfigs(
2653
+ platforms,
2654
+ opts,
2655
+ config,
2656
+ runtimes,
2657
+ executionMode,
2658
+ appiumUrl,
2659
+ baseAppiumCaps,
2660
+ cloudHelper,
2661
+ targetDevice,
2662
+ resolveFromConfig
2663
+ )
2664
+ );
2665
+ }
2666
+ const { redactor, reporters } = await setupReporters(
2667
+ reporterNames,
2668
+ config,
2669
+ resolveFromConfig,
2670
+ appiumUrl,
2671
+ opts
2672
+ );
2673
+ const totalFlowCount = selectedFlows.length * platforms.length;
2674
+ for (const reporter of reporters) {
2675
+ if (reporter.flowCount !== void 0 || "flowCount" in reporter) {
2676
+ reporter.flowCount = totalFlowCount;
2677
+ }
2678
+ }
2679
+ const platformCounts = {};
2680
+ for (const p of platforms) {
2681
+ platformCounts[p] = selectedFlows.length;
2682
+ }
2683
+ for (const reporter of reporters) {
2684
+ if ("platformFlowCounts" in reporter) {
2685
+ reporter.platformFlowCounts = platformCounts;
2686
+ }
2687
+ }
2688
+ const redactResult = (r) => {
2689
+ if (!r.error) return r;
2690
+ return {
2691
+ ...r,
2692
+ error: {
2693
+ ...r.error,
2694
+ message: redactor.redact(r.error.message),
2695
+ stack: r.error.stack ? redactor.redact(r.error.stack) : void 0,
2696
+ suggestion: r.error.suggestion ? redactor.redact(r.error.suggestion) : void 0
2697
+ }
2698
+ };
2699
+ };
2700
+ const retries = opts.retries ?? config.defaults?.retries ?? 0;
2701
+ const retryDelay = config.defaults?.retryDelay ?? 0;
2702
+ const result = await orchestrate(selectedFlows, platformConfigs, {
2703
+ retries,
2704
+ retryDelay,
2705
+ bail: opts.bail,
2706
+ parallelPlatforms: opts.parallel || !!opts.workers || !!opts.devices,
2707
+ onFlowStart(name, platform, workerName) {
2708
+ for (const reporter of reporters) {
2709
+ reporter.onFlowStart?.(name, platform, workerName);
2710
+ }
2711
+ },
2712
+ onResult(r) {
2713
+ const redacted = redactResult(r);
2714
+ for (const reporter of reporters) {
2715
+ if (redacted.status === "passed") {
2716
+ reporter.onFlowPass?.(redacted);
2717
+ } else if (redacted.status === "failed") {
2718
+ reporter.onFlowFail?.(redacted);
2719
+ if (opts.verbose && redacted.error) {
2720
+ console.log(
2721
+ `
2722
+ [verbose] Failure details for "${redacted.name}" on ${redacted.platform}:`
2723
+ );
2724
+ console.log(` Category: ${redacted.error.category}`);
2725
+ console.log(` Message: ${redacted.error.message}`);
2726
+ if (redacted.error.suggestion) {
2727
+ console.log(` Suggestion: ${redacted.error.suggestion}`);
2728
+ }
2729
+ for (const section of collectDiagnosticSections(redacted.attachments, {
2730
+ verbose: true
2731
+ })) {
2732
+ console.log(` ${section.title}: ${redactor.redact(section.path)}`);
2733
+ console.log(
2734
+ section.body.split("\n").map((line) => ` ${redactor.redact(line)}`).join("\n")
2735
+ );
2736
+ }
2737
+ if (redacted.error.stack) {
2738
+ console.log(
2739
+ ` Stack:
2740
+ ${redacted.error.stack.split("\n").map((l) => ` ${l}`).join("\n")}`
2741
+ );
2742
+ }
2743
+ }
2744
+ }
2745
+ }
2746
+ }
2747
+ });
2748
+ const redactedResults = result.results.map(redactResult);
2749
+ for (const reporter of reporters) {
2750
+ reporter.onRunComplete({
2751
+ total: result.results.length,
2752
+ passed: result.passed,
2753
+ failed: result.failed,
2754
+ skipped: result.skipped,
2755
+ flaky: result.flaky,
2756
+ durationMs: result.totalDurationMs,
2757
+ results: redactedResults,
2758
+ platforms,
2759
+ bailedOut: result.bailedOut,
2760
+ bailLimit: result.bailLimit,
2761
+ workerStats: result.workerStats
2762
+ });
2763
+ }
2764
+ const sourcePathsByFlowName = new Map(
2765
+ selectedLoadedFlows.map((loaded) => [loaded.flow.name, loaded.sourcePath])
2766
+ );
2767
+ const iterationStatePath = createLastRunStatePath(
2768
+ config.artifacts?.outputDir ?? resolveFromConfig("./spana-output")
2769
+ );
2770
+ try {
2771
+ await writeLastRunState(
2772
+ iterationStatePath,
2773
+ buildLastRunState({
2774
+ flowDir,
2775
+ platforms,
2776
+ results: result.results,
2777
+ sourcePathsByFlowName
2778
+ })
2779
+ );
2780
+ } catch (error) {
2781
+ console.log(
2782
+ `Warning: Failed to update last run state at ${iterationStatePath}: ${error instanceof Error ? error.message : error}`
2783
+ );
2784
+ }
2785
+ if (shouldReportToProvider && appiumUrl) {
2786
+ const { detectProvider: detectProvider2 } = await import("./provider-A57C3MU6.js");
2787
+ for (const rt of runtimes) {
2788
+ if (rt.metadata.mode === "appium" && rt.metadata.provider) {
2789
+ const provider = detectProvider2(appiumUrl);
2790
+ if (provider) {
2791
+ try {
2792
+ const meta = {};
2793
+ provider.extractMeta(rt.metadata.sessionId, rt.metadata.sessionCaps ?? {}, meta);
2794
+ await provider.reportResult(appiumUrl, meta, {
2795
+ passed: result.failed === 0,
2796
+ name: `spana ${platforms.join(",")}`
2797
+ });
2798
+ } catch (e) {
2799
+ console.log(
2800
+ `Warning: Failed to report to ${rt.metadata.provider}: ${e instanceof Error ? e.message : e}`
2801
+ );
2802
+ }
2803
+ }
2804
+ }
2805
+ }
2806
+ }
2807
+ return { success: result.failed === 0, watchRoots };
2808
+ } finally {
2809
+ for (const rt of runtimes) {
2810
+ try {
2811
+ await rt.cleanup();
2812
+ } catch {
2813
+ }
2814
+ }
2815
+ for (const cleanup of runCleanups) {
2816
+ try {
2817
+ await cleanup();
2818
+ } catch {
2819
+ }
2820
+ }
2821
+ process.removeListener("SIGINT", handleSignal);
2822
+ process.removeListener("SIGTERM", handleSignal);
2823
+ }
2824
+ }
2825
+ async function runTestCommand(opts) {
2826
+ if (!opts.watch) {
2827
+ return (await runTestCommandOnce(opts)).success;
2828
+ }
2829
+ let lastResult = await runTestCommandOnce({ ...opts, watch: false });
2830
+ if (lastResult.watchRoots.length === 0) {
2831
+ return lastResult.success;
2832
+ }
2833
+ console.log(
2834
+ `Watching ${lastResult.watchRoots.length} path(s) for changes. Press Ctrl+C to stop.`
2835
+ );
2836
+ await runWatchLoop({
2837
+ roots: lastResult.watchRoots,
2838
+ onChange: async (changedPaths) => {
2839
+ console.log(`
2840
+ Change detected:
2841
+ ${changedPaths.map((path) => ` ${path}`).join("\n")}
2842
+ `);
2843
+ lastResult = await runTestCommandOnce({ ...opts, watch: false });
2844
+ }
2845
+ });
2846
+ return lastResult.success;
2847
+ }
2848
+ export {
2849
+ loadCustomReporter,
2850
+ runTestCommand
2851
+ };
2852
+ //# sourceMappingURL=test-command-AHMOZLV4.js.map