spana-test 0.4.0 → 0.6.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 (157) hide show
  1. package/.agents/skills/spana-testing/SKILL.md +122 -246
  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 +11 -10
  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-GFW6OXPQ.js → android-4NVTZMHL.js} +6 -2
  12. package/dist/{android-GFW6OXPQ.js.map → android-4NVTZMHL.js.map} +0 -0
  13. package/dist/app-DcLXtpv4.d.ts +908 -0
  14. package/dist/appium-server-66GVUL24.js +0 -0
  15. package/dist/appium-server-66GVUL24.js.map +0 -0
  16. package/dist/baseline-manager-5TIUCNP5.js +0 -0
  17. package/dist/baseline-manager-5TIUCNP5.js.map +0 -0
  18. package/dist/chunk-3FSZNKEF.js +0 -0
  19. package/dist/chunk-3FSZNKEF.js.map +0 -0
  20. package/dist/chunk-3SH5JQF7.js +611 -0
  21. package/dist/chunk-3SH5JQF7.js.map +1 -0
  22. package/dist/chunk-4K3FZTSV.js +179 -0
  23. package/dist/chunk-4K3FZTSV.js.map +1 -0
  24. package/dist/chunk-C4E4XULT.js +540 -0
  25. package/dist/chunk-C4E4XULT.js.map +1 -0
  26. package/dist/{chunk-3J4NG7JU.js → chunk-CY3DKTBZ.js} +8 -2
  27. package/dist/chunk-CY3DKTBZ.js.map +1 -0
  28. package/dist/chunk-DGUM43GV.js +0 -0
  29. package/dist/chunk-DGUM43GV.js.map +0 -0
  30. package/dist/chunk-DTNK54C2.js +127 -0
  31. package/dist/chunk-DTNK54C2.js.map +1 -0
  32. package/dist/{chunk-EWIR2GVV.js → chunk-H27IBIGA.js} +19 -2
  33. package/dist/chunk-H27IBIGA.js.map +1 -0
  34. package/dist/{chunk-PZYZ4O6D.js → chunk-HCG4CJKR.js} +23 -5
  35. package/dist/chunk-HCG4CJKR.js.map +1 -0
  36. package/dist/{chunk-YGHDMA6D.js → chunk-HYSTRWYN.js} +142 -41
  37. package/dist/chunk-HYSTRWYN.js.map +1 -0
  38. package/dist/chunk-IHVZKQQW.js +0 -0
  39. package/dist/chunk-IHVZKQQW.js.map +0 -0
  40. package/dist/{chunk-7VOWF42B.js → chunk-KBRLIQRA.js} +89 -8
  41. package/dist/chunk-KBRLIQRA.js.map +1 -0
  42. package/dist/chunk-KEUZLBQS.js +2935 -0
  43. package/dist/chunk-KEUZLBQS.js.map +1 -0
  44. package/dist/chunk-KJPHH2TW.js +0 -0
  45. package/dist/chunk-KJPHH2TW.js.map +0 -0
  46. package/dist/chunk-LAMTF4LX.js +89 -0
  47. package/dist/chunk-LAMTF4LX.js.map +1 -0
  48. package/dist/chunk-LCV673G3.js +3050 -0
  49. package/dist/chunk-LCV673G3.js.map +1 -0
  50. package/dist/chunk-OBCFACUW.js +0 -0
  51. package/dist/chunk-OBCFACUW.js.map +0 -0
  52. package/dist/{chunk-3TRMQCUT.js → chunk-PLE7RFQE.js} +31 -2
  53. package/dist/chunk-PLE7RFQE.js.map +1 -0
  54. package/dist/chunk-PWUJT5HE.js +5679 -0
  55. package/dist/chunk-PWUJT5HE.js.map +1 -0
  56. package/dist/{chunk-FJAJ4YNC.js → chunk-S4JVAHBR.js} +2 -2
  57. package/dist/{chunk-FJAJ4YNC.js.map → chunk-S4JVAHBR.js.map} +0 -0
  58. package/dist/chunk-S5JNNDXS.js +0 -0
  59. package/dist/chunk-S5JNNDXS.js.map +0 -0
  60. package/dist/{chunk-KYPLYRKW.js → chunk-WBBMEAHU.js} +122 -15
  61. package/dist/chunk-WBBMEAHU.js.map +1 -0
  62. package/dist/chunk-X2TJP7LB.js +0 -0
  63. package/dist/chunk-X2TJP7LB.js.map +0 -0
  64. package/dist/{chunk-5245YBLL.js → chunk-Y2RZNOKU.js} +2 -2
  65. package/dist/{chunk-5245YBLL.js.map → chunk-Y2RZNOKU.js.map} +0 -0
  66. package/dist/cli.js +62 -22
  67. package/dist/cli.js.map +1 -1
  68. package/dist/compiler-X6WTFMYF.js +0 -0
  69. package/dist/compiler-X6WTFMYF.js.map +0 -0
  70. package/dist/config-loader-J4Z2PMUQ.js +9 -0
  71. package/dist/{config-loader-QM72GKEL.js.map → config-loader-J4Z2PMUQ.js.map} +0 -0
  72. package/dist/{console-7UW7VROK.js → console-MI2XB5RG.js} +8 -2
  73. package/dist/console-MI2XB5RG.js.map +1 -0
  74. package/dist/daemon-manager-FBISTX24.js +28 -0
  75. package/dist/{discover-CAQY6EG6.js.map → daemon-manager-FBISTX24.js.map} +0 -0
  76. package/dist/{discover-CAQY6EG6.js → discover-LHEBSUIP.js} +3 -3
  77. package/dist/{installer-PVBSX7UC.js.map → discover-LHEBSUIP.js.map} +0 -0
  78. package/dist/doctor-command-WEHFANT7.js +378 -0
  79. package/dist/doctor-command-WEHFANT7.js.map +1 -0
  80. package/dist/filters-MQG2RMPX.js +26 -0
  81. package/dist/{runner-6HK62Q7B.js.map → filters-MQG2RMPX.js.map} +0 -0
  82. package/dist/flow-C2JQ7gUu.d.ts +95 -0
  83. package/dist/gherkin/steps.d.ts +2 -2
  84. package/dist/gherkin/steps.js +0 -0
  85. package/dist/gherkin/steps.js.map +0 -0
  86. package/dist/github-pr-YMWIPCCZ.js +10 -0
  87. package/dist/{session-2MZVGYAC.js.map → github-pr-YMWIPCCZ.js.map} +0 -0
  88. package/dist/html-F3X3XPSX.js +0 -0
  89. package/dist/html-F3X3XPSX.js.map +0 -0
  90. package/dist/index.d.ts +1323 -6
  91. package/dist/index.js +742 -6
  92. package/dist/index.js.map +1 -1
  93. package/dist/{init-command-U66XCM66.js → init-command-Z3QREABL.js} +60 -1
  94. package/dist/init-command-Z3QREABL.js.map +1 -0
  95. package/dist/{init-flow-command-PR7J5FBM.js → init-flow-command-4EKRVTNT.js} +2 -2
  96. package/dist/{init-flow-command-PR7J5FBM.js.map → init-flow-command-4EKRVTNT.js.map} +0 -0
  97. package/dist/{installer-PVBSX7UC.js → installer-VUPFWP5X.js} +7 -2
  98. package/dist/{validator-HZ2A3NEI.js.map → installer-VUPFWP5X.js.map} +0 -0
  99. package/dist/ios-JPK43TFZ.js +0 -0
  100. package/dist/ios-JPK43TFZ.js.map +0 -0
  101. package/dist/json-JMRPUVY2.js +0 -0
  102. package/dist/json-JMRPUVY2.js.map +0 -0
  103. package/dist/junit-HLC62MK6.js +0 -0
  104. package/dist/junit-HLC62MK6.js.map +0 -0
  105. package/dist/machine-6H25TRTU.js +0 -0
  106. package/dist/machine-6H25TRTU.js.map +0 -0
  107. package/dist/provider-YIPU5K42.js +0 -0
  108. package/dist/provider-YIPU5K42.js.map +0 -0
  109. package/dist/redact-U72BUBBR.js +0 -0
  110. package/dist/redact-U72BUBBR.js.map +0 -0
  111. package/dist/{runner-6HK62Q7B.js → runner-TF4OKPYP.js} +2 -2
  112. package/dist/runner-TF4OKPYP.js.map +1 -0
  113. package/dist/screenshot-compare-5NINZVOK.js +136 -0
  114. package/dist/screenshot-compare-5NINZVOK.js.map +1 -0
  115. package/dist/server-3MGZNK67.js +14 -0
  116. package/dist/server-3MGZNK67.js.map +1 -0
  117. package/dist/{server-PZBRGU7P.js → server-OANRDAHN.js} +15 -14
  118. package/dist/{server-PZBRGU7P.js.map → server-OANRDAHN.js.map} +1 -1
  119. package/dist/session-Daq0mE_a.d.ts +140 -0
  120. package/dist/session-Q3QYHT4Q.js +18 -0
  121. package/dist/session-Q3QYHT4Q.js.map +1 -0
  122. package/dist/{studio-command-YDWQOMRX.js → studio-command-RJYLJT4I.js} +2 -2
  123. package/dist/{studio-command-YDWQOMRX.js.map → studio-command-RJYLJT4I.js.map} +0 -0
  124. package/dist/{test-command-B2VLWGDK.js → test-command-ALH5ZQY5.js} +247 -1343
  125. package/dist/test-command-ALH5ZQY5.js.map +1 -0
  126. package/dist/{validator-HZ2A3NEI.js → validator-BLOLIHUY.js} +3 -3
  127. package/dist/validator-BLOLIHUY.js.map +1 -0
  128. package/package.json +7 -3
  129. package/studio-dist/assets/index-C-Io44gy.js +0 -0
  130. package/studio-dist/assets/index-DfM9lK4p.css +0 -0
  131. package/studio-dist/index.html +0 -0
  132. package/dist/accessibility-audit-RS3VIWRT.js.map +0 -1
  133. package/dist/chunk-3J4NG7JU.js.map +0 -1
  134. package/dist/chunk-3TRMQCUT.js.map +0 -1
  135. package/dist/chunk-7VOWF42B.js.map +0 -1
  136. package/dist/chunk-EWIR2GVV.js.map +0 -1
  137. package/dist/chunk-KYPLYRKW.js.map +0 -1
  138. package/dist/chunk-LC3QJIHY.js +0 -440
  139. package/dist/chunk-LC3QJIHY.js.map +0 -1
  140. package/dist/chunk-MCT4DYDK.js +0 -2671
  141. package/dist/chunk-MCT4DYDK.js.map +0 -1
  142. package/dist/chunk-PZYZ4O6D.js.map +0 -1
  143. package/dist/chunk-YAV6KBSW.js +0 -1318
  144. package/dist/chunk-YAV6KBSW.js.map +0 -1
  145. package/dist/chunk-YGHDMA6D.js.map +0 -1
  146. package/dist/config-loader-QM72GKEL.js +0 -9
  147. package/dist/console-7UW7VROK.js.map +0 -1
  148. package/dist/doctor-command-YGQPO7GH.js +0 -71
  149. package/dist/doctor-command-YGQPO7GH.js.map +0 -1
  150. package/dist/element-DZ0HyJ3C.d.ts +0 -25
  151. package/dist/flow-thjUxXXx.d.ts +0 -168
  152. package/dist/init-command-U66XCM66.js.map +0 -1
  153. package/dist/screenshot-compare-JFHH2WR4.js +0 -75
  154. package/dist/screenshot-compare-JFHH2WR4.js.map +0 -1
  155. package/dist/session-2MZVGYAC.js +0 -17
  156. package/dist/storybook-pBOPe_1D.d.ts +0 -451
  157. package/dist/test-command-B2VLWGDK.js.map +0 -1
@@ -0,0 +1,2935 @@
1
+ import {
2
+ connectPlaywrightOverCDP,
3
+ connectPlaywrightOverWS,
4
+ createCoordinator,
5
+ createPromiseApp,
6
+ createUiAutomator2Driver,
7
+ createWDADriver,
8
+ ensureWarmBrowserDaemon,
9
+ flattenElements,
10
+ launchPlaywrightBrowser,
11
+ makeElectronDriver,
12
+ makePlaywrightDriver,
13
+ mergeLaunchOptions,
14
+ parseAndroidHierarchy,
15
+ parseIOSHierarchy,
16
+ parseWebHierarchy,
17
+ resolveNetworkConditions,
18
+ setupUiAutomator2
19
+ } from "./chunk-PWUJT5HE.js";
20
+ import {
21
+ CdpDomChannel,
22
+ DriverError,
23
+ createSpanaBridgeChannel,
24
+ makeElectrobunDriver
25
+ } from "./chunk-LCV673G3.js";
26
+ import {
27
+ setupWDA
28
+ } from "./chunk-HYSTRWYN.js";
29
+ import {
30
+ getHealthyWarmDaemon,
31
+ registerWarmDaemon,
32
+ updateWarmDaemonSession
33
+ } from "./chunk-DTNK54C2.js";
34
+ import {
35
+ connectPhysicalDevice,
36
+ ensureAppInstalled,
37
+ ensureIOSSimulator,
38
+ firstIOSPhysicalDevice
39
+ } from "./chunk-S5JNNDXS.js";
40
+ import {
41
+ allocatePort
42
+ } from "./chunk-OBCFACUW.js";
43
+ import {
44
+ adbReverse,
45
+ adbReverseRemove,
46
+ ensureAndroidDevice
47
+ } from "./chunk-H27IBIGA.js";
48
+
49
+ // src/api/expect.ts
50
+ import { Effect } from "effect";
51
+ function selectorToCss(sel) {
52
+ if (typeof sel === "string") return sel;
53
+ if (typeof sel === "object" && sel !== null && "testID" in sel && sel.testID)
54
+ return `[data-testid="${sel.testID}"]`;
55
+ if (typeof sel === "object" && sel !== null && "accessibilityLabel" in sel && sel.accessibilityLabel)
56
+ return `[aria-label="${sel.accessibilityLabel}"]`;
57
+ return "";
58
+ }
59
+ function createPromiseExpect(driver, config, recorder, flowContext, visualRegression) {
60
+ const ctx = flowContext ?? {
61
+ flowFilePath: "",
62
+ flowName: "unknown",
63
+ platform: "web"
64
+ };
65
+ const coord = createCoordinator(driver, config);
66
+ const run = (effect) => Effect.runPromise(effect);
67
+ const runStep = (command, selector, action) => recorder ? recorder.runStep(command, action, { selector, captureScreenshot: false }) : action();
68
+ return (selector) => ({
69
+ toBeVisible: (opts) => runStep(
70
+ "expect.toBeVisible",
71
+ selector,
72
+ () => run(coord.assertVisible(selector, opts)).then(() => {
73
+ })
74
+ ),
75
+ toBeHidden: (opts) => runStep("expect.toBeHidden", selector, () => run(coord.assertHidden(selector, opts))),
76
+ toHaveText: (expected, opts) => runStep(
77
+ `expect.toHaveText(${JSON.stringify(expected)})`,
78
+ selector,
79
+ () => run(coord.assertText(selector, expected, opts))
80
+ ),
81
+ toMatchText: (pattern, opts) => runStep(
82
+ `expect.toMatchText(${pattern})`,
83
+ selector,
84
+ () => run(coord.assertMatchesText(selector, pattern, opts))
85
+ ),
86
+ toHaveValue: (expected, opts) => runStep(
87
+ `expect.toHaveValue(${JSON.stringify(expected)})`,
88
+ selector,
89
+ () => run(coord.assertValue(selector, expected, opts))
90
+ ),
91
+ toHaveAttribute: (name, value, opts) => runStep(
92
+ `expect.toHaveAttribute(${JSON.stringify(name)})`,
93
+ selector,
94
+ () => run(coord.assertAttribute(selector, name, value, opts))
95
+ ),
96
+ toBeEnabled: (opts) => runStep("expect.toBeEnabled", selector, () => run(coord.assertEnabled(selector, opts))),
97
+ toBeDisabled: (opts) => runStep("expect.toBeDisabled", selector, () => run(coord.assertDisabled(selector, opts))),
98
+ toContainText: (expected, opts) => runStep(
99
+ `expect.toContainText(${JSON.stringify(expected)})`,
100
+ selector,
101
+ () => run(coord.assertContainsText(selector, expected, opts))
102
+ ),
103
+ toMatchScreenshot: (name, options) => runStep(
104
+ `expect.toMatchScreenshot(${JSON.stringify(name)})`,
105
+ selector,
106
+ () => run(
107
+ coord.assertScreenshot(selector, name, ctx.flowFilePath, ctx.flowName, ctx.platform, {
108
+ threshold: options?.threshold ?? visualRegression?.threshold,
109
+ maxDiffPixelRatio: options?.maxDiffPixelRatio ?? visualRegression?.maxDiffPixelRatio,
110
+ mask: [],
111
+ updateBaselines: ctx.updateBaselines,
112
+ baselinesDir: visualRegression?.baselinesDir
113
+ })
114
+ )
115
+ ),
116
+ toPassAccessibilityAudit: (options) => {
117
+ const excludeCss = options?.exclude?.map(selectorToCss).filter(Boolean) ?? [];
118
+ const targetCss = selectorToCss(selector);
119
+ return runStep(
120
+ "expect.toPassAccessibilityAudit",
121
+ selector,
122
+ () => run(
123
+ coord.assertAccessibilityAudit(ctx.platform, {
124
+ severity: options?.severity,
125
+ rules: options?.rules,
126
+ targetSelector: targetCss || void 0,
127
+ excludeSelectors: excludeCss
128
+ })
129
+ )
130
+ );
131
+ },
132
+ toHaveAccessibilityLabel: (expected) => runStep(
133
+ `expect.toHaveAccessibilityLabel(${expected !== void 0 ? JSON.stringify(expected) : ""})`,
134
+ selector,
135
+ () => run(coord.assertAccessibilityLabel(selector, expected))
136
+ ),
137
+ toBeFocusable: () => runStep(
138
+ "expect.toBeFocusable",
139
+ selector,
140
+ () => run(coord.assertFocusable(selector, ctx.platform))
141
+ ),
142
+ toHaveRole: (expected) => runStep(
143
+ `expect.toHaveRole(${JSON.stringify(expected)})`,
144
+ selector,
145
+ () => run(coord.assertRole(selector, expected, ctx.platform))
146
+ ),
147
+ toHaveMinTouchTarget: (size = 44) => runStep(
148
+ `expect.toHaveMinTouchTarget(${size})`,
149
+ selector,
150
+ () => run(coord.assertMinTouchTarget(selector, size))
151
+ )
152
+ });
153
+ }
154
+
155
+ // src/core/session-manager.ts
156
+ import { Effect as Effect2 } from "effect";
157
+ function createSessions(manager, driverFactory, coordinatorConfig) {
158
+ const coordConfig = coordinatorConfig ?? { parse: parseWebHierarchy };
159
+ return {
160
+ async open(opts) {
161
+ const existing = manager.all().find((s) => s.name === opts.name);
162
+ if (existing) {
163
+ throw new Error(`Session "${opts.name}" already exists`);
164
+ }
165
+ const driver = await driverFactory(opts);
166
+ const baseUrl = opts.baseUrl ?? "http://localhost:3000";
167
+ await Effect2.runPromise(driver.launchApp(baseUrl));
168
+ const app = createPromiseApp(driver, baseUrl, coordConfig, void 0, {
169
+ platform: "web"
170
+ });
171
+ const expect = createPromiseExpect(driver, coordConfig);
172
+ const session = {
173
+ name: opts.name,
174
+ platform: "web",
175
+ app,
176
+ expect,
177
+ async disconnect() {
178
+ await Effect2.runPromise(driver.killApp(baseUrl));
179
+ manager.remove(opts.name);
180
+ }
181
+ };
182
+ const cleanup = async () => {
183
+ await Effect2.runPromise(driver.killApp(baseUrl));
184
+ };
185
+ manager.register(session, cleanup);
186
+ return session;
187
+ }
188
+ };
189
+ }
190
+ var SessionManager = class {
191
+ sessions = [];
192
+ all() {
193
+ return this.sessions.map((s) => s.session);
194
+ }
195
+ register(session, cleanup) {
196
+ this.sessions.push({ session, cleanup });
197
+ }
198
+ remove(name) {
199
+ this.sessions = this.sessions.filter((s) => s.session.name !== name);
200
+ }
201
+ async disconnectAll() {
202
+ const errors = [];
203
+ for (const entry of [...this.sessions].toReversed()) {
204
+ try {
205
+ await entry.cleanup();
206
+ } catch (err) {
207
+ errors.push(err);
208
+ }
209
+ }
210
+ this.sessions = [];
211
+ if (errors.length > 0) {
212
+ console.warn(
213
+ `SessionManager: ${errors.length} error(s) during cleanup:`,
214
+ errors.map((e) => e instanceof Error ? e.message : String(e))
215
+ );
216
+ }
217
+ }
218
+ };
219
+
220
+ // src/drivers/cdp-browser.ts
221
+ import { spawn } from "child_process";
222
+ import { createHash } from "crypto";
223
+ import { existsSync, mkdtempSync, rmSync } from "fs";
224
+ import { copyFile, readFile, writeFile } from "fs/promises";
225
+ import { tmpdir } from "os";
226
+ import { join } from "path";
227
+ import { Effect as Effect3 } from "effect";
228
+ var INSTANT_ANIMATIONS_CDP_SCRIPT = `
229
+ (() => {
230
+ const inject = () => {
231
+ if (document.getElementById("__spana_instant_anim")) return;
232
+ const style = document.createElement("style");
233
+ style.id = "__spana_instant_anim";
234
+ style.textContent = "*, *::before, *::after { transition-duration: 0.001ms !important; transition-delay: 0ms !important; animation-duration: 0.001ms !important; animation-delay: 0ms !important; scroll-behavior: auto !important; }";
235
+ (document.head || document.documentElement).appendChild(style);
236
+ };
237
+ if (document.readyState === "loading") {
238
+ document.addEventListener("DOMContentLoaded", inject, { once: true });
239
+ } else {
240
+ inject();
241
+ }
242
+ })();
243
+ `;
244
+ function resolveDirectCdpScopeKey(scope) {
245
+ if (scope && scope.trim().length > 0) return scope.trim();
246
+ const cwdHash = createHash("sha1").update(process.cwd()).digest("hex").slice(0, 10);
247
+ return `cdp-${cwdHash}`;
248
+ }
249
+ function resolveChromiumExecutable(explicit) {
250
+ if (explicit && existsSync(explicit)) return explicit;
251
+ const candidates = process.platform === "darwin" ? [
252
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
253
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
254
+ "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
255
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"
256
+ ] : process.platform === "linux" ? [
257
+ "/usr/bin/google-chrome",
258
+ "/usr/bin/google-chrome-stable",
259
+ "/usr/bin/chromium",
260
+ "/usr/bin/chromium-browser"
261
+ ] : [
262
+ "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
263
+ "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
264
+ ];
265
+ for (const path of candidates) {
266
+ if (existsSync(path)) return path;
267
+ }
268
+ return explicit ?? "google-chrome";
269
+ }
270
+ async function fetchBrowserWsUrl(httpEndpoint, timeoutMs = 1e4) {
271
+ const deadline = Date.now() + timeoutMs;
272
+ while (Date.now() < deadline) {
273
+ try {
274
+ const res = await fetch(`${httpEndpoint}/json/version`, {
275
+ signal: AbortSignal.timeout(500)
276
+ });
277
+ if (res.ok) {
278
+ const data = await res.json();
279
+ if (data.webSocketDebuggerUrl) return data.webSocketDebuggerUrl;
280
+ }
281
+ } catch {
282
+ }
283
+ await new Promise((r) => setTimeout(r, 50));
284
+ }
285
+ throw new Error(`Direct CDP browser did not expose /json/version on ${httpEndpoint}`);
286
+ }
287
+ async function launchDirectCdpBrowser(options = {}) {
288
+ const daemonKey = resolveDirectCdpScopeKey(options.warmBrowserScope);
289
+ if (options.warmBrowser) {
290
+ const existing = await getHealthyWarmDaemon("chromium", daemonKey, {
291
+ statusPath: "/json/version"
292
+ });
293
+ if (existing) {
294
+ const httpEndpoint2 = `http://${existing.host}:${existing.port}`;
295
+ try {
296
+ const browserWsUrl2 = await fetchBrowserWsUrl(httpEndpoint2, 1500);
297
+ return {
298
+ httpEndpoint: httpEndpoint2,
299
+ browserWsUrl: browserWsUrl2,
300
+ reused: true,
301
+ pid: existing.pid,
302
+ close: async () => {
303
+ }
304
+ };
305
+ } catch {
306
+ }
307
+ }
308
+ }
309
+ let execPath = options.executablePath;
310
+ if (!execPath) {
311
+ try {
312
+ const { chromium } = await import("playwright-core");
313
+ const pwPath = chromium.executablePath();
314
+ if (pwPath && existsSync(pwPath)) {
315
+ execPath = pwPath;
316
+ }
317
+ } catch {
318
+ }
319
+ }
320
+ execPath = resolveChromiumExecutable(execPath);
321
+ const port = allocatePort(9350);
322
+ const userDataDir = mkdtempSync(join(tmpdir(), "spana-cdp-profile-"));
323
+ const chromeArgs = [
324
+ ...options.headless !== false ? ["--headless=new"] : [],
325
+ `--remote-debugging-port=${port}`,
326
+ "--remote-debugging-address=127.0.0.1",
327
+ `--user-data-dir=${userDataDir}`,
328
+ "--no-first-run",
329
+ "--no-default-browser-check",
330
+ "--disable-background-networking",
331
+ "--disable-background-timer-throttling",
332
+ "--disable-backgrounding-occluded-windows",
333
+ "--disable-renderer-backgrounding",
334
+ "--disable-ipc-flooding-protection",
335
+ "--disable-hang-monitor",
336
+ "--disable-default-apps",
337
+ "--disable-extensions",
338
+ "--disable-sync",
339
+ ...options.headless !== false ? ["--disable-gpu"] : [],
340
+ "--metrics-recording-only",
341
+ "--disable-features=Translate,BackForwardCache,AcceptCHFrame,MediaRouter,OptimizationHints",
342
+ ...options.args ?? [],
343
+ "about:blank"
344
+ ];
345
+ const child = spawn(execPath, chromeArgs, {
346
+ detached: Boolean(options.warmBrowser),
347
+ stdio: "ignore"
348
+ });
349
+ if (options.warmBrowser) {
350
+ child.unref();
351
+ }
352
+ const httpEndpoint = `http://127.0.0.1:${port}`;
353
+ const browserWsUrl = await fetchBrowserWsUrl(httpEndpoint, 1e4);
354
+ if (options.warmBrowser) {
355
+ registerWarmDaemon({
356
+ kind: "chromium",
357
+ deviceId: daemonKey,
358
+ host: "127.0.0.1",
359
+ port,
360
+ pid: child.pid,
361
+ startedAt: (/* @__PURE__ */ new Date()).toISOString()
362
+ });
363
+ }
364
+ return {
365
+ httpEndpoint,
366
+ browserWsUrl,
367
+ reused: Boolean(options.warmBrowser),
368
+ pid: child.pid,
369
+ close: async () => {
370
+ if (options.warmBrowser) return;
371
+ try {
372
+ child.kill("SIGTERM");
373
+ } catch {
374
+ }
375
+ await new Promise((r) => setTimeout(r, 200));
376
+ rmSync(userDataDir, { recursive: true, force: true });
377
+ }
378
+ };
379
+ }
380
+ var CDP_DUMP_HIERARCHY_SCRIPT = `(() => {
381
+ function walk(el) {
382
+ const rect = el.getBoundingClientRect ? el.getBoundingClientRect() : { x: 0, y: 0, width: 0, height: 0 };
383
+ const style = window.getComputedStyle ? window.getComputedStyle(el) : { display: "block", visibility: "visible", opacity: "1" };
384
+ const visible = rect.width > 0 && rect.height > 0 && style.display !== "none" && style.visibility !== "hidden" && parseFloat(style.opacity || "1") !== 0;
385
+ const tag = (el.tagName || "").toLowerCase();
386
+ return {
387
+ id: el.getAttribute?.("data-testid") || el.getAttribute?.("testID") || el.id || undefined,
388
+ text: el.children?.length === 0 ? (el.textContent || "").trim() || undefined : undefined,
389
+ accessibilityLabel: el.getAttribute?.("aria-label") || undefined,
390
+ elementType: tag,
391
+ bounds: { x: Math.round(rect.x), y: Math.round(rect.y), width: Math.round(rect.width), height: Math.round(rect.height) },
392
+ visible,
393
+ enabled: !el.hasAttribute?.("disabled"),
394
+ clickable: tag === "button" || tag === "a" || tag === "input" || el.getAttribute?.("role") === "button",
395
+ children: Array.from(el.children || []).map(walk),
396
+ };
397
+ }
398
+ return document.body ? JSON.stringify(walk(document.body)) : JSON.stringify({ bounds: { x: 0, y: 0, width: 0, height: 0 }, children: [] });
399
+ })()`;
400
+ function matchUrl(matcher, url) {
401
+ if (matcher instanceof RegExp) return matcher.test(url);
402
+ if (matcher.includes("*")) {
403
+ const escaped = matcher.replaceAll(/[.+?^${}()|[\]\\]/g, "\\$&").replaceAll("**", ".*").replaceAll("*", "[^/]*");
404
+ return new RegExp(escaped).test(url);
405
+ }
406
+ return url.includes(matcher);
407
+ }
408
+ var RESOURCE_BLOCK_PATTERNS = {
409
+ image: ["*.png", "*.jpg", "*.jpeg", "*.gif", "*.webp", "*.svg", "*.ico", "*.avif"],
410
+ font: ["*.woff", "*.woff2", "*.ttf", "*.otf", "*.eot"],
411
+ media: ["*.mp4", "*.webm", "*.ogg", "*.mp3", "*.wav", "*.m4a"],
412
+ stylesheet: ["*.css"]
413
+ };
414
+ function makeLightweightCdpDriver(options) {
415
+ return Effect3.gen(function* () {
416
+ const isBrowserWs = options.cdpUrl.includes("/devtools/browser/");
417
+ const useContexts = Boolean(
418
+ options.useBrowserContexts || options.freshContextPerFlow || isBrowserWs
419
+ );
420
+ const isWs = options.cdpUrl.startsWith("ws://") || options.cdpUrl.startsWith("wss://");
421
+ const httpEndpoint = isWs ? options.cdpUrl.replace(/^ws(s?):\/\//, "http$1://").replace(/\/devtools\/.*$/, "") : options.cdpUrl.replace(/\/+$/, "");
422
+ let connectWsUrl = isWs ? options.cdpUrl : void 0;
423
+ if (useContexts && !connectWsUrl) {
424
+ connectWsUrl = yield* Effect3.tryPromise({
425
+ try: () => fetchBrowserWsUrl(httpEndpoint, 5e3),
426
+ catch: (e) => new DriverError({
427
+ message: `Failed to resolve browser CDP WebSocket at ${options.cdpUrl}: ${e}`
428
+ })
429
+ });
430
+ }
431
+ const cdpChannel = new CdpDomChannel({
432
+ endpointUrl: httpEndpoint,
433
+ ...connectWsUrl ? { webSocketUrl: connectWsUrl } : {},
434
+ fetchFn: options.fetchFn,
435
+ createWebSocket: options.createWebSocket
436
+ });
437
+ yield* Effect3.tryPromise({
438
+ try: () => cdpChannel.connect(),
439
+ catch: (e) => new DriverError({
440
+ message: `Failed to connect lightweight CDP browser at ${options.cdpUrl}: ${e}`
441
+ })
442
+ });
443
+ const width = options.viewport?.width ?? 1280;
444
+ const height = options.viewport?.height ?? 720;
445
+ const label = options.engineLabel ?? "cdp";
446
+ let activeSlot;
447
+ let prefetchedSlotPromise;
448
+ let hasRunFirstFlow = false;
449
+ let activeAuthenticatorId;
450
+ const backgroundDisposals = [];
451
+ const consoleLogs = [];
452
+ const jsErrors = [];
453
+ const routeRules = [];
454
+ let fetchInterceptEnabled = false;
455
+ let nextTabSeq = 1;
456
+ let downloadDir;
457
+ const completedDownloads = [];
458
+ const downloadWaiters = [];
459
+ const pendingDownloadGuids = /* @__PURE__ */ new Map();
460
+ cdpChannel.onEvent("Browser.downloadWillBegin", (params) => {
461
+ if (params?.guid && downloadDir) {
462
+ pendingDownloadGuids.set(String(params.guid), join(downloadDir, String(params.guid)));
463
+ }
464
+ });
465
+ cdpChannel.onEvent("Browser.downloadProgress", (params) => {
466
+ if (params?.state === "completed" && params?.guid) {
467
+ const filePath = pendingDownloadGuids.get(String(params.guid)) ?? (downloadDir ? join(downloadDir, String(params.guid)) : "");
468
+ pendingDownloadGuids.delete(String(params.guid));
469
+ if (!filePath) return;
470
+ const waiter = downloadWaiters.shift();
471
+ if (waiter) waiter.resolve(filePath);
472
+ else completedDownloads.push(filePath);
473
+ }
474
+ });
475
+ const loadStorageStateFile = async (path) => {
476
+ if (!path) return null;
477
+ try {
478
+ const raw = await readFile(path, "utf8");
479
+ return JSON.parse(raw);
480
+ } catch {
481
+ return null;
482
+ }
483
+ };
484
+ const attachVirtualAuthenticatorForSession = async (sessionId, opts) => {
485
+ await cdpChannel.sendCommand("WebAuthn.enable", { enableUI: false }, sessionId);
486
+ const res = await cdpChannel.sendCommand(
487
+ "WebAuthn.addVirtualAuthenticator",
488
+ {
489
+ options: {
490
+ protocol: opts?.protocol ?? "ctap2",
491
+ transport: opts?.transport ?? "internal",
492
+ hasResidentKey: opts?.hasResidentKey ?? true,
493
+ hasUserVerification: opts?.hasUserVerification ?? true,
494
+ isUserVerified: opts?.isUserVerified ?? true,
495
+ automaticPresenceSimulation: opts?.automaticPresenceSimulation ?? true
496
+ }
497
+ },
498
+ sessionId
499
+ );
500
+ return res?.authenticatorId ?? "cdp-virtual-auth-1";
501
+ };
502
+ const configureSession = async (sessionId, storageStatePath) => {
503
+ const state = await loadStorageStateFile(storageStatePath);
504
+ const needsNetworkDomain = Boolean(
505
+ options.blockResources && options.blockResources.length > 0 || state?.cookies && state.cookies.length > 0
506
+ );
507
+ await Promise.all([
508
+ cdpChannel.sendCommand("Page.enable", {}, sessionId).catch(() => {
509
+ }),
510
+ cdpChannel.sendCommand("Runtime.enable", {}, sessionId).catch(() => {
511
+ }),
512
+ ...needsNetworkDomain ? [cdpChannel.sendCommand("Network.enable", {}, sessionId).catch(() => {
513
+ })] : [],
514
+ cdpChannel.sendCommand(
515
+ "Emulation.setDeviceMetricsOverride",
516
+ { width, height, deviceScaleFactor: 1, mobile: false },
517
+ sessionId
518
+ ).catch(() => {
519
+ })
520
+ ]);
521
+ if (options.instantAnimations) {
522
+ await cdpChannel.sendCommand(
523
+ "Page.addScriptToEvaluateOnNewDocument",
524
+ { source: INSTANT_ANIMATIONS_CDP_SCRIPT },
525
+ sessionId
526
+ ).catch(() => {
527
+ });
528
+ }
529
+ if (options.blockResources && options.blockResources.length > 0) {
530
+ const urls = options.blockResources.flatMap((t) => RESOURCE_BLOCK_PATTERNS[t] ?? []);
531
+ if (urls.length > 0) {
532
+ await cdpChannel.sendCommand("Network.setBlockedURLs", { urls }, sessionId).catch(() => {
533
+ });
534
+ }
535
+ }
536
+ if (state?.cookies && state.cookies.length > 0) {
537
+ await cdpChannel.sendCommand("Network.setCookies", { cookies: state.cookies }, sessionId).catch(() => {
538
+ });
539
+ }
540
+ if (state?.origins && state.origins.length > 0) {
541
+ const originsJson = JSON.stringify(state.origins);
542
+ await cdpChannel.sendCommand(
543
+ "Page.addScriptToEvaluateOnNewDocument",
544
+ {
545
+ source: `(() => {
546
+ const origins = ${originsJson};
547
+ const hit = origins.find((o) => o.origin === window.location.origin);
548
+ if (hit && Array.isArray(hit.localStorage)) {
549
+ for (const item of hit.localStorage) {
550
+ try { window.localStorage.setItem(item.name, item.value); } catch {}
551
+ }
552
+ }
553
+ })();`
554
+ },
555
+ sessionId
556
+ ).catch(() => {
557
+ });
558
+ }
559
+ if (routeRules.length > 0) {
560
+ await cdpChannel.sendCommand("Fetch.enable", { patterns: [{ urlPattern: "*" }] }, sessionId).catch(() => {
561
+ });
562
+ }
563
+ let authenticatorId;
564
+ if (options.virtualAuthenticator) {
565
+ const authOpts = typeof options.virtualAuthenticator === "object" ? options.virtualAuthenticator : void 0;
566
+ authenticatorId = await attachVirtualAuthenticatorForSession(sessionId, authOpts).catch(
567
+ () => void 0
568
+ );
569
+ }
570
+ return authenticatorId;
571
+ };
572
+ const createContextSlot = async (storageStatePath) => {
573
+ const ctxRes = await cdpChannel.sendCommand(
574
+ "Target.createBrowserContext",
575
+ { disposeOnDetach: true },
576
+ null
577
+ );
578
+ const targetRes = await cdpChannel.sendCommand(
579
+ "Target.createTarget",
580
+ { url: "about:blank", browserContextId: ctxRes.browserContextId, width, height },
581
+ null
582
+ );
583
+ const attachRes = await cdpChannel.sendCommand(
584
+ "Target.attachToTarget",
585
+ { targetId: targetRes.targetId, flatten: true },
586
+ null
587
+ );
588
+ const authenticatorId = await configureSession(
589
+ attachRes.sessionId,
590
+ storageStatePath ?? options.storageState
591
+ );
592
+ const firstTabId = `tab-${nextTabSeq++}`;
593
+ return {
594
+ browserContextId: ctxRes.browserContextId,
595
+ targetId: targetRes.targetId,
596
+ sessionId: attachRes.sessionId,
597
+ authenticatorId,
598
+ tabs: [{ tabId: firstTabId, targetId: targetRes.targetId, sessionId: attachRes.sessionId }]
599
+ };
600
+ };
601
+ const disposeSlotInBackground = (slot) => {
602
+ const p = new Promise((r) => setTimeout(r, 120)).then(
603
+ () => cdpChannel.sendCommand(
604
+ "Target.disposeBrowserContext",
605
+ { browserContextId: slot.browserContextId },
606
+ null
607
+ )
608
+ ).catch(() => {
609
+ }).finally(() => {
610
+ const idx = backgroundDisposals.indexOf(p);
611
+ if (idx >= 0) backgroundDisposals.splice(idx, 1);
612
+ });
613
+ backgroundDisposals.push(p);
614
+ };
615
+ const schedulePrefetch = () => {
616
+ if (!useContexts || !options.freshContextPerFlow || prefetchedSlotPromise) return;
617
+ prefetchedSlotPromise = createContextSlot(options.storageState);
618
+ prefetchedSlotPromise.catch(() => {
619
+ prefetchedSlotPromise = void 0;
620
+ });
621
+ };
622
+ cdpChannel.onEvent("Runtime.consoleAPICalled", (params, sid) => {
623
+ if (activeSlot && sid && sid !== activeSlot.sessionId) return;
624
+ const args = Array.isArray(params?.args) ? params.args.map((a) => a.value ?? a.description ?? "").join(" ") : "";
625
+ consoleLogs.push({ type: String(params?.type ?? "log"), text: args });
626
+ });
627
+ cdpChannel.onEvent("Runtime.exceptionThrown", (params, sid) => {
628
+ if (activeSlot && sid && sid !== activeSlot.sessionId) return;
629
+ const detail = params?.exceptionDetails;
630
+ jsErrors.push({
631
+ name: detail?.exception?.className ?? "Error",
632
+ message: detail?.exception?.description ?? detail?.text ?? "Uncaught exception"
633
+ });
634
+ });
635
+ cdpChannel.onEvent("Fetch.requestPaused", (params, sid) => {
636
+ const reqId = params?.requestId;
637
+ const url = String(params?.request?.url ?? "");
638
+ if (!reqId) return;
639
+ const rule = routeRules.find((r) => matchUrl(r.matcher, url));
640
+ if (!rule) {
641
+ void cdpChannel.sendCommand("Fetch.continueRequest", { requestId: reqId }, sid ?? null).catch(() => {
642
+ });
643
+ return;
644
+ }
645
+ if (rule.kind === "block") {
646
+ void cdpChannel.sendCommand(
647
+ "Fetch.failRequest",
648
+ { requestId: reqId, errorReason: "BlockedByClient" },
649
+ sid ?? null
650
+ ).catch(() => {
651
+ });
652
+ return;
653
+ }
654
+ const resp = rule.response ?? {};
655
+ const bodyStr = resp.json !== void 0 ? JSON.stringify(resp.json) : resp.body ?? "";
656
+ const headersObj = { ...resp.headers };
657
+ if (resp.contentType && !Object.keys(headersObj).some((k) => k.toLowerCase() === "content-type")) {
658
+ headersObj["content-type"] = resp.contentType;
659
+ } else if (resp.json !== void 0 && !Object.keys(headersObj).some((k) => k.toLowerCase() === "content-type")) {
660
+ headersObj["content-type"] = "application/json";
661
+ }
662
+ const responseHeaders = Object.entries(headersObj).map(([name, value]) => ({ name, value }));
663
+ void cdpChannel.sendCommand(
664
+ "Fetch.fulfillRequest",
665
+ {
666
+ requestId: reqId,
667
+ responseCode: resp.status ?? 200,
668
+ responseHeaders,
669
+ body: Buffer.from(bodyStr, "utf8").toString("base64")
670
+ },
671
+ sid ?? null
672
+ ).catch(() => {
673
+ });
674
+ });
675
+ if (useContexts) {
676
+ activeSlot = yield* Effect3.tryPromise({
677
+ try: () => createContextSlot(options.storageState),
678
+ catch: (e) => new DriverError({ message: `Failed to create direct CDP browser context: ${e}` })
679
+ });
680
+ cdpChannel.setSessionId(activeSlot.sessionId);
681
+ activeAuthenticatorId = activeSlot.authenticatorId;
682
+ }
683
+ const resolveUrl = (rawUrl) => rawUrl.startsWith("http://") || rawUrl.startsWith("https://") || rawUrl === "about:blank" ? rawUrl : options.baseUrl ? `${options.baseUrl.replace(/\/$/, "")}/${rawUrl.replace(/^\//, "")}` : rawUrl;
684
+ const navigate = async (rawUrl) => {
685
+ const target = resolveUrl(rawUrl);
686
+ if (!useContexts) {
687
+ await cdpChannel.sendCommand("Page.enable").catch(() => {
688
+ });
689
+ await cdpChannel.sendCommand("Page.navigate", { url: target });
690
+ return;
691
+ }
692
+ const waitUntil = options.waitUntil ?? "load";
693
+ const targetSid = activeSlot?.sessionId;
694
+ if (waitUntil === "commit" || target === "about:blank") {
695
+ await cdpChannel.sendCommand("Page.navigate", { url: target });
696
+ return;
697
+ }
698
+ const eventName = waitUntil === "domcontentloaded" ? "Page.domContentEventFired" : "Page.loadEventFired";
699
+ const waiter = cdpChannel.waitForEvent(
700
+ eventName,
701
+ 15e3,
702
+ (_p, sid) => !targetSid || !sid || sid === targetSid
703
+ );
704
+ await cdpChannel.sendCommand("Page.navigate", { url: target });
705
+ await waiter.catch(() => {
706
+ });
707
+ schedulePrefetch();
708
+ };
709
+ const ensureFetchIntercept = async () => {
710
+ if (fetchInterceptEnabled) return;
711
+ fetchInterceptEnabled = true;
712
+ await cdpChannel.sendCommand("Fetch.enable", { patterns: [{ urlPattern: "*" }] });
713
+ };
714
+ const service = {
715
+ domChannel: cdpChannel,
716
+ beginFlow: (_flowName) => Effect3.tryPromise({
717
+ try: async () => {
718
+ consoleLogs.length = 0;
719
+ jsErrors.length = 0;
720
+ if (useContexts && options.freshContextPerFlow && hasRunFirstFlow) {
721
+ const previousSlot = activeSlot;
722
+ const pending = prefetchedSlotPromise;
723
+ prefetchedSlotPromise = void 0;
724
+ activeSlot = pending ? await pending : await createContextSlot(options.storageState);
725
+ cdpChannel.setSessionId(activeSlot.sessionId);
726
+ activeAuthenticatorId = activeSlot.authenticatorId;
727
+ if (previousSlot) {
728
+ disposeSlotInBackground(previousSlot);
729
+ }
730
+ }
731
+ hasRunFirstFlow = true;
732
+ },
733
+ catch: (e) => new DriverError({ message: `CDP beginFlow failed: ${e}` })
734
+ }),
735
+ dumpHierarchy: () => Effect3.tryPromise({
736
+ try: async () => {
737
+ const raw = await cdpChannel.evaluate(CDP_DUMP_HIERARCHY_SCRIPT);
738
+ return raw ?? "{}";
739
+ },
740
+ catch: (e) => new DriverError({ message: `CDP dumpHierarchy failed: ${e}` })
741
+ }),
742
+ tapAtCoordinate: (x, y) => Effect3.tryPromise({
743
+ try: async () => {
744
+ await Promise.all([
745
+ cdpChannel.sendCommand("Input.dispatchMouseEvent", {
746
+ type: "mouseMoved",
747
+ x,
748
+ y
749
+ }),
750
+ cdpChannel.sendCommand("Input.dispatchMouseEvent", {
751
+ type: "mousePressed",
752
+ x,
753
+ y,
754
+ button: "left",
755
+ clickCount: 1
756
+ }),
757
+ cdpChannel.sendCommand("Input.dispatchMouseEvent", {
758
+ type: "mouseReleased",
759
+ x,
760
+ y,
761
+ button: "left",
762
+ clickCount: 1
763
+ })
764
+ ]);
765
+ },
766
+ catch: (e) => new DriverError({ message: `CDP tap failed at (${x}, ${y}): ${e}` })
767
+ }),
768
+ doubleTapAtCoordinate: (x, y) => Effect3.tryPromise({
769
+ try: async () => {
770
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
771
+ type: "mousePressed",
772
+ x,
773
+ y,
774
+ button: "left",
775
+ clickCount: 2
776
+ });
777
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
778
+ type: "mouseReleased",
779
+ x,
780
+ y,
781
+ button: "left",
782
+ clickCount: 2
783
+ });
784
+ },
785
+ catch: (e) => new DriverError({ message: `CDP doubleTap failed: ${e}` })
786
+ }),
787
+ longPressAtCoordinate: (x, y, duration) => Effect3.tryPromise({
788
+ try: async () => {
789
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
790
+ type: "mousePressed",
791
+ x,
792
+ y,
793
+ button: "left",
794
+ clickCount: 1
795
+ });
796
+ await new Promise((r) => setTimeout(r, duration));
797
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
798
+ type: "mouseReleased",
799
+ x,
800
+ y,
801
+ button: "left",
802
+ clickCount: 1
803
+ });
804
+ },
805
+ catch: (e) => new DriverError({ message: `CDP longPress failed: ${e}` })
806
+ }),
807
+ swipe: (startX, startY, endX, endY) => Effect3.tryPromise({
808
+ try: async () => {
809
+ const dx = startX - endX;
810
+ const dy = startY - endY;
811
+ await cdpChannel.evaluate(`window.scrollBy(${dx}, ${dy})`);
812
+ },
813
+ catch: (e) => new DriverError({ message: `CDP swipe failed: ${e}` })
814
+ }),
815
+ inputText: (text) => Effect3.tryPromise({
816
+ try: async () => {
817
+ await cdpChannel.sendCommand("Input.insertText", { text });
818
+ },
819
+ catch: (e) => new DriverError({ message: `CDP inputText failed: ${e}` })
820
+ }),
821
+ pressKey: (key) => Effect3.tryPromise({
822
+ try: async () => {
823
+ await cdpChannel.sendCommand("Input.dispatchKeyEvent", { type: "keyDown", key });
824
+ await cdpChannel.sendCommand("Input.dispatchKeyEvent", { type: "keyUp", key });
825
+ },
826
+ catch: (e) => new DriverError({ message: `CDP pressKey failed: ${e}` })
827
+ }),
828
+ hideKeyboard: () => Effect3.void,
829
+ takeScreenshot: () => Effect3.tryPromise({
830
+ try: async () => {
831
+ const res = await cdpChannel.sendCommand("Page.captureScreenshot", {
832
+ format: "png"
833
+ });
834
+ return new Uint8Array(Buffer.from(res?.data ?? "", "base64"));
835
+ },
836
+ catch: (e) => new DriverError({ message: `CDP screenshot failed: ${e}` })
837
+ }),
838
+ getDeviceInfo: () => Effect3.succeed({
839
+ platform: "web",
840
+ deviceId: `${label}:${options.cdpUrl}`,
841
+ name: `${label} (CDP-direct)`,
842
+ isEmulator: true,
843
+ screenWidth: width,
844
+ screenHeight: height,
845
+ driverType: "cdp"
846
+ }),
847
+ launchApp: (url, opts) => Effect3.tryPromise({
848
+ try: async () => {
849
+ if (opts?.clearState) {
850
+ await cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
851
+ });
852
+ await cdpChannel.evaluate(
853
+ "try { localStorage.clear(); sessionStorage.clear(); } catch {}"
854
+ );
855
+ }
856
+ await navigate(opts?.deepLink || url || options.baseUrl || "about:blank");
857
+ },
858
+ catch: (e) => new DriverError({ message: `CDP launchApp failed: ${e}` })
859
+ }),
860
+ stopApp: () => Effect3.tryPromise({
861
+ try: () => navigate("about:blank"),
862
+ catch: (e) => new DriverError({ message: `CDP stopApp failed: ${e}` })
863
+ }),
864
+ killApp: () => Effect3.tryPromise({
865
+ try: async () => {
866
+ const pendingPrefetch = prefetchedSlotPromise;
867
+ prefetchedSlotPromise = void 0;
868
+ if (useContexts) {
869
+ const slotsToDispose = [];
870
+ if (activeSlot) slotsToDispose.push(activeSlot);
871
+ if (pendingPrefetch) {
872
+ const prefetched = await pendingPrefetch.catch(() => void 0);
873
+ if (prefetched) slotsToDispose.push(prefetched);
874
+ }
875
+ await Promise.allSettled([
876
+ ...slotsToDispose.map(
877
+ (s) => cdpChannel.sendCommand(
878
+ "Target.disposeBrowserContext",
879
+ { browserContextId: s.browserContextId },
880
+ null
881
+ )
882
+ ),
883
+ ...backgroundDisposals
884
+ ]);
885
+ }
886
+ if (downloadDir) {
887
+ try {
888
+ rmSync(downloadDir, { recursive: true, force: true });
889
+ } catch {
890
+ }
891
+ downloadDir = void 0;
892
+ }
893
+ await cdpChannel.disconnect();
894
+ },
895
+ catch: (e) => new DriverError({ message: `CDP disconnect failed: ${e}` })
896
+ }),
897
+ clearAppState: () => Effect3.tryPromise({
898
+ try: async () => {
899
+ await cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
900
+ });
901
+ await cdpChannel.evaluate(
902
+ "try { localStorage.clear(); sessionStorage.clear(); } catch {}"
903
+ );
904
+ },
905
+ catch: (e) => new DriverError({ message: `CDP clearAppState failed: ${e}` })
906
+ }),
907
+ openLink: (url) => Effect3.tryPromise({
908
+ try: () => navigate(url),
909
+ catch: (e) => new DriverError({ message: `CDP openLink failed: ${e}` })
910
+ }),
911
+ back: () => Effect3.tryPromise({
912
+ try: async () => {
913
+ await cdpChannel.evaluate("window.history.back()");
914
+ },
915
+ catch: (e) => new DriverError({ message: `CDP back failed: ${e}` })
916
+ }),
917
+ evaluate: (fn, ...args) => Effect3.tryPromise({
918
+ try: async () => {
919
+ if (typeof fn === "string") {
920
+ return await cdpChannel.evaluate(fn);
921
+ }
922
+ const serializedArgs = args.map((a) => JSON.stringify(a)).join(", ");
923
+ return await cdpChannel.evaluate(`(${fn.toString()})(${serializedArgs})`);
924
+ },
925
+ catch: (e) => new DriverError({ message: `CDP evaluate failed: ${e}` })
926
+ }),
927
+ getRawPage: () => ({
928
+ kind: "cdp",
929
+ cdpChannel,
930
+ sessionId: activeSlot?.sessionId ?? null,
931
+ browserContextId: activeSlot?.browserContextId ?? null
932
+ }),
933
+ mockNetwork: (matcher, response) => Effect3.tryPromise({
934
+ try: async () => {
935
+ routeRules.push({ kind: "mock", matcher, response });
936
+ await ensureFetchIntercept();
937
+ },
938
+ catch: (e) => new DriverError({ message: `CDP mockNetwork failed: ${e}` })
939
+ }),
940
+ blockNetwork: (matcher) => Effect3.tryPromise({
941
+ try: async () => {
942
+ routeRules.push({ kind: "block", matcher });
943
+ await ensureFetchIntercept();
944
+ },
945
+ catch: (e) => new DriverError({ message: `CDP blockNetwork failed: ${e}` })
946
+ }),
947
+ clearNetworkMocks: () => Effect3.tryPromise({
948
+ try: async () => {
949
+ routeRules.length = 0;
950
+ if (fetchInterceptEnabled) {
951
+ fetchInterceptEnabled = false;
952
+ await cdpChannel.sendCommand("Fetch.disable").catch(() => {
953
+ });
954
+ }
955
+ },
956
+ catch: (e) => new DriverError({ message: `CDP clearNetworkMocks failed: ${e}` })
957
+ }),
958
+ saveCookies: (path) => Effect3.tryPromise({
959
+ try: async () => {
960
+ const res = await cdpChannel.sendCommand("Network.getCookies");
961
+ await writeFile(path, JSON.stringify(res?.cookies ?? [], null, 2), "utf8");
962
+ },
963
+ catch: (e) => new DriverError({ message: `CDP saveCookies failed: ${e}` })
964
+ }),
965
+ loadCookies: (path) => Effect3.tryPromise({
966
+ try: async () => {
967
+ const cookies = JSON.parse(await readFile(path, "utf8"));
968
+ if (Array.isArray(cookies)) {
969
+ await cdpChannel.sendCommand("Network.setCookies", { cookies });
970
+ }
971
+ },
972
+ catch: (e) => new DriverError({ message: `CDP loadCookies failed: ${e}` })
973
+ }),
974
+ saveAuthState: (path) => Effect3.tryPromise({
975
+ try: async () => {
976
+ const res = await cdpChannel.sendCommand("Network.getCookies");
977
+ const originState = await cdpChannel.evaluate(
978
+ `(() => {
979
+ const entries = [];
980
+ try {
981
+ for (let i = 0; i < localStorage.length; i++) {
982
+ const k = localStorage.key(i);
983
+ if (k !== null) entries.push({ name: k, value: localStorage.getItem(k) ?? "" });
984
+ }
985
+ } catch {}
986
+ return { origin: window.location.origin, localStorage: entries };
987
+ })()`
988
+ ).catch(() => null);
989
+ const payload = {
990
+ cookies: res?.cookies ?? [],
991
+ origins: originState && originState.origin !== "null" ? [originState] : []
992
+ };
993
+ await writeFile(path, JSON.stringify(payload, null, 2), "utf8");
994
+ },
995
+ catch: (e) => new DriverError({ message: `CDP saveAuthState failed: ${e}` })
996
+ }),
997
+ loadAuthState: (path) => Effect3.tryPromise({
998
+ try: async () => {
999
+ if (useContexts) {
1000
+ const previousSlot = activeSlot;
1001
+ activeSlot = await createContextSlot(path);
1002
+ cdpChannel.setSessionId(activeSlot.sessionId);
1003
+ activeAuthenticatorId = activeSlot.authenticatorId;
1004
+ if (previousSlot) disposeSlotInBackground(previousSlot);
1005
+ return;
1006
+ }
1007
+ const state = await loadStorageStateFile(path);
1008
+ if (state?.cookies?.length) {
1009
+ await cdpChannel.sendCommand("Network.setCookies", { cookies: state.cookies });
1010
+ }
1011
+ },
1012
+ catch: (e) => new DriverError({ message: `CDP loadAuthState failed: ${e}` })
1013
+ }),
1014
+ enableVirtualAuthenticator: (opts) => Effect3.tryPromise({
1015
+ try: async () => {
1016
+ activeAuthenticatorId = await attachVirtualAuthenticatorForSession(
1017
+ activeSlot?.sessionId ?? null,
1018
+ opts
1019
+ );
1020
+ return activeAuthenticatorId;
1021
+ },
1022
+ catch: (e) => new DriverError({ message: `CDP enableVirtualAuthenticator failed: ${e}` })
1023
+ }),
1024
+ removeVirtualAuthenticator: (authenticatorId) => Effect3.tryPromise({
1025
+ try: async () => {
1026
+ const id = authenticatorId ?? activeAuthenticatorId;
1027
+ if (!id) return;
1028
+ await cdpChannel.sendCommand("WebAuthn.removeVirtualAuthenticator", {
1029
+ authenticatorId: id
1030
+ });
1031
+ if (id === activeAuthenticatorId) activeAuthenticatorId = void 0;
1032
+ },
1033
+ catch: (e) => new DriverError({ message: `CDP removeVirtualAuthenticator failed: ${e}` })
1034
+ }),
1035
+ getVirtualCredentials: (authenticatorId) => Effect3.tryPromise({
1036
+ try: async () => {
1037
+ const id = authenticatorId ?? activeAuthenticatorId;
1038
+ if (!id) return [];
1039
+ const res = await cdpChannel.sendCommand("WebAuthn.getCredentials", {
1040
+ authenticatorId: id
1041
+ });
1042
+ return Array.isArray(res?.credentials) ? res.credentials : [];
1043
+ },
1044
+ catch: (e) => new DriverError({ message: `CDP getVirtualCredentials failed: ${e}` })
1045
+ }),
1046
+ clearVirtualCredentials: (authenticatorId) => Effect3.tryPromise({
1047
+ try: async () => {
1048
+ const id = authenticatorId ?? activeAuthenticatorId;
1049
+ if (!id) return;
1050
+ await cdpChannel.sendCommand("WebAuthn.clearCredentials", { authenticatorId: id });
1051
+ },
1052
+ catch: (e) => new DriverError({ message: `CDP clearVirtualCredentials failed: ${e}` })
1053
+ }),
1054
+ getConsoleLogs: () => Effect3.succeed([...consoleLogs]),
1055
+ getJSErrors: () => Effect3.succeed([...jsErrors]),
1056
+ setNetworkConditions: (conditions) => Effect3.tryPromise({
1057
+ try: async () => {
1058
+ const resolved = resolveNetworkConditions(conditions);
1059
+ await cdpChannel.sendCommand("Network.enable");
1060
+ await cdpChannel.sendCommand("Network.emulateNetworkConditions", {
1061
+ offline: resolved.offline,
1062
+ latency: resolved.latencyMs,
1063
+ downloadThroughput: resolved.downloadThroughputKbps < 0 ? -1 : Math.max(Math.round(resolved.downloadThroughputKbps * 1024 / 8), 0),
1064
+ uploadThroughput: resolved.uploadThroughputKbps < 0 ? -1 : Math.max(Math.round(resolved.uploadThroughputKbps * 1024 / 8), 0)
1065
+ });
1066
+ },
1067
+ catch: (e) => new DriverError({ message: `CDP setNetworkConditions failed: ${e}` })
1068
+ }),
1069
+ uploadFile: (selector, filePath) => Effect3.tryPromise({
1070
+ try: async () => {
1071
+ const serialized = JSON.stringify(selector);
1072
+ const expr = `(function(sel) {
1073
+ if (typeof sel === "object" && sel !== null && "testID" in sel) {
1074
+ return document.querySelector('[data-testid="' + sel.testID + '"], [testID="' + sel.testID + '"]');
1075
+ }
1076
+ if (typeof sel === "object" && sel !== null && "accessibilityLabel" in sel) {
1077
+ return document.querySelector('[aria-label="' + sel.accessibilityLabel + '"]');
1078
+ }
1079
+ return document.querySelector('input[type="file"]');
1080
+ })(${serialized})`;
1081
+ await cdpChannel.sendCommand("DOM.enable");
1082
+ const evalRes = await cdpChannel.sendCommand("Runtime.evaluate", {
1083
+ expression: expr,
1084
+ returnByValue: false
1085
+ });
1086
+ const objectId = evalRes?.result?.objectId;
1087
+ if (!objectId) {
1088
+ throw new Error(`No matching file input found for selector ${serialized}`);
1089
+ }
1090
+ const nodeRes = await cdpChannel.sendCommand("DOM.requestNode", { objectId });
1091
+ if (!nodeRes?.nodeId) {
1092
+ throw new Error("Failed to resolve DOM nodeId for file input");
1093
+ }
1094
+ await cdpChannel.sendCommand("DOM.setFileInputFiles", {
1095
+ nodeId: nodeRes.nodeId,
1096
+ files: [filePath]
1097
+ });
1098
+ },
1099
+ catch: (e) => new DriverError({ message: `CDP uploadFile failed: ${e}` })
1100
+ }),
1101
+ downloadFile: (destPath) => Effect3.tryPromise({
1102
+ try: async () => {
1103
+ if (!downloadDir) {
1104
+ downloadDir = mkdtempSync(join(tmpdir(), "spana-cdp-dl-"));
1105
+ await cdpChannel.sendCommand(
1106
+ "Browser.setDownloadBehavior",
1107
+ {
1108
+ behavior: "allowAndName",
1109
+ downloadPath: downloadDir,
1110
+ eventsEnabled: true,
1111
+ ...activeSlot?.browserContextId ? { browserContextId: activeSlot.browserContextId } : {}
1112
+ },
1113
+ null
1114
+ );
1115
+ }
1116
+ const downloaded = completedDownloads.shift() ?? await new Promise((resolve, reject) => {
1117
+ const timer = setTimeout(() => {
1118
+ reject(new Error("Timed out waiting for CDP file download"));
1119
+ }, 15e3);
1120
+ downloadWaiters.push({
1121
+ resolve: (fp) => {
1122
+ clearTimeout(timer);
1123
+ resolve(fp);
1124
+ },
1125
+ reject: (err) => {
1126
+ clearTimeout(timer);
1127
+ reject(err);
1128
+ }
1129
+ });
1130
+ });
1131
+ await copyFile(downloaded, destPath);
1132
+ },
1133
+ catch: (e) => new DriverError({ message: `CDP downloadFile failed: ${e}` })
1134
+ }),
1135
+ newTab: (url) => Effect3.tryPromise({
1136
+ try: async () => {
1137
+ if (!activeSlot) {
1138
+ throw new Error("newTab() requires browser-context mode (engine: 'cdp')");
1139
+ }
1140
+ const targetRes = await cdpChannel.sendCommand(
1141
+ "Target.createTarget",
1142
+ {
1143
+ url: url ? resolveUrl(url) : "about:blank",
1144
+ browserContextId: activeSlot.browserContextId,
1145
+ width,
1146
+ height
1147
+ },
1148
+ null
1149
+ );
1150
+ const attachRes = await cdpChannel.sendCommand(
1151
+ "Target.attachToTarget",
1152
+ { targetId: targetRes.targetId, flatten: true },
1153
+ null
1154
+ );
1155
+ await configureSession(attachRes.sessionId, options.storageState);
1156
+ const tabId = `tab-${nextTabSeq++}`;
1157
+ activeSlot.tabs.push({
1158
+ tabId,
1159
+ targetId: targetRes.targetId,
1160
+ sessionId: attachRes.sessionId
1161
+ });
1162
+ activeSlot.targetId = targetRes.targetId;
1163
+ activeSlot.sessionId = attachRes.sessionId;
1164
+ cdpChannel.setSessionId(attachRes.sessionId);
1165
+ return tabId;
1166
+ },
1167
+ catch: (e) => new DriverError({ message: `CDP newTab failed: ${e}` })
1168
+ }),
1169
+ switchToTab: (index) => Effect3.tryPromise({
1170
+ try: async () => {
1171
+ if (!activeSlot || !activeSlot.tabs[index]) {
1172
+ throw new Error(`Tab index ${index} is out of range.`);
1173
+ }
1174
+ const target = activeSlot.tabs[index];
1175
+ activeSlot.targetId = target.targetId;
1176
+ activeSlot.sessionId = target.sessionId;
1177
+ cdpChannel.setSessionId(target.sessionId);
1178
+ await cdpChannel.sendCommand("Target.activateTarget", { targetId: target.targetId }, null).catch(() => {
1179
+ });
1180
+ },
1181
+ catch: (e) => new DriverError({ message: `CDP switchToTab failed: ${e}` })
1182
+ }),
1183
+ closeTab: () => Effect3.tryPromise({
1184
+ try: async () => {
1185
+ if (!activeSlot) return;
1186
+ if (activeSlot.tabs.length <= 1) {
1187
+ await navigate("about:blank");
1188
+ return;
1189
+ }
1190
+ const idx = activeSlot.tabs.findIndex((t) => t.sessionId === activeSlot.sessionId);
1191
+ const closing = activeSlot.tabs[idx >= 0 ? idx : activeSlot.tabs.length - 1];
1192
+ activeSlot.tabs = activeSlot.tabs.filter((t) => t.sessionId !== closing.sessionId);
1193
+ const fallback = activeSlot.tabs[Math.max(0, Math.min(idx - 1, activeSlot.tabs.length - 1))];
1194
+ activeSlot.targetId = fallback.targetId;
1195
+ activeSlot.sessionId = fallback.sessionId;
1196
+ cdpChannel.setSessionId(fallback.sessionId);
1197
+ await cdpChannel.sendCommand("Target.closeTarget", { targetId: closing.targetId }, null).catch(() => {
1198
+ });
1199
+ },
1200
+ catch: (e) => new DriverError({ message: `CDP closeTab failed: ${e}` })
1201
+ }),
1202
+ getTabIds: () => Effect3.sync(() => activeSlot ? activeSlot.tabs.map((t) => t.tabId) : ["tab-1"])
1203
+ };
1204
+ return service;
1205
+ });
1206
+ }
1207
+
1208
+ // src/runtime/local.ts
1209
+ import { Effect as Effect4 } from "effect";
1210
+ async function safeCleanup(...fns) {
1211
+ for (const fn of fns) {
1212
+ try {
1213
+ await fn();
1214
+ } catch {
1215
+ }
1216
+ }
1217
+ }
1218
+ async function maybeStartBridge(appBridge, globalBridge) {
1219
+ const merged = appBridge ?? globalBridge;
1220
+ if (!merged) return void 0;
1221
+ const enabled = merged.enabled ?? Boolean(merged.port || merged.url);
1222
+ if (!enabled) return void 0;
1223
+ const channel = createSpanaBridgeChannel({
1224
+ host: merged.host ?? "127.0.0.1",
1225
+ port: merged.port ?? 9333,
1226
+ connectTimeoutMs: merged.connectTimeout ?? 5e3
1227
+ });
1228
+ await channel.start();
1229
+ return channel;
1230
+ }
1231
+ function buildEngineConfig(appId, platform, parseFn, config, screenSize) {
1232
+ return {
1233
+ appId,
1234
+ platform,
1235
+ coordinatorConfig: {
1236
+ parse: parseFn,
1237
+ defaults: {
1238
+ timeout: config.defaults?.waitTimeout,
1239
+ pollInterval: config.defaults?.pollInterval,
1240
+ settleTimeout: config.defaults?.settleTimeout,
1241
+ initialPollInterval: config.defaults?.initialPollInterval,
1242
+ tapMode: config.defaults?.tapMode,
1243
+ platform,
1244
+ failFastWhenIdle: config.defaults?.failFastWhenIdle
1245
+ },
1246
+ waitForIdleTimeout: config.defaults?.waitForIdleTimeout,
1247
+ typingDelay: config.defaults?.typingDelay,
1248
+ hierarchyCacheTtl: config.defaults?.hierarchyCacheTtl,
1249
+ screenWidth: screenSize?.width,
1250
+ screenHeight: screenSize?.height,
1251
+ tapMode: config.defaults?.tapMode,
1252
+ platform
1253
+ },
1254
+ autoLaunch: true,
1255
+ flowTimeout: config.defaults?.waitTimeout ? config.defaults.waitTimeout * 10 : 6e4,
1256
+ artifactConfig: config.artifacts,
1257
+ launchOptions: config.launchOptions,
1258
+ hooks: config.hooks,
1259
+ storybook: platform === "web" ? config.execution?.web?.storybook : void 0,
1260
+ visualRegression: config.visualRegression
1261
+ };
1262
+ }
1263
+ function speculativelyPrelaunchWebBrowser(config) {
1264
+ const webExecution = config.execution?.web;
1265
+ if (webExecution?.engine === "lightpanda") {
1266
+ return void 0;
1267
+ }
1268
+ if (webExecution?.engine === "cdp") {
1269
+ if (webExecution.cdpUrl) return void 0;
1270
+ const useWarm2 = webExecution.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false;
1271
+ const cdpBrowserPromise = launchDirectCdpBrowser({
1272
+ executablePath: webExecution.executablePath,
1273
+ headless: webExecution.headless ?? true,
1274
+ warmBrowser: useWarm2,
1275
+ warmBrowserScope: webExecution.warmBrowserScope ? `${webExecution.warmBrowserScope}-w0` : void 0
1276
+ });
1277
+ cdpBrowserPromise.catch(() => {
1278
+ });
1279
+ return {
1280
+ browserPromise: Promise.resolve(void 0),
1281
+ ownsBrowser: false,
1282
+ cdpBrowserPromise
1283
+ };
1284
+ }
1285
+ const useWarm = (webExecution?.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false) && (webExecution?.browser ?? "chromium") === "chromium";
1286
+ const ownsBrowser = !useWarm && !webExecution?.cdpUrl && !webExecution?.wsEndpoint;
1287
+ const browserPromise = webExecution?.wsEndpoint ? connectPlaywrightOverWS(webExecution.wsEndpoint, webExecution.browser) : webExecution?.cdpUrl ? connectPlaywrightOverCDP(webExecution.cdpUrl) : useWarm ? ensureWarmBrowserDaemon({
1288
+ headless: webExecution?.headless ?? true,
1289
+ executablePath: webExecution?.executablePath,
1290
+ warmBrowserScope: webExecution?.warmBrowserScope
1291
+ }).then((r) => r.browser) : launchPlaywrightBrowser({
1292
+ browser: webExecution?.browser,
1293
+ headless: webExecution?.headless ?? true,
1294
+ executablePath: webExecution?.executablePath,
1295
+ channel: webExecution?.channel
1296
+ });
1297
+ browserPromise.catch(() => {
1298
+ });
1299
+ return { browserPromise, ownsBrowser };
1300
+ }
1301
+ async function buildWebRuntime(config, prelaunched) {
1302
+ const webUrl = config.apps?.web?.url ?? "http://localhost:3000";
1303
+ const webExecution = config.execution?.web;
1304
+ const bridge = await maybeStartBridge(config.apps?.web?.bridge, config.execution?.bridge);
1305
+ const prelaunchedBrowser = prelaunched && !prelaunched.cdpBrowserPromise ? await prelaunched.browserPromise : void 0;
1306
+ let launchedDirectCdp;
1307
+ let rawDriver;
1308
+ if (webExecution?.engine === "cdp" || webExecution?.engine === "lightpanda") {
1309
+ let targetCdpUrl = webExecution.cdpUrl;
1310
+ const useContexts = webExecution.engine === "cdp";
1311
+ if (!targetCdpUrl && webExecution.engine === "cdp") {
1312
+ launchedDirectCdp = prelaunched?.cdpBrowserPromise ? await prelaunched.cdpBrowserPromise : await launchDirectCdpBrowser({
1313
+ executablePath: webExecution.executablePath,
1314
+ headless: webExecution.headless ?? true,
1315
+ warmBrowser: webExecution.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false,
1316
+ warmBrowserScope: webExecution.warmBrowserScope ? `${webExecution.warmBrowserScope}-w0` : void 0
1317
+ });
1318
+ targetCdpUrl = launchedDirectCdp.browserWsUrl;
1319
+ }
1320
+ rawDriver = await Effect4.runPromise(
1321
+ makeLightweightCdpDriver({
1322
+ cdpUrl: targetCdpUrl ?? "http://127.0.0.1:9222",
1323
+ baseUrl: webUrl,
1324
+ engineLabel: webExecution.engine,
1325
+ useBrowserContexts: useContexts,
1326
+ freshContextPerFlow: webExecution.freshContextPerFlow,
1327
+ waitUntil: webExecution.waitUntil,
1328
+ instantAnimations: webExecution.instantAnimations,
1329
+ blockResources: webExecution.blockResources,
1330
+ virtualAuthenticator: webExecution.virtualAuthenticator,
1331
+ storageState: webExecution.storageState
1332
+ })
1333
+ );
1334
+ } else {
1335
+ rawDriver = await Effect4.runPromise(
1336
+ makePlaywrightDriver({
1337
+ browser: webExecution?.browser,
1338
+ headless: webExecution?.headless ?? true,
1339
+ executablePath: webExecution?.executablePath,
1340
+ channel: webExecution?.channel,
1341
+ baseUrl: webUrl,
1342
+ storageState: webExecution?.storageState,
1343
+ verboseLogging: webExecution?.verboseLogging,
1344
+ recordHar: Boolean(config.artifacts?.har),
1345
+ waitUntil: webExecution?.waitUntil,
1346
+ instantAnimations: webExecution?.instantAnimations,
1347
+ blockResources: webExecution?.blockResources,
1348
+ freshContextPerFlow: webExecution?.freshContextPerFlow,
1349
+ virtualAuthenticator: webExecution?.virtualAuthenticator,
1350
+ warmBrowserScope: webExecution?.warmBrowserScope,
1351
+ sharedBrowser: prelaunchedBrowser,
1352
+ cdpEndpoint: prelaunchedBrowser ? void 0 : webExecution?.cdpUrl,
1353
+ wsEndpoint: prelaunchedBrowser ? void 0 : webExecution?.wsEndpoint,
1354
+ warmBrowser: prelaunchedBrowser ? false : webExecution?.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false
1355
+ })
1356
+ );
1357
+ }
1358
+ const driver = bridge ? { ...rawDriver, domChannel: bridge } : rawDriver;
1359
+ const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
1360
+ return {
1361
+ runtime: {
1362
+ driver,
1363
+ cleanup: () => safeCleanup(
1364
+ () => Effect4.runPromise(driver.killApp("")),
1365
+ () => prelaunchedBrowser && prelaunched?.ownsBrowser ? prelaunchedBrowser.close() : Promise.resolve(),
1366
+ () => launchedDirectCdp ? launchedDirectCdp.close() : Promise.resolve(),
1367
+ () => bridge?.disconnect() ?? Promise.resolve()
1368
+ ),
1369
+ metadata: {
1370
+ platform: "web",
1371
+ mode: "local"
1372
+ }
1373
+ },
1374
+ engineConfig: buildEngineConfig(webUrl, "web", parseWebHierarchy, config, {
1375
+ width: deviceInfo.screenWidth,
1376
+ height: deviceInfo.screenHeight
1377
+ })
1378
+ };
1379
+ }
1380
+ async function buildWebRuntimePool(config, workerCount, prelaunched) {
1381
+ const webExecution = config.execution?.web;
1382
+ if (workerCount <= 1 || webExecution?.engine === "lightpanda") {
1383
+ return [await buildWebRuntime(config, prelaunched)];
1384
+ }
1385
+ const webUrl = config.apps?.web?.url ?? "http://localhost:3000";
1386
+ const maxPerBrowser = Math.max(
1387
+ 1,
1388
+ webExecution?.maxContextsPerBrowser ?? (webExecution?.engine === "cdp" ? 1 : 2)
1389
+ );
1390
+ if (webExecution?.engine === "cdp") {
1391
+ const useExternalCdp = Boolean(webExecution.cdpUrl);
1392
+ const browserCount2 = useExternalCdp ? 1 : Math.ceil(workerCount / maxPerBrowser);
1393
+ const handles = [];
1394
+ if (useExternalCdp) {
1395
+ handles.push({ cdpUrl: webExecution.cdpUrl, remaining: workerCount });
1396
+ } else {
1397
+ const useWarm2 = webExecution.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false;
1398
+ const baseScope = webExecution.warmBrowserScope ?? "pool";
1399
+ const launched = await Promise.all(
1400
+ Array.from(
1401
+ { length: browserCount2 },
1402
+ (_v, bIdx) => bIdx === 0 && prelaunched?.cdpBrowserPromise ? prelaunched.cdpBrowserPromise : launchDirectCdpBrowser({
1403
+ executablePath: webExecution.executablePath,
1404
+ headless: webExecution.headless ?? true,
1405
+ warmBrowser: useWarm2,
1406
+ warmBrowserScope: `${baseScope}-w${bIdx}`
1407
+ })
1408
+ )
1409
+ );
1410
+ for (const h of launched) {
1411
+ handles.push({ cdpUrl: h.browserWsUrl, handle: h, remaining: 0 });
1412
+ }
1413
+ for (let i = 0; i < workerCount; i++) {
1414
+ handles[i % handles.length].remaining += 1;
1415
+ }
1416
+ }
1417
+ const results2 = [];
1418
+ for (let i = 0; i < workerCount; i++) {
1419
+ const bucket = handles[i % handles.length];
1420
+ const driver = await Effect4.runPromise(
1421
+ makeLightweightCdpDriver({
1422
+ cdpUrl: bucket.cdpUrl,
1423
+ baseUrl: webUrl,
1424
+ engineLabel: "cdp",
1425
+ useBrowserContexts: true,
1426
+ freshContextPerFlow: webExecution.freshContextPerFlow,
1427
+ waitUntil: webExecution.waitUntil,
1428
+ instantAnimations: webExecution.instantAnimations,
1429
+ blockResources: webExecution.blockResources,
1430
+ virtualAuthenticator: webExecution.virtualAuthenticator,
1431
+ storageState: webExecution.storageState
1432
+ })
1433
+ );
1434
+ const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
1435
+ let cleaned = false;
1436
+ results2.push({
1437
+ runtime: {
1438
+ driver,
1439
+ cleanup: () => safeCleanup(async () => {
1440
+ if (cleaned) return;
1441
+ cleaned = true;
1442
+ await Effect4.runPromise(driver.killApp(""));
1443
+ bucket.remaining -= 1;
1444
+ if (bucket.remaining <= 0 && bucket.handle) {
1445
+ await bucket.handle.close();
1446
+ }
1447
+ }),
1448
+ metadata: {
1449
+ platform: "web",
1450
+ mode: "local",
1451
+ deviceId: `cdp-context-${i + 1}`
1452
+ }
1453
+ },
1454
+ engineConfig: buildEngineConfig(webUrl, "web", parseWebHierarchy, config, {
1455
+ width: deviceInfo.screenWidth,
1456
+ height: deviceInfo.screenHeight
1457
+ })
1458
+ });
1459
+ }
1460
+ return results2;
1461
+ }
1462
+ const useWarm = (webExecution?.warmBrowser ?? config.execution?.warmDaemons?.enabled ?? false) && (webExecution?.browser ?? "chromium") === "chromium";
1463
+ const singleExternalEndpoint = Boolean(webExecution?.cdpUrl || webExecution?.wsEndpoint);
1464
+ const browserCount = singleExternalEndpoint ? 1 : Math.ceil(workerCount / maxPerBrowser);
1465
+ const launchOneBrowser = async (idx) => {
1466
+ if (idx === 0 && prelaunched) {
1467
+ return {
1468
+ browser: await prelaunched.browserPromise,
1469
+ owns: prelaunched.ownsBrowser,
1470
+ remaining: 0
1471
+ };
1472
+ }
1473
+ if (webExecution?.wsEndpoint) {
1474
+ return {
1475
+ browser: await connectPlaywrightOverWS(webExecution.wsEndpoint, webExecution.browser),
1476
+ owns: false,
1477
+ remaining: 0
1478
+ };
1479
+ }
1480
+ if (webExecution?.cdpUrl) {
1481
+ return {
1482
+ browser: await connectPlaywrightOverCDP(webExecution.cdpUrl),
1483
+ owns: false,
1484
+ remaining: 0
1485
+ };
1486
+ }
1487
+ if (idx === 0 && useWarm) {
1488
+ const warm = await ensureWarmBrowserDaemon({
1489
+ headless: webExecution?.headless ?? true,
1490
+ executablePath: webExecution?.executablePath,
1491
+ warmBrowserScope: webExecution?.warmBrowserScope
1492
+ });
1493
+ return { browser: warm.browser, owns: false, remaining: 0 };
1494
+ }
1495
+ return {
1496
+ browser: await launchPlaywrightBrowser({
1497
+ browser: webExecution?.browser,
1498
+ headless: webExecution?.headless ?? true,
1499
+ executablePath: webExecution?.executablePath,
1500
+ channel: webExecution?.channel
1501
+ }),
1502
+ owns: true,
1503
+ remaining: 0
1504
+ };
1505
+ };
1506
+ const browserBuckets = await Promise.all(
1507
+ Array.from({ length: browserCount }, (_v, idx) => launchOneBrowser(idx))
1508
+ );
1509
+ for (let i = 0; i < workerCount; i++) {
1510
+ browserBuckets[i % browserBuckets.length].remaining += 1;
1511
+ }
1512
+ const results = [];
1513
+ for (let i = 0; i < workerCount; i++) {
1514
+ const bucket = browserBuckets[i % browserBuckets.length];
1515
+ const driver = await Effect4.runPromise(
1516
+ makePlaywrightDriver({
1517
+ browser: webExecution?.browser,
1518
+ headless: webExecution?.headless ?? true,
1519
+ executablePath: webExecution?.executablePath,
1520
+ channel: webExecution?.channel,
1521
+ baseUrl: webUrl,
1522
+ storageState: webExecution?.storageState,
1523
+ verboseLogging: webExecution?.verboseLogging,
1524
+ sharedBrowser: bucket.browser,
1525
+ recordHar: Boolean(config.artifacts?.har),
1526
+ waitUntil: webExecution?.waitUntil,
1527
+ instantAnimations: webExecution?.instantAnimations,
1528
+ blockResources: webExecution?.blockResources,
1529
+ freshContextPerFlow: webExecution?.freshContextPerFlow,
1530
+ virtualAuthenticator: webExecution?.virtualAuthenticator,
1531
+ warmBrowserScope: webExecution?.warmBrowserScope
1532
+ })
1533
+ );
1534
+ const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
1535
+ let cleaned = false;
1536
+ results.push({
1537
+ runtime: {
1538
+ driver,
1539
+ cleanup: () => safeCleanup(async () => {
1540
+ if (cleaned) return;
1541
+ cleaned = true;
1542
+ await Effect4.runPromise(driver.killApp(""));
1543
+ bucket.remaining -= 1;
1544
+ if (bucket.remaining <= 0 && bucket.owns) {
1545
+ await bucket.browser.close();
1546
+ }
1547
+ }),
1548
+ metadata: {
1549
+ platform: "web",
1550
+ mode: "local",
1551
+ deviceId: `playwright-context-${i + 1}`
1552
+ }
1553
+ },
1554
+ engineConfig: buildEngineConfig(webUrl, "web", parseWebHierarchy, config, {
1555
+ width: deviceInfo.screenWidth,
1556
+ height: deviceInfo.screenHeight
1557
+ })
1558
+ });
1559
+ }
1560
+ return results;
1561
+ }
1562
+ async function buildElectronRuntime(config, resolveFromConfig) {
1563
+ const electronCfg = config.apps?.electron ?? {};
1564
+ const bridge = await maybeStartBridge(electronCfg.bridge, config.execution?.bridge);
1565
+ const driver = await Effect4.runPromise(
1566
+ makeElectronDriver({
1567
+ entry: electronCfg.entry ? resolveFromConfig(electronCfg.entry) : void 0,
1568
+ executablePath: electronCfg.executablePath ? resolveFromConfig(electronCfg.executablePath) : void 0,
1569
+ args: electronCfg.args,
1570
+ cwd: electronCfg.cwd ? resolveFromConfig(electronCfg.cwd) : void 0,
1571
+ env: {
1572
+ ...electronCfg.env,
1573
+ ...bridge?.url ? { SPANA_BRIDGE: "1", SPANA_BRIDGE_URL: bridge.url } : {}
1574
+ },
1575
+ cdpUrl: electronCfg.cdpUrl,
1576
+ cdpPort: electronCfg.cdpPort,
1577
+ url: electronCfg.url,
1578
+ domChannel: bridge
1579
+ })
1580
+ );
1581
+ const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
1582
+ return {
1583
+ runtime: {
1584
+ driver,
1585
+ cleanup: () => safeCleanup(
1586
+ () => Effect4.runPromise(driver.killApp("")),
1587
+ () => bridge?.disconnect() ?? Promise.resolve()
1588
+ ),
1589
+ metadata: {
1590
+ platform: "electron",
1591
+ mode: "local",
1592
+ deviceId: deviceInfo.deviceId
1593
+ }
1594
+ },
1595
+ engineConfig: buildEngineConfig(
1596
+ electronCfg.url ?? electronCfg.entry ?? "electron",
1597
+ "electron",
1598
+ parseWebHierarchy,
1599
+ config,
1600
+ {
1601
+ width: deviceInfo.screenWidth,
1602
+ height: deviceInfo.screenHeight
1603
+ }
1604
+ )
1605
+ };
1606
+ }
1607
+ async function buildElectrobunRuntime(config, resolveFromConfig) {
1608
+ const electrobunCfg = config.apps?.electrobun ?? {};
1609
+ const bridge = await maybeStartBridge(electrobunCfg.bridge, config.execution?.bridge);
1610
+ const driver = await Effect4.runPromise(
1611
+ makeElectrobunDriver({
1612
+ executablePath: electrobunCfg.executablePath ? resolveFromConfig(electrobunCfg.executablePath) : void 0,
1613
+ appDir: electrobunCfg.appDir ? resolveFromConfig(electrobunCfg.appDir) : void 0,
1614
+ args: electrobunCfg.args,
1615
+ cwd: electrobunCfg.cwd ? resolveFromConfig(electrobunCfg.cwd) : void 0,
1616
+ env: {
1617
+ ...electrobunCfg.env,
1618
+ ...bridge?.url ? { SPANA_BRIDGE: "1", SPANA_BRIDGE_URL: bridge.url } : {}
1619
+ },
1620
+ renderer: electrobunCfg.renderer,
1621
+ cdpUrl: electrobunCfg.cdpUrl,
1622
+ cdpPort: electrobunCfg.cdpPort,
1623
+ webkitInspectorPort: electrobunCfg.webkitInspectorPort,
1624
+ url: electrobunCfg.url,
1625
+ domChannel: bridge
1626
+ })
1627
+ );
1628
+ const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
1629
+ return {
1630
+ runtime: {
1631
+ driver,
1632
+ cleanup: () => safeCleanup(
1633
+ () => Effect4.runPromise(driver.killApp("")),
1634
+ () => bridge?.disconnect() ?? Promise.resolve()
1635
+ ),
1636
+ metadata: {
1637
+ platform: "electrobun",
1638
+ mode: "local",
1639
+ deviceId: deviceInfo.deviceId
1640
+ }
1641
+ },
1642
+ engineConfig: buildEngineConfig(
1643
+ electrobunCfg.url ?? electrobunCfg.executablePath ?? "electrobun",
1644
+ "electrobun",
1645
+ parseWebHierarchy,
1646
+ config,
1647
+ {
1648
+ width: deviceInfo.screenWidth,
1649
+ height: deviceInfo.screenHeight
1650
+ }
1651
+ )
1652
+ };
1653
+ }
1654
+ async function buildLocalAndroidRuntime(config, targetDevice, resolveFromConfig) {
1655
+ const device = targetDevice?.platform === "android" ? {
1656
+ serial: targetDevice.id,
1657
+ state: "device",
1658
+ type: targetDevice.type
1659
+ } : ensureAndroidDevice();
1660
+ if (!device) {
1661
+ console.log("No Android device/emulator available. Skipping android platform.");
1662
+ return null;
1663
+ }
1664
+ const packageName = config.apps?.android?.packageName ?? "";
1665
+ const androidAppPath = config.apps?.android?.appPath;
1666
+ if (androidAppPath && packageName) {
1667
+ try {
1668
+ const { adbShell, adbInstall } = await import("./android-4NVTZMHL.js");
1669
+ const output = adbShell(device.serial, `pm list packages ${packageName}`);
1670
+ if (!output.includes(packageName)) {
1671
+ console.log(`Installing ${packageName} on Android device...`);
1672
+ adbInstall(device.serial, resolveFromConfig(androidAppPath));
1673
+ }
1674
+ } catch {
1675
+ console.log(`Installing ${packageName} on Android device...`);
1676
+ const { adbInstall } = await import("./android-4NVTZMHL.js");
1677
+ adbInstall(device.serial, resolveFromConfig(androidAppPath));
1678
+ }
1679
+ }
1680
+ const hostPort = allocatePort(8200);
1681
+ const warmDaemons = config.execution?.warmDaemons;
1682
+ const bridge = await maybeStartBridge(config.apps?.android?.bridge, config.execution?.bridge);
1683
+ const reversedBridgePort = bridge?.port ?? null;
1684
+ if (reversedBridgePort !== null) {
1685
+ try {
1686
+ adbReverse(device.serial, reversedBridgePort, reversedBridgePort);
1687
+ } catch {
1688
+ }
1689
+ }
1690
+ try {
1691
+ const conn = await setupUiAutomator2(device.serial, hostPort, {
1692
+ warm: warmDaemons?.enabled,
1693
+ daemonStateFile: warmDaemons?.stateFile
1694
+ });
1695
+ const driver = await Effect4.runPromise(
1696
+ createUiAutomator2Driver(conn.host, conn.port, device.serial, packageName, {
1697
+ domChannel: bridge,
1698
+ cdpPort: config.apps?.android?.cdpPort
1699
+ })
1700
+ );
1701
+ const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
1702
+ return {
1703
+ runtime: {
1704
+ driver,
1705
+ cleanup: () => safeCleanup(
1706
+ () => Effect4.runPromise(driver.killApp("")),
1707
+ () => bridge?.disconnect() ?? Promise.resolve(),
1708
+ () => {
1709
+ if (reversedBridgePort !== null) {
1710
+ adbReverseRemove(device.serial, reversedBridgePort);
1711
+ }
1712
+ return Promise.resolve();
1713
+ },
1714
+ () => conn.cleanup?.() ?? Promise.resolve()
1715
+ ),
1716
+ metadata: {
1717
+ platform: "android",
1718
+ mode: "local",
1719
+ deviceId: device.serial
1720
+ }
1721
+ },
1722
+ engineConfig: buildEngineConfig(packageName, "android", parseAndroidHierarchy, config, {
1723
+ width: deviceInfo.screenWidth,
1724
+ height: deviceInfo.screenHeight
1725
+ })
1726
+ };
1727
+ } catch (e) {
1728
+ await bridge?.disconnect().catch(() => {
1729
+ });
1730
+ console.log(`Android setup failed on ${device.serial}: ${e instanceof Error ? e.message : e}`);
1731
+ return null;
1732
+ }
1733
+ }
1734
+ async function buildLocalIOSRuntime(config, targetDevice, resolveFromConfig) {
1735
+ const bundleId = config.apps?.ios?.bundleId ?? "";
1736
+ const iosAppPath = config.apps?.ios?.appPath;
1737
+ const signing = config.apps?.ios?.signing;
1738
+ const snapshotMaxDepth = config.defaults?.snapshotMaxDepth ?? 100;
1739
+ const warmDaemons = config.execution?.warmDaemons;
1740
+ const bridge = await maybeStartBridge(config.apps?.ios?.bridge, config.execution?.bridge);
1741
+ const createIOSRuntime = async (deviceId, conn, simulatorUdid) => {
1742
+ const reuseSession = warmDaemons?.enabled && warmDaemons.reuseSession !== false;
1743
+ const driver = await Effect4.runPromise(
1744
+ createWDADriver(conn.host, conn.port, bundleId, simulatorUdid, snapshotMaxDepth, {
1745
+ domChannel: bridge,
1746
+ webkitInspectorUrl: config.apps?.ios?.webkitInspectorUrl,
1747
+ webkitInspectorPort: config.apps?.ios?.webkitInspectorPort,
1748
+ autoStartInspectorProxy: true,
1749
+ warmSessionId: reuseSession ? conn.warmSessionId : void 0,
1750
+ onSessionCreated: reuseSession ? (sessionId) => updateWarmDaemonSession("wda", deviceId, sessionId, bundleId, warmDaemons?.stateFile) : void 0
1751
+ })
1752
+ );
1753
+ const deviceInfo = await Effect4.runPromise(driver.getDeviceInfo());
1754
+ return {
1755
+ runtime: {
1756
+ driver,
1757
+ cleanup: () => safeCleanup(
1758
+ () => Effect4.runPromise(driver.killApp("")),
1759
+ () => bridge?.disconnect() ?? Promise.resolve(),
1760
+ () => conn.cleanup?.() ?? Promise.resolve()
1761
+ ),
1762
+ metadata: {
1763
+ platform: "ios",
1764
+ mode: "local",
1765
+ deviceId
1766
+ }
1767
+ },
1768
+ engineConfig: buildEngineConfig(bundleId, "ios", parseIOSHierarchy, config, {
1769
+ width: deviceInfo.screenWidth,
1770
+ height: deviceInfo.screenHeight
1771
+ })
1772
+ };
1773
+ };
1774
+ const connectPhysicalRuntime = async (physicalDevice2, allowSimulatorFallback) => {
1775
+ let conn;
1776
+ try {
1777
+ console.log(`Found physical iOS device: ${physicalDevice2.name} (${physicalDevice2.udid})`);
1778
+ if (iosAppPath && bundleId) {
1779
+ ensureAppInstalled({
1780
+ udid: physicalDevice2.udid,
1781
+ bundleId,
1782
+ appPath: resolveFromConfig(iosAppPath),
1783
+ isPhysicalDevice: true
1784
+ });
1785
+ }
1786
+ if (signing?.teamId) {
1787
+ const { setupWDAForDevice } = await import("./installer-VUPFWP5X.js");
1788
+ const wdaPort2 = allocatePort(8100);
1789
+ conn = await setupWDAForDevice(
1790
+ physicalDevice2.udid,
1791
+ wdaPort2,
1792
+ signing.teamId,
1793
+ signing.signingIdentity,
1794
+ { warm: warmDaemons?.enabled, daemonStateFile: warmDaemons?.stateFile }
1795
+ );
1796
+ } else {
1797
+ conn = connectPhysicalDevice(physicalDevice2.udid);
1798
+ }
1799
+ return await createIOSRuntime(physicalDevice2.udid, conn);
1800
+ } catch (e) {
1801
+ if (conn?.cleanup) {
1802
+ try {
1803
+ await conn.cleanup();
1804
+ } catch (cleanupError) {
1805
+ console.warn(
1806
+ `Failed to clean up physical device tunnel: ${cleanupError instanceof Error ? cleanupError.message : cleanupError}`
1807
+ );
1808
+ }
1809
+ }
1810
+ if (!allowSimulatorFallback) {
1811
+ await bridge?.disconnect().catch(() => {
1812
+ });
1813
+ console.log(
1814
+ `iOS setup failed for device ${physicalDevice2.udid}: ${e instanceof Error ? e.message : e}`
1815
+ );
1816
+ return null;
1817
+ }
1818
+ console.log(
1819
+ `Physical device setup failed (${physicalDevice2.name}): ${e instanceof Error ? e.message : e}. Falling back to simulator.`
1820
+ );
1821
+ return null;
1822
+ }
1823
+ };
1824
+ if (targetDevice?.platform === "ios" && targetDevice.type === "simulator") {
1825
+ if (iosAppPath && bundleId) {
1826
+ ensureAppInstalled({
1827
+ udid: targetDevice.id,
1828
+ bundleId,
1829
+ appPath: resolveFromConfig(iosAppPath),
1830
+ isPhysicalDevice: false
1831
+ });
1832
+ }
1833
+ const wdaPort2 = allocatePort(8100);
1834
+ try {
1835
+ const conn = await setupWDA(targetDevice.id, wdaPort2, {
1836
+ warm: warmDaemons?.enabled,
1837
+ daemonStateFile: warmDaemons?.stateFile
1838
+ });
1839
+ return await createIOSRuntime(targetDevice.id, conn, targetDevice.id);
1840
+ } catch (e) {
1841
+ await bridge?.disconnect().catch(() => {
1842
+ });
1843
+ console.log(
1844
+ `iOS setup failed for device ${targetDevice.id}: ${e instanceof Error ? e.message : e}`
1845
+ );
1846
+ return null;
1847
+ }
1848
+ }
1849
+ if (targetDevice?.platform === "ios" && targetDevice.type === "device") {
1850
+ return connectPhysicalRuntime({ udid: targetDevice.id, name: targetDevice.name }, false);
1851
+ }
1852
+ const physicalDevice = firstIOSPhysicalDevice();
1853
+ if (physicalDevice) {
1854
+ const runtime = await connectPhysicalRuntime(physicalDevice, true);
1855
+ if (runtime) {
1856
+ return runtime;
1857
+ }
1858
+ }
1859
+ const simulator = ensureIOSSimulator(bundleId);
1860
+ if (!simulator) {
1861
+ await bridge?.disconnect().catch(() => {
1862
+ });
1863
+ console.log("No iOS simulator or physical device available. Skipping ios platform.");
1864
+ return null;
1865
+ }
1866
+ if (iosAppPath && bundleId) {
1867
+ ensureAppInstalled({
1868
+ udid: simulator.udid,
1869
+ bundleId,
1870
+ appPath: resolveFromConfig(iosAppPath),
1871
+ isPhysicalDevice: false
1872
+ });
1873
+ }
1874
+ const wdaPort = allocatePort(8100);
1875
+ try {
1876
+ const conn = await setupWDA(simulator.udid, wdaPort, {
1877
+ warm: warmDaemons?.enabled,
1878
+ daemonStateFile: warmDaemons?.stateFile
1879
+ });
1880
+ return await createIOSRuntime(simulator.udid, conn, simulator.udid);
1881
+ } catch (e) {
1882
+ await bridge?.disconnect().catch(() => {
1883
+ });
1884
+ console.log(`iOS setup failed on ${simulator.name}: ${e instanceof Error ? e.message : e}`);
1885
+ return null;
1886
+ }
1887
+ }
1888
+
1889
+ // src/core/engine.ts
1890
+ import { Effect as Effect7 } from "effect";
1891
+
1892
+ // src/core/artifacts.ts
1893
+ import { writeFileSync, mkdirSync } from "fs";
1894
+ import { join as join2 } from "path";
1895
+ import { Effect as Effect5 } from "effect";
1896
+ var DEFAULT_ARTIFACT_CONFIG = {
1897
+ outputDir: "./spana-output",
1898
+ captureOnFailure: true,
1899
+ captureOnSuccess: false,
1900
+ captureSteps: false,
1901
+ screenshot: true,
1902
+ uiHierarchy: true,
1903
+ consoleLogs: true,
1904
+ jsErrors: true,
1905
+ har: true
1906
+ };
1907
+ function safeName(value) {
1908
+ return value.replaceAll(/[^a-zA-Z0-9-_]/g, "_").replaceAll(/_+/g, "_").replaceAll(/^_+|_+$/g, "").slice(0, 80) || "artifact";
1909
+ }
1910
+ function flowArtifactDir(config, flowName, platform) {
1911
+ const dir = join2(config.outputDir, `${safeName(flowName)}-${platform}`);
1912
+ mkdirSync(dir, { recursive: true });
1913
+ return dir;
1914
+ }
1915
+ function createAttachment(name, contentType, path) {
1916
+ return { name, contentType, path };
1917
+ }
1918
+ function writeJsonAttachment(dir, fileName, attachmentName, value) {
1919
+ const path = join2(dir, fileName);
1920
+ writeFileSync(path, JSON.stringify(value, null, 2), "utf-8");
1921
+ return createAttachment(attachmentName, "application/json", path);
1922
+ }
1923
+ function writeTextAttachment(dir, fileName, attachmentName, value) {
1924
+ const path = join2(dir, fileName);
1925
+ writeFileSync(path, value, "utf-8");
1926
+ return createAttachment(attachmentName, "text/plain", path);
1927
+ }
1928
+ function resolveArtifactConfig(...configs) {
1929
+ return configs.reduce(
1930
+ (resolved, config) => ({
1931
+ ...resolved,
1932
+ ...config
1933
+ }),
1934
+ { ...DEFAULT_ARTIFACT_CONFIG }
1935
+ );
1936
+ }
1937
+ async function captureArtifacts(driver, config, flowName, platform, status) {
1938
+ const shouldCapture = status === "failed" && config.captureOnFailure || status === "passed" && config.captureOnSuccess;
1939
+ if (!shouldCapture) return [];
1940
+ const attachments = [];
1941
+ const dir = flowArtifactDir(config, flowName, platform);
1942
+ if (config.screenshot) {
1943
+ try {
1944
+ const screenshot = await Effect5.runPromise(Effect5.orDie(driver.takeScreenshot()));
1945
+ const path = join2(dir, "screenshot.png");
1946
+ writeFileSync(path, screenshot);
1947
+ attachments.push(createAttachment(`${status}-screenshot`, "image/png", path));
1948
+ } catch {
1949
+ }
1950
+ }
1951
+ if (config.uiHierarchy) {
1952
+ try {
1953
+ const hierarchy = await Effect5.runPromise(Effect5.orDie(driver.dumpHierarchy()));
1954
+ const path = join2(dir, "hierarchy.json");
1955
+ writeFileSync(path, hierarchy, "utf-8");
1956
+ attachments.push(createAttachment(`${status}-hierarchy`, "application/json", path));
1957
+ } catch {
1958
+ }
1959
+ }
1960
+ if (config.consoleLogs && driver.getConsoleLogs) {
1961
+ try {
1962
+ const consoleLogs = await Effect5.runPromise(Effect5.orDie(driver.getConsoleLogs()));
1963
+ if (consoleLogs.length > 0) {
1964
+ attachments.push(
1965
+ writeJsonAttachment(dir, "console-logs.json", `${status}-console-logs`, consoleLogs)
1966
+ );
1967
+ }
1968
+ } catch {
1969
+ }
1970
+ }
1971
+ if (config.jsErrors && driver.getJSErrors) {
1972
+ try {
1973
+ const jsErrors = await Effect5.runPromise(Effect5.orDie(driver.getJSErrors()));
1974
+ if (jsErrors.length > 0) {
1975
+ attachments.push(
1976
+ writeJsonAttachment(dir, "js-errors.json", `${status}-js-errors`, jsErrors)
1977
+ );
1978
+ }
1979
+ } catch {
1980
+ }
1981
+ }
1982
+ if (config.har && driver.getHAR) {
1983
+ try {
1984
+ const har = await Effect5.runPromise(Effect5.orDie(driver.getHAR()));
1985
+ if (har.log.entries.length > 0) {
1986
+ attachments.push(writeJsonAttachment(dir, "network.har", `${status}-network-har`, har));
1987
+ }
1988
+ } catch {
1989
+ }
1990
+ }
1991
+ if (status === "failed" && driver.getDriverLogs) {
1992
+ try {
1993
+ const driverLogs = await Effect5.runPromise(Effect5.orDie(driver.getDriverLogs()));
1994
+ if (driverLogs.length > 0) {
1995
+ attachments.push(
1996
+ writeTextAttachment(
1997
+ dir,
1998
+ "driver-logs.txt",
1999
+ `${status}-driver-logs`,
2000
+ driverLogs.join("\n")
2001
+ )
2002
+ );
2003
+ }
2004
+ } catch {
2005
+ }
2006
+ }
2007
+ return attachments;
2008
+ }
2009
+ async function captureStepScreenshot(driver, config, flowName, platform, stepIndex, stepName, screenshot) {
2010
+ if (!config.screenshot) return void 0;
2011
+ try {
2012
+ const dir = join2(flowArtifactDir(config, flowName, platform), "steps");
2013
+ mkdirSync(dir, { recursive: true });
2014
+ const fileName = `${String(stepIndex).padStart(3, "0")}-${safeName(stepName)}.png`;
2015
+ const path = join2(dir, fileName);
2016
+ const bytes = screenshot ?? await Effect5.runPromise(Effect5.orDie(driver.takeScreenshot()));
2017
+ writeFileSync(path, bytes);
2018
+ return createAttachment(stepName, "image/png", path);
2019
+ } catch {
2020
+ return void 0;
2021
+ }
2022
+ }
2023
+
2024
+ // src/core/debug-repl.ts
2025
+ import * as repl from "repl";
2026
+ import { Effect as Effect6 } from "effect";
2027
+ var didStartDebugRepl = false;
2028
+ function toSuggestedSelectors(root) {
2029
+ return flattenElements(root).filter((el) => el.visible !== false && (el.id || el.text || el.accessibilityLabel)).map((el) => ({
2030
+ suggestedSelector: el.id ? { testID: el.id } : el.accessibilityLabel ? { accessibilityLabel: el.accessibilityLabel } : el.text ? { text: el.text } : "",
2031
+ elementType: el.elementType,
2032
+ text: el.text,
2033
+ accessibilityLabel: el.accessibilityLabel,
2034
+ bounds: el.bounds,
2035
+ id: el.id
2036
+ }));
2037
+ }
2038
+ async function runDebugReplOnce(context) {
2039
+ if (didStartDebugRepl) {
2040
+ return false;
2041
+ }
2042
+ didStartDebugRepl = true;
2043
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
2044
+ console.log("Skipping debug REPL because stdin/stdout is not interactive.");
2045
+ return false;
2046
+ }
2047
+ const hierarchy = async () => context.parseHierarchy(await Effect6.runPromise(context.driver.dumpHierarchy()));
2048
+ const selectors = async () => toSuggestedSelectors(await hierarchy());
2049
+ console.log("");
2050
+ console.log(`Entering debug REPL for failed flow "${context.flowName}" on ${context.platform}.`);
2051
+ console.log(
2052
+ "Available bindings: app, expect, driver, platform, flowName, error, hierarchy(), selectors(), help()"
2053
+ );
2054
+ console.log('Use top-level await for async calls, for example: await app.tap({ text: "Login" })');
2055
+ const replServer = repl.start({
2056
+ prompt: `spana:${context.platform}> `,
2057
+ ignoreUndefined: true,
2058
+ useGlobal: false
2059
+ });
2060
+ replServer.context.app = context.app;
2061
+ replServer.context.expect = context.expect;
2062
+ replServer.context.driver = context.driver;
2063
+ replServer.context.platform = context.platform;
2064
+ replServer.context.flowName = context.flowName;
2065
+ replServer.context.error = context.error;
2066
+ replServer.context.hierarchy = hierarchy;
2067
+ replServer.context.selectors = selectors;
2068
+ replServer.context.help = () => {
2069
+ console.log("app Promise-based app API with auto-waiting");
2070
+ console.log("expect Assertion helper, e.g. await expect({ text: 'Done' }).toBeVisible()");
2071
+ console.log("driver Raw driver service");
2072
+ console.log("hierarchy Async helper returning the parsed UI tree");
2073
+ console.log("selectors Async helper returning suggested selectors");
2074
+ console.log(".exit Leave the REPL");
2075
+ };
2076
+ await new Promise((resolve) => replServer.on("exit", resolve));
2077
+ console.log("");
2078
+ return true;
2079
+ }
2080
+
2081
+ // src/core/step-recorder.ts
2082
+ function errorMessage(error) {
2083
+ return error instanceof Error ? error.message : String(error);
2084
+ }
2085
+ function createStepResult(command, durationMs, status, selector, error, attachments) {
2086
+ return {
2087
+ command,
2088
+ selector,
2089
+ status,
2090
+ durationMs,
2091
+ error,
2092
+ attachments: attachments && attachments.length > 0 ? attachments : void 0
2093
+ };
2094
+ }
2095
+ function createStepRecorder(driver, artifactConfig, flowName, platform) {
2096
+ const steps = [];
2097
+ return {
2098
+ async runStep(command, action, opts) {
2099
+ const startedAt = Date.now();
2100
+ try {
2101
+ const result = await action();
2102
+ const attachments = [];
2103
+ if (opts?.captureScreenshot && artifactConfig.captureSteps) {
2104
+ const attachment = await captureStepScreenshot(
2105
+ driver,
2106
+ artifactConfig,
2107
+ flowName,
2108
+ platform,
2109
+ steps.length + 1,
2110
+ command
2111
+ );
2112
+ if (attachment) attachments.push(attachment);
2113
+ }
2114
+ steps.push(
2115
+ createStepResult(
2116
+ command,
2117
+ Date.now() - startedAt,
2118
+ "passed",
2119
+ opts?.selector,
2120
+ void 0,
2121
+ attachments
2122
+ )
2123
+ );
2124
+ return result;
2125
+ } catch (error) {
2126
+ steps.push(
2127
+ createStepResult(
2128
+ command,
2129
+ Date.now() - startedAt,
2130
+ "failed",
2131
+ opts?.selector,
2132
+ errorMessage(error)
2133
+ )
2134
+ );
2135
+ throw error;
2136
+ }
2137
+ },
2138
+ async runScreenshotStep(command, action, opts) {
2139
+ const startedAt = Date.now();
2140
+ try {
2141
+ const screenshot = await action();
2142
+ const attachment = await captureStepScreenshot(
2143
+ driver,
2144
+ artifactConfig,
2145
+ flowName,
2146
+ platform,
2147
+ steps.length + 1,
2148
+ opts?.name ?? command,
2149
+ screenshot
2150
+ );
2151
+ steps.push(
2152
+ createStepResult(
2153
+ command,
2154
+ Date.now() - startedAt,
2155
+ "passed",
2156
+ opts?.selector,
2157
+ void 0,
2158
+ attachment ? [attachment] : void 0
2159
+ )
2160
+ );
2161
+ return screenshot;
2162
+ } catch (error) {
2163
+ steps.push(
2164
+ createStepResult(
2165
+ command,
2166
+ Date.now() - startedAt,
2167
+ "failed",
2168
+ opts?.selector,
2169
+ errorMessage(error)
2170
+ )
2171
+ );
2172
+ throw error;
2173
+ }
2174
+ },
2175
+ getSteps() {
2176
+ return steps;
2177
+ }
2178
+ };
2179
+ }
2180
+
2181
+ // src/report/classify-error.ts
2182
+ var TAG_KEY = "_tag";
2183
+ function selectorHint(selector) {
2184
+ if (selector && typeof selector === "object") {
2185
+ const s = selector;
2186
+ if (s.testID) return `testID="${s.testID}"`;
2187
+ if (s.text) return `text="${s.text}"`;
2188
+ if (s.accessibilityLabel) return `accessibilityLabel="${s.accessibilityLabel}"`;
2189
+ }
2190
+ return JSON.stringify(selector);
2191
+ }
2192
+ function categorizeElementFailure(message) {
2193
+ const lower = message.toLowerCase();
2194
+ if (lower.includes("not visible") || lower.includes("visible=false")) {
2195
+ return "element-not-visible";
2196
+ }
2197
+ if (lower.includes("off-screen") || lower.includes("zero size")) {
2198
+ return "element-off-screen";
2199
+ }
2200
+ if (lower.includes("disabled") || lower.includes("not interactive")) {
2201
+ return "element-not-interactive";
2202
+ }
2203
+ return "element-not-found";
2204
+ }
2205
+ function elementSuggestion(category, selector, timeoutMs) {
2206
+ switch (category) {
2207
+ case "element-not-visible":
2208
+ return [
2209
+ `Selector ${selector} matched an element, but it is currently hidden.`,
2210
+ "Check whether an animation, modal, or loading state is covering it before retrying.",
2211
+ "Consider increasing waitTimeout if the element becomes visible after a delay."
2212
+ ].join("\n");
2213
+ case "element-off-screen":
2214
+ return [
2215
+ `Selector ${selector} matched an element that is off-screen.`,
2216
+ "Use scrollUntilVisible() or scroll to the element before interacting with it.",
2217
+ "If the target is above the current viewport, reverse the search direction."
2218
+ ].join("\n");
2219
+ case "element-not-interactive":
2220
+ return [
2221
+ `Selector ${selector} matched an element that is disabled or not interactive.`,
2222
+ "Wait for the app to enable it, or verify the prerequisite app state first.",
2223
+ "Consider increasing waitTimeout if the control becomes enabled after async work completes."
2224
+ ].join("\n");
2225
+ default:
2226
+ return [
2227
+ `Selector ${selector} was not found within ${timeoutMs ?? "?"}ms.`,
2228
+ "Run `spana selectors` to inspect the current screen and confirm the best selector.",
2229
+ "Consider increasing waitTimeout if the element appears after a delay."
2230
+ ].join("\n");
2231
+ }
2232
+ }
2233
+ function categorizeDynamic(error, tag, msg) {
2234
+ if (tag === "ElementNotFoundError" || tag === "WaitTimeoutError") {
2235
+ const sel = selectorHint(error.selector);
2236
+ if (msg.includes("scroll(s) toward")) {
2237
+ return {
2238
+ category: "element-not-found",
2239
+ suggestion: [
2240
+ `Selector ${sel} stayed off-screen while scrolling.`,
2241
+ "Try increasing `maxScrolls` or `timeout`, or reverse the search direction",
2242
+ 'if the target is actually above the current viewport (for example `{ direction: "up" }`).'
2243
+ ].join("\n")
2244
+ };
2245
+ }
2246
+ if (msg.includes("back action(s)")) {
2247
+ return {
2248
+ category: "element-not-found",
2249
+ suggestion: [
2250
+ `Selector ${sel} was not reached while navigating back.`,
2251
+ "Try increasing `maxBacks` or `timeout`, or prefer an explicit in-app",
2252
+ "back / close control on iOS-style screens instead of relying on system back."
2253
+ ].join("\n")
2254
+ };
2255
+ }
2256
+ const category = categorizeElementFailure(msg);
2257
+ return {
2258
+ category,
2259
+ suggestion: elementSuggestion(category, sel, error.timeoutMs)
2260
+ };
2261
+ }
2262
+ if (tag === "TextMismatchError") {
2263
+ const e = error;
2264
+ return {
2265
+ category: "text-mismatch",
2266
+ suggestion: [
2267
+ `Expected text "${e.expected}" but found "${e.actual ?? "(empty)"}".`,
2268
+ "The element exists but its content differs. Check for whitespace, truncation,",
2269
+ "or platform-specific text rendering differences."
2270
+ ].join("\n")
2271
+ };
2272
+ }
2273
+ if (tag === "DeviceDisconnectedError") {
2274
+ const id = error.deviceId ? ` (${error.deviceId})` : "";
2275
+ return {
2276
+ category: "device-disconnected",
2277
+ suggestion: [
2278
+ `The device${id} disconnected during the test.`,
2279
+ "Check the physical connection or emulator/simulator stability.",
2280
+ "Run `spana devices` to verify available devices."
2281
+ ].join("\n")
2282
+ };
2283
+ }
2284
+ if (tag === "AppCrashedError") {
2285
+ const app = error.appId ? ` (${error.appId})` : "";
2286
+ return {
2287
+ category: "app-crashed",
2288
+ suggestion: [
2289
+ `The app${app} crashed during the test.`,
2290
+ "Check the device logs for a crash stack trace:",
2291
+ " Android: `adb logcat -d | grep FATAL`",
2292
+ " iOS: Check Console.app or `log show --predicate 'process == \"your-app\"'`"
2293
+ ].join("\n")
2294
+ };
2295
+ }
2296
+ if (tag === "AppNotInstalledError") {
2297
+ return {
2298
+ category: "app-not-installed",
2299
+ suggestion: [
2300
+ `App "${error.appId}" is not installed on the device.`,
2301
+ "Install it before running tests, or configure `apps.android.appPath`",
2302
+ "/ `apps.ios.appPath` in spana.config.ts for auto-install."
2303
+ ].join("\n")
2304
+ };
2305
+ }
2306
+ if (tag === "DriverError") {
2307
+ return categorizeDynamicDriver(error, msg);
2308
+ }
2309
+ return void 0;
2310
+ }
2311
+ function categorizeDynamicDriver(error, msg) {
2312
+ for (const rule of driverRules) {
2313
+ if (rule.pattern && matchesPattern(msg, rule.pattern)) {
2314
+ return {
2315
+ category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
2316
+ suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
2317
+ };
2318
+ }
2319
+ }
2320
+ return {
2321
+ category: "driver-error",
2322
+ 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."
2323
+ };
2324
+ }
2325
+ var driverRules = [
2326
+ {
2327
+ pattern: "dismissKeyboard()",
2328
+ category: "driver-error",
2329
+ suggestion: [
2330
+ "Keyboard dismissal failed.",
2331
+ 'On Android, try `app.dismissKeyboard({ strategy: "back" })`.',
2332
+ "On iOS, prefer tapping a visible Done / Close control or a non-input element."
2333
+ ].join("\n")
2334
+ },
2335
+ {
2336
+ pattern: "backUntilVisible()",
2337
+ category: "driver-error",
2338
+ suggestion: [
2339
+ "System back navigation failed before the target screen became visible.",
2340
+ "If this route uses app-level navigation, tap the visible back / close control instead.",
2341
+ "This is especially common on iOS where a system back button may not exist."
2342
+ ].join("\n")
2343
+ },
2344
+ {
2345
+ pattern: "Input text failed",
2346
+ category: "driver-error",
2347
+ suggestion: [
2348
+ "Text input failed at the driver layer.",
2349
+ "Make sure the field is focused first, and retry with shorter input chunks if needed.",
2350
+ "If the keyboard is in the way, dismiss it before continuing the flow."
2351
+ ].join("\n")
2352
+ }
2353
+ ];
2354
+ var tagOnlyRules = [
2355
+ {
2356
+ tag: "TimeoutError",
2357
+ category: "timeout",
2358
+ suggestion: [
2359
+ "The operation took longer than the allowed timeout.",
2360
+ "Try increasing `defaults.waitTimeout` in spana.config.ts,",
2361
+ "or set a per-flow timeout: `flow('name', { timeout: 30000 }, ...)`."
2362
+ ].join("\n")
2363
+ },
2364
+ {
2365
+ tag: ["ConfigError", "FlowSyntaxError"],
2366
+ category: "config-error",
2367
+ suggestion: "Run `spana validate-config` to check your configuration."
2368
+ }
2369
+ ];
2370
+ var heuristicRules = [
2371
+ {
2372
+ pattern: /[Tt]imed out/,
2373
+ category: "timeout",
2374
+ suggestion: "The operation timed out. Try increasing `defaults.waitTimeout` in spana.config.ts."
2375
+ },
2376
+ {
2377
+ pattern: /not found|not visible/,
2378
+ category: (msg) => categorizeElementFailure(msg),
2379
+ suggestion: (_error, msg) => {
2380
+ if (msg.includes("scroll(s) toward")) {
2381
+ return "The target stayed off-screen while scrolling. Increase `maxScrolls` / `timeout`, or reverse the scroll search direction.";
2382
+ }
2383
+ const category = categorizeElementFailure(msg);
2384
+ return elementSuggestion(category, "the target selector", void 0);
2385
+ }
2386
+ },
2387
+ {
2388
+ pattern: "dismissKeyboard()",
2389
+ category: "driver-error",
2390
+ suggestion: 'Keyboard dismissal failed. On Android try `app.dismissKeyboard({ strategy: "back" })`; on iOS prefer an explicit Done / Close control.'
2391
+ },
2392
+ {
2393
+ pattern: /ECONNREFUSED|ECONNRESET|disconnected/,
2394
+ category: "device-disconnected",
2395
+ suggestion: "The connection was lost. Check the device or emulator/simulator is still running."
2396
+ }
2397
+ ];
2398
+ function matchesPattern(msg, pattern) {
2399
+ return typeof pattern === "string" ? msg.includes(pattern) : pattern.test(msg);
2400
+ }
2401
+ function matchesTag(tag, rule) {
2402
+ if (!rule.tag) return true;
2403
+ if (Array.isArray(rule.tag)) return tag != null && rule.tag.includes(tag);
2404
+ return tag === rule.tag;
2405
+ }
2406
+ function categorize(error) {
2407
+ const tag = error[TAG_KEY];
2408
+ const msg = error.message ?? "";
2409
+ const dynamic = categorizeDynamic(error, tag, msg);
2410
+ if (dynamic) return dynamic;
2411
+ for (const rule of tagOnlyRules) {
2412
+ if (matchesTag(tag, rule)) {
2413
+ return {
2414
+ category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
2415
+ suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
2416
+ };
2417
+ }
2418
+ }
2419
+ for (const rule of heuristicRules) {
2420
+ if (rule.pattern && matchesPattern(msg, rule.pattern)) {
2421
+ return {
2422
+ category: typeof rule.category === "function" ? rule.category(msg) : rule.category,
2423
+ suggestion: typeof rule.suggestion === "function" ? rule.suggestion(error, msg) : rule.suggestion
2424
+ };
2425
+ }
2426
+ }
2427
+ return { category: "unknown" };
2428
+ }
2429
+ function classifyError(error) {
2430
+ const tagged = error;
2431
+ const { category, suggestion } = categorize(tagged);
2432
+ return {
2433
+ message: error.message,
2434
+ stack: error.stack,
2435
+ category,
2436
+ suggestion
2437
+ };
2438
+ }
2439
+
2440
+ // src/core/engine.ts
2441
+ import { join as join4 } from "path";
2442
+
2443
+ // src/report/failure-bundle.ts
2444
+ import { writeFileSync as writeFileSync2, readFileSync, existsSync as existsSync2 } from "fs";
2445
+ import { join as join3, basename } from "path";
2446
+ function levenshtein(a, b) {
2447
+ const m = a.length;
2448
+ const n = b.length;
2449
+ const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
2450
+ for (let i = 0; i <= m; i++) dp[i][0] = i;
2451
+ for (let j = 0; j <= n; j++) dp[0][j] = j;
2452
+ for (let i = 1; i <= m; i++) {
2453
+ for (let j = 1; j <= n; j++) {
2454
+ 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]);
2455
+ }
2456
+ }
2457
+ return dp[m][n];
2458
+ }
2459
+ function extractIdentifiers(hierarchyJson) {
2460
+ const testIDs = [];
2461
+ const texts = [];
2462
+ try {
2463
+ const root = JSON.parse(hierarchyJson);
2464
+ const queue = [root];
2465
+ while (queue.length > 0) {
2466
+ const node = queue.pop();
2467
+ if (!node || typeof node !== "object") continue;
2468
+ if (node.testID && typeof node.testID === "string") testIDs.push(node.testID);
2469
+ if (node.text && typeof node.text === "string") texts.push(node.text);
2470
+ if (Array.isArray(node.children)) {
2471
+ for (const child of node.children) queue.push(child);
2472
+ }
2473
+ }
2474
+ } catch {
2475
+ }
2476
+ return { testIDs, texts };
2477
+ }
2478
+ function findNearbySelectors(attempted, hierarchyJson) {
2479
+ if (!hierarchyJson) return [];
2480
+ const { testIDs, texts } = extractIdentifiers(hierarchyJson);
2481
+ let target;
2482
+ let candidates;
2483
+ if (typeof attempted === "string") {
2484
+ target = attempted.toLowerCase();
2485
+ candidates = [...testIDs, ...texts];
2486
+ } else if (attempted && typeof attempted === "object") {
2487
+ const sel = attempted;
2488
+ if (typeof sel.testID === "string") {
2489
+ target = sel.testID.toLowerCase();
2490
+ candidates = testIDs;
2491
+ } else if (typeof sel.text === "string") {
2492
+ target = sel.text.toLowerCase();
2493
+ candidates = texts;
2494
+ } else if (typeof sel.accessibilityLabel === "string") {
2495
+ target = sel.accessibilityLabel.toLowerCase();
2496
+ candidates = [...testIDs, ...texts];
2497
+ } else {
2498
+ return [];
2499
+ }
2500
+ } else {
2501
+ return [];
2502
+ }
2503
+ const scored = candidates.filter((c) => c !== target).map((c) => {
2504
+ const cl = c.toLowerCase();
2505
+ const substringMatch = cl.includes(target) || target.includes(cl);
2506
+ const dist = levenshtein(target, cl);
2507
+ return { value: c, score: substringMatch ? 0 : dist };
2508
+ }).filter((s) => s.score <= 5).toSorted((a, b) => a.score - b.score);
2509
+ const seen = /* @__PURE__ */ new Set();
2510
+ const results = [];
2511
+ for (const s of scored) {
2512
+ if (!seen.has(s.value)) {
2513
+ seen.add(s.value);
2514
+ results.push(s.value);
2515
+ if (results.length >= 5) break;
2516
+ }
2517
+ }
2518
+ return results;
2519
+ }
2520
+ function buildArtifactMap(attachments) {
2521
+ const map = {};
2522
+ if (!attachments) return map;
2523
+ for (const att of attachments) {
2524
+ const filename = basename(att.path);
2525
+ if (filename === "screenshot.png") map.screenshot = filename;
2526
+ else if (filename === "hierarchy.json") map.hierarchy = filename;
2527
+ else if (filename === "console-logs.json") map.consoleLogs = filename;
2528
+ else if (filename === "js-errors.json") map.jsErrors = filename;
2529
+ else if (filename === "network.har") map.har = filename;
2530
+ else if (filename === "driver-logs.txt") map.driverLogs = filename;
2531
+ }
2532
+ return map;
2533
+ }
2534
+ function createFailureBundle(flowName, platform, steps, error, artifactDir, attachments, flowPath) {
2535
+ const failedStepIndex = steps.findLastIndex((s) => s.status === "failed");
2536
+ const failedStep = failedStepIndex >= 0 ? {
2537
+ index: failedStepIndex,
2538
+ command: steps[failedStepIndex].command,
2539
+ selector: steps[failedStepIndex].selector ?? null,
2540
+ durationMs: steps[failedStepIndex].durationMs,
2541
+ error: steps[failedStepIndex].error
2542
+ } : null;
2543
+ const lastPassedIndex = failedStepIndex > 0 ? steps.findLastIndex((s, i) => i < failedStepIndex && s.status === "passed") : -1;
2544
+ const lastPassedStep = lastPassedIndex >= 0 ? {
2545
+ index: lastPassedIndex,
2546
+ command: steps[lastPassedIndex].command,
2547
+ selector: steps[lastPassedIndex].selector ?? null,
2548
+ durationMs: steps[lastPassedIndex].durationMs
2549
+ } : null;
2550
+ let selectorContext;
2551
+ if (failedStep?.selector && (error.category === "element-not-found" || error.category === "element-not-visible")) {
2552
+ const hierarchyPath = join3(artifactDir, "hierarchy.json");
2553
+ let hierarchyJson = null;
2554
+ if (existsSync2(hierarchyPath)) {
2555
+ try {
2556
+ hierarchyJson = readFileSync(hierarchyPath, "utf-8");
2557
+ } catch {
2558
+ }
2559
+ }
2560
+ const nearbyAlternatives = findNearbySelectors(failedStep.selector, hierarchyJson);
2561
+ selectorContext = {
2562
+ attempted: failedStep.selector,
2563
+ nearbyAlternatives
2564
+ };
2565
+ }
2566
+ const flowFile = flowPath ?? `flows/${flowName.replaceAll(" ", "-")}.flow.ts`;
2567
+ const reproCommand = `spana test ${flowFile} --platform ${platform} --grep '${flowName}'`;
2568
+ let runtimeDiagnostics;
2569
+ const consolePath = join3(artifactDir, "console-logs.json");
2570
+ const jsErrPath = join3(artifactDir, "js-errors.json");
2571
+ if (existsSync2(consolePath) || existsSync2(jsErrPath)) {
2572
+ let consoleErrorCount = 0;
2573
+ let consoleWarnCount = 0;
2574
+ const recentConsoleErrors = [];
2575
+ let jsErrorCount = 0;
2576
+ const recentJsErrors = [];
2577
+ if (existsSync2(consolePath)) {
2578
+ try {
2579
+ const logs = JSON.parse(readFileSync(consolePath, "utf-8"));
2580
+ if (Array.isArray(logs)) {
2581
+ for (const entry of logs) {
2582
+ const lvl = (entry.type ?? entry.level ?? "").toLowerCase();
2583
+ const text = entry.text ?? entry.message ?? "";
2584
+ if (lvl === "error") {
2585
+ consoleErrorCount++;
2586
+ if (text) recentConsoleErrors.push(text);
2587
+ } else if (lvl === "warn" || lvl === "warning") {
2588
+ consoleWarnCount++;
2589
+ }
2590
+ }
2591
+ }
2592
+ } catch {
2593
+ }
2594
+ }
2595
+ if (existsSync2(jsErrPath)) {
2596
+ try {
2597
+ const errs = JSON.parse(readFileSync(jsErrPath, "utf-8"));
2598
+ if (Array.isArray(errs)) {
2599
+ jsErrorCount = errs.length;
2600
+ for (const e of errs.slice(-5)) {
2601
+ const msg = e.message ?? e.text ?? String(e);
2602
+ if (msg) recentJsErrors.push(msg);
2603
+ }
2604
+ }
2605
+ } catch {
2606
+ }
2607
+ }
2608
+ if (consoleErrorCount > 0 || consoleWarnCount > 0 || jsErrorCount > 0) {
2609
+ runtimeDiagnostics = {
2610
+ consoleErrorCount,
2611
+ consoleWarnCount,
2612
+ recentConsoleErrors: recentConsoleErrors.slice(-5),
2613
+ jsErrorCount,
2614
+ recentJsErrors
2615
+ };
2616
+ }
2617
+ }
2618
+ const bundle = {
2619
+ schemaVersion: 1,
2620
+ flow: flowName,
2621
+ platform,
2622
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2623
+ failedStep,
2624
+ lastPassedStep,
2625
+ error: {
2626
+ message: error.message,
2627
+ category: error.category,
2628
+ suggestion: error.suggestion,
2629
+ errorCode: error.errorCode
2630
+ },
2631
+ selectorContext,
2632
+ ...runtimeDiagnostics ? { runtimeDiagnostics } : {},
2633
+ artifacts: buildArtifactMap(attachments),
2634
+ reproCommand,
2635
+ durationMs: steps.reduce((sum, s) => sum + s.durationMs, 0)
2636
+ };
2637
+ return bundle;
2638
+ }
2639
+ function writeFailureBundle(bundle, artifactDir) {
2640
+ const path = join3(artifactDir, "failure-bundle.json");
2641
+ writeFileSync2(path, JSON.stringify(bundle, null, 2), "utf-8");
2642
+ return path;
2643
+ }
2644
+
2645
+ // src/core/engine.ts
2646
+ async function executeFlow(flow, driver, config) {
2647
+ const start2 = Date.now();
2648
+ const { platform, coordinatorConfig, appId } = config;
2649
+ const autoLaunch = flow.config.autoLaunch ?? config.autoLaunch ?? true;
2650
+ const timeout = flow.config.timeout ?? config.flowTimeout ?? 6e4;
2651
+ const artifactConfig = resolveArtifactConfig(config.artifactConfig, flow.config.artifacts);
2652
+ const stepRecorder = createStepRecorder(driver, artifactConfig, flow.name, platform);
2653
+ const launchOptions = mergeLaunchOptions(config.launchOptions, flow.config.launchOptions);
2654
+ const flowDefaults = flow.config.defaults;
2655
+ const mergedCoordinatorConfig = flowDefaults ? {
2656
+ ...coordinatorConfig,
2657
+ defaults: {
2658
+ ...coordinatorConfig.defaults,
2659
+ timeout: flowDefaults.waitTimeout ?? coordinatorConfig.defaults?.timeout,
2660
+ pollInterval: flowDefaults.pollInterval ?? coordinatorConfig.defaults?.pollInterval,
2661
+ settleTimeout: flowDefaults.settleTimeout ?? coordinatorConfig.defaults?.settleTimeout,
2662
+ initialPollInterval: flowDefaults.initialPollInterval ?? coordinatorConfig.defaults?.initialPollInterval
2663
+ },
2664
+ waitForIdleTimeout: flowDefaults.waitForIdleTimeout ?? coordinatorConfig.waitForIdleTimeout,
2665
+ typingDelay: flowDefaults.typingDelay ?? coordinatorConfig.typingDelay,
2666
+ hierarchyCacheTtl: flowDefaults.hierarchyCacheTtl ?? coordinatorConfig.hierarchyCacheTtl
2667
+ } : coordinatorConfig;
2668
+ const app = createPromiseApp(driver, appId, mergedCoordinatorConfig, stepRecorder, {
2669
+ platform,
2670
+ storybook: config.storybook,
2671
+ launchOptions
2672
+ });
2673
+ const flowMeta = {
2674
+ flowFilePath: flow.sourcePath ?? "",
2675
+ flowName: flow.name,
2676
+ platform,
2677
+ updateBaselines: config.updateBaselines ?? false
2678
+ };
2679
+ const expect = createPromiseExpect(
2680
+ driver,
2681
+ mergedCoordinatorConfig,
2682
+ stepRecorder,
2683
+ flowMeta,
2684
+ config.visualRegression
2685
+ );
2686
+ const flowCtx = { app, expect, platform, updateBaselines: flowMeta.updateBaselines };
2687
+ const sessionManager = new SessionManager();
2688
+ const sessions = createSessions(
2689
+ sessionManager,
2690
+ async (opts) => {
2691
+ const pwDriver = await Effect7.runPromise(
2692
+ makePlaywrightDriver({
2693
+ browser: opts.browser,
2694
+ headless: opts.headless ?? true,
2695
+ baseUrl: opts.baseUrl,
2696
+ storageState: opts.storageState,
2697
+ verboseLogging: opts.verboseLogging
2698
+ })
2699
+ );
2700
+ return pwDriver;
2701
+ },
2702
+ { parse: (raw) => parseWebHierarchy(raw) }
2703
+ );
2704
+ flowCtx.sessions = sessions;
2705
+ const buildFailureResult = async (error) => {
2706
+ const attachments = await captureArtifacts(
2707
+ driver,
2708
+ artifactConfig,
2709
+ flow.name,
2710
+ platform,
2711
+ "failed"
2712
+ );
2713
+ const normalized = error instanceof Error ? error : new Error(String(error));
2714
+ return {
2715
+ name: flow.name,
2716
+ platform,
2717
+ status: "failed",
2718
+ durationMs: Date.now() - start2,
2719
+ error: classifyError(normalized),
2720
+ attachments,
2721
+ steps: stepRecorder.getSteps(),
2722
+ scenarioSteps: flowCtx.__scenarioSteps
2723
+ };
2724
+ };
2725
+ if (driver.beginFlow) {
2726
+ try {
2727
+ await Effect7.runPromise(driver.beginFlow(flow.name));
2728
+ } catch (error) {
2729
+ return buildFailureResult(error);
2730
+ }
2731
+ }
2732
+ if (config.hooks?.beforeEach) {
2733
+ try {
2734
+ await config.hooks.beforeEach({ app, platform });
2735
+ } catch (error) {
2736
+ return buildFailureResult(error);
2737
+ }
2738
+ }
2739
+ let result;
2740
+ try {
2741
+ if (autoLaunch) {
2742
+ await app.launch();
2743
+ }
2744
+ await Promise.race([
2745
+ flow.fn(flowCtx),
2746
+ new Promise(
2747
+ (_, reject) => setTimeout(
2748
+ () => reject(new Error(`Flow "${flow.name}" timed out after ${timeout}ms`)),
2749
+ timeout
2750
+ )
2751
+ )
2752
+ ]);
2753
+ const attachments = await captureArtifacts(
2754
+ driver,
2755
+ artifactConfig,
2756
+ flow.name,
2757
+ platform,
2758
+ "passed"
2759
+ );
2760
+ result = {
2761
+ name: flow.name,
2762
+ platform,
2763
+ status: "passed",
2764
+ durationMs: Date.now() - start2,
2765
+ attachments,
2766
+ steps: stepRecorder.getSteps(),
2767
+ scenarioSteps: flowCtx.__scenarioSteps
2768
+ };
2769
+ } catch (error) {
2770
+ const attachments = await captureArtifacts(
2771
+ driver,
2772
+ artifactConfig,
2773
+ flow.name,
2774
+ platform,
2775
+ "failed"
2776
+ );
2777
+ const flowError = error instanceof Error ? error : new Error(String(error));
2778
+ result = {
2779
+ name: flow.name,
2780
+ platform,
2781
+ status: "failed",
2782
+ durationMs: Date.now() - start2,
2783
+ error: classifyError(flowError),
2784
+ attachments,
2785
+ steps: stepRecorder.getSteps(),
2786
+ scenarioSteps: flowCtx.__scenarioSteps
2787
+ };
2788
+ if (artifactConfig.captureOnFailure && result.error) {
2789
+ try {
2790
+ const artDir = join4(
2791
+ artifactConfig.outputDir,
2792
+ `${flow.name.replaceAll(/[^a-zA-Z0-9-_]/g, "_").replaceAll(/_+/g, "_").slice(0, 80) || "artifact"}-${platform}`
2793
+ );
2794
+ const bundle = createFailureBundle(
2795
+ flow.name,
2796
+ platform,
2797
+ stepRecorder.getSteps(),
2798
+ result.error,
2799
+ artDir,
2800
+ attachments
2801
+ );
2802
+ writeFailureBundle(bundle, artDir);
2803
+ } catch {
2804
+ }
2805
+ }
2806
+ if (config.debugOnFailure) {
2807
+ await runDebugReplOnce({
2808
+ app,
2809
+ expect,
2810
+ driver,
2811
+ error: flowError,
2812
+ flowName: flow.name,
2813
+ platform,
2814
+ parseHierarchy: coordinatorConfig.parse
2815
+ });
2816
+ }
2817
+ }
2818
+ try {
2819
+ await sessionManager.disconnectAll();
2820
+ } catch {
2821
+ }
2822
+ if (config.hooks?.afterEach) {
2823
+ try {
2824
+ await config.hooks.afterEach({ app, platform, result });
2825
+ } catch (hookError) {
2826
+ console.warn(
2827
+ `afterEach hook failed: ${hookError instanceof Error ? hookError.message : hookError}`
2828
+ );
2829
+ }
2830
+ }
2831
+ return result;
2832
+ }
2833
+
2834
+ // src/core/parallel.ts
2835
+ function orderFlowsLongestFirst(flows, durationHintsMs) {
2836
+ if (!durationHintsMs || Object.keys(durationHintsMs).length === 0) {
2837
+ return flows;
2838
+ }
2839
+ return flows.toSorted((a, b) => (durationHintsMs[b.name] ?? 0) - (durationHintsMs[a.name] ?? 0));
2840
+ }
2841
+ async function runParallel(config) {
2842
+ const {
2843
+ workers,
2844
+ flows: rawFlows,
2845
+ onFlowComplete,
2846
+ onFlowStart,
2847
+ retries = 0,
2848
+ retryDelay = 0,
2849
+ bail,
2850
+ durationHintsMs
2851
+ } = config;
2852
+ const flows = orderFlowsLongestFirst(rawFlows, durationHintsMs);
2853
+ const start2 = Date.now();
2854
+ const results = [];
2855
+ let nextFlowIndex = 0;
2856
+ let failureCount = 0;
2857
+ let bailedOut = false;
2858
+ const workerPromises = workers.map(async (worker) => {
2859
+ const stats = { flowCount: 0, totalMs: 0 };
2860
+ while (true) {
2861
+ if (bail !== void 0 && failureCount >= bail) break;
2862
+ const flowIdx = nextFlowIndex++;
2863
+ if (flowIdx >= flows.length) break;
2864
+ const flow = flows[flowIdx];
2865
+ let result;
2866
+ let attempts = 0;
2867
+ onFlowStart?.(flow.name, worker.name);
2868
+ for (let attempt = 0; attempt <= retries; attempt++) {
2869
+ if (attempt > 0 && retryDelay > 0) {
2870
+ await new Promise((resolve) => setTimeout(resolve, retryDelay));
2871
+ }
2872
+ result = await executeFlow(flow, worker.driver, worker.engineConfig);
2873
+ attempts++;
2874
+ if (result.status === "passed") break;
2875
+ }
2876
+ if (result.status === "passed" && attempts > 1) {
2877
+ result.flaky = true;
2878
+ }
2879
+ result.attempts = attempts;
2880
+ results.push(result);
2881
+ stats.flowCount++;
2882
+ stats.totalMs += result.durationMs;
2883
+ if (result.status === "failed") {
2884
+ failureCount++;
2885
+ }
2886
+ onFlowComplete?.(result, worker.name);
2887
+ }
2888
+ return { workerId: worker.id, stats };
2889
+ });
2890
+ const workerResults = await Promise.all(workerPromises);
2891
+ if (bail !== void 0 && failureCount >= bail) {
2892
+ bailedOut = true;
2893
+ while (nextFlowIndex < flows.length) {
2894
+ const flow = flows[nextFlowIndex++];
2895
+ results.push({
2896
+ name: flow.name,
2897
+ platform: workers[0].engineConfig.platform,
2898
+ status: "skipped",
2899
+ durationMs: 0,
2900
+ attempts: 0
2901
+ });
2902
+ }
2903
+ }
2904
+ const workerStats = /* @__PURE__ */ new Map();
2905
+ for (const wr of workerResults) {
2906
+ workerStats.set(wr.workerId, wr.stats);
2907
+ }
2908
+ return {
2909
+ results,
2910
+ totalDurationMs: Date.now() - start2,
2911
+ passed: results.filter((r) => r.status === "passed").length,
2912
+ failed: results.filter((r) => r.status === "failed").length,
2913
+ skipped: results.filter((r) => r.status === "skipped").length,
2914
+ flaky: results.filter((r) => r.flaky === true).length,
2915
+ bailedOut: bailedOut || void 0,
2916
+ workerStats
2917
+ };
2918
+ }
2919
+
2920
+ export {
2921
+ launchDirectCdpBrowser,
2922
+ makeLightweightCdpDriver,
2923
+ speculativelyPrelaunchWebBrowser,
2924
+ buildWebRuntime,
2925
+ buildWebRuntimePool,
2926
+ buildElectronRuntime,
2927
+ buildElectrobunRuntime,
2928
+ buildLocalAndroidRuntime,
2929
+ buildLocalIOSRuntime,
2930
+ classifyError,
2931
+ executeFlow,
2932
+ orderFlowsLongestFirst,
2933
+ runParallel
2934
+ };
2935
+ //# sourceMappingURL=chunk-KEUZLBQS.js.map