spana-test 0.3.0 → 0.5.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 (152) hide show
  1. package/.agents/skills/spana-testing/SKILL.md +0 -0
  2. package/LICENSE +0 -0
  3. package/README.md +199 -68
  4. package/dist/{accessibility-audit-RS3VIWRT.js → accessibility-audit-YZOPUY3D.js} +7 -3
  5. package/dist/accessibility-audit-YZOPUY3D.js.map +1 -0
  6. package/dist/agent/index.d.ts +3 -84
  7. package/dist/agent/index.js +12 -11
  8. package/dist/agent/index.js.map +0 -0
  9. package/dist/allure-RNMEYTXS.js +0 -0
  10. package/dist/allure-RNMEYTXS.js.map +0 -0
  11. package/dist/{android-PAPJJWVN.js → android-4NVTZMHL.js} +20 -2
  12. package/dist/{android-PAPJJWVN.js.map → android-4NVTZMHL.js.map} +0 -0
  13. package/dist/appium-server-66GVUL24.js +0 -0
  14. package/dist/appium-server-66GVUL24.js.map +0 -0
  15. package/dist/baseline-manager-5TIUCNP5.js +0 -0
  16. package/dist/baseline-manager-5TIUCNP5.js.map +0 -0
  17. package/dist/chunk-3FSZNKEF.js +0 -0
  18. package/dist/chunk-3FSZNKEF.js.map +0 -0
  19. package/dist/chunk-3TRMQCUT.js +0 -0
  20. package/dist/chunk-3TRMQCUT.js.map +0 -0
  21. package/dist/chunk-3YE2POGD.js +471 -0
  22. package/dist/chunk-3YE2POGD.js.map +1 -0
  23. package/dist/chunk-5245YBLL.js +0 -0
  24. package/dist/chunk-5245YBLL.js.map +0 -0
  25. package/dist/{chunk-3J4NG7JU.js → chunk-CY3DKTBZ.js} +8 -2
  26. package/dist/chunk-CY3DKTBZ.js.map +1 -0
  27. package/dist/chunk-DGUM43GV.js +0 -0
  28. package/dist/chunk-DGUM43GV.js.map +0 -0
  29. package/dist/chunk-DTNK54C2.js +127 -0
  30. package/dist/chunk-DTNK54C2.js.map +1 -0
  31. package/dist/{chunk-GZK22EIE.js → chunk-H27IBIGA.js} +71 -1
  32. package/dist/chunk-H27IBIGA.js.map +1 -0
  33. package/dist/chunk-H3RWZCID.js +439 -0
  34. package/dist/chunk-H3RWZCID.js.map +1 -0
  35. package/dist/{chunk-DSTUWLSW.js → chunk-HCG4CJKR.js} +24 -6
  36. package/dist/chunk-HCG4CJKR.js.map +1 -0
  37. package/dist/{chunk-QPIE3IMG.js → chunk-HYSTRWYN.js} +143 -42
  38. package/dist/chunk-HYSTRWYN.js.map +1 -0
  39. package/dist/chunk-IHVZKQQW.js +0 -0
  40. package/dist/chunk-IHVZKQQW.js.map +0 -0
  41. package/dist/chunk-KJPHH2TW.js +0 -0
  42. package/dist/chunk-KJPHH2TW.js.map +0 -0
  43. package/dist/chunk-LAMTF4LX.js +89 -0
  44. package/dist/chunk-LAMTF4LX.js.map +1 -0
  45. package/dist/chunk-LRGT342X.js +2300 -0
  46. package/dist/chunk-LRGT342X.js.map +1 -0
  47. package/dist/chunk-OBCFACUW.js +0 -0
  48. package/dist/chunk-OBCFACUW.js.map +0 -0
  49. package/dist/chunk-PJKIXVSO.js +5019 -0
  50. package/dist/chunk-PJKIXVSO.js.map +1 -0
  51. package/dist/{chunk-4OHBO7LD.js → chunk-S5JNNDXS.js} +44 -1
  52. package/dist/{chunk-4OHBO7LD.js.map → chunk-S5JNNDXS.js.map} +1 -1
  53. package/dist/{chunk-7VOWF42B.js → chunk-SQL3YRR5.js} +74 -8
  54. package/dist/chunk-SQL3YRR5.js.map +1 -0
  55. package/dist/{chunk-7IA2XG3G.js → chunk-UJQ7PID5.js} +47 -15
  56. package/dist/chunk-UJQ7PID5.js.map +1 -0
  57. package/dist/{chunk-FJAJ4YNC.js → chunk-WSA5QPTA.js} +2 -2
  58. package/dist/{chunk-FJAJ4YNC.js.map → chunk-WSA5QPTA.js.map} +0 -0
  59. package/dist/chunk-X2TJP7LB.js +0 -0
  60. package/dist/chunk-X2TJP7LB.js.map +0 -0
  61. package/dist/chunk-XENRC3YO.js +2486 -0
  62. package/dist/chunk-XENRC3YO.js.map +1 -0
  63. package/dist/cli.js +60 -20
  64. package/dist/cli.js.map +1 -1
  65. package/dist/compiler-X6WTFMYF.js +0 -0
  66. package/dist/compiler-X6WTFMYF.js.map +0 -0
  67. package/dist/config-loader-XGDDJGVY.js +9 -0
  68. package/dist/{config-loader-QM72GKEL.js.map → config-loader-XGDDJGVY.js.map} +0 -0
  69. package/dist/{console-7UW7VROK.js → console-MI2XB5RG.js} +8 -2
  70. package/dist/console-MI2XB5RG.js.map +1 -0
  71. package/dist/daemon-manager-FBISTX24.js +28 -0
  72. package/dist/{discover-NPNF6SWQ.js.map → daemon-manager-FBISTX24.js.map} +0 -0
  73. package/dist/{discover-NPNF6SWQ.js → discover-LHEBSUIP.js} +4 -4
  74. package/dist/{installer-W5DITECS.js.map → discover-LHEBSUIP.js.map} +0 -0
  75. package/dist/doctor-command-WB3O2H64.js +378 -0
  76. package/dist/doctor-command-WB3O2H64.js.map +1 -0
  77. package/dist/filters-Q3ALKWZ5.js +24 -0
  78. package/dist/{ios-3GRECXAP.js.map → filters-Q3ALKWZ5.js.map} +0 -0
  79. package/dist/{flow-CW0_j7tw.d.ts → flow-CyRC-tTc.d.ts} +37 -7
  80. package/dist/gherkin/steps.d.ts +2 -2
  81. package/dist/gherkin/steps.js +0 -0
  82. package/dist/gherkin/steps.js.map +0 -0
  83. package/dist/github-pr-YMWIPCCZ.js +10 -0
  84. package/dist/{session-3UZ5WAAD.js.map → github-pr-YMWIPCCZ.js.map} +0 -0
  85. package/dist/html-F3X3XPSX.js +0 -0
  86. package/dist/html-F3X3XPSX.js.map +0 -0
  87. package/dist/index.d.ts +1129 -6
  88. package/dist/index.js +575 -6
  89. package/dist/index.js.map +1 -1
  90. package/dist/{init-command-U66XCM66.js → init-command-Z3QREABL.js} +60 -1
  91. package/dist/init-command-Z3QREABL.js.map +1 -0
  92. package/dist/{init-flow-command-PR7J5FBM.js → init-flow-command-4EKRVTNT.js} +2 -2
  93. package/dist/{init-flow-command-PR7J5FBM.js.map → init-flow-command-4EKRVTNT.js.map} +0 -0
  94. package/dist/{installer-W5DITECS.js → installer-VUPFWP5X.js} +7 -2
  95. package/dist/installer-VUPFWP5X.js.map +1 -0
  96. package/dist/{ios-3GRECXAP.js → ios-JPK43TFZ.js} +10 -2
  97. package/dist/ios-JPK43TFZ.js.map +1 -0
  98. package/dist/json-JMRPUVY2.js +0 -0
  99. package/dist/json-JMRPUVY2.js.map +0 -0
  100. package/dist/junit-HLC62MK6.js +0 -0
  101. package/dist/junit-HLC62MK6.js.map +0 -0
  102. package/dist/machine-6H25TRTU.js +0 -0
  103. package/dist/machine-6H25TRTU.js.map +0 -0
  104. package/dist/provider-YIPU5K42.js +0 -0
  105. package/dist/provider-YIPU5K42.js.map +0 -0
  106. package/dist/redact-U72BUBBR.js +0 -0
  107. package/dist/redact-U72BUBBR.js.map +0 -0
  108. package/dist/runner-6HK62Q7B.js +0 -0
  109. package/dist/runner-6HK62Q7B.js.map +0 -0
  110. package/dist/screenshot-compare-3QRHHSFZ.js +116 -0
  111. package/dist/screenshot-compare-3QRHHSFZ.js.map +1 -0
  112. package/dist/{server-MZERO364.js → server-PRM7BVVD.js} +14 -13
  113. package/dist/{server-MZERO364.js.map → server-PRM7BVVD.js.map} +1 -1
  114. package/dist/server-QWJJB3WG.js +14 -0
  115. package/dist/server-QWJJB3WG.js.map +1 -0
  116. package/dist/session-2E6OK6BH.js +18 -0
  117. package/dist/session-2E6OK6BH.js.map +1 -0
  118. package/dist/session-Ddem-Q5n.d.ts +119 -0
  119. package/dist/{storybook-BK2JE4ld.d.ts → storybook-CxaP3YDz.d.ts} +271 -6
  120. package/dist/{studio-command-5BUER2RH.js → studio-command-O3NN5BCG.js} +2 -2
  121. package/dist/{studio-command-5BUER2RH.js.map → studio-command-O3NN5BCG.js.map} +0 -0
  122. package/dist/{test-command-2PXTHASW.js → test-command-FYOZ6QAE.js} +275 -1314
  123. package/dist/test-command-FYOZ6QAE.js.map +1 -0
  124. package/dist/validator-HZ2A3NEI.js +0 -0
  125. package/dist/validator-HZ2A3NEI.js.map +0 -0
  126. package/package.json +7 -3
  127. package/studio-dist/assets/index-C-Io44gy.js +0 -0
  128. package/studio-dist/assets/index-DfM9lK4p.css +0 -0
  129. package/studio-dist/index.html +0 -0
  130. package/dist/accessibility-audit-RS3VIWRT.js.map +0 -1
  131. package/dist/chunk-24KSKK2I.js +0 -1289
  132. package/dist/chunk-24KSKK2I.js.map +0 -1
  133. package/dist/chunk-3J4NG7JU.js.map +0 -1
  134. package/dist/chunk-7IA2XG3G.js.map +0 -1
  135. package/dist/chunk-7VOWF42B.js.map +0 -1
  136. package/dist/chunk-DSTUWLSW.js.map +0 -1
  137. package/dist/chunk-GZK22EIE.js.map +0 -1
  138. package/dist/chunk-KAKHFSVA.js +0 -2580
  139. package/dist/chunk-KAKHFSVA.js.map +0 -1
  140. package/dist/chunk-QPIE3IMG.js.map +0 -1
  141. package/dist/chunk-YXQEPVEW.js +0 -372
  142. package/dist/chunk-YXQEPVEW.js.map +0 -1
  143. package/dist/config-loader-QM72GKEL.js +0 -9
  144. package/dist/console-7UW7VROK.js.map +0 -1
  145. package/dist/doctor-command-C3SEQGRQ.js +0 -71
  146. package/dist/doctor-command-C3SEQGRQ.js.map +0 -1
  147. package/dist/element-DZ0HyJ3C.d.ts +0 -25
  148. package/dist/init-command-U66XCM66.js.map +0 -1
  149. package/dist/screenshot-compare-JFHH2WR4.js +0 -75
  150. package/dist/screenshot-compare-JFHH2WR4.js.map +0 -1
  151. package/dist/session-3UZ5WAAD.js +0 -17
  152. package/dist/test-command-2PXTHASW.js.map +0 -1
@@ -1,38 +1,26 @@
1
1
  import {
2
2
  loadConfig
3
- } from "./chunk-FJAJ4YNC.js";
3
+ } from "./chunk-WSA5QPTA.js";
4
4
  import {
5
5
  collectDiagnosticSections
6
6
  } from "./chunk-KJPHH2TW.js";
7
7
  import {
8
- createPromiseApp,
9
- createPromiseExpect
10
- } from "./chunk-YXQEPVEW.js";
11
- import "./chunk-7VOWF42B.js";
8
+ buildElectrobunRuntime,
9
+ buildElectronRuntime,
10
+ buildLocalAndroidRuntime,
11
+ buildLocalIOSRuntime,
12
+ buildWebRuntime,
13
+ buildWebRuntimePool,
14
+ classifyError,
15
+ executeFlow,
16
+ runParallel,
17
+ speculativelyPrelaunchWebBrowser
18
+ } from "./chunk-LRGT342X.js";
19
+ import "./chunk-SQL3YRR5.js";
12
20
  import {
13
- createUiAutomator2Driver,
14
- createWDADriver,
15
- makePlaywrightDriver,
16
- parseAndroidHierarchy,
17
- parseIOSHierarchy,
18
- parseWebHierarchy,
19
- setupUiAutomator2
20
- } from "./chunk-KAKHFSVA.js";
21
- import {
22
- setupWDA
23
- } from "./chunk-QPIE3IMG.js";
24
- import {
25
- ensureAndroidDevice
26
- } from "./chunk-GZK22EIE.js";
27
- import {
28
- connectPhysicalDevice,
29
- ensureAppInstalled,
30
- ensureIOSSimulator,
31
- firstIOSPhysicalDevice
32
- } from "./chunk-4OHBO7LD.js";
33
- import {
34
- allocatePort
35
- } from "./chunk-OBCFACUW.js";
21
+ createCloudProviderHelper,
22
+ detectProvider
23
+ } from "./chunk-X2TJP7LB.js";
36
24
  import {
37
25
  applyShard,
38
26
  discoverFlows,
@@ -42,965 +30,27 @@ import {
42
30
  loadTestSource
43
31
  } from "./chunk-3TRMQCUT.js";
44
32
  import {
45
- DriverError,
46
33
  buildIOSLaunchConfiguration,
47
34
  deviceStateToAppiumCapabilities,
48
- flattenElements,
49
35
  hasLaunchDeviceState,
50
- mergeLaunchOptions,
36
+ parseAndroidHierarchy,
37
+ parseIOSHierarchy,
38
+ resolveNetworkConditions,
51
39
  splitGraphemes
52
- } from "./chunk-24KSKK2I.js";
40
+ } from "./chunk-PJKIXVSO.js";
53
41
  import {
54
- createCloudProviderHelper,
55
- detectProvider
56
- } from "./chunk-X2TJP7LB.js";
42
+ DriverError
43
+ } from "./chunk-XENRC3YO.js";
44
+ import "./chunk-HYSTRWYN.js";
45
+ import "./chunk-DTNK54C2.js";
46
+ import "./chunk-S5JNNDXS.js";
47
+ import "./chunk-OBCFACUW.js";
48
+ import "./chunk-H27IBIGA.js";
57
49
  import "./chunk-DGUM43GV.js";
58
50
 
59
51
  // src/cli/test-command.ts
60
52
  import { resolve as resolve3, dirname as dirname3 } from "path";
61
53
 
62
- // src/core/engine.ts
63
- import { Effect as Effect3 } from "effect";
64
-
65
- // src/core/artifacts.ts
66
- import { writeFileSync, mkdirSync } from "fs";
67
- import { join } from "path";
68
- import { Effect } from "effect";
69
- var DEFAULT_ARTIFACT_CONFIG = {
70
- outputDir: "./spana-output",
71
- captureOnFailure: true,
72
- captureOnSuccess: false,
73
- captureSteps: false,
74
- screenshot: true,
75
- uiHierarchy: true,
76
- consoleLogs: true,
77
- jsErrors: true,
78
- har: true
79
- };
80
- function safeName(value) {
81
- return value.replaceAll(/[^a-zA-Z0-9-_]/g, "_").replaceAll(/_+/g, "_").replaceAll(/^_+|_+$/g, "").slice(0, 80) || "artifact";
82
- }
83
- function flowArtifactDir(config, flowName, platform) {
84
- const dir = join(config.outputDir, `${safeName(flowName)}-${platform}`);
85
- mkdirSync(dir, { recursive: true });
86
- return dir;
87
- }
88
- function createAttachment(name, contentType, path) {
89
- return { name, contentType, path };
90
- }
91
- function writeJsonAttachment(dir, fileName, attachmentName, value) {
92
- const path = join(dir, fileName);
93
- writeFileSync(path, JSON.stringify(value, null, 2), "utf-8");
94
- return createAttachment(attachmentName, "application/json", path);
95
- }
96
- function writeTextAttachment(dir, fileName, attachmentName, value) {
97
- const path = join(dir, fileName);
98
- writeFileSync(path, value, "utf-8");
99
- return createAttachment(attachmentName, "text/plain", path);
100
- }
101
- function resolveArtifactConfig(...configs) {
102
- return configs.reduce(
103
- (resolved, config) => ({
104
- ...resolved,
105
- ...config
106
- }),
107
- { ...DEFAULT_ARTIFACT_CONFIG }
108
- );
109
- }
110
- async function captureArtifacts(driver, config, flowName, platform, status) {
111
- const shouldCapture = status === "failed" && config.captureOnFailure || status === "passed" && config.captureOnSuccess;
112
- if (!shouldCapture) return [];
113
- const attachments = [];
114
- const dir = flowArtifactDir(config, flowName, platform);
115
- if (config.screenshot) {
116
- try {
117
- const screenshot = await Effect.runPromise(Effect.orDie(driver.takeScreenshot()));
118
- const path = join(dir, "screenshot.png");
119
- writeFileSync(path, screenshot);
120
- attachments.push(createAttachment(`${status}-screenshot`, "image/png", path));
121
- } catch {
122
- }
123
- }
124
- if (config.uiHierarchy) {
125
- try {
126
- const hierarchy = await Effect.runPromise(Effect.orDie(driver.dumpHierarchy()));
127
- const path = join(dir, "hierarchy.json");
128
- writeFileSync(path, hierarchy, "utf-8");
129
- attachments.push(createAttachment(`${status}-hierarchy`, "application/json", path));
130
- } catch {
131
- }
132
- }
133
- if (config.consoleLogs && driver.getConsoleLogs) {
134
- try {
135
- const consoleLogs = await Effect.runPromise(Effect.orDie(driver.getConsoleLogs()));
136
- if (consoleLogs.length > 0) {
137
- attachments.push(
138
- writeJsonAttachment(dir, "console-logs.json", `${status}-console-logs`, consoleLogs)
139
- );
140
- }
141
- } catch {
142
- }
143
- }
144
- if (config.jsErrors && driver.getJSErrors) {
145
- try {
146
- const jsErrors = await Effect.runPromise(Effect.orDie(driver.getJSErrors()));
147
- if (jsErrors.length > 0) {
148
- attachments.push(
149
- writeJsonAttachment(dir, "js-errors.json", `${status}-js-errors`, jsErrors)
150
- );
151
- }
152
- } catch {
153
- }
154
- }
155
- if (config.har && driver.getHAR) {
156
- try {
157
- const har = await Effect.runPromise(Effect.orDie(driver.getHAR()));
158
- if (har.log.entries.length > 0) {
159
- attachments.push(writeJsonAttachment(dir, "network.har", `${status}-network-har`, har));
160
- }
161
- } catch {
162
- }
163
- }
164
- if (status === "failed" && driver.getDriverLogs) {
165
- try {
166
- const driverLogs = await Effect.runPromise(Effect.orDie(driver.getDriverLogs()));
167
- if (driverLogs.length > 0) {
168
- attachments.push(
169
- writeTextAttachment(
170
- dir,
171
- "driver-logs.txt",
172
- `${status}-driver-logs`,
173
- driverLogs.join("\n")
174
- )
175
- );
176
- }
177
- } catch {
178
- }
179
- }
180
- return attachments;
181
- }
182
- async function captureStepScreenshot(driver, config, flowName, platform, stepIndex, stepName, screenshot) {
183
- if (!config.screenshot) return void 0;
184
- try {
185
- const dir = join(flowArtifactDir(config, flowName, platform), "steps");
186
- mkdirSync(dir, { recursive: true });
187
- const fileName = `${String(stepIndex).padStart(3, "0")}-${safeName(stepName)}.png`;
188
- const path = join(dir, fileName);
189
- const bytes = screenshot ?? await Effect.runPromise(Effect.orDie(driver.takeScreenshot()));
190
- writeFileSync(path, bytes);
191
- return createAttachment(stepName, "image/png", path);
192
- } catch {
193
- return void 0;
194
- }
195
- }
196
-
197
- // src/core/debug-repl.ts
198
- import * as repl from "repl";
199
- import { Effect as Effect2 } from "effect";
200
- var didStartDebugRepl = false;
201
- function toSuggestedSelectors(root) {
202
- return flattenElements(root).filter((el) => el.visible !== false && (el.id || el.text || el.accessibilityLabel)).map((el) => ({
203
- suggestedSelector: el.id ? { testID: el.id } : el.accessibilityLabel ? { accessibilityLabel: el.accessibilityLabel } : el.text ? { text: el.text } : "",
204
- elementType: el.elementType,
205
- text: el.text,
206
- accessibilityLabel: el.accessibilityLabel,
207
- bounds: el.bounds,
208
- id: el.id
209
- }));
210
- }
211
- async function runDebugReplOnce(context) {
212
- if (didStartDebugRepl) {
213
- return false;
214
- }
215
- didStartDebugRepl = true;
216
- if (!process.stdin.isTTY || !process.stdout.isTTY) {
217
- console.log("Skipping debug REPL because stdin/stdout is not interactive.");
218
- return false;
219
- }
220
- const hierarchy = async () => context.parseHierarchy(await Effect2.runPromise(context.driver.dumpHierarchy()));
221
- const selectors = async () => toSuggestedSelectors(await hierarchy());
222
- console.log("");
223
- console.log(`Entering debug REPL for failed flow "${context.flowName}" on ${context.platform}.`);
224
- console.log(
225
- "Available bindings: app, expect, driver, platform, flowName, error, hierarchy(), selectors(), help()"
226
- );
227
- console.log('Use top-level await for async calls, for example: await app.tap({ text: "Login" })');
228
- const replServer = repl.start({
229
- prompt: `spana:${context.platform}> `,
230
- ignoreUndefined: true,
231
- useGlobal: false
232
- });
233
- replServer.context.app = context.app;
234
- replServer.context.expect = context.expect;
235
- replServer.context.driver = context.driver;
236
- replServer.context.platform = context.platform;
237
- replServer.context.flowName = context.flowName;
238
- replServer.context.error = context.error;
239
- replServer.context.hierarchy = hierarchy;
240
- replServer.context.selectors = selectors;
241
- replServer.context.help = () => {
242
- console.log("app Promise-based app API with auto-waiting");
243
- console.log("expect Assertion helper, e.g. await expect({ text: 'Done' }).toBeVisible()");
244
- console.log("driver Raw driver service");
245
- console.log("hierarchy Async helper returning the parsed UI tree");
246
- console.log("selectors Async helper returning suggested selectors");
247
- console.log(".exit Leave the REPL");
248
- };
249
- await new Promise((resolve4) => replServer.on("exit", resolve4));
250
- console.log("");
251
- return true;
252
- }
253
-
254
- // src/core/step-recorder.ts
255
- function errorMessage(error) {
256
- return error instanceof Error ? error.message : String(error);
257
- }
258
- function createStepResult(command, durationMs, status, selector, error, attachments) {
259
- return {
260
- command,
261
- selector,
262
- status,
263
- durationMs,
264
- error,
265
- attachments: attachments && attachments.length > 0 ? attachments : void 0
266
- };
267
- }
268
- function createStepRecorder(driver, artifactConfig, flowName, platform) {
269
- const steps = [];
270
- return {
271
- async runStep(command, action, opts) {
272
- const startedAt = Date.now();
273
- try {
274
- const result = await action();
275
- const attachments = [];
276
- if (opts?.captureScreenshot && artifactConfig.captureSteps) {
277
- const attachment = await captureStepScreenshot(
278
- driver,
279
- artifactConfig,
280
- flowName,
281
- platform,
282
- steps.length + 1,
283
- command
284
- );
285
- if (attachment) attachments.push(attachment);
286
- }
287
- steps.push(
288
- createStepResult(
289
- command,
290
- Date.now() - startedAt,
291
- "passed",
292
- opts?.selector,
293
- void 0,
294
- attachments
295
- )
296
- );
297
- return result;
298
- } catch (error) {
299
- steps.push(
300
- createStepResult(
301
- command,
302
- Date.now() - startedAt,
303
- "failed",
304
- opts?.selector,
305
- errorMessage(error)
306
- )
307
- );
308
- throw error;
309
- }
310
- },
311
- async runScreenshotStep(command, action, opts) {
312
- const startedAt = Date.now();
313
- try {
314
- const screenshot = await action();
315
- const attachment = await captureStepScreenshot(
316
- driver,
317
- artifactConfig,
318
- flowName,
319
- platform,
320
- steps.length + 1,
321
- opts?.name ?? command,
322
- screenshot
323
- );
324
- steps.push(
325
- createStepResult(
326
- command,
327
- Date.now() - startedAt,
328
- "passed",
329
- opts?.selector,
330
- void 0,
331
- attachment ? [attachment] : void 0
332
- )
333
- );
334
- return screenshot;
335
- } catch (error) {
336
- steps.push(
337
- createStepResult(
338
- command,
339
- Date.now() - startedAt,
340
- "failed",
341
- opts?.selector,
342
- errorMessage(error)
343
- )
344
- );
345
- throw error;
346
- }
347
- },
348
- getSteps() {
349
- return steps;
350
- }
351
- };
352
- }
353
-
354
- // src/report/classify-error.ts
355
- var TAG_KEY = "_tag";
356
- function selectorHint(selector) {
357
- if (selector && typeof selector === "object") {
358
- const s = selector;
359
- if (s.testID) return `testID="${s.testID}"`;
360
- if (s.text) return `text="${s.text}"`;
361
- if (s.accessibilityLabel) return `accessibilityLabel="${s.accessibilityLabel}"`;
362
- }
363
- return JSON.stringify(selector);
364
- }
365
- function categorizeElementFailure(message) {
366
- const lower = message.toLowerCase();
367
- if (lower.includes("not visible") || lower.includes("visible=false")) {
368
- return "element-not-visible";
369
- }
370
- if (lower.includes("off-screen") || lower.includes("zero size")) {
371
- return "element-off-screen";
372
- }
373
- if (lower.includes("disabled") || lower.includes("not interactive")) {
374
- return "element-not-interactive";
375
- }
376
- return "element-not-found";
377
- }
378
- function elementSuggestion(category, selector, timeoutMs) {
379
- switch (category) {
380
- case "element-not-visible":
381
- return [
382
- `Selector ${selector} matched an element, but it is currently hidden.`,
383
- "Check whether an animation, modal, or loading state is covering it before retrying.",
384
- "Consider increasing waitTimeout if the element becomes visible after a delay."
385
- ].join("\n");
386
- case "element-off-screen":
387
- return [
388
- `Selector ${selector} matched an element that is off-screen.`,
389
- "Use scrollUntilVisible() or scroll to the element before interacting with it.",
390
- "If the target is above the current viewport, reverse the search direction."
391
- ].join("\n");
392
- case "element-not-interactive":
393
- return [
394
- `Selector ${selector} matched an element that is disabled or not interactive.`,
395
- "Wait for the app to enable it, or verify the prerequisite app state first.",
396
- "Consider increasing waitTimeout if the control becomes enabled after async work completes."
397
- ].join("\n");
398
- default:
399
- return [
400
- `Selector ${selector} was not found within ${timeoutMs ?? "?"}ms.`,
401
- "Run `spana selectors` to inspect the current screen and confirm the best selector.",
402
- "Consider increasing waitTimeout if the element appears after a delay."
403
- ].join("\n");
404
- }
405
- }
406
- function categorizeDynamic(error, tag, msg) {
407
- if (tag === "ElementNotFoundError" || tag === "WaitTimeoutError") {
408
- const sel = selectorHint(error.selector);
409
- if (msg.includes("scroll(s) toward")) {
410
- return {
411
- category: "element-not-found",
412
- suggestion: [
413
- `Selector ${sel} stayed off-screen while scrolling.`,
414
- "Try increasing `maxScrolls` or `timeout`, or reverse the search direction",
415
- 'if the target is actually above the current viewport (for example `{ direction: "up" }`).'
416
- ].join("\n")
417
- };
418
- }
419
- if (msg.includes("back action(s)")) {
420
- return {
421
- category: "element-not-found",
422
- suggestion: [
423
- `Selector ${sel} was not reached while navigating back.`,
424
- "Try increasing `maxBacks` or `timeout`, or prefer an explicit in-app",
425
- "back / close control on iOS-style screens instead of relying on system back."
426
- ].join("\n")
427
- };
428
- }
429
- const category = categorizeElementFailure(msg);
430
- return {
431
- category,
432
- suggestion: elementSuggestion(category, sel, error.timeoutMs)
433
- };
434
- }
435
- if (tag === "TextMismatchError") {
436
- const e = error;
437
- return {
438
- category: "text-mismatch",
439
- suggestion: [
440
- `Expected text "${e.expected}" but found "${e.actual ?? "(empty)"}".`,
441
- "The element exists but its content differs. Check for whitespace, truncation,",
442
- "or platform-specific text rendering differences."
443
- ].join("\n")
444
- };
445
- }
446
- if (tag === "DeviceDisconnectedError") {
447
- const id = error.deviceId ? ` (${error.deviceId})` : "";
448
- return {
449
- category: "device-disconnected",
450
- suggestion: [
451
- `The device${id} disconnected during the test.`,
452
- "Check the physical connection or emulator/simulator stability.",
453
- "Run `spana devices` to verify available devices."
454
- ].join("\n")
455
- };
456
- }
457
- if (tag === "AppCrashedError") {
458
- const app = error.appId ? ` (${error.appId})` : "";
459
- return {
460
- category: "app-crashed",
461
- suggestion: [
462
- `The app${app} crashed during the test.`,
463
- "Check the device logs for a crash stack trace:",
464
- " Android: `adb logcat -d | grep FATAL`",
465
- " iOS: Check Console.app or `log show --predicate 'process == \"your-app\"'`"
466
- ].join("\n")
467
- };
468
- }
469
- if (tag === "AppNotInstalledError") {
470
- return {
471
- category: "app-not-installed",
472
- suggestion: [
473
- `App "${error.appId}" is not installed on the device.`,
474
- "Install it before running tests, or configure `apps.android.appPath`",
475
- "/ `apps.ios.appPath` in spana.config.ts for auto-install."
476
- ].join("\n")
477
- };
478
- }
479
- if (tag === "DriverError") {
480
- return categorizeDynamicDriver(error, msg);
481
- }
482
- return void 0;
483
- }
484
- function categorizeDynamicDriver(error, msg) {
485
- for (const rule of driverRules) {
486
- if (rule.pattern && matchesPattern(msg, rule.pattern)) {
487
- return {
488
- category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
489
- suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
490
- };
491
- }
492
- }
493
- return {
494
- category: "driver-error",
495
- 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."
496
- };
497
- }
498
- var driverRules = [
499
- {
500
- pattern: "dismissKeyboard()",
501
- category: "driver-error",
502
- suggestion: [
503
- "Keyboard dismissal failed.",
504
- 'On Android, try `app.dismissKeyboard({ strategy: "back" })`.',
505
- "On iOS, prefer tapping a visible Done / Close control or a non-input element."
506
- ].join("\n")
507
- },
508
- {
509
- pattern: "backUntilVisible()",
510
- category: "driver-error",
511
- suggestion: [
512
- "System back navigation failed before the target screen became visible.",
513
- "If this route uses app-level navigation, tap the visible back / close control instead.",
514
- "This is especially common on iOS where a system back button may not exist."
515
- ].join("\n")
516
- },
517
- {
518
- pattern: "Input text failed",
519
- category: "driver-error",
520
- suggestion: [
521
- "Text input failed at the driver layer.",
522
- "Make sure the field is focused first, and retry with shorter input chunks if needed.",
523
- "If the keyboard is in the way, dismiss it before continuing the flow."
524
- ].join("\n")
525
- }
526
- ];
527
- var tagOnlyRules = [
528
- {
529
- tag: "TimeoutError",
530
- category: "timeout",
531
- suggestion: [
532
- "The operation took longer than the allowed timeout.",
533
- "Try increasing `defaults.waitTimeout` in spana.config.ts,",
534
- "or set a per-flow timeout: `flow('name', { timeout: 30000 }, ...)`."
535
- ].join("\n")
536
- },
537
- {
538
- tag: ["ConfigError", "FlowSyntaxError"],
539
- category: "config-error",
540
- suggestion: "Run `spana validate-config` to check your configuration."
541
- }
542
- ];
543
- var heuristicRules = [
544
- {
545
- pattern: /[Tt]imed out/,
546
- category: "timeout",
547
- suggestion: "The operation timed out. Try increasing `defaults.waitTimeout` in spana.config.ts."
548
- },
549
- {
550
- pattern: /not found|not visible/,
551
- category: (msg) => categorizeElementFailure(msg),
552
- suggestion: (_error, msg) => {
553
- if (msg.includes("scroll(s) toward")) {
554
- return "The target stayed off-screen while scrolling. Increase `maxScrolls` / `timeout`, or reverse the scroll search direction.";
555
- }
556
- const category = categorizeElementFailure(msg);
557
- return elementSuggestion(category, "the target selector", void 0);
558
- }
559
- },
560
- {
561
- pattern: "dismissKeyboard()",
562
- category: "driver-error",
563
- suggestion: 'Keyboard dismissal failed. On Android try `app.dismissKeyboard({ strategy: "back" })`; on iOS prefer an explicit Done / Close control.'
564
- },
565
- {
566
- pattern: /ECONNREFUSED|ECONNRESET|disconnected/,
567
- category: "device-disconnected",
568
- suggestion: "The connection was lost. Check the device or emulator/simulator is still running."
569
- }
570
- ];
571
- function matchesPattern(msg, pattern) {
572
- return typeof pattern === "string" ? msg.includes(pattern) : pattern.test(msg);
573
- }
574
- function matchesTag(tag, rule) {
575
- if (!rule.tag) return true;
576
- if (Array.isArray(rule.tag)) return tag != null && rule.tag.includes(tag);
577
- return tag === rule.tag;
578
- }
579
- function categorize(error) {
580
- const tag = error[TAG_KEY];
581
- const msg = error.message ?? "";
582
- const dynamic = categorizeDynamic(error, tag, msg);
583
- if (dynamic) return dynamic;
584
- for (const rule of tagOnlyRules) {
585
- if (matchesTag(tag, rule)) {
586
- return {
587
- category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
588
- suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
589
- };
590
- }
591
- }
592
- for (const rule of heuristicRules) {
593
- if (rule.pattern && matchesPattern(msg, rule.pattern)) {
594
- return {
595
- category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
596
- suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
597
- };
598
- }
599
- }
600
- return { category: "unknown" };
601
- }
602
- function classifyError(error) {
603
- const tagged = error;
604
- const { category, suggestion } = categorize(tagged);
605
- return {
606
- message: error.message,
607
- stack: error.stack,
608
- category,
609
- suggestion
610
- };
611
- }
612
-
613
- // src/core/engine.ts
614
- import { join as join3 } from "path";
615
-
616
- // src/report/failure-bundle.ts
617
- import { writeFileSync as writeFileSync2, readFileSync, existsSync } from "fs";
618
- import { join as join2, basename } from "path";
619
- function levenshtein(a, b) {
620
- const m = a.length;
621
- const n = b.length;
622
- const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
623
- for (let i = 0; i <= m; i++) dp[i][0] = i;
624
- for (let j = 0; j <= n; j++) dp[0][j] = j;
625
- for (let i = 1; i <= m; i++) {
626
- for (let j = 1; j <= n; j++) {
627
- dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
628
- }
629
- }
630
- return dp[m][n];
631
- }
632
- function extractIdentifiers(hierarchyJson) {
633
- const testIDs = [];
634
- const texts = [];
635
- try {
636
- const root = JSON.parse(hierarchyJson);
637
- const queue = [root];
638
- while (queue.length > 0) {
639
- const node = queue.pop();
640
- if (!node || typeof node !== "object") continue;
641
- if (node.testID && typeof node.testID === "string") testIDs.push(node.testID);
642
- if (node.text && typeof node.text === "string") texts.push(node.text);
643
- if (Array.isArray(node.children)) {
644
- for (const child of node.children) queue.push(child);
645
- }
646
- }
647
- } catch {
648
- }
649
- return { testIDs, texts };
650
- }
651
- function findNearbySelectors(attempted, hierarchyJson) {
652
- if (!hierarchyJson) return [];
653
- const { testIDs, texts } = extractIdentifiers(hierarchyJson);
654
- let target;
655
- let candidates;
656
- if (typeof attempted === "string") {
657
- target = attempted.toLowerCase();
658
- candidates = [...testIDs, ...texts];
659
- } else if (attempted && typeof attempted === "object") {
660
- const sel = attempted;
661
- if (typeof sel.testID === "string") {
662
- target = sel.testID.toLowerCase();
663
- candidates = testIDs;
664
- } else if (typeof sel.text === "string") {
665
- target = sel.text.toLowerCase();
666
- candidates = texts;
667
- } else if (typeof sel.accessibilityLabel === "string") {
668
- target = sel.accessibilityLabel.toLowerCase();
669
- candidates = [...testIDs, ...texts];
670
- } else {
671
- return [];
672
- }
673
- } else {
674
- return [];
675
- }
676
- const scored = candidates.filter((c) => c !== target).map((c) => {
677
- const cl = c.toLowerCase();
678
- const substringMatch = cl.includes(target) || target.includes(cl);
679
- const dist = levenshtein(target, cl);
680
- return { value: c, score: substringMatch ? 0 : dist };
681
- }).filter((s) => s.score <= 5).toSorted((a, b) => a.score - b.score);
682
- const seen = /* @__PURE__ */ new Set();
683
- const results = [];
684
- for (const s of scored) {
685
- if (!seen.has(s.value)) {
686
- seen.add(s.value);
687
- results.push(s.value);
688
- if (results.length >= 5) break;
689
- }
690
- }
691
- return results;
692
- }
693
- function buildArtifactMap(attachments) {
694
- const map = {};
695
- if (!attachments) return map;
696
- for (const att of attachments) {
697
- const filename = basename(att.path);
698
- if (filename === "screenshot.png") map.screenshot = filename;
699
- else if (filename === "hierarchy.json") map.hierarchy = filename;
700
- else if (filename === "console-logs.json") map.consoleLogs = filename;
701
- else if (filename === "js-errors.json") map.jsErrors = filename;
702
- else if (filename === "network.har") map.har = filename;
703
- else if (filename === "driver-logs.txt") map.driverLogs = filename;
704
- }
705
- return map;
706
- }
707
- function createFailureBundle(flowName, platform, steps, error, artifactDir, attachments, flowPath) {
708
- const failedStepIndex = steps.findLastIndex((s) => s.status === "failed");
709
- const failedStep = failedStepIndex >= 0 ? {
710
- index: failedStepIndex,
711
- command: steps[failedStepIndex].command,
712
- selector: steps[failedStepIndex].selector ?? null,
713
- durationMs: steps[failedStepIndex].durationMs,
714
- error: steps[failedStepIndex].error
715
- } : null;
716
- const lastPassedIndex = failedStepIndex > 0 ? steps.findLastIndex((s, i) => i < failedStepIndex && s.status === "passed") : -1;
717
- const lastPassedStep = lastPassedIndex >= 0 ? {
718
- index: lastPassedIndex,
719
- command: steps[lastPassedIndex].command,
720
- selector: steps[lastPassedIndex].selector ?? null,
721
- durationMs: steps[lastPassedIndex].durationMs
722
- } : null;
723
- let selectorContext;
724
- if (failedStep?.selector && (error.category === "element-not-found" || error.category === "element-not-visible")) {
725
- const hierarchyPath = join2(artifactDir, "hierarchy.json");
726
- let hierarchyJson = null;
727
- if (existsSync(hierarchyPath)) {
728
- try {
729
- hierarchyJson = readFileSync(hierarchyPath, "utf-8");
730
- } catch {
731
- }
732
- }
733
- const nearbyAlternatives = findNearbySelectors(failedStep.selector, hierarchyJson);
734
- selectorContext = {
735
- attempted: failedStep.selector,
736
- nearbyAlternatives
737
- };
738
- }
739
- const flowFile = flowPath ?? `flows/${flowName.replaceAll(" ", "-")}.flow.ts`;
740
- const reproCommand = `spana test ${flowFile} --platform ${platform} --grep '${flowName}'`;
741
- const bundle = {
742
- schemaVersion: 1,
743
- flow: flowName,
744
- platform,
745
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
746
- failedStep,
747
- lastPassedStep,
748
- error: {
749
- message: error.message,
750
- category: error.category,
751
- suggestion: error.suggestion,
752
- errorCode: error.errorCode
753
- },
754
- selectorContext,
755
- artifacts: buildArtifactMap(attachments),
756
- reproCommand,
757
- durationMs: steps.reduce((sum, s) => sum + s.durationMs, 0)
758
- };
759
- return bundle;
760
- }
761
- function writeFailureBundle(bundle, artifactDir) {
762
- const path = join2(artifactDir, "failure-bundle.json");
763
- writeFileSync2(path, JSON.stringify(bundle, null, 2), "utf-8");
764
- return path;
765
- }
766
-
767
- // src/core/engine.ts
768
- async function executeFlow(flow, driver, config) {
769
- const start2 = Date.now();
770
- const { platform, coordinatorConfig, appId } = config;
771
- const autoLaunch = flow.config.autoLaunch ?? config.autoLaunch ?? true;
772
- const timeout = flow.config.timeout ?? config.flowTimeout ?? 6e4;
773
- const artifactConfig = resolveArtifactConfig(config.artifactConfig, flow.config.artifacts);
774
- const stepRecorder = createStepRecorder(driver, artifactConfig, flow.name, platform);
775
- const launchOptions = mergeLaunchOptions(config.launchOptions, flow.config.launchOptions);
776
- const flowDefaults = flow.config.defaults;
777
- const mergedCoordinatorConfig = flowDefaults ? {
778
- ...coordinatorConfig,
779
- defaults: {
780
- ...coordinatorConfig.defaults,
781
- timeout: flowDefaults.waitTimeout ?? coordinatorConfig.defaults?.timeout,
782
- pollInterval: flowDefaults.pollInterval ?? coordinatorConfig.defaults?.pollInterval,
783
- settleTimeout: flowDefaults.settleTimeout ?? coordinatorConfig.defaults?.settleTimeout,
784
- initialPollInterval: flowDefaults.initialPollInterval ?? coordinatorConfig.defaults?.initialPollInterval
785
- },
786
- waitForIdleTimeout: flowDefaults.waitForIdleTimeout ?? coordinatorConfig.waitForIdleTimeout,
787
- typingDelay: flowDefaults.typingDelay ?? coordinatorConfig.typingDelay,
788
- hierarchyCacheTtl: flowDefaults.hierarchyCacheTtl ?? coordinatorConfig.hierarchyCacheTtl
789
- } : coordinatorConfig;
790
- const app = createPromiseApp(driver, appId, mergedCoordinatorConfig, stepRecorder, {
791
- platform,
792
- storybook: config.storybook,
793
- launchOptions
794
- });
795
- const flowMeta = {
796
- flowFilePath: flow.sourcePath ?? "",
797
- flowName: flow.name,
798
- platform,
799
- updateBaselines: config.updateBaselines ?? false
800
- };
801
- const expect = createPromiseExpect(
802
- driver,
803
- mergedCoordinatorConfig,
804
- stepRecorder,
805
- flowMeta,
806
- config.visualRegression
807
- );
808
- const flowCtx = { app, expect, platform, updateBaselines: flowMeta.updateBaselines };
809
- const buildFailureResult = async (error) => {
810
- const attachments = await captureArtifacts(
811
- driver,
812
- artifactConfig,
813
- flow.name,
814
- platform,
815
- "failed"
816
- );
817
- const normalized = error instanceof Error ? error : new Error(String(error));
818
- return {
819
- name: flow.name,
820
- platform,
821
- status: "failed",
822
- durationMs: Date.now() - start2,
823
- error: classifyError(normalized),
824
- attachments,
825
- steps: stepRecorder.getSteps(),
826
- scenarioSteps: flowCtx.__scenarioSteps
827
- };
828
- };
829
- if (driver.beginFlow) {
830
- try {
831
- await Effect3.runPromise(driver.beginFlow(flow.name));
832
- } catch (error) {
833
- return buildFailureResult(error);
834
- }
835
- }
836
- if (config.hooks?.beforeEach) {
837
- try {
838
- await config.hooks.beforeEach({ app, platform });
839
- } catch (error) {
840
- return buildFailureResult(error);
841
- }
842
- }
843
- let result;
844
- try {
845
- if (autoLaunch) {
846
- await app.launch();
847
- }
848
- await Promise.race([
849
- flow.fn(flowCtx),
850
- new Promise(
851
- (_, reject) => setTimeout(
852
- () => reject(new Error(`Flow "${flow.name}" timed out after ${timeout}ms`)),
853
- timeout
854
- )
855
- )
856
- ]);
857
- const attachments = await captureArtifacts(
858
- driver,
859
- artifactConfig,
860
- flow.name,
861
- platform,
862
- "passed"
863
- );
864
- result = {
865
- name: flow.name,
866
- platform,
867
- status: "passed",
868
- durationMs: Date.now() - start2,
869
- attachments,
870
- steps: stepRecorder.getSteps(),
871
- scenarioSteps: flowCtx.__scenarioSteps
872
- };
873
- } catch (error) {
874
- const attachments = await captureArtifacts(
875
- driver,
876
- artifactConfig,
877
- flow.name,
878
- platform,
879
- "failed"
880
- );
881
- const flowError = error instanceof Error ? error : new Error(String(error));
882
- result = {
883
- name: flow.name,
884
- platform,
885
- status: "failed",
886
- durationMs: Date.now() - start2,
887
- error: classifyError(flowError),
888
- attachments,
889
- steps: stepRecorder.getSteps(),
890
- scenarioSteps: flowCtx.__scenarioSteps
891
- };
892
- if (artifactConfig.captureOnFailure && result.error) {
893
- try {
894
- const artDir = join3(
895
- artifactConfig.outputDir,
896
- `${flow.name.replaceAll(/[^a-zA-Z0-9-_]/g, "_").replaceAll(/_+/g, "_").slice(0, 80) || "artifact"}-${platform}`
897
- );
898
- const bundle = createFailureBundle(
899
- flow.name,
900
- platform,
901
- stepRecorder.getSteps(),
902
- result.error,
903
- artDir,
904
- attachments
905
- );
906
- writeFailureBundle(bundle, artDir);
907
- } catch {
908
- }
909
- }
910
- if (config.debugOnFailure) {
911
- await runDebugReplOnce({
912
- app,
913
- expect,
914
- driver,
915
- error: flowError,
916
- flowName: flow.name,
917
- platform,
918
- parseHierarchy: coordinatorConfig.parse
919
- });
920
- }
921
- }
922
- if (config.hooks?.afterEach) {
923
- try {
924
- await config.hooks.afterEach({ app, platform, result });
925
- } catch (hookError) {
926
- console.warn(
927
- `afterEach hook failed: ${hookError instanceof Error ? hookError.message : hookError}`
928
- );
929
- }
930
- }
931
- return result;
932
- }
933
-
934
- // src/core/parallel.ts
935
- async function runParallel(config) {
936
- const { workers, flows, onFlowComplete, onFlowStart, retries = 0, retryDelay = 0, bail } = config;
937
- const start2 = Date.now();
938
- const results = [];
939
- let nextFlowIndex = 0;
940
- let failureCount = 0;
941
- let bailedOut = false;
942
- const workerPromises = workers.map(async (worker) => {
943
- const stats = { flowCount: 0, totalMs: 0 };
944
- while (true) {
945
- if (bail !== void 0 && failureCount >= bail) break;
946
- const flowIdx = nextFlowIndex++;
947
- if (flowIdx >= flows.length) break;
948
- const flow = flows[flowIdx];
949
- let result;
950
- let attempts = 0;
951
- onFlowStart?.(flow.name, worker.name);
952
- for (let attempt = 0; attempt <= retries; attempt++) {
953
- if (attempt > 0 && retryDelay > 0) {
954
- await new Promise((resolve4) => setTimeout(resolve4, retryDelay));
955
- }
956
- result = await executeFlow(flow, worker.driver, worker.engineConfig);
957
- attempts++;
958
- if (result.status === "passed") break;
959
- }
960
- if (result.status === "passed" && attempts > 1) {
961
- result.flaky = true;
962
- }
963
- result.attempts = attempts;
964
- results.push(result);
965
- stats.flowCount++;
966
- stats.totalMs += result.durationMs;
967
- if (result.status === "failed") {
968
- failureCount++;
969
- }
970
- onFlowComplete?.(result, worker.name);
971
- }
972
- return { workerId: worker.id, stats };
973
- });
974
- const workerResults = await Promise.all(workerPromises);
975
- if (bail !== void 0 && failureCount >= bail) {
976
- bailedOut = true;
977
- while (nextFlowIndex < flows.length) {
978
- const flow = flows[nextFlowIndex++];
979
- results.push({
980
- name: flow.name,
981
- platform: workers[0].engineConfig.platform,
982
- status: "skipped",
983
- durationMs: 0,
984
- attempts: 0
985
- });
986
- }
987
- }
988
- const workerStats = /* @__PURE__ */ new Map();
989
- for (const wr of workerResults) {
990
- workerStats.set(wr.workerId, wr.stats);
991
- }
992
- return {
993
- results,
994
- totalDurationMs: Date.now() - start2,
995
- passed: results.filter((r) => r.status === "passed").length,
996
- failed: results.filter((r) => r.status === "failed").length,
997
- skipped: results.filter((r) => r.status === "skipped").length,
998
- flaky: results.filter((r) => r.flaky === true).length,
999
- bailedOut: bailedOut || void 0,
1000
- workerStats
1001
- };
1002
- }
1003
-
1004
54
  // src/core/orchestrator.ts
1005
55
  async function sleep(ms) {
1006
56
  if (ms <= 0) return;
@@ -1055,6 +105,7 @@ async function runPlatform(flows, platformConfig, options, shouldBail, noteFailu
1055
105
  retries: options?.retries ?? 0,
1056
106
  retryDelay: options?.retryDelay ?? 0,
1057
107
  bail: options?.bail,
108
+ durationHintsMs: options?.durationHintsMs,
1058
109
  onFlowStart: (name, workerName) => {
1059
110
  options?.onFlowStart?.(name, platform, workerName);
1060
111
  },
@@ -1124,7 +175,7 @@ async function runPlatform(flows, platformConfig, options, shouldBail, noteFailu
1124
175
  return { results };
1125
176
  }
1126
177
  async function orchestrate(flows, platforms, options) {
1127
- const start2 = Date.now();
178
+ const start = Date.now();
1128
179
  const bail = options?.bail;
1129
180
  let failureCount = 0;
1130
181
  let bailedOut = false;
@@ -1161,7 +212,7 @@ async function orchestrate(flows, platforms, options) {
1161
212
  }
1162
213
  return {
1163
214
  results: allResults,
1164
- totalDurationMs: Date.now() - start2,
215
+ totalDurationMs: Date.now() - start,
1165
216
  passed: allResults.filter((r) => r.status === "passed").length,
1166
217
  failed: allResults.filter((r) => r.status === "failed").length,
1167
218
  skipped: allResults.filter((r) => r.status === "skipped").length,
@@ -1196,258 +247,8 @@ async function resolveCapabilities(config, opts) {
1196
247
  return { ...launchDeviceCaps, ...configCaps, ...platformCaps, ...fileCaps, ...cliCaps };
1197
248
  }
1198
249
 
1199
- // src/runtime/local.ts
1200
- import { Effect as Effect4 } from "effect";
1201
- async function safeCleanup(...fns) {
1202
- for (const fn of fns) {
1203
- try {
1204
- await fn();
1205
- } catch {
1206
- }
1207
- }
1208
- }
1209
- function buildEngineConfig(appId, platform, parseFn, config, screenSize) {
1210
- return {
1211
- appId,
1212
- platform,
1213
- coordinatorConfig: {
1214
- parse: parseFn,
1215
- defaults: {
1216
- timeout: config.defaults?.waitTimeout,
1217
- pollInterval: config.defaults?.pollInterval,
1218
- settleTimeout: config.defaults?.settleTimeout,
1219
- initialPollInterval: config.defaults?.initialPollInterval
1220
- },
1221
- waitForIdleTimeout: config.defaults?.waitForIdleTimeout,
1222
- typingDelay: config.defaults?.typingDelay,
1223
- hierarchyCacheTtl: config.defaults?.hierarchyCacheTtl,
1224
- screenWidth: screenSize?.width,
1225
- screenHeight: screenSize?.height
1226
- },
1227
- autoLaunch: true,
1228
- flowTimeout: config.defaults?.waitTimeout ? config.defaults.waitTimeout * 10 : 6e4,
1229
- artifactConfig: config.artifacts,
1230
- launchOptions: config.launchOptions,
1231
- hooks: config.hooks,
1232
- storybook: platform === "web" ? config.execution?.web?.storybook : void 0,
1233
- visualRegression: config.visualRegression
1234
- };
1235
- }
1236
- async function buildWebRuntime(config) {
1237
- const webUrl = config.apps?.web?.url ?? "http://localhost:3000";
1238
- const webExecution = config.execution?.web;
1239
- const driver = await Effect4.runPromise(
1240
- makePlaywrightDriver({
1241
- browser: webExecution?.browser,
1242
- headless: webExecution?.headless ?? true,
1243
- baseUrl: webUrl,
1244
- storageState: webExecution?.storageState,
1245
- verboseLogging: webExecution?.verboseLogging
1246
- })
1247
- );
1248
- const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
1249
- return {
1250
- runtime: {
1251
- driver,
1252
- cleanup: () => safeCleanup(() => Effect4.runPromise(driver.killApp(""))),
1253
- metadata: {
1254
- platform: "web",
1255
- mode: "local"
1256
- }
1257
- },
1258
- engineConfig: buildEngineConfig(webUrl, "web", parseWebHierarchy, config, {
1259
- width: deviceInfo.screenWidth,
1260
- height: deviceInfo.screenHeight
1261
- })
1262
- };
1263
- }
1264
- async function buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig) {
1265
- const device = targetDevice?.platform === "android" ? {
1266
- serial: targetDevice.id,
1267
- state: "device",
1268
- type: targetDevice.type
1269
- } : ensureAndroidDevice();
1270
- if (!device) {
1271
- console.log("No Android device/emulator available. Skipping android platform.");
1272
- return null;
1273
- }
1274
- const packageName = config.apps?.android?.packageName ?? "";
1275
- const androidAppPath = config.apps?.android?.appPath;
1276
- if (androidAppPath && packageName) {
1277
- try {
1278
- const { adbShell, adbInstall } = await import("./android-PAPJJWVN.js");
1279
- const output = adbShell(device.serial, `pm list packages ${packageName}`);
1280
- if (!output.includes(packageName)) {
1281
- console.log(`Installing ${packageName} on Android device...`);
1282
- adbInstall(device.serial, resolveFromConfig(androidAppPath));
1283
- }
1284
- } catch {
1285
- console.log(`Installing ${packageName} on Android device...`);
1286
- const { adbInstall } = await import("./android-PAPJJWVN.js");
1287
- adbInstall(device.serial, resolveFromConfig(androidAppPath));
1288
- }
1289
- }
1290
- const hostPort = allocatePort(8200);
1291
- try {
1292
- const conn = await setupUiAutomator2(device.serial, hostPort);
1293
- const driver = await Effect4.runPromise(
1294
- createUiAutomator2Driver(conn.host, conn.port, device.serial, packageName)
1295
- );
1296
- const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
1297
- return {
1298
- runtime: {
1299
- driver,
1300
- cleanup: () => safeCleanup(
1301
- () => Effect4.runPromise(driver.killApp("")),
1302
- () => conn.cleanup?.() ?? Promise.resolve()
1303
- ),
1304
- metadata: {
1305
- platform: "android",
1306
- mode: "local",
1307
- deviceId: device.serial
1308
- }
1309
- },
1310
- engineConfig: buildEngineConfig(packageName, "android", parseAndroidHierarchy, config, {
1311
- width: deviceInfo.screenWidth,
1312
- height: deviceInfo.screenHeight
1313
- })
1314
- };
1315
- } catch (e) {
1316
- console.log(`Android setup failed on ${device.serial}: ${e instanceof Error ? e.message : e}`);
1317
- return null;
1318
- }
1319
- }
1320
- async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
1321
- const bundleId = config.apps?.ios?.bundleId ?? "";
1322
- const iosAppPath = config.apps?.ios?.appPath;
1323
- const signing = config.apps?.ios?.signing;
1324
- const snapshotMaxDepth = config.defaults?.snapshotMaxDepth ?? 100;
1325
- const createIOSRuntime = async (deviceId, conn, simulatorUdid) => {
1326
- const driver = await Effect4.runPromise(
1327
- createWDADriver(conn.host, conn.port, bundleId, simulatorUdid, snapshotMaxDepth)
1328
- );
1329
- const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
1330
- return {
1331
- runtime: {
1332
- driver,
1333
- cleanup: () => safeCleanup(
1334
- () => Effect4.runPromise(driver.killApp("")),
1335
- () => conn.cleanup?.() ?? Promise.resolve()
1336
- ),
1337
- metadata: {
1338
- platform: "ios",
1339
- mode: "local",
1340
- deviceId
1341
- }
1342
- },
1343
- engineConfig: buildEngineConfig(bundleId, "ios", parseIOSHierarchy, config, {
1344
- width: deviceInfo.screenWidth,
1345
- height: deviceInfo.screenHeight
1346
- })
1347
- };
1348
- };
1349
- const connectPhysicalRuntime = async (physicalDevice2, allowSimulatorFallback) => {
1350
- let conn;
1351
- try {
1352
- console.log(`Found physical iOS device: ${physicalDevice2.name} (${physicalDevice2.udid})`);
1353
- if (iosAppPath && bundleId) {
1354
- ensureAppInstalled({
1355
- udid: physicalDevice2.udid,
1356
- bundleId,
1357
- appPath: resolveFromConfig(iosAppPath),
1358
- isPhysicalDevice: true
1359
- });
1360
- }
1361
- if (signing?.teamId) {
1362
- const { setupWDAForDevice } = await import("./installer-W5DITECS.js");
1363
- const wdaPort2 = allocatePort(8100);
1364
- conn = await setupWDAForDevice(
1365
- physicalDevice2.udid,
1366
- wdaPort2,
1367
- signing.teamId,
1368
- signing.signingIdentity
1369
- );
1370
- } else {
1371
- conn = connectPhysicalDevice(physicalDevice2.udid);
1372
- }
1373
- return await createIOSRuntime(physicalDevice2.udid, conn);
1374
- } catch (e) {
1375
- if (conn?.cleanup) {
1376
- try {
1377
- await conn.cleanup();
1378
- } catch (cleanupError) {
1379
- console.warn(
1380
- `Failed to clean up physical device tunnel: ${cleanupError instanceof Error ? cleanupError.message : cleanupError}`
1381
- );
1382
- }
1383
- }
1384
- if (!allowSimulatorFallback) {
1385
- console.log(
1386
- `iOS setup failed for device ${physicalDevice2.udid}: ${e instanceof Error ? e.message : e}`
1387
- );
1388
- return null;
1389
- }
1390
- console.log(
1391
- `Physical device setup failed (${physicalDevice2.name}): ${e instanceof Error ? e.message : e}. Falling back to simulator.`
1392
- );
1393
- return null;
1394
- }
1395
- };
1396
- if (targetDevice?.platform === "ios" && targetDevice.type === "simulator") {
1397
- if (iosAppPath && bundleId) {
1398
- ensureAppInstalled({
1399
- udid: targetDevice.id,
1400
- bundleId,
1401
- appPath: resolveFromConfig(iosAppPath),
1402
- isPhysicalDevice: false
1403
- });
1404
- }
1405
- const wdaPort2 = allocatePort(8100);
1406
- try {
1407
- const conn = await setupWDA(targetDevice.id, wdaPort2);
1408
- return await createIOSRuntime(targetDevice.id, conn, targetDevice.id);
1409
- } catch (e) {
1410
- console.log(
1411
- `iOS setup failed for device ${targetDevice.id}: ${e instanceof Error ? e.message : e}`
1412
- );
1413
- return null;
1414
- }
1415
- }
1416
- if (targetDevice?.platform === "ios" && targetDevice.type === "device") {
1417
- return connectPhysicalRuntime({ udid: targetDevice.id, name: targetDevice.name }, false);
1418
- }
1419
- const physicalDevice = firstIOSPhysicalDevice();
1420
- if (physicalDevice) {
1421
- const runtime = await connectPhysicalRuntime(physicalDevice, true);
1422
- if (runtime) {
1423
- return runtime;
1424
- }
1425
- }
1426
- const simulator = ensureIOSSimulator(bundleId);
1427
- if (!simulator) {
1428
- console.log("No iOS simulator or physical device available. Skipping ios platform.");
1429
- return null;
1430
- }
1431
- if (iosAppPath && bundleId) {
1432
- ensureAppInstalled({
1433
- udid: simulator.udid,
1434
- bundleId,
1435
- appPath: resolveFromConfig(iosAppPath),
1436
- isPhysicalDevice: false
1437
- });
1438
- }
1439
- const wdaPort = allocatePort(8100);
1440
- try {
1441
- const conn = await setupWDA(simulator.udid, wdaPort);
1442
- return await createIOSRuntime(simulator.udid, conn, simulator.udid);
1443
- } catch (e) {
1444
- console.log(`iOS setup failed on ${simulator.name}: ${e instanceof Error ? e.message : e}`);
1445
- return null;
1446
- }
1447
- }
1448
-
1449
250
  // src/runtime/appium.ts
1450
- import { Effect as Effect7 } from "effect";
251
+ import { Effect as Effect3 } from "effect";
1451
252
 
1452
253
  // src/drivers/appium/client.ts
1453
254
  var AppiumClient = class {
@@ -1577,7 +378,7 @@ var AppiumClient = class {
1577
378
  };
1578
379
 
1579
380
  // src/drivers/appium/android.ts
1580
- import { Effect as Effect5 } from "effect";
381
+ import { Effect } from "effect";
1581
382
 
1582
383
  // src/drivers/appium/window-size.ts
1583
384
  async function getAppiumWindowSize(client) {
@@ -1599,14 +400,14 @@ function createAppiumAndroidDriver(client, defaultBundleId) {
1599
400
  // -----------------------------------------------------------------------
1600
401
  // Hierarchy
1601
402
  // -----------------------------------------------------------------------
1602
- dumpHierarchy: () => Effect5.tryPromise({
403
+ dumpHierarchy: () => Effect.tryPromise({
1603
404
  try: () => client.request("GET", client.sessionPath("/source")),
1604
405
  catch: (e) => new DriverError({ message: `Failed to get page source: ${e}` })
1605
406
  }),
1606
407
  // -----------------------------------------------------------------------
1607
408
  // Coordinate-level actions
1608
409
  // -----------------------------------------------------------------------
1609
- tapAtCoordinate: (x, y) => Effect5.tryPromise({
410
+ tapAtCoordinate: (x, y) => Effect.tryPromise({
1610
411
  try: () => client.request("POST", client.sessionPath("/actions"), {
1611
412
  actions: [
1612
413
  {
@@ -1623,7 +424,7 @@ function createAppiumAndroidDriver(client, defaultBundleId) {
1623
424
  }),
1624
425
  catch: (e) => new DriverError({ message: `Tap failed: ${e}` })
1625
426
  }),
1626
- doubleTapAtCoordinate: (x, y) => Effect5.tryPromise({
427
+ doubleTapAtCoordinate: (x, y) => Effect.tryPromise({
1627
428
  try: async () => {
1628
429
  const tapSequence = [
1629
430
  {
@@ -1643,7 +444,7 @@ function createAppiumAndroidDriver(client, defaultBundleId) {
1643
444
  },
1644
445
  catch: (e) => new DriverError({ message: `Double tap failed: ${e}` })
1645
446
  }),
1646
- longPressAtCoordinate: (x, y, duration) => Effect5.tryPromise({
447
+ longPressAtCoordinate: (x, y, duration) => Effect.tryPromise({
1647
448
  try: () => client.request("POST", client.sessionPath("/actions"), {
1648
449
  actions: [
1649
450
  {
@@ -1661,7 +462,7 @@ function createAppiumAndroidDriver(client, defaultBundleId) {
1661
462
  }),
1662
463
  catch: (e) => new DriverError({ message: `Long press failed: ${e}` })
1663
464
  }),
1664
- swipe: (sx, sy, ex, ey, dur) => Effect5.tryPromise({
465
+ swipe: (sx, sy, ex, ey, dur) => Effect.tryPromise({
1665
466
  try: () => client.request("POST", client.sessionPath("/actions"), {
1666
467
  actions: [
1667
468
  {
@@ -1682,7 +483,7 @@ function createAppiumAndroidDriver(client, defaultBundleId) {
1682
483
  // -----------------------------------------------------------------------
1683
484
  // Text input
1684
485
  // -----------------------------------------------------------------------
1685
- inputText: (text) => Effect5.tryPromise({
486
+ inputText: (text) => Effect.tryPromise({
1686
487
  try: () => {
1687
488
  const keyActions = [];
1688
489
  for (const segment of splitGraphemes(text)) {
@@ -1701,27 +502,27 @@ function createAppiumAndroidDriver(client, defaultBundleId) {
1701
502
  },
1702
503
  catch: (e) => new DriverError({ message: `Input text failed: ${e}` })
1703
504
  }),
1704
- pressKey: (key) => Effect5.tryPromise({
505
+ pressKey: (key) => Effect.tryPromise({
1705
506
  try: () => client.request("POST", client.sessionPath("/appium/device/press_keycode"), {
1706
507
  keycode: parseInt(key, 10) || 0
1707
508
  }),
1708
509
  catch: (e) => new DriverError({ message: `Press key failed: ${e}` })
1709
510
  }),
1710
- hideKeyboard: () => Effect5.tryPromise({
511
+ hideKeyboard: () => Effect.tryPromise({
1711
512
  try: () => client.request("POST", client.sessionPath("/appium/device/hide_keyboard")),
1712
513
  catch: (e) => new DriverError({ message: `Hide keyboard failed: ${e}` })
1713
514
  }),
1714
515
  // -----------------------------------------------------------------------
1715
516
  // Queries
1716
517
  // -----------------------------------------------------------------------
1717
- takeScreenshot: () => Effect5.tryPromise({
518
+ takeScreenshot: () => Effect.tryPromise({
1718
519
  try: async () => {
1719
520
  const base64 = await client.request("GET", client.sessionPath("/screenshot"));
1720
521
  return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
1721
522
  },
1722
523
  catch: (e) => new DriverError({ message: `Screenshot failed: ${e}` })
1723
524
  }),
1724
- getDeviceInfo: () => Effect5.tryPromise({
525
+ getDeviceInfo: () => Effect.tryPromise({
1725
526
  try: async () => {
1726
527
  const size = await getAppiumWindowSize(client);
1727
528
  const caps = client.getSessionCaps();
@@ -1740,7 +541,7 @@ function createAppiumAndroidDriver(client, defaultBundleId) {
1740
541
  // -----------------------------------------------------------------------
1741
542
  // App lifecycle
1742
543
  // -----------------------------------------------------------------------
1743
- launchApp: (bundleId, opts) => Effect5.tryPromise({
544
+ launchApp: (bundleId, opts) => Effect.tryPromise({
1744
545
  try: async () => {
1745
546
  if (opts?.clearState) {
1746
547
  try {
@@ -1776,19 +577,19 @@ function createAppiumAndroidDriver(client, defaultBundleId) {
1776
577
  },
1777
578
  catch: (e) => new DriverError({ message: `Launch app failed: ${e}` })
1778
579
  }),
1779
- stopApp: (bundleId) => Effect5.tryPromise({
580
+ stopApp: (bundleId) => Effect.tryPromise({
1780
581
  try: () => client.request("POST", client.sessionPath("/appium/device/terminate_app"), {
1781
582
  appId: bundleId
1782
583
  }),
1783
584
  catch: (e) => new DriverError({ message: `Stop app failed: ${e}` })
1784
585
  }),
1785
- killApp: (bundleId) => Effect5.tryPromise({
586
+ killApp: (bundleId) => Effect.tryPromise({
1786
587
  try: () => client.request("POST", client.sessionPath("/appium/device/terminate_app"), {
1787
588
  appId: bundleId
1788
589
  }),
1789
590
  catch: (e) => new DriverError({ message: `Kill app failed: ${e}` })
1790
591
  }),
1791
- clearAppState: (bundleId) => Effect5.tryPromise({
592
+ clearAppState: (bundleId) => Effect.tryPromise({
1792
593
  try: async () => {
1793
594
  try {
1794
595
  await client.request("POST", client.sessionPath("/appium/device/terminate_app"), {
@@ -1803,7 +604,7 @@ function createAppiumAndroidDriver(client, defaultBundleId) {
1803
604
  // -----------------------------------------------------------------------
1804
605
  // Navigation
1805
606
  // -----------------------------------------------------------------------
1806
- openLink: (url) => Effect5.tryPromise({
607
+ openLink: (url) => Effect.tryPromise({
1807
608
  try: () => {
1808
609
  const args = { url };
1809
610
  if (defaultBundleId) args.package = defaultBundleId;
@@ -1811,14 +612,14 @@ function createAppiumAndroidDriver(client, defaultBundleId) {
1811
612
  },
1812
613
  catch: (e) => new DriverError({ message: `Open link failed: ${e}` })
1813
614
  }),
1814
- back: () => Effect5.tryPromise({
615
+ back: () => Effect.tryPromise({
1815
616
  try: () => client.request("POST", client.sessionPath("/back")),
1816
617
  catch: (e) => new DriverError({ message: `Back failed: ${e}` })
1817
618
  }),
1818
619
  // -----------------------------------------------------------------------
1819
620
  // Scripting (works when switched to a WebView context)
1820
621
  // -----------------------------------------------------------------------
1821
- evaluate: (script, ...args) => Effect5.tryPromise({
622
+ evaluate: (script, ...args) => Effect.tryPromise({
1822
623
  try: () => client.executeScript(
1823
624
  typeof script === "function" ? `return (${script})(...arguments)` : script,
1824
625
  args
@@ -1828,37 +629,60 @@ function createAppiumAndroidDriver(client, defaultBundleId) {
1828
629
  // -----------------------------------------------------------------------
1829
630
  // WebView / hybrid context switching
1830
631
  // -----------------------------------------------------------------------
1831
- getContexts: () => Effect5.tryPromise({
632
+ getContexts: () => Effect.tryPromise({
1832
633
  try: () => client.getContexts(),
1833
634
  catch: (e) => new DriverError({ message: `getContexts failed: ${e}` })
1834
635
  }),
1835
- getCurrentContext: () => Effect5.tryPromise({
636
+ getCurrentContext: () => Effect.tryPromise({
1836
637
  try: () => client.getCurrentContext(),
1837
638
  catch: (e) => new DriverError({ message: `getCurrentContext failed: ${e}` })
1838
639
  }),
1839
- setContext: (contextId) => Effect5.tryPromise({
640
+ setContext: (contextId) => Effect.tryPromise({
1840
641
  try: () => client.setContext(contextId),
1841
642
  catch: (e) => new DriverError({ message: `setContext failed: ${e}` })
643
+ }),
644
+ // -----------------------------------------------------------------------
645
+ // Network conditions
646
+ // -----------------------------------------------------------------------
647
+ setNetworkConditions: (conditions) => Effect.tryPromise({
648
+ try: () => {
649
+ const resolved = resolveNetworkConditions(conditions);
650
+ const hasAnyValue = conditions.profile !== void 0 || conditions.offline !== void 0 || conditions.latencyMs !== void 0 || conditions.downloadThroughputKbps !== void 0 || conditions.uploadThroughputKbps !== void 0;
651
+ if (!hasAnyValue) {
652
+ return client.executeScript("mobile: setConnectivity", [
653
+ { wifi: true, data: true, airplaneMode: false }
654
+ ]);
655
+ }
656
+ if (resolved.offline) {
657
+ return client.executeScript("mobile: setConnectivity", [
658
+ { wifi: false, data: false, airplaneMode: true }
659
+ ]);
660
+ }
661
+ return client.executeScript("mobile: setConnectivity", [
662
+ { wifi: true, data: true, airplaneMode: false }
663
+ ]);
664
+ },
665
+ catch: (e) => new DriverError({ message: `setNetworkConditions failed: ${e}` })
1842
666
  })
1843
667
  };
1844
- return Effect5.succeed(service);
668
+ return Effect.succeed(service);
1845
669
  }
1846
670
 
1847
671
  // src/drivers/appium/ios.ts
1848
- import { Effect as Effect6 } from "effect";
672
+ import { Effect as Effect2 } from "effect";
1849
673
  function createAppiumIOSDriver(client) {
1850
674
  const service = {
1851
675
  // -----------------------------------------------------------------------
1852
676
  // Hierarchy
1853
677
  // -----------------------------------------------------------------------
1854
- dumpHierarchy: () => Effect6.tryPromise({
678
+ dumpHierarchy: () => Effect2.tryPromise({
1855
679
  try: () => client.request("GET", client.sessionPath("/source")),
1856
680
  catch: (e) => new DriverError({ message: `Failed to get page source: ${e}` })
1857
681
  }),
1858
682
  // -----------------------------------------------------------------------
1859
683
  // Coordinate-level actions (W3C touch pointer actions for iOS)
1860
684
  // -----------------------------------------------------------------------
1861
- tapAtCoordinate: (x, y) => Effect6.tryPromise({
685
+ tapAtCoordinate: (x, y) => Effect2.tryPromise({
1862
686
  try: () => client.request("POST", client.sessionPath("/actions"), {
1863
687
  actions: [
1864
688
  {
@@ -1875,7 +699,7 @@ function createAppiumIOSDriver(client) {
1875
699
  }),
1876
700
  catch: (e) => new DriverError({ message: `Tap failed: ${e}` })
1877
701
  }),
1878
- doubleTapAtCoordinate: (x, y) => Effect6.tryPromise({
702
+ doubleTapAtCoordinate: (x, y) => Effect2.tryPromise({
1879
703
  try: () => client.request("POST", client.sessionPath("/actions"), {
1880
704
  actions: [
1881
705
  {
@@ -1895,7 +719,7 @@ function createAppiumIOSDriver(client) {
1895
719
  }),
1896
720
  catch: (e) => new DriverError({ message: `Double tap failed: ${e}` })
1897
721
  }),
1898
- longPressAtCoordinate: (x, y, duration) => Effect6.tryPromise({
722
+ longPressAtCoordinate: (x, y, duration) => Effect2.tryPromise({
1899
723
  try: () => client.request("POST", client.sessionPath("/actions"), {
1900
724
  actions: [
1901
725
  {
@@ -1913,7 +737,7 @@ function createAppiumIOSDriver(client) {
1913
737
  }),
1914
738
  catch: (e) => new DriverError({ message: `Long press failed: ${e}` })
1915
739
  }),
1916
- swipe: (sx, sy, ex, ey, dur) => Effect6.tryPromise({
740
+ swipe: (sx, sy, ex, ey, dur) => Effect2.tryPromise({
1917
741
  try: () => client.request("POST", client.sessionPath("/actions"), {
1918
742
  actions: [
1919
743
  {
@@ -1934,7 +758,7 @@ function createAppiumIOSDriver(client) {
1934
758
  // -----------------------------------------------------------------------
1935
759
  // Text input
1936
760
  // -----------------------------------------------------------------------
1937
- inputText: (text) => Effect6.tryPromise({
761
+ inputText: (text) => Effect2.tryPromise({
1938
762
  try: () => {
1939
763
  const keyActions = [];
1940
764
  for (const segment of splitGraphemes(text)) {
@@ -1953,7 +777,7 @@ function createAppiumIOSDriver(client) {
1953
777
  },
1954
778
  catch: (e) => new DriverError({ message: `Input text failed: ${e}` })
1955
779
  }),
1956
- pressKey: (key) => Effect6.tryPromise({
780
+ pressKey: (key) => Effect2.tryPromise({
1957
781
  try: () => client.request("POST", client.sessionPath("/actions"), {
1958
782
  actions: [
1959
783
  {
@@ -1968,21 +792,21 @@ function createAppiumIOSDriver(client) {
1968
792
  }),
1969
793
  catch: (e) => new DriverError({ message: `Press key failed: ${e}` })
1970
794
  }),
1971
- hideKeyboard: () => Effect6.tryPromise({
795
+ hideKeyboard: () => Effect2.tryPromise({
1972
796
  try: () => client.request("POST", client.sessionPath("/appium/device/hide_keyboard")),
1973
797
  catch: (e) => new DriverError({ message: `Hide keyboard failed: ${e}` })
1974
798
  }),
1975
799
  // -----------------------------------------------------------------------
1976
800
  // Queries
1977
801
  // -----------------------------------------------------------------------
1978
- takeScreenshot: () => Effect6.tryPromise({
802
+ takeScreenshot: () => Effect2.tryPromise({
1979
803
  try: async () => {
1980
804
  const base64 = await client.request("GET", client.sessionPath("/screenshot"));
1981
805
  return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
1982
806
  },
1983
807
  catch: (e) => new DriverError({ message: `Screenshot failed: ${e}` })
1984
808
  }),
1985
- getDeviceInfo: () => Effect6.tryPromise({
809
+ getDeviceInfo: () => Effect2.tryPromise({
1986
810
  try: async () => {
1987
811
  const size = await getAppiumWindowSize(client);
1988
812
  const caps = client.getSessionCaps();
@@ -2001,7 +825,7 @@ function createAppiumIOSDriver(client) {
2001
825
  // -----------------------------------------------------------------------
2002
826
  // App lifecycle
2003
827
  // -----------------------------------------------------------------------
2004
- launchApp: (bundleId, opts) => Effect6.tryPromise({
828
+ launchApp: (bundleId, opts) => Effect2.tryPromise({
2005
829
  try: async () => {
2006
830
  const launchConfig = buildIOSLaunchConfiguration(opts);
2007
831
  if (opts?.clearState) {
@@ -2052,19 +876,19 @@ function createAppiumIOSDriver(client) {
2052
876
  },
2053
877
  catch: (e) => new DriverError({ message: `Launch app failed: ${e}` })
2054
878
  }),
2055
- stopApp: (bundleId) => Effect6.tryPromise({
879
+ stopApp: (bundleId) => Effect2.tryPromise({
2056
880
  try: () => client.request("POST", client.sessionPath("/appium/device/terminate_app"), {
2057
881
  appId: bundleId
2058
882
  }),
2059
883
  catch: (e) => new DriverError({ message: `Stop app failed: ${e}` })
2060
884
  }),
2061
- killApp: (bundleId) => Effect6.tryPromise({
885
+ killApp: (bundleId) => Effect2.tryPromise({
2062
886
  try: () => client.request("POST", client.sessionPath("/appium/device/terminate_app"), {
2063
887
  appId: bundleId
2064
888
  }),
2065
889
  catch: (e) => new DriverError({ message: `Kill app failed: ${e}` })
2066
890
  }),
2067
- clearAppState: (bundleId) => Effect6.tryPromise({
891
+ clearAppState: (bundleId) => Effect2.tryPromise({
2068
892
  try: async () => {
2069
893
  try {
2070
894
  await client.request("POST", client.sessionPath("/appium/device/terminate_app"), {
@@ -2081,11 +905,11 @@ function createAppiumIOSDriver(client) {
2081
905
  // -----------------------------------------------------------------------
2082
906
  // Navigation
2083
907
  // -----------------------------------------------------------------------
2084
- openLink: (url) => Effect6.tryPromise({
908
+ openLink: (url) => Effect2.tryPromise({
2085
909
  try: () => client.request("POST", client.sessionPath("/url"), { url }),
2086
910
  catch: (e) => new DriverError({ message: `Open link failed: ${e}` })
2087
911
  }),
2088
- back: () => Effect6.fail(
912
+ back: () => Effect2.fail(
2089
913
  new DriverError({
2090
914
  message: "back() is not supported on iOS. Use navigation within the app or swipe gestures."
2091
915
  })
@@ -2093,7 +917,7 @@ function createAppiumIOSDriver(client) {
2093
917
  // -----------------------------------------------------------------------
2094
918
  // Scripting (works when switched to a WebView context)
2095
919
  // -----------------------------------------------------------------------
2096
- evaluate: (script, ...args) => Effect6.tryPromise({
920
+ evaluate: (script, ...args) => Effect2.tryPromise({
2097
921
  try: () => client.executeScript(
2098
922
  typeof script === "function" ? `return (${script})(...arguments)` : script,
2099
923
  args
@@ -2103,20 +927,43 @@ function createAppiumIOSDriver(client) {
2103
927
  // -----------------------------------------------------------------------
2104
928
  // WebView / hybrid context switching
2105
929
  // -----------------------------------------------------------------------
2106
- getContexts: () => Effect6.tryPromise({
930
+ getContexts: () => Effect2.tryPromise({
2107
931
  try: () => client.getContexts(),
2108
932
  catch: (e) => new DriverError({ message: `getContexts failed: ${e}` })
2109
933
  }),
2110
- getCurrentContext: () => Effect6.tryPromise({
934
+ getCurrentContext: () => Effect2.tryPromise({
2111
935
  try: () => client.getCurrentContext(),
2112
936
  catch: (e) => new DriverError({ message: `getCurrentContext failed: ${e}` })
2113
937
  }),
2114
- setContext: (contextId) => Effect6.tryPromise({
938
+ setContext: (contextId) => Effect2.tryPromise({
2115
939
  try: () => client.setContext(contextId),
2116
940
  catch: (e) => new DriverError({ message: `setContext failed: ${e}` })
941
+ }),
942
+ // -----------------------------------------------------------------------
943
+ // Network conditions
944
+ // -----------------------------------------------------------------------
945
+ setNetworkConditions: (conditions) => Effect2.tryPromise({
946
+ try: () => {
947
+ const resolved = resolveNetworkConditions(conditions);
948
+ const hasAnyValue = conditions.profile !== void 0 || conditions.offline !== void 0 || conditions.latencyMs !== void 0 || conditions.downloadThroughputKbps !== void 0 || conditions.uploadThroughputKbps !== void 0;
949
+ if (!hasAnyValue) {
950
+ return client.executeScript("mobile: setConnectivity", [
951
+ { wifi: true, data: true, airplaneMode: false }
952
+ ]);
953
+ }
954
+ if (resolved.offline) {
955
+ return client.executeScript("mobile: setConnectivity", [
956
+ { wifi: false, data: false, airplaneMode: true }
957
+ ]);
958
+ }
959
+ return client.executeScript("mobile: setConnectivity", [
960
+ { wifi: true, data: true, airplaneMode: false }
961
+ ]);
962
+ },
963
+ catch: (e) => new DriverError({ message: `setNetworkConditions failed: ${e}` })
2117
964
  })
2118
965
  };
2119
- return Effect6.succeed(service);
966
+ return Effect2.succeed(service);
2120
967
  }
2121
968
 
2122
969
  // src/runtime/appium.ts
@@ -2127,8 +974,8 @@ async function buildAppiumAndroidRuntime(config, appiumUrl, caps) {
2127
974
  platformName: "Android",
2128
975
  ...caps
2129
976
  });
2130
- const driver = await Effect7.runPromise(createAppiumAndroidDriver(client, appId || void 0));
2131
- const deviceInfo = await Effect7.runPromise(driver.getDeviceInfo());
977
+ const driver = await Effect3.runPromise(createAppiumAndroidDriver(client, appId || void 0));
978
+ const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
2132
979
  const sessionId = client.getSessionId() ?? void 0;
2133
980
  const sessionCaps = client.getSessionCaps();
2134
981
  const detectedProvider = detectProvider(appiumUrl);
@@ -2193,8 +1040,8 @@ async function buildAppiumIOSRuntime(config, appiumUrl, caps) {
2193
1040
  } catch (e) {
2194
1041
  console.warn(`Failed to set snapshotMaxDepth (continuing): ${e}`);
2195
1042
  }
2196
- const driver = await Effect7.runPromise(createAppiumIOSDriver(client));
2197
- const deviceInfo = await Effect7.runPromise(driver.getDeviceInfo());
1043
+ const driver = await Effect3.runPromise(createAppiumIOSDriver(client));
1044
+ const deviceInfo = await Effect3.runPromise(driver.getDeviceInfo());
2198
1045
  const sessionId = client.getSessionId() ?? void 0;
2199
1046
  const sessionCaps = client.getSessionCaps();
2200
1047
  const detectedProvider = detectProvider(appiumUrl);
@@ -2247,8 +1094,8 @@ async function buildAppiumIOSRuntime(config, appiumUrl, caps) {
2247
1094
  // src/cli/iteration.ts
2248
1095
  import { execFileSync } from "child_process";
2249
1096
  import { readFile as readFile2, writeFile } from "fs/promises";
2250
- import { dirname, join as join4, resolve } from "path";
2251
- import { mkdirSync as mkdirSync2, existsSync as existsSync2 } from "fs";
1097
+ import { dirname, join, resolve } from "path";
1098
+ import { mkdirSync, existsSync } from "fs";
2252
1099
  var SCHEMA_VERSION = 1;
2253
1100
  function buildLastRunState(options) {
2254
1101
  const { flowDir, platforms, results, sourcePathsByFlowName } = options;
@@ -2258,7 +1105,13 @@ function buildLastRunState(options) {
2258
1105
  for (const result of results) {
2259
1106
  const passed = result.status === "passed";
2260
1107
  const sourcePath = sourcePathsByFlowName.get(result.name);
2261
- flows.push({ name: result.name, platform: result.platform, passed, sourcePath });
1108
+ flows.push({
1109
+ name: result.name,
1110
+ platform: result.platform,
1111
+ passed,
1112
+ durationMs: result.durationMs,
1113
+ sourcePath
1114
+ });
2262
1115
  if (!passed) {
2263
1116
  if (!failedFlowNames.includes(result.name)) failedFlowNames.push(result.name);
2264
1117
  if (sourcePath && !failedSourcePaths.includes(sourcePath)) failedSourcePaths.push(sourcePath);
@@ -2283,9 +1136,19 @@ async function readLastRunState(filePath) {
2283
1136
  return null;
2284
1137
  }
2285
1138
  }
1139
+ function extractDurationHints(state) {
1140
+ const hints = {};
1141
+ if (!state?.flows) return hints;
1142
+ for (const entry of state.flows) {
1143
+ if (typeof entry.durationMs === "number" && entry.durationMs > 0) {
1144
+ hints[entry.name] = Math.max(hints[entry.name] ?? 0, entry.durationMs);
1145
+ }
1146
+ }
1147
+ return hints;
1148
+ }
2286
1149
  async function writeLastRunState(filePath, state) {
2287
1150
  const dir = dirname(filePath);
2288
- if (!existsSync2(dir)) mkdirSync2(dir, { recursive: true });
1151
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
2289
1152
  await writeFile(filePath, JSON.stringify(state, null, 2), "utf8");
2290
1153
  }
2291
1154
  function getGitChangedFiles(cwd) {
@@ -2327,7 +1190,7 @@ function selectChangedFlowPaths(options) {
2327
1190
  return { mode: "none", reason: "No changed flow files detected.", flowPaths: [] };
2328
1191
  }
2329
1192
  function createLastRunStatePath(outputDir) {
2330
- return join4(outputDir, ".spana", "last-run.json");
1193
+ return join(outputDir, ".spana", "last-run.json");
2331
1194
  }
2332
1195
 
2333
1196
  // src/cli/watch-mode.ts
@@ -2420,8 +1283,8 @@ function validateOptions(opts) {
2420
1283
  }
2421
1284
  return null;
2422
1285
  }
2423
- async function buildParallelPlatformConfigs(platforms, opts, config, runtimes, resolveFromConfig) {
2424
- const { discoverDevices, findDeviceById } = await import("./discover-NPNF6SWQ.js");
1286
+ async function buildParallelPlatformConfigs(platforms, opts, config, runtimes, resolveFromConfig, prelaunchedWeb) {
1287
+ const { discoverDevices, findDeviceById } = await import("./discover-LHEBSUIP.js");
2425
1288
  let allDevices;
2426
1289
  if (opts.devices) {
2427
1290
  allDevices = [];
@@ -2451,11 +1314,12 @@ async function buildParallelPlatformConfigs(platforms, opts, config, runtimes, r
2451
1314
  if (platform === "web") {
2452
1315
  const webWorkers = maxWorkers ?? 1;
2453
1316
  if (webWorkers > 1) {
2454
- const primaryResult = await buildWebRuntime(config);
1317
+ const pooledResults = await buildWebRuntimePool(config, webWorkers, prelaunchedWeb);
1318
+ const primaryResult = pooledResults[0];
2455
1319
  runtimes.push(primaryResult.runtime);
2456
1320
  const additionalWorkers = [];
2457
- for (let i = 1; i < webWorkers; i++) {
2458
- const result = await buildWebRuntime(config);
1321
+ for (let i = 1; i < pooledResults.length; i++) {
1322
+ const result = pooledResults[i];
2459
1323
  runtimes.push(result.runtime);
2460
1324
  additionalWorkers.push({
2461
1325
  id: `web-context-${i + 1}`,
@@ -2479,7 +1343,7 @@ async function buildParallelPlatformConfigs(platforms, opts, config, runtimes, r
2479
1343
  additionalWorkers: additionalWorkers.length > 0 ? additionalWorkers : void 0
2480
1344
  });
2481
1345
  } else {
2482
- const result = await buildWebRuntime(config);
1346
+ const result = await buildWebRuntime(config, prelaunchedWeb);
2483
1347
  runtimes.push(result.runtime);
2484
1348
  platformConfigs.push({
2485
1349
  platform,
@@ -2491,6 +1355,30 @@ async function buildParallelPlatformConfigs(platforms, opts, config, runtimes, r
2491
1355
  }
2492
1356
  });
2493
1357
  }
1358
+ } else if (platform === "electron") {
1359
+ const result = await buildElectronRuntime(config, resolveFromConfig);
1360
+ runtimes.push(result.runtime);
1361
+ platformConfigs.push({
1362
+ platform,
1363
+ driver: result.runtime.driver,
1364
+ engineConfig: {
1365
+ ...result.engineConfig,
1366
+ debugOnFailure: opts.debugOnFailure,
1367
+ updateBaselines: opts.updateBaselines
1368
+ }
1369
+ });
1370
+ } else if (platform === "electrobun") {
1371
+ const result = await buildElectrobunRuntime(config, resolveFromConfig);
1372
+ runtimes.push(result.runtime);
1373
+ platformConfigs.push({
1374
+ platform,
1375
+ driver: result.runtime.driver,
1376
+ engineConfig: {
1377
+ ...result.engineConfig,
1378
+ debugOnFailure: opts.debugOnFailure,
1379
+ updateBaselines: opts.updateBaselines
1380
+ }
1381
+ });
2494
1382
  } else if (platformDevices.length === 0) {
2495
1383
  console.log(`No ${platform} devices found. Skipping ${platform} platform.`);
2496
1384
  } else {
@@ -2540,7 +1428,7 @@ async function buildParallelPlatformConfigs(platforms, opts, config, runtimes, r
2540
1428
  }
2541
1429
  return platformConfigs;
2542
1430
  }
2543
- async function buildSerialPlatformConfigs(platforms, opts, config, runtimes, executionMode, appiumUrl, appiumConfig, cloudHelper, targetDevice, resolveFromConfig) {
1431
+ async function buildSerialPlatformConfigs(platforms, opts, config, runtimes, executionMode, appiumUrl, appiumConfig, cloudHelper, targetDevice, resolveFromConfig, prelaunchedWeb) {
2544
1432
  const platformConfigs = [];
2545
1433
  for (const platform of platforms) {
2546
1434
  if (executionMode === "appium" && (platform === "android" || platform === "ios")) {
@@ -2568,7 +1456,7 @@ async function buildSerialPlatformConfigs(platforms, opts, config, runtimes, exe
2568
1456
  }
2569
1457
  });
2570
1458
  } else if (platform === "web") {
2571
- const result = await buildWebRuntime(config);
1459
+ const result = await buildWebRuntime(config, prelaunchedWeb);
2572
1460
  runtimes.push(result.runtime);
2573
1461
  platformConfigs.push({
2574
1462
  platform,
@@ -2605,11 +1493,35 @@ async function buildSerialPlatformConfigs(platforms, opts, config, runtimes, exe
2605
1493
  updateBaselines: opts.updateBaselines
2606
1494
  }
2607
1495
  });
1496
+ } else if (platform === "electron") {
1497
+ const result = await buildElectronRuntime(config, resolveFromConfig);
1498
+ runtimes.push(result.runtime);
1499
+ platformConfigs.push({
1500
+ platform,
1501
+ driver: result.runtime.driver,
1502
+ engineConfig: {
1503
+ ...result.engineConfig,
1504
+ debugOnFailure: opts.debugOnFailure,
1505
+ updateBaselines: opts.updateBaselines
1506
+ }
1507
+ });
1508
+ } else if (platform === "electrobun") {
1509
+ const result = await buildElectrobunRuntime(config, resolveFromConfig);
1510
+ runtimes.push(result.runtime);
1511
+ platformConfigs.push({
1512
+ platform,
1513
+ driver: result.runtime.driver,
1514
+ engineConfig: {
1515
+ ...result.engineConfig,
1516
+ debugOnFailure: opts.debugOnFailure,
1517
+ updateBaselines: opts.updateBaselines
1518
+ }
1519
+ });
2608
1520
  }
2609
1521
  }
2610
1522
  return platformConfigs;
2611
1523
  }
2612
- var BUILTIN_REPORTERS = /* @__PURE__ */ new Set(["console", "json", "junit", "html", "allure"]);
1524
+ var BUILTIN_REPORTERS = /* @__PURE__ */ new Set(["console", "json", "junit", "html", "allure", "github"]);
2613
1525
  async function loadCustomReporter(modulePath, configDir) {
2614
1526
  const resolvedPath = modulePath.startsWith(".") ? resolve3(configDir, modulePath) : modulePath;
2615
1527
  let mod;
@@ -2637,15 +1549,16 @@ async function loadCustomReporter(modulePath, configDir) {
2637
1549
  `Custom reporter "${modulePath}" default export must be a Reporter object or factory function, got ${typeof exported}.`
2638
1550
  );
2639
1551
  }
2640
- async function setupReporters(reporterNames, config, resolveFromConfig, appiumUrl, opts) {
1552
+ async function setupReporters(reporterNames, config, resolveFromConfig, appiumUrl, opts, filterSummaries = []) {
2641
1553
  const { createRedactor, registerUrlSecrets } = await import("./redact-U72BUBBR.js");
2642
1554
  const redactor = createRedactor();
2643
1555
  if (appiumUrl) registerUrlSecrets(redactor, appiumUrl);
2644
- const { createConsoleReporter } = await import("./console-7UW7VROK.js");
1556
+ const { createConsoleReporter } = await import("./console-MI2XB5RG.js");
2645
1557
  const { createJsonReporter } = await import("./json-JMRPUVY2.js");
2646
1558
  const { createJUnitReporter } = await import("./junit-HLC62MK6.js");
2647
1559
  const { createHtmlReporter } = await import("./html-F3X3XPSX.js");
2648
1560
  const { createAllureReporter } = await import("./allure-RNMEYTXS.js");
1561
+ const { createGitHubPrReporter } = await import("./github-pr-YMWIPCCZ.js");
2649
1562
  const resolvedOutputDir = config.artifacts?.outputDir ?? resolveFromConfig("./spana-output");
2650
1563
  const reporters = [];
2651
1564
  for (const name of reporterNames.split(",")) {
@@ -2665,6 +1578,9 @@ async function setupReporters(reporterNames, config, resolveFromConfig, appiumUr
2665
1578
  case "allure":
2666
1579
  reporters.push(createAllureReporter());
2667
1580
  break;
1581
+ case "github":
1582
+ reporters.push(createGitHubPrReporter({ outputDir: resolvedOutputDir, filterSummaries }));
1583
+ break;
2668
1584
  default:
2669
1585
  reporters.push(createConsoleReporter({ quiet: opts.quiet }));
2670
1586
  break;
@@ -2737,10 +1653,10 @@ async function resolveExecutionContext(opts) {
2737
1653
  };
2738
1654
  }
2739
1655
  async function resolveTargetDevice(deviceId, platforms, cliPlatforms) {
2740
- const { findDeviceById } = await import("./discover-NPNF6SWQ.js");
1656
+ const { findDeviceById } = await import("./discover-LHEBSUIP.js");
2741
1657
  const targetDevice = findDeviceById(deviceId);
2742
1658
  if (!targetDevice) {
2743
- const { discoverDevices } = await import("./discover-NPNF6SWQ.js");
1659
+ const { discoverDevices } = await import("./discover-LHEBSUIP.js");
2744
1660
  const available = discoverDevices(["web", "android", "ios"]);
2745
1661
  console.log(`Device "${deviceId}" not found. Available devices:`);
2746
1662
  for (const d of available) {
@@ -2818,6 +1734,34 @@ async function discoverAndFilterFlows(input) {
2818
1734
  );
2819
1735
  const allowedFlows = new Set(filteredFlows);
2820
1736
  let filteredLoadedFlows = loadedFlows.filter((l) => allowedFlows.has(l.flow));
1737
+ let filterSummaries = [];
1738
+ if (input.changedSince && input.filters && input.filters.length > 0 && filteredLoadedFlows.length > 0) {
1739
+ const { applyTestFilters, buildFilterCandidates, collectGitChanges, formatFilterSummary } = await import("./filters-Q3ALKWZ5.js");
1740
+ try {
1741
+ const cwd = process.cwd();
1742
+ const changes = collectGitChanges(input.changedSince, cwd);
1743
+ const candidates = buildFilterCandidates(filteredLoadedFlows, cwd);
1744
+ const result = await applyTestFilters(filteredLoadedFlows, candidates, input.filters, {
1745
+ cwd,
1746
+ changes,
1747
+ configPath: input.configPath,
1748
+ platforms: input.platforms
1749
+ });
1750
+ filterSummaries = formatFilterSummary(result.reports);
1751
+ for (const line of filterSummaries) {
1752
+ console.log(line);
1753
+ }
1754
+ filteredLoadedFlows = result.kept;
1755
+ if (filteredLoadedFlows.length === 0) {
1756
+ console.log("All flows were filtered out by --changed-since filters.");
1757
+ return { ok: false, success: true, watchRoots };
1758
+ }
1759
+ } catch (err) {
1760
+ console.log(
1761
+ `Warning: --changed-since ${input.changedSince} failed (${err instanceof Error ? err.message : String(err)}) \u2014 failing open and running all flows.`
1762
+ );
1763
+ }
1764
+ }
2821
1765
  if (input.lastFailed) {
2822
1766
  const lastRunStatePath = createLastRunStatePath(input.outputDir);
2823
1767
  const state = await readLastRunState(lastRunStatePath);
@@ -2854,7 +1798,7 @@ async function discoverAndFilterFlows(input) {
2854
1798
  `Running shard ${input.shard.current}/${input.shard.total} (${selectedFlows.length}/${filteredLoadedFlows.length} flow(s))...`
2855
1799
  );
2856
1800
  }
2857
- return { ok: true, selectedLoadedFlows, selectedFlows, watchRoots };
1801
+ return { ok: true, selectedLoadedFlows, selectedFlows, watchRoots, filterSummaries };
2858
1802
  }
2859
1803
  function createResultHandler(reporters, redactResult, redactor, opts) {
2860
1804
  return (r) => {
@@ -2941,19 +1885,32 @@ async function runTestCommandOnce(opts) {
2941
1885
  }
2942
1886
  const reporterNames = opts.reporter?.trim() ? opts.reporter : config.reporters && config.reporters.length > 0 ? config.reporters.join(",") : "console";
2943
1887
  const outputDir = config.artifacts?.outputDir ?? resolveFromConfig("./spana-output");
2944
- const flowResult = await discoverAndFilterFlows({
2945
- flowDir,
2946
- configPath,
2947
- tags: opts.tags,
2948
- grep: opts.grep,
2949
- platforms,
2950
- shard: opts.shard,
2951
- lastFailed: opts.lastFailed,
2952
- changed: opts.changed,
2953
- outputDir
2954
- });
2955
- if (!flowResult.ok) return { success: flowResult.success, watchRoots: flowResult.watchRoots };
2956
- const { selectedLoadedFlows, selectedFlows, watchRoots } = flowResult;
1888
+ const prelaunchedWeb = executionMode === "local" && platforms.includes("web") ? speculativelyPrelaunchWebBrowser(config) : void 0;
1889
+ const [flowResult, priorRunState] = await Promise.all([
1890
+ discoverAndFilterFlows({
1891
+ flowDir,
1892
+ configPath,
1893
+ tags: opts.tags,
1894
+ grep: opts.grep,
1895
+ platforms,
1896
+ shard: opts.shard,
1897
+ lastFailed: opts.lastFailed,
1898
+ changed: opts.changed,
1899
+ changedSince: opts.changedSince,
1900
+ filters: config.filters,
1901
+ outputDir
1902
+ }),
1903
+ readLastRunState(createLastRunStatePath(outputDir))
1904
+ ]);
1905
+ if (!flowResult.ok) {
1906
+ if (prelaunchedWeb?.ownsBrowser) {
1907
+ await prelaunchedWeb.browserPromise.then((b) => b.close()).catch(() => {
1908
+ });
1909
+ }
1910
+ return { success: flowResult.success, watchRoots: flowResult.watchRoots };
1911
+ }
1912
+ const { selectedLoadedFlows, selectedFlows, watchRoots, filterSummaries } = flowResult;
1913
+ const durationHintsMs = extractDurationHints(priorRunState);
2957
1914
  console.log(`Running ${selectedFlows.length} flow(s) on ${platforms.join(", ")}...
2958
1915
  `);
2959
1916
  const runtimes = [];
@@ -3007,7 +1964,8 @@ async function runTestCommandOnce(opts) {
3007
1964
  opts,
3008
1965
  config,
3009
1966
  runtimes,
3010
- resolveFromConfig
1967
+ resolveFromConfig,
1968
+ prelaunchedWeb
3011
1969
  )
3012
1970
  );
3013
1971
  } else {
@@ -3022,7 +1980,8 @@ async function runTestCommandOnce(opts) {
3022
1980
  appiumConfig,
3023
1981
  cloudHelper,
3024
1982
  targetDevice,
3025
- resolveFromConfig
1983
+ resolveFromConfig,
1984
+ prelaunchedWeb
3026
1985
  )
3027
1986
  );
3028
1987
  }
@@ -3031,7 +1990,8 @@ async function runTestCommandOnce(opts) {
3031
1990
  config,
3032
1991
  resolveFromConfig,
3033
1992
  appiumUrl,
3034
- opts
1993
+ opts,
1994
+ filterSummaries
3035
1995
  );
3036
1996
  const totalFlowCount = selectedFlows.length * platforms.length;
3037
1997
  for (const reporter of reporters) {
@@ -3067,6 +2027,7 @@ async function runTestCommandOnce(opts) {
3067
2027
  retries,
3068
2028
  retryDelay,
3069
2029
  bail: opts.bail,
2030
+ durationHintsMs: Object.keys(durationHintsMs).length > 0 ? durationHintsMs : void 0,
3070
2031
  parallelPlatforms: opts.parallel || config.parallelPlatforms || !!opts.workers || !!opts.devices,
3071
2032
  onFlowStart(name, platform, workerName) {
3072
2033
  for (const reporter of reporters) {
@@ -3158,4 +2119,4 @@ export {
3158
2119
  loadCustomReporter,
3159
2120
  runTestCommand
3160
2121
  };
3161
- //# sourceMappingURL=test-command-2PXTHASW.js.map
2122
+ //# sourceMappingURL=test-command-FYOZ6QAE.js.map