spana-test 0.7.0 → 0.9.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 (96) hide show
  1. package/dist/agent/index.d.ts +2 -2
  2. package/dist/agent/index.js +9 -9
  3. package/dist/{allure-RNMEYTXS.js → allure-RAEK4SIH.js} +2 -2
  4. package/dist/allure-RAEK4SIH.js.map +1 -0
  5. package/dist/{android-4NVTZMHL.js → android-6BOQTMM3.js} +2 -2
  6. package/dist/app-DSh1ejLh.d.ts +1266 -0
  7. package/dist/{chunk-H27IBIGA.js → chunk-2AFWVHQK.js} +63 -43
  8. package/dist/chunk-2AFWVHQK.js.map +1 -0
  9. package/dist/{chunk-RURZVMZ7.js → chunk-2KRVN4WN.js} +3 -3
  10. package/dist/{chunk-T5CROOR7.js → chunk-3UVSUVHW.js} +1828 -299
  11. package/dist/chunk-3UVSUVHW.js.map +1 -0
  12. package/dist/{chunk-6B5Y75V4.js → chunk-ALPQES3J.js} +1001 -281
  13. package/dist/chunk-ALPQES3J.js.map +1 -0
  14. package/dist/{chunk-2IXXEXTL.js → chunk-FP6PVHHR.js} +2 -2
  15. package/dist/{chunk-KNSAHEXI.js → chunk-IGTK5MHB.js} +8 -8
  16. package/dist/chunk-JPZCZHL4.js +79 -0
  17. package/dist/chunk-JPZCZHL4.js.map +1 -0
  18. package/dist/{chunk-JYFPZRCN.js → chunk-JZZ2W2XH.js} +5 -2
  19. package/dist/chunk-JZZ2W2XH.js.map +1 -0
  20. package/dist/{chunk-HCG4CJKR.js → chunk-SF7UYW4I.js} +3 -3
  21. package/dist/{chunk-T3EBOYLS.js → chunk-UEWZ2EXL.js} +1314 -129
  22. package/dist/chunk-UEWZ2EXL.js.map +1 -0
  23. package/dist/{chunk-HYSTRWYN.js → chunk-VP6V4XEJ.js} +4 -4
  24. package/dist/{chunk-S5JNNDXS.js → chunk-WV3ALL3H.js} +65 -37
  25. package/dist/chunk-WV3ALL3H.js.map +1 -0
  26. package/dist/chunk-Z6K4QQAR.js +358 -0
  27. package/dist/chunk-Z6K4QQAR.js.map +1 -0
  28. package/dist/cli.js +23 -11
  29. package/dist/cli.js.map +1 -1
  30. package/dist/config-loader-F5YAY7RP.js +9 -0
  31. package/dist/{console-MI2XB5RG.js → console-BGAK7Z2L.js} +11 -1
  32. package/dist/{console-MI2XB5RG.js.map → console-BGAK7Z2L.js.map} +1 -1
  33. package/dist/{daemon-manager-FBISTX24.js → daemon-manager-2EQDVUVM.js} +10 -2
  34. package/dist/{discover-LHEBSUIP.js → discover-RLSKEBAX.js} +5 -5
  35. package/dist/{doctor-command-WPEVZEZ4.js → doctor-command-YTCQ2SC7.js} +26 -18
  36. package/dist/doctor-command-YTCQ2SC7.js.map +1 -0
  37. package/dist/{flow-g6AICPAl.d.ts → flow-CSMwD9Fh.d.ts} +3 -29
  38. package/dist/gherkin/steps.d.ts +2 -2
  39. package/dist/{html-IKCTZH2U.js → html-JO2YNRWX.js} +3 -3
  40. package/dist/html-JO2YNRWX.js.map +1 -0
  41. package/dist/index.d.ts +215 -21
  42. package/dist/index.js +246 -147
  43. package/dist/index.js.map +1 -1
  44. package/dist/{installer-VUPFWP5X.js → installer-5UHTYQTB.js} +4 -4
  45. package/dist/{ios-JPK43TFZ.js → ios-Y4TO5MBR.js} +7 -3
  46. package/dist/{server-EBPYK3VE.js → server-4YLBAZEM.js} +50 -36
  47. package/dist/server-4YLBAZEM.js.map +1 -0
  48. package/dist/{server-IGLBFEU7.js → server-IS4K5FCT.js} +2 -2
  49. package/dist/{session-cJ_tZjCL.d.ts → session-CgvT-Oso.d.ts} +3 -1
  50. package/dist/session-K7FCRKOC.js +18 -0
  51. package/dist/{studio-command-FLA5HKRK.js → studio-command-RFPV2DS7.js} +2 -2
  52. package/dist/{test-command-P5W7UD52.js → test-command-UEJG5AI6.js} +223 -27
  53. package/dist/test-command-UEJG5AI6.js.map +1 -0
  54. package/native/darwin-arm64/libspana_native.dylib +0 -0
  55. package/native/darwin-x64/libspana_native.dylib +0 -0
  56. package/native/linux-arm64/libspana_native.so +0 -0
  57. package/native/linux-x64/libspana_native.so +0 -0
  58. package/native/win32-x64/spana_native.dll +0 -0
  59. package/package.json +1 -1
  60. package/studio-dist/assets/index-CBFsOh-9.js +193 -0
  61. package/studio-dist/assets/index-DH_18EyL.css +1 -0
  62. package/studio-dist/index.html +2 -2
  63. package/dist/allure-RNMEYTXS.js.map +0 -1
  64. package/dist/app-D_UyZBsl.d.ts +0 -915
  65. package/dist/chunk-6B5Y75V4.js.map +0 -1
  66. package/dist/chunk-DTNK54C2.js +0 -127
  67. package/dist/chunk-DTNK54C2.js.map +0 -1
  68. package/dist/chunk-H27IBIGA.js.map +0 -1
  69. package/dist/chunk-JYFPZRCN.js.map +0 -1
  70. package/dist/chunk-OBCFACUW.js +0 -28
  71. package/dist/chunk-OBCFACUW.js.map +0 -1
  72. package/dist/chunk-S5JNNDXS.js.map +0 -1
  73. package/dist/chunk-T3EBOYLS.js.map +0 -1
  74. package/dist/chunk-T5CROOR7.js.map +0 -1
  75. package/dist/config-loader-NIDQGP3K.js +0 -9
  76. package/dist/doctor-command-WPEVZEZ4.js.map +0 -1
  77. package/dist/html-IKCTZH2U.js.map +0 -1
  78. package/dist/server-EBPYK3VE.js.map +0 -1
  79. package/dist/session-QRWH3SPW.js +0 -18
  80. package/dist/test-command-P5W7UD52.js.map +0 -1
  81. package/studio-dist/assets/index-C-Io44gy.js +0 -193
  82. package/studio-dist/assets/index-DfM9lK4p.css +0 -1
  83. /package/dist/{android-4NVTZMHL.js.map → android-6BOQTMM3.js.map} +0 -0
  84. /package/dist/{chunk-RURZVMZ7.js.map → chunk-2KRVN4WN.js.map} +0 -0
  85. /package/dist/{chunk-2IXXEXTL.js.map → chunk-FP6PVHHR.js.map} +0 -0
  86. /package/dist/{chunk-KNSAHEXI.js.map → chunk-IGTK5MHB.js.map} +0 -0
  87. /package/dist/{chunk-HCG4CJKR.js.map → chunk-SF7UYW4I.js.map} +0 -0
  88. /package/dist/{chunk-HYSTRWYN.js.map → chunk-VP6V4XEJ.js.map} +0 -0
  89. /package/dist/{config-loader-NIDQGP3K.js.map → config-loader-F5YAY7RP.js.map} +0 -0
  90. /package/dist/{daemon-manager-FBISTX24.js.map → daemon-manager-2EQDVUVM.js.map} +0 -0
  91. /package/dist/{discover-LHEBSUIP.js.map → discover-RLSKEBAX.js.map} +0 -0
  92. /package/dist/{installer-VUPFWP5X.js.map → installer-5UHTYQTB.js.map} +0 -0
  93. /package/dist/{ios-JPK43TFZ.js.map → ios-Y4TO5MBR.js.map} +0 -0
  94. /package/dist/{server-IGLBFEU7.js.map → server-IS4K5FCT.js.map} +0 -0
  95. /package/dist/{session-QRWH3SPW.js.map → session-K7FCRKOC.js.map} +0 -0
  96. /package/dist/{studio-command-FLA5HKRK.js.map → studio-command-RFPV2DS7.js.map} +0 -0
@@ -3,6 +3,7 @@ import {
3
3
  ElementNotFoundError,
4
4
  TextMismatchError,
5
5
  WaitTimeoutError,
6
+ buildDomActionabilityDiagScript,
6
7
  buildDomFillScript,
7
8
  buildDomQueryScript,
8
9
  buildDomScrollIntoViewScript,
@@ -14,11 +15,11 @@ import {
14
15
  createCompositeDomChannel,
15
16
  createWebKitInspectorChannel,
16
17
  domMatchToElement
17
- } from "./chunk-T3EBOYLS.js";
18
+ } from "./chunk-UEWZ2EXL.js";
18
19
  import {
19
20
  getHealthyWarmDaemon,
20
21
  registerWarmDaemon
21
- } from "./chunk-DTNK54C2.js";
22
+ } from "./chunk-Z6K4QQAR.js";
22
23
  import {
23
24
  installedUrlSchemesOnSimulator,
24
25
  launchOnSimulator,
@@ -28,11 +29,12 @@ import {
28
29
  pfctlSetThrottle,
29
30
  resetSimulatorKeychain,
30
31
  terminateOnSimulator
31
- } from "./chunk-S5JNNDXS.js";
32
+ } from "./chunk-WV3ALL3H.js";
32
33
  import {
34
+ allocateFreePort,
33
35
  allocatePort,
34
36
  releasePort
35
- } from "./chunk-OBCFACUW.js";
37
+ } from "./chunk-JPZCZHL4.js";
36
38
  import {
37
39
  adbClearApp,
38
40
  adbForceStop,
@@ -48,7 +50,7 @@ import {
48
50
  adbSetWifi,
49
51
  adbShell,
50
52
  findADB
51
- } from "./chunk-H27IBIGA.js";
53
+ } from "./chunk-2AFWVHQK.js";
52
54
 
53
55
  // src/schemas/selector.ts
54
56
  import { Schema } from "effect";
@@ -61,6 +63,16 @@ var _AccessibilityLabelSelectorSchema = Schema.Struct({
61
63
  accessibilityLabel: Schema.String,
62
64
  systemUI: Schema.optional(Schema.Boolean)
63
65
  });
66
+ var _RoleSelectorSchema = Schema.Struct({
67
+ role: Schema.String,
68
+ name: Schema.optional(Schema.String),
69
+ exact: Schema.optional(Schema.Boolean),
70
+ level: Schema.optional(Schema.Number),
71
+ includeHidden: Schema.optional(Schema.Boolean)
72
+ });
73
+ var _CssSelectorSchema = Schema.Struct({
74
+ css: Schema.String
75
+ });
64
76
  var _PointSelectorSchema = Schema.Struct({
65
77
  point: Schema.Struct({ x: Schema.Number, y: Schema.Number })
66
78
  });
@@ -69,11 +81,70 @@ var SelectorSchema = Schema.Union(
69
81
  _TestIDSelectorSchema,
70
82
  _TextSelectorSchema,
71
83
  _AccessibilityLabelSelectorSchema,
84
+ _RoleSelectorSchema,
85
+ _CssSelectorSchema,
72
86
  _PointSelectorSchema
73
87
  );
74
88
  function isRelativeSelector(sel) {
75
89
  return typeof sel === "object" && sel !== null && "selector" in sel;
76
90
  }
91
+ function toObjectSelector(sel) {
92
+ if (typeof sel === "string") {
93
+ return { text: sel };
94
+ }
95
+ return sel;
96
+ }
97
+ function byRole(role, nameOrOpts, opts) {
98
+ if (typeof nameOrOpts === "string" || nameOrOpts instanceof RegExp) {
99
+ return { role, name: nameOrOpts, ...opts };
100
+ }
101
+ return { role, ...nameOrOpts };
102
+ }
103
+ function byCss(css, opts) {
104
+ return { css, ...opts };
105
+ }
106
+ function or(...selectors) {
107
+ const flat = [];
108
+ for (const s of selectors) {
109
+ if (typeof s === "object" && s !== null && "anyOf" in s && Array.isArray(s.anyOf) && !("within" in s && s.within) && !("frame" in s && s.frame) && !("hasText" in s && s.hasText !== void 0) && !("hasNotText" in s && s.hasNotText !== void 0) && !("has" in s && s.has !== void 0) && !("hasNot" in s && s.hasNot !== void 0) && !("first" in s && s.first) && !("last" in s && s.last) && !("nth" in s && s.nth !== void 0)) {
110
+ flat.push(...s.anyOf);
111
+ } else {
112
+ flat.push(s);
113
+ }
114
+ }
115
+ return { anyOf: flat };
116
+ }
117
+ function within(parent, child) {
118
+ const obj = toObjectSelector(child);
119
+ if ("point" in obj) return obj;
120
+ const chainedWithin = obj.within ? within(parent, obj.within) : parent;
121
+ return { ...obj, within: chainedWithin };
122
+ }
123
+ function inFrame(frame, child) {
124
+ const obj = toObjectSelector(child);
125
+ if ("point" in obj) return obj;
126
+ return { ...obj, frame };
127
+ }
128
+ function nth(sel, index) {
129
+ const obj = toObjectSelector(sel);
130
+ if ("point" in obj) return obj;
131
+ return { ...obj, nth: index, first: void 0, last: void 0 };
132
+ }
133
+ function first(sel) {
134
+ const obj = toObjectSelector(sel);
135
+ if ("point" in obj) return obj;
136
+ return { ...obj, first: true, last: void 0, nth: void 0 };
137
+ }
138
+ function last(sel) {
139
+ const obj = toObjectSelector(sel);
140
+ if ("point" in obj) return obj;
141
+ return { ...obj, last: true, first: void 0, nth: void 0 };
142
+ }
143
+ function filterSelector(sel, filter) {
144
+ const obj = toObjectSelector(sel);
145
+ if ("point" in obj) return obj;
146
+ return { ...obj, ...filter };
147
+ }
77
148
  function systemUI(selector) {
78
149
  return { ...selector, systemUI: true };
79
150
  }
@@ -87,6 +158,10 @@ function isSystemUISelector(sel) {
87
158
  function isTestIDSelector(sel) {
88
159
  return typeof sel === "object" && sel !== null && "testID" in sel && !isRelativeSelector(sel);
89
160
  }
161
+ function isComposableDomSelector(sel) {
162
+ if (typeof sel !== "object" || sel === null || isRelativeSelector(sel)) return false;
163
+ return "role" in sel || "css" in sel || "anyOf" in sel || "within" in sel || "frame" in sel || "hasText" in sel || "hasNotText" in sel || "has" in sel || "hasNot" in sel || "nth" in sel || "first" in sel || "last" in sel;
164
+ }
90
165
 
91
166
  // src/smart/element-matcher.ts
92
167
  function flattenElements(root) {
@@ -107,24 +182,65 @@ function matchesSelector(element, selector) {
107
182
  if (typeof selector === "string") {
108
183
  return element.text?.toLowerCase().includes(selector.toLowerCase()) ?? false;
109
184
  }
185
+ let baseMatch = false;
110
186
  if ("testID" in selector) {
111
- return element.id === selector.testID;
112
- }
113
- if ("text" in selector) {
114
- return element.text?.toLowerCase().includes(selector.text.toLowerCase()) ?? false;
115
- }
116
- if ("accessibilityLabel" in selector) {
117
- return element.accessibilityLabel === selector.accessibilityLabel;
118
- }
119
- if ("point" in selector) {
187
+ baseMatch = element.id === selector.testID;
188
+ } else if ("text" in selector) {
189
+ baseMatch = selector.exact ? element.text === selector.text : element.text?.toLowerCase().includes(selector.text.toLowerCase()) ?? false;
190
+ } else if ("accessibilityLabel" in selector) {
191
+ baseMatch = element.accessibilityLabel === selector.accessibilityLabel;
192
+ } else if ("role" in selector) {
193
+ const elRole = (element.attributes?.role ?? element.elementType ?? "").toLowerCase();
194
+ const roleMatch = elRole === selector.role.toLowerCase();
195
+ if (!roleMatch) return false;
196
+ if (selector.name === void 0) {
197
+ baseMatch = true;
198
+ } else {
199
+ const candidateName = element.accessibilityLabel ?? element.text ?? "";
200
+ baseMatch = selector.name instanceof RegExp ? selector.name.test(candidateName) : selector.exact ? candidateName === selector.name : candidateName.toLowerCase().includes(selector.name.toLowerCase());
201
+ }
202
+ } else if ("css" in selector) {
203
+ baseMatch = false;
204
+ } else if ("anyOf" in selector && Array.isArray(selector.anyOf)) {
205
+ baseMatch = selector.anyOf.some((branch) => matchesSelector(element, branch));
206
+ } else if ("point" in selector) {
120
207
  const { x, y } = selector.point;
121
208
  const b = element.bounds;
122
- return x >= b.x && x <= b.x + b.width && y >= b.y && y <= b.y + b.height;
209
+ baseMatch = x >= b.x && x <= b.x + b.width && y >= b.y && y <= b.y + b.height;
210
+ }
211
+ if (!baseMatch) return false;
212
+ if (!("point" in selector)) {
213
+ const text = element.text ?? element.accessibilityLabel ?? "";
214
+ if (selector.hasText !== void 0) {
215
+ const ok = selector.hasText instanceof RegExp ? selector.hasText.test(text) : text.toLowerCase().includes(selector.hasText.toLowerCase());
216
+ if (!ok) return false;
217
+ }
218
+ if (selector.hasNotText !== void 0) {
219
+ const bad = selector.hasNotText instanceof RegExp ? selector.hasNotText.test(text) : text.toLowerCase().includes(selector.hasNotText.toLowerCase());
220
+ if (bad) return false;
221
+ }
222
+ if (selector.has !== void 0) {
223
+ const descendants = flattenElements(element).slice(1);
224
+ if (!descendants.some((d) => matchesSelector(d, selector.has))) return false;
225
+ }
226
+ if (selector.hasNot !== void 0) {
227
+ const descendants = flattenElements(element).slice(1);
228
+ if (descendants.some((d) => matchesSelector(d, selector.hasNot))) return false;
229
+ }
123
230
  }
124
- return false;
231
+ return true;
125
232
  }
126
233
  function findElements(root, selector) {
127
- return flattenElements(root).filter((el) => matchesSelector(el, selector));
234
+ const matched = flattenElements(root).filter((el) => matchesSelector(el, selector));
235
+ if (typeof selector === "object" && selector !== null && !("point" in selector)) {
236
+ if (selector.first) return matched.length > 0 ? [matched[0]] : [];
237
+ if (selector.last) return matched.length > 0 ? [matched[matched.length - 1]] : [];
238
+ if (selector.nth !== void 0) {
239
+ const idx = selector.nth < 0 ? matched.length + selector.nth : selector.nth;
240
+ return idx >= 0 && idx < matched.length ? [matched[idx]] : [];
241
+ }
242
+ }
243
+ return matched;
128
244
  }
129
245
  function isProbablyOnScreen(element) {
130
246
  const centerX = element.bounds.x + element.bounds.width / 2;
@@ -192,11 +308,42 @@ function formatSelector(sel) {
192
308
  }
193
309
  function formatSimpleSelector(sel) {
194
310
  if (typeof sel === "string") return `"${sel}"`;
195
- if ("testID" in sel) return `testID: "${sel.testID}"`;
196
- if ("text" in sel) return `text: "${sel.text}"`;
197
- if ("accessibilityLabel" in sel) return `accessibilityLabel: "${sel.accessibilityLabel}"`;
198
- if ("point" in sel) return `point: (${sel.point.x}, ${sel.point.y})`;
199
- return JSON.stringify(sel);
311
+ let base;
312
+ if ("testID" in sel) base = `testID: "${sel.testID}"`;
313
+ else if ("text" in sel) base = `text: "${sel.text}"`;
314
+ else if ("accessibilityLabel" in sel) base = `accessibilityLabel: "${sel.accessibilityLabel}"`;
315
+ else if ("role" in sel) {
316
+ const parts = [`role: "${sel.role}"`];
317
+ if (sel.name !== void 0) {
318
+ parts.push(
319
+ `name: ${sel.name instanceof RegExp ? sel.name.toString() : JSON.stringify(sel.name)}`
320
+ );
321
+ }
322
+ if (sel.level !== void 0) parts.push(`level: ${sel.level}`);
323
+ base = parts.join(", ");
324
+ } else if ("css" in sel) base = `css: "${sel.css}"`;
325
+ else if ("anyOf" in sel) base = `or(${sel.anyOf.map(formatSimpleSelector).join(", ")})`;
326
+ else if ("point" in sel) return `point: (${sel.point.x}, ${sel.point.y})`;
327
+ else return JSON.stringify(sel);
328
+ const mods = [];
329
+ if (sel.frame) mods.push(`inFrame(${formatSimpleSelector(sel.frame)})`);
330
+ if (sel.within) mods.push(`within(${formatSimpleSelector(sel.within)})`);
331
+ if (sel.hasText !== void 0) {
332
+ mods.push(
333
+ `hasText(${sel.hasText instanceof RegExp ? sel.hasText.toString() : JSON.stringify(sel.hasText)})`
334
+ );
335
+ }
336
+ if (sel.hasNotText !== void 0) {
337
+ mods.push(
338
+ `hasNotText(${sel.hasNotText instanceof RegExp ? sel.hasNotText.toString() : JSON.stringify(sel.hasNotText)})`
339
+ );
340
+ }
341
+ if (sel.has !== void 0) mods.push(`has(${formatSimpleSelector(sel.has)})`);
342
+ if (sel.hasNot !== void 0) mods.push(`hasNot(${formatSimpleSelector(sel.hasNot)})`);
343
+ if (sel.first) mods.push("first");
344
+ else if (sel.last) mods.push("last");
345
+ else if (sel.nth !== void 0) mods.push(`nth(${sel.nth})`);
346
+ return mods.length > 0 ? `${base} [${mods.join(", ")}]` : base;
200
347
  }
201
348
  function findElementExtended(root, selector) {
202
349
  if (!isRelativeSelector(selector)) {
@@ -324,12 +471,12 @@ function resolveElementAcrossChannels(driver, selector, parse, cache, options =
324
471
  const isSystemUI = isSystemUISelector(selector);
325
472
  const forAction = options.forAction ?? false;
326
473
  const tapMode = options.tapMode ?? "native";
327
- const canTryDom = !isSystemUI && !isRelativeSelector(selector) && domChannel !== void 0 && (isTestIDSelector(selector) || domChannel.isConnected());
474
+ const canTryDom = !isSystemUI && !isRelativeSelector(selector) && domChannel !== void 0 && (isTestIDSelector(selector) || isComposableDomSelector(selector) || domChannel.isConnected());
328
475
  if (canTryDom) {
329
476
  const domMatches = yield* Effect.tryPromise({
330
477
  try: async () => {
331
478
  if (!domChannel.isConnected()) {
332
- if (!isTestIDSelector(selector)) return [];
479
+ if (!isTestIDSelector(selector) && !isComposableDomSelector(selector)) return [];
333
480
  try {
334
481
  await domChannel.connect();
335
482
  } catch {
@@ -558,7 +705,7 @@ function waitForResolvedAcrossChannels(driver, selector, parse, forAction, opts,
558
705
  const start = Date.now();
559
706
  let waitedForIdle = false;
560
707
  let isFirstPoll = true;
561
- const canReactiveDomWait = !isSystemUISelector(selector) && !isRelativeSelectorLike(selector) && (opts?.platform === "web" || isTestIDSelector(selector));
708
+ const canReactiveDomWait = !isSystemUISelector(selector) && !isRelativeSelectorLike(selector) && (opts?.platform === "web" || isTestIDSelector(selector) || isComposableDomSelector(selector));
562
709
  const initialDomChannel = driver.domChannel;
563
710
  if (opts?.platform === "web" && canReactiveDomWait && settleTimeout === 0 && initialDomChannel?.isConnected() && initialDomChannel.waitForSelector) {
564
711
  const reactiveMatches = yield* Effect2.tryPromise({
@@ -566,7 +713,8 @@ function waitForResolvedAcrossChannels(driver, selector, parse, forAction, opts,
566
713
  timeoutMs: timeout,
567
714
  forAction,
568
715
  failFastWhenIdle: opts?.failFastWhenIdle,
569
- idleQuietMs: opts?.idleQuietMs
716
+ idleQuietMs: opts?.idleQuietMs,
717
+ ...opts?.actionStableFrames !== void 0 ? { stableFrames: opts.actionStableFrames } : {}
570
718
  }),
571
719
  catch: () => null
572
720
  }).pipe(Effect2.catchAll(() => Effect2.succeed(null)));
@@ -579,7 +727,27 @@ function waitForResolvedAcrossChannels(driver, selector, parse, forAction, opts,
579
727
  domMatch: match
580
728
  };
581
729
  }
582
- if (Array.isArray(reactiveMatches) && reactiveMatches.length === 0 && (opts?.failFastWhenIdle || Date.now() - start >= timeout)) {
730
+ if (Array.isArray(reactiveMatches) && reactiveMatches.length === 0 && (forAction || opts?.failFastWhenIdle || Date.now() - start >= timeout)) {
731
+ if (forAction) {
732
+ const actionDiag = yield* Effect2.tryPromise({
733
+ try: () => initialDomChannel.evaluate(buildDomActionabilityDiagScript(selector)),
734
+ catch: () => null
735
+ }).pipe(Effect2.catchAll(() => Effect2.succeed(null)));
736
+ if (actionDiag?.found && actionDiag.obstructedBy) {
737
+ return yield* new ElementNotFoundError({
738
+ message: `Element is covered by ${actionDiag.obstructedBy} (not actionable within ${timeout}ms) \u2014 selector: ${formatSelector(selector)}`,
739
+ selector,
740
+ timeoutMs: timeout
741
+ });
742
+ }
743
+ if (actionDiag?.found && actionDiag.visible && actionDiag.enabled === false) {
744
+ return yield* new ElementNotFoundError({
745
+ message: `Element is disabled (not actionable within ${timeout}ms) \u2014 selector: ${formatSelector(selector)}`,
746
+ selector,
747
+ timeoutMs: timeout
748
+ });
749
+ }
750
+ }
583
751
  if (cache) cache.invalidate();
584
752
  const diagRoot2 = yield* getHierarchy(driver, parse, cache);
585
753
  const diagnostic2 = diagnoseElementNotFound(diagRoot2, selector);
@@ -592,7 +760,7 @@ ${diagMessage2}`,
592
760
  });
593
761
  }
594
762
  }
595
- while (Date.now() - start < timeout) {
763
+ while (isFirstPoll || Date.now() - start < timeout) {
596
764
  if (!isFirstPoll && cache) cache.invalidate();
597
765
  isFirstPoll = false;
598
766
  const resolved = yield* resolveElementAcrossChannels(driver, selector, parse, cache, {
@@ -623,7 +791,8 @@ ${diagMessage2}`,
623
791
  timeoutMs: Math.min(remaining, opts?.platform === "web" ? remaining : 1e3),
624
792
  forAction,
625
793
  failFastWhenIdle: opts?.failFastWhenIdle,
626
- idleQuietMs: opts?.idleQuietMs
794
+ idleQuietMs: opts?.idleQuietMs,
795
+ ...opts?.actionStableFrames !== void 0 ? { stableFrames: opts.actionStableFrames } : {}
627
796
  }),
628
797
  catch: () => null
629
798
  }).pipe(Effect2.catchAll(() => Effect2.succeed(null)));
@@ -681,7 +850,7 @@ function waitForNotVisible(driver, selector, parse, opts, cache) {
681
850
  let waitedForIdle = false;
682
851
  let isFirstPoll = true;
683
852
  const domChannel = driver.domChannel;
684
- const canReactiveHidden = !isSystemUISelector(selector) && !isRelativeSelectorLike(selector) && (opts?.platform === "web" || isTestIDSelector(selector));
853
+ const canReactiveHidden = !isSystemUISelector(selector) && !isRelativeSelectorLike(selector) && (opts?.platform === "web" || isTestIDSelector(selector) || isComposableDomSelector(selector));
685
854
  if (canReactiveHidden && domChannel?.isConnected() && domChannel.waitForHidden) {
686
855
  const hidden = yield* Effect2.tryPromise({
687
856
  try: () => domChannel.waitForHidden(selector, { timeoutMs: timeout }),
@@ -696,7 +865,7 @@ function waitForNotVisible(driver, selector, parse, opts, cache) {
696
865
  });
697
866
  }
698
867
  }
699
- while (Date.now() - start < timeout) {
868
+ while (isFirstPoll || Date.now() - start < timeout) {
700
869
  if (!isFirstPoll && cache) cache.invalidate();
701
870
  isFirstPoll = false;
702
871
  const resolved = yield* resolveElementAcrossChannels(driver, selector, parse, cache, {
@@ -817,7 +986,14 @@ function createCoordinator(driver, config) {
817
986
  500
818
987
  );
819
988
  if (config.platform !== "web") {
820
- yield* Effect4.promise(() => new Promise((r) => setTimeout(r, 300)));
989
+ if (driver.domChannel?.isConnected() && driver.domChannel.waitForIdle) {
990
+ yield* Effect4.tryPromise({
991
+ try: () => driver.domChannel.waitForIdle({ timeout: 150, quietPeriodMs: 30 }),
992
+ catch: () => void 0
993
+ }).pipe(Effect4.catchAll(() => Effect4.void));
994
+ } else {
995
+ yield* Effect4.promise(() => new Promise((r) => setTimeout(r, 100)));
996
+ }
821
997
  }
822
998
  yield* afterMutation();
823
999
  });
@@ -850,7 +1026,24 @@ function createCoordinator(driver, config) {
850
1026
  };
851
1027
  return directionMap[direction];
852
1028
  };
853
- const pollUntilMatch = (selector, opts, check, formatError, domMatchSpec) => Effect4.gen(function* () {
1029
+ const normalizeWhitespace = (s) => s.replaceAll(/\s+/g, " ").trim();
1030
+ const collectContainerText = (el) => {
1031
+ if (el.text) return el.text;
1032
+ const parts = [];
1033
+ const stack = [...el.children ?? []].toReversed();
1034
+ while (stack.length > 0) {
1035
+ const node = stack.pop();
1036
+ if (node.visible === false) continue;
1037
+ if (node.text) parts.push(node.text);
1038
+ if (node.children) {
1039
+ for (let i = node.children.length - 1; i >= 0; i--) {
1040
+ stack.push(node.children[i]);
1041
+ }
1042
+ }
1043
+ }
1044
+ return parts.join(" ").trim();
1045
+ };
1046
+ const pollUntilMatch = (selector, opts, check, formatError, domMatchSpec, negate = false) => Effect4.gen(function* () {
854
1047
  const timeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
855
1048
  const pollInterval = opts?.pollInterval ?? defaults?.pollInterval ?? 200;
856
1049
  const start = Date.now();
@@ -860,6 +1053,7 @@ function createCoordinator(driver, config) {
860
1053
  const reactive = yield* Effect4.tryPromise({
861
1054
  try: () => domChannel.waitForMatch(selector, {
862
1055
  ...domMatchSpec,
1056
+ ...negate ? { negate: true } : {},
863
1057
  timeoutMs: timeout
864
1058
  }),
865
1059
  catch: () => null
@@ -885,7 +1079,7 @@ function createCoordinator(driver, config) {
885
1079
  const element = resolved?.element;
886
1080
  if (element) {
887
1081
  const result = check(element);
888
- if (result.matched) return;
1082
+ if (negate ? !result.matched : result.matched) return;
889
1083
  lastActual = result.actual;
890
1084
  }
891
1085
  yield* Effect4.sleep(Duration2.millis(pollInterval));
@@ -949,32 +1143,45 @@ function createCoordinator(driver, config) {
949
1143
  const createAssertions = () => ({
950
1144
  assertVisible: (selector, opts) => waitForElement(driver, selector, parse, { ...defaults, ...opts }, cache),
951
1145
  assertHidden: (selector, opts) => waitForNotVisible(driver, selector, parse, { ...defaults, ...opts }, cache),
952
- assertText: (selector, expected, opts) => pollUntilMatch(
953
- selector,
954
- opts,
955
- (el) => ({ matched: el.text === expected, actual: el.text }),
956
- (actual, timeout) => ({
957
- message: `Expected text "${expected}" but got "${actual ?? "(no text)"}" after ${timeout}ms`,
958
- expected
959
- }),
960
- { kind: "text", expected }
961
- ),
962
- assertContainsText: (selector, expected, opts) => pollUntilMatch(
963
- selector,
964
- opts,
965
- (el) => {
966
- const actual = el.text ?? "";
967
- return {
968
- matched: actual.toLowerCase().includes(expected.toLowerCase()),
969
- actual: el.text
970
- };
971
- },
972
- (actual, timeout) => ({
973
- message: `Expected text to contain "${expected}" but got "${actual ?? "(no text)"}" after ${timeout}ms`,
974
- expected
975
- }),
976
- { kind: "containsText", expected }
977
- ),
1146
+ assertText: (selector, expected, opts, negate = false) => {
1147
+ const normalizedExpected = normalizeWhitespace(expected);
1148
+ return pollUntilMatch(
1149
+ selector,
1150
+ opts,
1151
+ (el) => {
1152
+ const raw = el.textContent ?? el.text;
1153
+ const actual = raw !== void 0 ? normalizeWhitespace(raw) : void 0;
1154
+ return { matched: actual === normalizedExpected, actual };
1155
+ },
1156
+ (actual, timeout) => ({
1157
+ message: negate ? `Expected text NOT to be "${expected}" after ${timeout}ms` : `Expected text "${expected}" but got "${actual ?? "(no text)"}" after ${timeout}ms`,
1158
+ expected: negate ? `not ${expected}` : expected
1159
+ }),
1160
+ { kind: "text", expected },
1161
+ negate
1162
+ );
1163
+ },
1164
+ assertContainsText: (selector, expected, opts, negate = false) => {
1165
+ const normalizedExpected = normalizeWhitespace(expected).toLowerCase();
1166
+ return pollUntilMatch(
1167
+ selector,
1168
+ opts,
1169
+ (el) => {
1170
+ const raw = el.textContent ?? el.text ?? "";
1171
+ const actual = normalizeWhitespace(raw);
1172
+ return {
1173
+ matched: actual.toLowerCase().includes(normalizedExpected),
1174
+ actual
1175
+ };
1176
+ },
1177
+ (actual, timeout) => ({
1178
+ message: negate ? `Expected text NOT to contain "${expected}" but got "${actual ?? "(no text)"}" after ${timeout}ms` : `Expected text to contain "${expected}" but got "${actual ?? "(no text)"}" after ${timeout}ms`,
1179
+ expected: negate ? `not containing ${expected}` : expected
1180
+ }),
1181
+ { kind: "containsText", expected },
1182
+ negate
1183
+ );
1184
+ },
978
1185
  assertEnabled: (selector, opts) => assertEnabledState(selector, true, opts),
979
1186
  assertDisabled: (selector, opts) => assertEnabledState(selector, false, opts),
980
1187
  getText: (selector, opts) => Effect4.gen(function* () {
@@ -982,22 +1189,45 @@ function createCoordinator(driver, config) {
982
1189
  driver,
983
1190
  selector,
984
1191
  parse,
985
- { ...defaults, ...opts },
1192
+ { ...defaults, ...opts, platform: opts?.platform ?? config.platform },
986
1193
  cache
987
1194
  );
988
- return element.text ?? "";
1195
+ return collectContainerText(element);
1196
+ }),
1197
+ count: (selector, opts) => Effect4.gen(function* () {
1198
+ cache.invalidate();
1199
+ const domChannel = driver.domChannel;
1200
+ if (!isSystemUISelector(selector) && !isRelativeSelectorLike2(selector) && domChannel?.isConnected()) {
1201
+ const matches = yield* Effect4.tryPromise({
1202
+ try: () => domChannel.query(selector),
1203
+ catch: () => null
1204
+ }).pipe(Effect4.catchAll(() => Effect4.succeed(null)));
1205
+ if (matches) {
1206
+ return matches.filter((m) => m.visible).length;
1207
+ }
1208
+ }
1209
+ const raw = yield* driver.dumpHierarchy();
1210
+ const root = parse(raw);
1211
+ if (isRelativeSelectorLike2(selector)) {
1212
+ const resolved = yield* resolveElementAcrossChannels(driver, selector, parse, cache, {
1213
+ forAction: false,
1214
+ platform: opts?.platform ?? config.platform
1215
+ });
1216
+ return resolved ? 1 : 0;
1217
+ }
1218
+ return findElements(root, selector).filter((el) => el.visible !== false).length;
989
1219
  }),
990
1220
  isElementEnabled: (selector, opts) => Effect4.gen(function* () {
991
1221
  const element = yield* waitForElement(
992
1222
  driver,
993
1223
  selector,
994
1224
  parse,
995
- { ...defaults, ...opts },
1225
+ { ...defaults, ...opts, platform: opts?.platform ?? config.platform },
996
1226
  cache
997
1227
  );
998
1228
  return element.enabled !== false;
999
1229
  }),
1000
- assertValue: (selector, expected, opts) => {
1230
+ assertValue: (selector, expected, opts, negate = false) => {
1001
1231
  const expectedStr = String(expected);
1002
1232
  return pollUntilMatch(
1003
1233
  selector,
@@ -1007,13 +1237,14 @@ function createCoordinator(driver, config) {
1007
1237
  return { matched: actual === expectedStr, actual };
1008
1238
  },
1009
1239
  (actual, timeout) => ({
1010
- message: `Expected value "${expectedStr}" but got "${actual ?? "(no value)"}" after ${timeout}ms`,
1011
- expected: expectedStr
1240
+ message: negate ? `Expected value NOT to be "${expectedStr}" after ${timeout}ms` : `Expected value "${expectedStr}" but got "${actual ?? "(no value)"}" after ${timeout}ms`,
1241
+ expected: negate ? `not ${expectedStr}` : expectedStr
1012
1242
  }),
1013
- { kind: "value", expected: expectedStr }
1243
+ { kind: "value", expected: expectedStr },
1244
+ negate
1014
1245
  );
1015
1246
  },
1016
- assertAttribute: (selector, name, expectedValue, opts) => pollUntilMatch(
1247
+ assertAttribute: (selector, name, expectedValue, opts, negate = false) => pollUntilMatch(
1017
1248
  selector,
1018
1249
  opts,
1019
1250
  (el) => {
@@ -1023,34 +1254,66 @@ function createCoordinator(driver, config) {
1023
1254
  }
1024
1255
  return { matched: actual === expectedValue, actual };
1025
1256
  },
1026
- (actual, timeout) => expectedValue === void 0 ? {
1257
+ (actual, timeout) => negate ? expectedValue === void 0 ? {
1258
+ message: `Expected attribute "${name}" NOT to exist but got "${actual ?? ""}" after ${timeout}ms`,
1259
+ expected: `not ${name}`
1260
+ } : {
1261
+ message: `Expected attribute "${name}" NOT to be "${expectedValue}" after ${timeout}ms`,
1262
+ expected: `not ${expectedValue}`
1263
+ } : expectedValue === void 0 ? {
1027
1264
  message: `Expected attribute "${name}" to exist but it was not found after ${timeout}ms`,
1028
1265
  expected: name
1029
1266
  } : {
1030
1267
  message: `Expected attribute "${name}" to be "${expectedValue}" but got "${actual ?? "(not found)"}" after ${timeout}ms`,
1031
1268
  expected: expectedValue
1032
1269
  },
1033
- { kind: "attribute", attributeName: name, expected: expectedValue }
1270
+ { kind: "attribute", attributeName: name, expected: expectedValue },
1271
+ negate
1034
1272
  ),
1035
- assertMatchesText: (selector, pattern, opts) => pollUntilMatch(
1273
+ assertMatchesText: (selector, pattern, opts, negate = false) => pollUntilMatch(
1036
1274
  selector,
1037
1275
  opts,
1038
1276
  (el) => {
1039
- const actual = el.text ?? "";
1277
+ const actual = normalizeWhitespace(el.textContent ?? el.text ?? "");
1040
1278
  return { matched: pattern.test(actual), actual };
1041
1279
  },
1042
1280
  (actual, timeout) => ({
1043
- message: `Expected text to match ${pattern} but got "${actual ?? "(no text)"}" after ${timeout}ms`,
1044
- expected: String(pattern)
1281
+ message: negate ? `Expected text NOT to match ${pattern} but got "${actual ?? "(no text)"}" after ${timeout}ms` : `Expected text to match ${pattern} but got "${actual ?? "(no text)"}" after ${timeout}ms`,
1282
+ expected: negate ? `not ${String(pattern)}` : String(pattern)
1045
1283
  }),
1046
- { kind: "matchesText", patternSource: pattern.source, patternFlags: pattern.flags }
1284
+ { kind: "matchesText", patternSource: pattern.source, patternFlags: pattern.flags },
1285
+ negate
1047
1286
  ),
1048
1287
  getAttribute: (selector, name, opts) => Effect4.gen(function* () {
1288
+ const timeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
1289
+ const pollInterval = opts?.pollInterval ?? defaults?.pollInterval ?? 100;
1290
+ const domChannel = driver.domChannel;
1291
+ if (!isSystemUISelector(selector) && !isRelativeSelectorLike2(selector) && domChannel?.isConnected()) {
1292
+ const start = Date.now();
1293
+ while (true) {
1294
+ const matches = yield* Effect4.tryPromise({
1295
+ try: () => domChannel.query(selector),
1296
+ catch: () => null
1297
+ }).pipe(Effect4.catchAll(() => Effect4.succeed(null)));
1298
+ if (matches && matches.length > 0) {
1299
+ const target = matches[matches.length - 1];
1300
+ return target.attributes?.[name];
1301
+ }
1302
+ if (Date.now() - start >= timeout) {
1303
+ return yield* new ElementNotFoundError({
1304
+ message: `Element not found within ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1305
+ selector,
1306
+ timeoutMs: timeout
1307
+ });
1308
+ }
1309
+ yield* Effect4.sleep(Duration2.millis(Math.min(pollInterval, 100)));
1310
+ }
1311
+ }
1049
1312
  const element = yield* waitForElement(
1050
1313
  driver,
1051
1314
  selector,
1052
1315
  parse,
1053
- { ...defaults, ...opts },
1316
+ { ...defaults, ...opts, platform: opts?.platform ?? config.platform },
1054
1317
  cache
1055
1318
  );
1056
1319
  return element.attributes?.[name];
@@ -1096,11 +1359,11 @@ function createCoordinator(driver, config) {
1096
1359
  });
1097
1360
  if (!result.match) {
1098
1361
  const { writeFileSync, mkdirSync } = yield* Effect4.promise(() => import("fs"));
1099
- const { join: join2 } = yield* Effect4.promise(() => import("path"));
1362
+ const { join: join3 } = yield* Effect4.promise(() => import("path"));
1100
1363
  const outDir = options.outputDir ?? config.outputDir ?? "spana-output";
1101
1364
  mkdirSync(outDir, { recursive: true });
1102
1365
  const safeFlowName = flowName.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-").replaceAll(/^-|-$/g, "");
1103
- const prefix = join2(outDir, `${safeFlowName}-${platform}-${name}`);
1366
+ const prefix = join3(outDir, `${safeFlowName}-${platform}-${name}`);
1104
1367
  writeFileSync(`${prefix}-expected.png`, existing);
1105
1368
  writeFileSync(`${prefix}-actual.png`, actualBuf);
1106
1369
  if (result.diffImage) {
@@ -1131,6 +1394,157 @@ function createCoordinator(driver, config) {
1131
1394
  },
1132
1395
  { kind: "accessibilityLabel", expected }
1133
1396
  ),
1397
+ assertAccessibleName: (selector, expected, opts, negate = false) => pollUntilMatch(
1398
+ selector,
1399
+ opts,
1400
+ (el) => {
1401
+ const actual = el.accessibilityLabel || el.text || "";
1402
+ const matched = expected instanceof RegExp ? expected.test(actual) : actual.trim() === expected.trim();
1403
+ return { matched, actual };
1404
+ },
1405
+ (actual, timeout) => ({
1406
+ message: negate ? `Expected accessible name NOT to match ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got "${actual ?? "(none)"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}` : `Expected accessible name ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got "${actual ?? "(none)"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1407
+ expected: negate ? `not ${String(expected)}` : String(expected)
1408
+ }),
1409
+ expected instanceof RegExp ? {
1410
+ kind: "accessibleName",
1411
+ patternSource: expected.source,
1412
+ patternFlags: expected.flags
1413
+ } : { kind: "accessibleName", expected },
1414
+ negate
1415
+ ),
1416
+ assertAccessibleDescription: (selector, expected, opts, negate = false) => pollUntilMatch(
1417
+ selector,
1418
+ opts,
1419
+ (el) => {
1420
+ const actual = el.accessibleDescription ?? el.attributes?.["aria-description"] ?? "";
1421
+ const matched = expected instanceof RegExp ? expected.test(actual) : actual.trim() === expected.trim();
1422
+ return { matched, actual };
1423
+ },
1424
+ (actual, timeout) => ({
1425
+ message: negate ? `Expected accessible description NOT to match ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got "${actual ?? "(none)"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}` : `Expected accessible description ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got "${actual ?? "(none)"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1426
+ expected: negate ? `not ${String(expected)}` : String(expected)
1427
+ }),
1428
+ expected instanceof RegExp ? {
1429
+ kind: "accessibleDescription",
1430
+ patternSource: expected.source,
1431
+ patternFlags: expected.flags
1432
+ } : { kind: "accessibleDescription", expected },
1433
+ negate
1434
+ ),
1435
+ assertFocused: (selector, opts, negate = false) => pollUntilMatch(
1436
+ selector,
1437
+ opts,
1438
+ (el) => ({
1439
+ matched: el.focused === true,
1440
+ actual: el.focused ? "focused" : "not focused"
1441
+ }),
1442
+ (actual, timeout) => ({
1443
+ message: negate ? `Expected element NOT to be focused but it was "${actual ?? "focused"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}` : `Expected element to be focused but it was "${actual ?? "not focused"}" after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1444
+ expected: negate ? "not focused" : "focused"
1445
+ }),
1446
+ { kind: "focused" },
1447
+ negate
1448
+ ),
1449
+ assertCount: (selector, expectedCount, opts, negate = false) => Effect4.gen(function* () {
1450
+ const timeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
1451
+ const pollInterval = opts?.pollInterval ?? defaults?.pollInterval ?? 200;
1452
+ const start = Date.now();
1453
+ let lastCount = -1;
1454
+ const domChannel = driver.domChannel;
1455
+ if (config.platform === "web" && !isSystemUISelector(selector) && !isRelativeSelectorLike2(selector) && domChannel?.isConnected() && domChannel.waitForMatch) {
1456
+ const reactive = yield* Effect4.tryPromise({
1457
+ try: () => domChannel.waitForMatch(selector, {
1458
+ kind: "count",
1459
+ expectedCount,
1460
+ ...negate ? { negate: true } : {},
1461
+ timeoutMs: timeout
1462
+ }),
1463
+ catch: () => null
1464
+ }).pipe(Effect4.catchAll(() => Effect4.succeed(null)));
1465
+ if (reactive) {
1466
+ if (reactive.matched) return;
1467
+ return yield* new TextMismatchError({
1468
+ message: negate ? `Expected count NOT to be ${expectedCount} after ${timeout}ms \u2014 selector: ${formatSelector(selector)}` : `Expected count ${expectedCount} but got ${reactive.actual ?? "0"} after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1469
+ expected: negate ? `not ${expectedCount}` : String(expectedCount),
1470
+ actual: reactive.actual ?? "0",
1471
+ selector
1472
+ });
1473
+ }
1474
+ }
1475
+ while (Date.now() - start < timeout) {
1476
+ cache.invalidate();
1477
+ if (!isSystemUISelector(selector) && !isRelativeSelectorLike2(selector) && domChannel?.isConnected()) {
1478
+ const matches = yield* Effect4.tryPromise({
1479
+ try: () => domChannel.query(selector),
1480
+ catch: () => null
1481
+ }).pipe(Effect4.catchAll(() => Effect4.succeed(null)));
1482
+ if (matches) {
1483
+ const count2 = matches.filter((m) => m.visible).length;
1484
+ lastCount = count2;
1485
+ if (negate ? count2 !== expectedCount : count2 === expectedCount) return;
1486
+ yield* Effect4.sleep(Duration2.millis(pollInterval));
1487
+ continue;
1488
+ }
1489
+ }
1490
+ const raw = yield* driver.dumpHierarchy();
1491
+ const root = parse(raw);
1492
+ const count = findElements(root, selector).filter(
1493
+ (el) => el.visible !== false
1494
+ ).length;
1495
+ lastCount = count;
1496
+ if (negate ? count !== expectedCount : count === expectedCount) return;
1497
+ yield* Effect4.sleep(Duration2.millis(pollInterval));
1498
+ }
1499
+ return yield* new TextMismatchError({
1500
+ message: negate ? `Expected count NOT to be ${expectedCount} after ${timeout}ms \u2014 selector: ${formatSelector(selector)}` : `Expected count ${expectedCount} but got ${lastCount >= 0 ? lastCount : 0} after ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1501
+ expected: negate ? `not ${expectedCount}` : String(expectedCount),
1502
+ actual: String(lastCount >= 0 ? lastCount : 0),
1503
+ selector
1504
+ });
1505
+ }),
1506
+ waitForURL: (expected, opts, negate = false) => Effect4.gen(function* () {
1507
+ const timeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
1508
+ const pollInterval = opts?.pollInterval ?? defaults?.pollInterval ?? 100;
1509
+ const start = Date.now();
1510
+ let lastUrl = "";
1511
+ const matchesUrl = (url) => expected instanceof RegExp ? expected.test(url) : url === expected || url.includes(expected);
1512
+ const domChannel = driver.domChannel;
1513
+ if (config.platform === "web" && domChannel?.isConnected() && domChannel.waitForMatch) {
1514
+ const reactive = yield* Effect4.tryPromise({
1515
+ try: () => domChannel.waitForMatch("", {
1516
+ kind: "url",
1517
+ ...expected instanceof RegExp ? { patternSource: expected.source, patternFlags: expected.flags } : { expected },
1518
+ ...negate ? { negate: true } : {},
1519
+ timeoutMs: timeout
1520
+ }),
1521
+ catch: () => null
1522
+ }).pipe(Effect4.catchAll(() => Effect4.succeed(null)));
1523
+ if (reactive) {
1524
+ if (reactive.matched) return;
1525
+ return yield* new TextMismatchError({
1526
+ message: negate ? `Expected URL NOT to match ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got ${JSON.stringify(reactive.actual ?? "")} after ${timeout}ms` : `Expected URL ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got ${JSON.stringify(reactive.actual ?? "")} after ${timeout}ms`,
1527
+ expected: negate ? `not ${String(expected)}` : String(expected),
1528
+ actual: reactive.actual ?? "",
1529
+ selector: "url"
1530
+ });
1531
+ }
1532
+ }
1533
+ while (Date.now() - start < timeout) {
1534
+ const url = driver.getUrl ? yield* driver.getUrl() : yield* driver.evaluate(
1535
+ "typeof window !== 'undefined' && window.location ? window.location.href : ''"
1536
+ ).pipe(Effect4.catchAll(() => Effect4.succeed("")));
1537
+ lastUrl = url;
1538
+ if (negate ? !matchesUrl(url) : matchesUrl(url)) return;
1539
+ yield* Effect4.sleep(Duration2.millis(pollInterval));
1540
+ }
1541
+ return yield* new TextMismatchError({
1542
+ message: negate ? `Expected URL NOT to match ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got ${JSON.stringify(lastUrl)} after ${timeout}ms` : `Expected URL ${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)} but got ${JSON.stringify(lastUrl)} after ${timeout}ms`,
1543
+ expected: negate ? `not ${String(expected)}` : String(expected),
1544
+ actual: lastUrl,
1545
+ selector: "url"
1546
+ });
1547
+ }),
1134
1548
  assertFocusable: (selector, platform, opts) => Effect4.gen(function* () {
1135
1549
  const { isFocusable } = yield* Effect4.promise(
1136
1550
  () => import("./accessibility-audit-YZOPUY3D.js")
@@ -1280,7 +1694,7 @@ function createCoordinator(driver, config) {
1280
1694
  driver,
1281
1695
  selector,
1282
1696
  parse,
1283
- { ...defaults, ...opts },
1697
+ { ...defaults, ...opts, platform: opts?.platform ?? config.platform },
1284
1698
  cache
1285
1699
  );
1286
1700
  const { x, y } = centerOf(element);
@@ -1294,7 +1708,7 @@ function createCoordinator(driver, config) {
1294
1708
  driver,
1295
1709
  selector,
1296
1710
  parse,
1297
- { ...defaults, ...opts },
1711
+ { ...defaults, ...opts, platform: opts?.platform ?? config.platform },
1298
1712
  cache
1299
1713
  );
1300
1714
  const { x, y } = centerOf(element);
@@ -1317,23 +1731,113 @@ function createCoordinator(driver, config) {
1317
1731
  }
1318
1732
  yield* afterMutation();
1319
1733
  }),
1734
+ /**
1735
+ * Hover the pointer over an actionable element (moves pointer to its center).
1736
+ */
1737
+ hover: (selector, opts) => Effect4.gen(function* () {
1738
+ const mergedOpts = {
1739
+ ...defaults,
1740
+ ...opts,
1741
+ platform: opts?.platform ?? config.platform
1742
+ };
1743
+ const resolved = yield* waitForResolvedElementResult(
1744
+ driver,
1745
+ selector,
1746
+ parse,
1747
+ true,
1748
+ mergedOpts,
1749
+ cache
1750
+ );
1751
+ const { x, y } = centerOf(resolved.element);
1752
+ if (driver.hoverAtCoordinate) {
1753
+ yield* driver.hoverAtCoordinate(x, y);
1754
+ } else if (config.platform === "web") {
1755
+ yield* driver.evaluate(
1756
+ `(() => {
1757
+ const el = document.elementFromPoint(${x}, ${y});
1758
+ if (!el) return;
1759
+ const init = { bubbles: true, cancelable: true, composed: true, clientX: ${x}, clientY: ${y} };
1760
+ try { el.dispatchEvent(new PointerEvent("pointerover", init)); } catch {}
1761
+ try { el.dispatchEvent(new PointerEvent("pointerenter", { ...init, bubbles: false })); } catch {}
1762
+ try { el.dispatchEvent(new MouseEvent("mouseover", init)); } catch {}
1763
+ try { el.dispatchEvent(new MouseEvent("mouseenter", { ...init, bubbles: false })); } catch {}
1764
+ try { el.dispatchEvent(new MouseEvent("mousemove", init)); } catch {}
1765
+ })()`
1766
+ );
1767
+ } else {
1768
+ return yield* new DriverError({
1769
+ message: "hover() is not supported on this driver/platform"
1770
+ });
1771
+ }
1772
+ yield* afterMutation();
1773
+ }),
1320
1774
  /**
1321
1775
  * Atomic 1-round-trip form fill: on web/DOM channels, waits for actionability,
1322
- * focuses, clears, sets the React/Vue-safe value, and dispatches `input` + `change`
1323
- * in ONE single round trip (~1-2ms). Falls back to `tap` + `inputText` on native mobile.
1776
+ * focuses, clears, sets the React/Vue-safe value, verifies the value survived
1777
+ * React re-render/remount, and retries up to 3x. For contenteditable editors
1778
+ * (TipTap/ProseMirror/Lexical/Slate) or stubborn controlled inputs, falls back
1779
+ * seamlessly to native tap + SelectAll + Backspace + keyboard input.
1324
1780
  */
1325
1781
  fill: (selector, text, opts) => Effect4.gen(function* () {
1326
1782
  const timeout = opts?.timeout ?? defaults?.timeout ?? 5e3;
1783
+ const fillStart = Date.now();
1327
1784
  const domChannel = driver.domChannel;
1328
1785
  if (!isSystemUISelector(selector) && !isRelativeSelectorLike2(selector) && domChannel?.isConnected() && domChannel.fillDom) {
1329
- const filled = yield* Effect4.tryPromise({
1330
- try: () => domChannel.fillDom(selector, text, { timeoutMs: timeout }),
1331
- catch: (e) => new DriverError({ message: `DOM fill failed: ${e}` })
1332
- });
1333
- if (filled) {
1786
+ const fillAttempt = yield* Effect4.either(
1787
+ Effect4.tryPromise({
1788
+ try: () => domChannel.fillDom(selector, text, { timeoutMs: timeout }),
1789
+ catch: (e) => new DriverError({ message: `DOM fill failed: ${e}` })
1790
+ })
1791
+ );
1792
+ if (fillAttempt._tag === "Right" && fillAttempt.right) {
1334
1793
  yield* afterMutation();
1335
1794
  return;
1336
1795
  }
1796
+ const remaining = Math.max(50, timeout - (Date.now() - fillStart));
1797
+ const fallbackEl = yield* Effect4.either(
1798
+ waitForActionElement(
1799
+ driver,
1800
+ selector,
1801
+ parse,
1802
+ {
1803
+ ...defaults,
1804
+ ...opts,
1805
+ timeout: Math.min(remaining, 1500),
1806
+ platform: opts?.platform ?? config.platform
1807
+ },
1808
+ cache
1809
+ )
1810
+ );
1811
+ if (fallbackEl._tag === "Right") {
1812
+ const { x: x2, y: y2 } = centerOf(fallbackEl.right);
1813
+ yield* driver.tapAtCoordinate(x2, y2);
1814
+ const selectAllKey = process.platform === "darwin" ? "Meta+a" : "Control+a";
1815
+ yield* Effect4.either(driver.pressKey(selectAllKey));
1816
+ yield* Effect4.either(driver.pressKey("Backspace"));
1817
+ if (text.length > 0) {
1818
+ yield* driver.inputText(text);
1819
+ }
1820
+ yield* afterMutation();
1821
+ return;
1822
+ }
1823
+ const actionDiag = yield* Effect4.tryPromise({
1824
+ try: () => domChannel.evaluate(buildDomActionabilityDiagScript(selector)),
1825
+ catch: () => null
1826
+ }).pipe(Effect4.catchAll(() => Effect4.succeed(null)));
1827
+ if (actionDiag?.found && actionDiag.obstructedBy) {
1828
+ return yield* new ElementNotFoundError({
1829
+ message: `Element is covered by ${actionDiag.obstructedBy} (not fillable within ${timeout}ms) \u2014 selector: ${formatSelector(selector)}`,
1830
+ selector,
1831
+ timeoutMs: timeout
1832
+ });
1833
+ }
1834
+ if (actionDiag?.found && actionDiag.visible && actionDiag.enabled === false) {
1835
+ return yield* new ElementNotFoundError({
1836
+ message: `Element is disabled (not fillable within ${timeout}ms) \u2014 selector: ${formatSelector(selector)}`,
1837
+ selector,
1838
+ timeoutMs: timeout
1839
+ });
1840
+ }
1337
1841
  return yield* new ElementNotFoundError({
1338
1842
  message: `Element not fillable within ${timeout}ms \u2014 selector: ${formatSelector(selector)}`,
1339
1843
  selector,
@@ -1521,8 +2025,350 @@ function buildStorybookUrl(storyId, options, runtime) {
1521
2025
  return url.toString();
1522
2026
  }
1523
2027
 
1524
- // src/api/app.ts
2028
+ // src/api/expect.ts
1525
2029
  import { Effect as Effect5 } from "effect";
2030
+ function selectorToCss(sel) {
2031
+ if (typeof sel === "string") return sel;
2032
+ if (typeof sel === "object" && sel !== null && "css" in sel && sel.css) return sel.css;
2033
+ if (typeof sel === "object" && sel !== null && "testID" in sel && sel.testID)
2034
+ return `[data-testid="${sel.testID}"]`;
2035
+ if (typeof sel === "object" && sel !== null && "accessibilityLabel" in sel && sel.accessibilityLabel)
2036
+ return `[aria-label="${sel.accessibilityLabel}"]`;
2037
+ return "";
2038
+ }
2039
+ function deepEqual(a, b) {
2040
+ if (Object.is(a, b)) return true;
2041
+ if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
2042
+ if (a instanceof RegExp && b instanceof RegExp)
2043
+ return a.source === b.source && a.flags === b.flags;
2044
+ if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
2045
+ if (Array.isArray(a) || Array.isArray(b)) {
2046
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
2047
+ for (let i = 0; i < a.length; i++) {
2048
+ if (!deepEqual(a[i], b[i])) return false;
2049
+ }
2050
+ return true;
2051
+ }
2052
+ const aKeys = Object.keys(a);
2053
+ const bKeys = Object.keys(b);
2054
+ if (aKeys.length !== bKeys.length) return false;
2055
+ for (const k of aKeys) {
2056
+ if (!Object.prototype.hasOwnProperty.call(b, k) || !deepEqual(a[k], b[k])) {
2057
+ return false;
2058
+ }
2059
+ }
2060
+ return true;
2061
+ }
2062
+ async function retryUntilPass(fn, opts, defaultTimeout) {
2063
+ const timeout = opts?.timeout ?? defaultTimeout;
2064
+ const intervals = opts?.intervals && opts.intervals.length > 0 ? opts.intervals : [50, 100, 250, 500];
2065
+ const deadline = Date.now() + timeout;
2066
+ let attempt = 0;
2067
+ let lastError;
2068
+ while (true) {
2069
+ try {
2070
+ await fn();
2071
+ return;
2072
+ } catch (err) {
2073
+ lastError = err;
2074
+ const remaining = deadline - Date.now();
2075
+ if (remaining <= 0) break;
2076
+ const delay = intervals[Math.min(attempt, intervals.length - 1)] ?? 250;
2077
+ attempt += 1;
2078
+ await new Promise((r) => setTimeout(r, Math.min(delay, remaining)));
2079
+ }
2080
+ }
2081
+ throw lastError instanceof Error ? lastError : new Error(`expect(fn).toPass() timed out after ${timeout}ms: ${String(lastError)}`);
2082
+ }
2083
+ function createPromiseExpect(driver, config, recorder, flowContext, visualRegression) {
2084
+ const ctx = flowContext ?? {
2085
+ flowFilePath: "",
2086
+ flowName: "unknown",
2087
+ platform: "web"
2088
+ };
2089
+ const coord = createCoordinator(driver, config);
2090
+ const defaultTimeout = config.defaults?.timeout ?? 5e3;
2091
+ const run = (effect) => Effect5.runPromise(effect);
2092
+ const runStep = (command, selector, action) => recorder ? recorder.runStep(command, action, { selector, captureScreenshot: false }) : action();
2093
+ const runPageStep = (command, action) => recorder ? recorder.runStep(command, action, { captureScreenshot: false }) : action();
2094
+ const buildNegatedExpectation = (selector) => ({
2095
+ toBeVisible: (opts) => runStep("expect.not.toBeVisible", selector, () => run(coord.assertHidden(selector, opts))),
2096
+ toBeHidden: (opts) => runStep(
2097
+ "expect.not.toBeHidden",
2098
+ selector,
2099
+ () => run(coord.assertVisible(selector, opts)).then(() => {
2100
+ })
2101
+ ),
2102
+ toHaveText: (expected, opts) => runStep(
2103
+ `expect.not.toHaveText(${JSON.stringify(expected)})`,
2104
+ selector,
2105
+ () => run(coord.assertText(selector, expected, opts, true))
2106
+ ),
2107
+ toMatchText: (pattern, opts) => runStep(
2108
+ `expect.not.toMatchText(${pattern})`,
2109
+ selector,
2110
+ () => run(coord.assertMatchesText(selector, pattern, opts, true))
2111
+ ),
2112
+ toHaveValue: (expected, opts) => runStep(
2113
+ `expect.not.toHaveValue(${JSON.stringify(expected)})`,
2114
+ selector,
2115
+ () => run(coord.assertValue(selector, expected, opts, true))
2116
+ ),
2117
+ toHaveAttribute: (name, value, opts) => runStep(
2118
+ `expect.not.toHaveAttribute(${JSON.stringify(name)})`,
2119
+ selector,
2120
+ () => run(coord.assertAttribute(selector, name, value, opts, true))
2121
+ ),
2122
+ toBeEnabled: (opts) => runStep("expect.not.toBeEnabled", selector, () => run(coord.assertDisabled(selector, opts))),
2123
+ toBeDisabled: (opts) => runStep("expect.not.toBeDisabled", selector, () => run(coord.assertEnabled(selector, opts))),
2124
+ toContainText: (expected, opts) => runStep(
2125
+ `expect.not.toContainText(${JSON.stringify(expected)})`,
2126
+ selector,
2127
+ () => run(coord.assertContainsText(selector, expected, opts, true))
2128
+ ),
2129
+ toHaveCount: (expected, opts) => runStep(
2130
+ `expect.not.toHaveCount(${expected})`,
2131
+ selector,
2132
+ () => run(coord.assertCount(selector, expected, opts, true))
2133
+ ),
2134
+ toBeFocused: (opts) => runStep(
2135
+ "expect.not.toBeFocused",
2136
+ selector,
2137
+ () => run(coord.assertFocused(selector, opts, true))
2138
+ ),
2139
+ toHaveAccessibleName: (expected, opts) => runStep(
2140
+ `expect.not.toHaveAccessibleName(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`,
2141
+ selector,
2142
+ () => run(coord.assertAccessibleName(selector, expected, opts, true))
2143
+ ),
2144
+ toHaveAccessibleDescription: (expected, opts) => runStep(
2145
+ `expect.not.toHaveAccessibleDescription(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`,
2146
+ selector,
2147
+ () => run(coord.assertAccessibleDescription(selector, expected, opts, true))
2148
+ )
2149
+ });
2150
+ const buildPollMatchers = (fn, opts, negate) => {
2151
+ const check = (label, predicate, describeFail) => runPageStep(
2152
+ `expect.poll.${negate ? "not." : ""}${label}`,
2153
+ () => retryUntilPass(
2154
+ async () => {
2155
+ const val = await fn();
2156
+ const ok = predicate(val);
2157
+ if (negate ? ok : !ok) {
2158
+ throw new Error(describeFail(val));
2159
+ }
2160
+ },
2161
+ opts,
2162
+ defaultTimeout
2163
+ )
2164
+ );
2165
+ return {
2166
+ toBe: (expected) => check(
2167
+ `toBe(${JSON.stringify(expected)})`,
2168
+ (v) => Object.is(v, expected),
2169
+ (v) => negate ? `Expected polled value NOT to be ${JSON.stringify(expected)}` : `Expected polled value to be ${JSON.stringify(expected)}, received ${JSON.stringify(v)}`
2170
+ ),
2171
+ toEqual: (expected) => check(
2172
+ `toEqual(${JSON.stringify(expected)})`,
2173
+ (v) => deepEqual(v, expected),
2174
+ (v) => negate ? `Expected polled value NOT to equal ${JSON.stringify(expected)}` : `Expected polled value to equal ${JSON.stringify(expected)}, received ${JSON.stringify(v)}`
2175
+ ),
2176
+ toContain: (expected) => check(
2177
+ `toContain(${JSON.stringify(expected)})`,
2178
+ (v) => {
2179
+ if (typeof v === "string") return v.includes(String(expected));
2180
+ if (Array.isArray(v)) return v.some((item) => deepEqual(item, expected));
2181
+ return false;
2182
+ },
2183
+ (v) => negate ? `Expected polled value NOT to contain ${JSON.stringify(expected)}, received ${JSON.stringify(v)}` : `Expected polled value to contain ${JSON.stringify(expected)}, received ${JSON.stringify(v)}`
2184
+ ),
2185
+ toMatch: (pattern) => check(
2186
+ `toMatch(${pattern instanceof RegExp ? String(pattern) : JSON.stringify(pattern)})`,
2187
+ (v) => {
2188
+ const str = String(v ?? "");
2189
+ return pattern instanceof RegExp ? pattern.test(str) : str.includes(pattern);
2190
+ },
2191
+ (v) => negate ? `Expected polled value NOT to match ${String(pattern)}, received ${JSON.stringify(v)}` : `Expected polled value to match ${String(pattern)}, received ${JSON.stringify(v)}`
2192
+ ),
2193
+ toBeGreaterThan: (expected) => check(
2194
+ `toBeGreaterThan(${expected})`,
2195
+ (v) => typeof v === "number" && v > expected,
2196
+ (v) => negate ? `Expected polled value NOT to be > ${expected}, received ${String(v)}` : `Expected polled value > ${expected}, received ${String(v)}`
2197
+ ),
2198
+ toBeLessThan: (expected) => check(
2199
+ `toBeLessThan(${expected})`,
2200
+ (v) => typeof v === "number" && v < expected,
2201
+ (v) => negate ? `Expected polled value NOT to be < ${expected}, received ${String(v)}` : `Expected polled value < ${expected}, received ${String(v)}`
2202
+ ),
2203
+ toBeGreaterThanOrEqual: (expected) => check(
2204
+ `toBeGreaterThanOrEqual(${expected})`,
2205
+ (v) => typeof v === "number" && v >= expected,
2206
+ (v) => negate ? `Expected polled value NOT to be >= ${expected}, received ${String(v)}` : `Expected polled value >= ${expected}, received ${String(v)}`
2207
+ ),
2208
+ toBeLessThanOrEqual: (expected) => check(
2209
+ `toBeLessThanOrEqual(${expected})`,
2210
+ (v) => typeof v === "number" && v <= expected,
2211
+ (v) => negate ? `Expected polled value NOT to be <= ${expected}, received ${String(v)}` : `Expected polled value <= ${expected}, received ${String(v)}`
2212
+ ),
2213
+ toBeTruthy: () => check(
2214
+ "toBeTruthy",
2215
+ (v) => Boolean(v),
2216
+ (v) => negate ? `Expected polled value NOT to be truthy, received ${JSON.stringify(v)}` : `Expected polled value to be truthy, received ${JSON.stringify(v)}`
2217
+ ),
2218
+ toBeFalsy: () => check(
2219
+ "toBeFalsy",
2220
+ (v) => !v,
2221
+ (v) => negate ? `Expected polled value NOT to be falsy, received ${JSON.stringify(v)}` : `Expected polled value to be falsy, received ${JSON.stringify(v)}`
2222
+ ),
2223
+ toBeDefined: () => check(
2224
+ "toBeDefined",
2225
+ (v) => v !== void 0,
2226
+ () => negate ? `Expected polled value to be undefined` : `Expected polled value to be defined`
2227
+ ),
2228
+ toBeUndefined: () => check(
2229
+ "toBeUndefined",
2230
+ (v) => v === void 0,
2231
+ (v) => negate ? `Expected polled value NOT to be undefined` : `Expected polled value to be undefined, received ${JSON.stringify(v)}`
2232
+ ),
2233
+ toHaveLength: (expected) => check(
2234
+ `toHaveLength(${expected})`,
2235
+ (v) => v !== null && v !== void 0 && typeof v.length === "number" && v.length === expected,
2236
+ (v) => negate ? `Expected polled value NOT to have length ${expected}` : `Expected polled value to have length ${expected}, received ${JSON.stringify(v)}`
2237
+ )
2238
+ };
2239
+ };
2240
+ const expectFn = ((selectorOrFn) => {
2241
+ if (typeof selectorOrFn === "function") {
2242
+ return {
2243
+ toPass: (opts) => runPageStep("expect.toPass", () => retryUntilPass(selectorOrFn, opts, defaultTimeout))
2244
+ };
2245
+ }
2246
+ const selector = selectorOrFn;
2247
+ return {
2248
+ toBeVisible: (opts) => runStep(
2249
+ "expect.toBeVisible",
2250
+ selector,
2251
+ () => run(coord.assertVisible(selector, opts)).then(() => {
2252
+ })
2253
+ ),
2254
+ toBeHidden: (opts) => runStep("expect.toBeHidden", selector, () => run(coord.assertHidden(selector, opts))),
2255
+ toHaveText: (expected, opts) => runStep(
2256
+ `expect.toHaveText(${JSON.stringify(expected)})`,
2257
+ selector,
2258
+ () => run(coord.assertText(selector, expected, opts))
2259
+ ),
2260
+ toMatchText: (pattern, opts) => runStep(
2261
+ `expect.toMatchText(${pattern})`,
2262
+ selector,
2263
+ () => run(coord.assertMatchesText(selector, pattern, opts))
2264
+ ),
2265
+ toHaveValue: (expected, opts) => runStep(
2266
+ `expect.toHaveValue(${JSON.stringify(expected)})`,
2267
+ selector,
2268
+ () => run(coord.assertValue(selector, expected, opts))
2269
+ ),
2270
+ toHaveAttribute: (name, value, opts) => runStep(
2271
+ `expect.toHaveAttribute(${JSON.stringify(name)})`,
2272
+ selector,
2273
+ () => run(coord.assertAttribute(selector, name, value, opts))
2274
+ ),
2275
+ toBeEnabled: (opts) => runStep("expect.toBeEnabled", selector, () => run(coord.assertEnabled(selector, opts))),
2276
+ toBeDisabled: (opts) => runStep("expect.toBeDisabled", selector, () => run(coord.assertDisabled(selector, opts))),
2277
+ toContainText: (expected, opts) => runStep(
2278
+ `expect.toContainText(${JSON.stringify(expected)})`,
2279
+ selector,
2280
+ () => run(coord.assertContainsText(selector, expected, opts))
2281
+ ),
2282
+ toHaveCount: (expected, opts) => runStep(
2283
+ `expect.toHaveCount(${expected})`,
2284
+ selector,
2285
+ () => run(coord.assertCount(selector, expected, opts))
2286
+ ),
2287
+ toBeFocused: (opts) => runStep("expect.toBeFocused", selector, () => run(coord.assertFocused(selector, opts))),
2288
+ toHaveAccessibleName: (expected, opts) => runStep(
2289
+ `expect.toHaveAccessibleName(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`,
2290
+ selector,
2291
+ () => run(coord.assertAccessibleName(selector, expected, opts))
2292
+ ),
2293
+ toHaveAccessibleDescription: (expected, opts) => runStep(
2294
+ `expect.toHaveAccessibleDescription(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`,
2295
+ selector,
2296
+ () => run(coord.assertAccessibleDescription(selector, expected, opts))
2297
+ ),
2298
+ not: buildNegatedExpectation(selector),
2299
+ toMatchScreenshot: (name, options) => runStep(
2300
+ `expect.toMatchScreenshot(${JSON.stringify(name)})`,
2301
+ selector,
2302
+ () => run(
2303
+ coord.assertScreenshot(selector, name, ctx.flowFilePath, ctx.flowName, ctx.platform, {
2304
+ threshold: options?.threshold ?? visualRegression?.threshold,
2305
+ maxDiffPixelRatio: options?.maxDiffPixelRatio ?? visualRegression?.maxDiffPixelRatio,
2306
+ mask: [],
2307
+ updateBaselines: ctx.updateBaselines,
2308
+ baselinesDir: visualRegression?.baselinesDir
2309
+ })
2310
+ )
2311
+ ),
2312
+ toPassAccessibilityAudit: (options) => {
2313
+ const excludeCss = options?.exclude?.map(selectorToCss).filter(Boolean) ?? [];
2314
+ const targetCss = selectorToCss(selector);
2315
+ return runStep(
2316
+ "expect.toPassAccessibilityAudit",
2317
+ selector,
2318
+ () => run(
2319
+ coord.assertAccessibilityAudit(ctx.platform, {
2320
+ severity: options?.severity,
2321
+ rules: options?.rules,
2322
+ targetSelector: targetCss || void 0,
2323
+ excludeSelectors: excludeCss
2324
+ })
2325
+ )
2326
+ );
2327
+ },
2328
+ toHaveAccessibilityLabel: (expected) => runStep(
2329
+ `expect.toHaveAccessibilityLabel(${expected !== void 0 ? JSON.stringify(expected) : ""})`,
2330
+ selector,
2331
+ () => run(coord.assertAccessibilityLabel(selector, expected))
2332
+ ),
2333
+ toBeFocusable: () => runStep(
2334
+ "expect.toBeFocusable",
2335
+ selector,
2336
+ () => run(coord.assertFocusable(selector, ctx.platform))
2337
+ ),
2338
+ toHaveRole: (expected) => runStep(
2339
+ `expect.toHaveRole(${JSON.stringify(expected)})`,
2340
+ selector,
2341
+ () => run(coord.assertRole(selector, expected, ctx.platform))
2342
+ ),
2343
+ toHaveMinTouchTarget: (size = 44) => runStep(
2344
+ `expect.toHaveMinTouchTarget(${size})`,
2345
+ selector,
2346
+ () => run(coord.assertMinTouchTarget(selector, size))
2347
+ )
2348
+ };
2349
+ });
2350
+ expectFn.toHaveURL = (expected, opts) => {
2351
+ const label = `expect.toHaveURL(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`;
2352
+ return runPageStep(label, () => run(coord.waitForURL(expected, opts)));
2353
+ };
2354
+ Object.defineProperty(expectFn, "not", {
2355
+ enumerable: true,
2356
+ value: {
2357
+ toHaveURL: (expected, opts) => {
2358
+ const label = `expect.not.toHaveURL(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`;
2359
+ return runPageStep(label, () => run(coord.waitForURL(expected, opts, true)));
2360
+ }
2361
+ }
2362
+ });
2363
+ expectFn.poll = (fn, opts) => ({
2364
+ ...buildPollMatchers(fn, opts, false),
2365
+ not: buildPollMatchers(fn, opts, true)
2366
+ });
2367
+ return expectFn;
2368
+ }
2369
+
2370
+ // src/api/app.ts
2371
+ import { Effect as Effect6 } from "effect";
1526
2372
 
1527
2373
  // src/drivers/launch-options.ts
1528
2374
  function mergeRecord(base, override) {
@@ -1630,15 +2476,217 @@ function buildIOSLaunchConfiguration(options) {
1630
2476
 
1631
2477
  // src/api/app.ts
1632
2478
  var describeMatcher = (matcher) => typeof matcher === "string" ? matcher : matcher.toString();
2479
+ function formatEvaluateCommand(fn) {
2480
+ const raw = typeof fn === "string" ? fn : fn.toString();
2481
+ const compact = raw.replaceAll(/\s+/g, " ").trim();
2482
+ const snippet = compact.length > 72 ? `${compact.slice(0, 69)}...` : compact;
2483
+ return `evaluate(${snippet})`;
2484
+ }
2485
+ function parseSetCookieHeader(headerValue, originUrl) {
2486
+ const parts = headerValue.split(";").map((p) => p.trim());
2487
+ const first2 = parts[0];
2488
+ if (!first2) return null;
2489
+ const eqIdx = first2.indexOf("=");
2490
+ if (eqIdx <= 0) return null;
2491
+ const name = first2.slice(0, eqIdx).trim();
2492
+ const value = first2.slice(eqIdx + 1).trim();
2493
+ const cookie = {
2494
+ name,
2495
+ value,
2496
+ url: `${originUrl.origin}/`,
2497
+ path: "/"
2498
+ };
2499
+ for (const attr of parts.slice(1)) {
2500
+ const [rawK, ...rest] = attr.split("=");
2501
+ const k = (rawK ?? "").trim().toLowerCase();
2502
+ const v = rest.join("=").trim();
2503
+ if (k === "path" && v) cookie.path = v;
2504
+ else if (k === "domain" && v) {
2505
+ cookie.domain = v;
2506
+ delete cookie.url;
2507
+ } else if (k === "httponly") cookie.httpOnly = true;
2508
+ else if (k === "secure") cookie.secure = true;
2509
+ else if (k === "samesite") {
2510
+ const norm = v.toLowerCase();
2511
+ if (norm === "strict") cookie.sameSite = "Strict";
2512
+ else if (norm === "lax") cookie.sameSite = "Lax";
2513
+ else if (norm === "none") cookie.sameSite = "None";
2514
+ } else if (k === "max-age") {
2515
+ const sec = Number.parseInt(v, 10);
2516
+ if (Number.isFinite(sec)) cookie.expires = Math.floor(Date.now() / 1e3) + sec;
2517
+ } else if (k === "expires") {
2518
+ const ts = Date.parse(v);
2519
+ if (Number.isFinite(ts)) cookie.expires = Math.floor(ts / 1e3);
2520
+ }
2521
+ }
2522
+ return cookie;
2523
+ }
2524
+ var RECORDED_RAW_PAGE_METHODS = /* @__PURE__ */ new Set([
2525
+ "goto",
2526
+ "reload",
2527
+ "click",
2528
+ "dblclick",
2529
+ "fill",
2530
+ "hover",
2531
+ "press",
2532
+ "type",
2533
+ "check",
2534
+ "uncheck",
2535
+ "selectOption",
2536
+ "setInputFiles",
2537
+ "waitForURL",
2538
+ "waitForResponse",
2539
+ "waitForSelector",
2540
+ "evaluate"
2541
+ ]);
2542
+ function wrapRawPageWithStepRecording(rawPage, recorder) {
2543
+ if (!recorder || !rawPage || typeof rawPage !== "object") return rawPage;
2544
+ const candidate = rawPage;
2545
+ if (typeof candidate["goto"] !== "function" || typeof candidate["click"] !== "function") {
2546
+ return rawPage;
2547
+ }
2548
+ return new Proxy(candidate, {
2549
+ get(target, prop, receiver) {
2550
+ if (prop === "then") return void 0;
2551
+ const value = Reflect.get(target, prop, receiver);
2552
+ if (typeof value !== "function") return value;
2553
+ if (typeof prop === "string" && RECORDED_RAW_PAGE_METHODS.has(prop)) {
2554
+ return (...callArgs) => {
2555
+ const argHint = typeof callArgs[0] === "string" ? callArgs[0].length > 60 ? `${callArgs[0].slice(0, 57)}...` : callArgs[0] : void 0;
2556
+ const cmd = argHint ? `page.${prop}(${JSON.stringify(argHint)})` : `page.${prop}`;
2557
+ return recorder.runStep(cmd, () => Promise.resolve(value.apply(target, callArgs)), {
2558
+ captureScreenshot: false
2559
+ });
2560
+ };
2561
+ }
2562
+ return value.bind(target);
2563
+ }
2564
+ });
2565
+ }
1633
2566
  function createPromiseApp(driver, appId, config, recorder, options = {}) {
1634
2567
  const coord = createCoordinator(driver, config);
1635
2568
  const platform = options.platform ?? (appId.startsWith("http://") || appId.startsWith("https://") ? "web" : void 0);
1636
- const run = (effect) => Effect5.runPromise(effect);
1637
- const unsupportedWebFeature = (feature) => Effect5.fail(new DriverError({ message: `${feature}() is only supported on the web platform` }));
2569
+ const run = (effect) => Effect6.runPromise(effect);
2570
+ const unsupportedWebFeature = (feature) => Effect6.fail(new DriverError({ message: `${feature}() is only supported on the web platform` }));
1638
2571
  const optionalMethod = (name, method) => method ?? ((..._args) => unsupportedWebFeature(name));
1639
2572
  const runStep = (command, action, opts) => recorder ? recorder.runStep(command, action, opts) : action();
1640
2573
  const runScreenshotStep = (command, action, opts) => recorder ? recorder.runScreenshotStep(command, action, opts) : action();
1641
- return {
2574
+ const getCurrentUrl = async () => {
2575
+ if (driver.getUrl) {
2576
+ return run(driver.getUrl());
2577
+ }
2578
+ return run(
2579
+ driver.evaluate(
2580
+ "typeof window !== 'undefined' && window.location ? String(window.location.href || '') : ''"
2581
+ ).pipe(Effect6.catchAll(() => Effect6.succeed("")))
2582
+ );
2583
+ };
2584
+ const resolveRequestUrl = async (rawUrl) => {
2585
+ if (rawUrl.startsWith("http://") || rawUrl.startsWith("https://")) {
2586
+ return new URL(rawUrl);
2587
+ }
2588
+ const pageUrl = await getCurrentUrl();
2589
+ const base = pageUrl && (pageUrl.startsWith("http://") || pageUrl.startsWith("https://")) ? pageUrl : appId.startsWith("http://") || appId.startsWith("https://") ? appId : "http://localhost";
2590
+ return new URL(rawUrl, base);
2591
+ };
2592
+ const performBrowserRequest = async (method, rawUrl, init) => {
2593
+ const targetUrl = await resolveRequestUrl(rawUrl);
2594
+ if (init?.query) {
2595
+ for (const [k, v] of Object.entries(init.query)) {
2596
+ if (v !== void 0) targetUrl.searchParams.set(k, String(v));
2597
+ }
2598
+ }
2599
+ const headers = { ...init?.headers };
2600
+ const hasCookieHeader = Object.keys(headers).some((k) => k.toLowerCase() === "cookie");
2601
+ if (!hasCookieHeader && driver.getCookies) {
2602
+ const cookies = await run(driver.getCookies([targetUrl.toString()])).catch(() => []);
2603
+ if (cookies.length > 0) {
2604
+ headers["cookie"] = cookies.map((c) => `${c.name}=${c.value}`).join("; ");
2605
+ }
2606
+ }
2607
+ let requestBody;
2608
+ if (init?.body !== void 0) {
2609
+ if (typeof init.body === "string") {
2610
+ requestBody = init.body;
2611
+ } else {
2612
+ requestBody = JSON.stringify(init.body);
2613
+ if (!Object.keys(headers).some((k) => k.toLowerCase() === "content-type")) {
2614
+ headers["content-type"] = "application/json";
2615
+ }
2616
+ }
2617
+ }
2618
+ const res = await fetch(targetUrl.toString(), {
2619
+ method,
2620
+ headers,
2621
+ ...requestBody !== void 0 ? { body: requestBody } : {},
2622
+ ...init?.signal ? { signal: init.signal } : {}
2623
+ });
2624
+ if (driver.setCookies) {
2625
+ const rawSetCookies = typeof res.headers.getSetCookie === "function" ? res.headers.getSetCookie() : res.headers.get("set-cookie") ? [res.headers.get("set-cookie")] : [];
2626
+ const parsedCookies = rawSetCookies.map((line) => parseSetCookieHeader(line, targetUrl)).filter((c) => c !== null);
2627
+ if (parsedCookies.length > 0) {
2628
+ await run(driver.setCookies(parsedCookies)).catch(() => {
2629
+ });
2630
+ }
2631
+ }
2632
+ const rawText = await res.text();
2633
+ const contentType = res.headers.get("content-type") ?? "";
2634
+ let data = rawText;
2635
+ if (contentType.includes("application/json")) {
2636
+ try {
2637
+ data = JSON.parse(rawText);
2638
+ } catch {
2639
+ data = rawText;
2640
+ }
2641
+ } else if (rawText.trim().startsWith("{") || rawText.trim().startsWith("[")) {
2642
+ try {
2643
+ data = JSON.parse(rawText);
2644
+ } catch {
2645
+ data = rawText;
2646
+ }
2647
+ }
2648
+ return {
2649
+ status: res.status,
2650
+ statusText: res.statusText,
2651
+ ok: res.ok,
2652
+ url: res.url || targetUrl.toString(),
2653
+ headers: res.headers,
2654
+ data,
2655
+ text: async () => rawText,
2656
+ json: async () => JSON.parse(rawText)
2657
+ };
2658
+ };
2659
+ const requestClient = {
2660
+ fetch: (url, init) => {
2661
+ const method = (init?.method ?? "GET").toUpperCase();
2662
+ return runStep(
2663
+ `request.${method}(${url})`,
2664
+ () => performBrowserRequest(method, url, init)
2665
+ );
2666
+ },
2667
+ get: (url, opts) => runStep(`request.GET(${url})`, () => performBrowserRequest("GET", url, opts)),
2668
+ post: (url, body, opts) => runStep(
2669
+ `request.POST(${url})`,
2670
+ () => performBrowserRequest("POST", url, { ...opts, body })
2671
+ ),
2672
+ put: (url, body, opts) => runStep(
2673
+ `request.PUT(${url})`,
2674
+ () => performBrowserRequest("PUT", url, { ...opts, body })
2675
+ ),
2676
+ patch: (url, body, opts) => runStep(
2677
+ `request.PATCH(${url})`,
2678
+ () => performBrowserRequest("PATCH", url, { ...opts, body })
2679
+ ),
2680
+ delete: (url, opts) => runStep(`request.DELETE(${url})`, () => performBrowserRequest("DELETE", url, opts))
2681
+ };
2682
+ const appExpect = createPromiseExpect(
2683
+ driver,
2684
+ config,
2685
+ recorder,
2686
+ options.flowContext,
2687
+ options.visualRegression
2688
+ );
2689
+ const appObj = {
1642
2690
  tap: (selector, opts) => runStep("tap", () => run(coord.tap(selector, opts)), { selector, captureScreenshot: true }),
1643
2691
  tapXY: (x, y) => runStep("tapXY", () => run(coord.tapXY(x, y)), {
1644
2692
  selector: { point: { x, y } },
@@ -1656,6 +2704,10 @@ function createPromiseApp(driver, appId, config, recorder, options = {}) {
1656
2704
  selector: { point: { x, y } },
1657
2705
  captureScreenshot: true
1658
2706
  }),
2707
+ hover: (selector, opts) => runStep("hover", () => run(coord.hover(selector, opts)), {
2708
+ selector,
2709
+ captureScreenshot: true
2710
+ }),
1659
2711
  inputText: (text) => runStep("inputText", () => run(coord.inputText(text)), { captureScreenshot: true }),
1660
2712
  fill: (selector, value, opts) => runStep("fill", () => run(coord.fill(selector, value, opts)), {
1661
2713
  selector,
@@ -1741,12 +2793,39 @@ function createPromiseApp(driver, appId, config, recorder, options = {}) {
1741
2793
  }
1742
2794
  ),
1743
2795
  back: () => runStep("back", () => run(driver.back()), { captureScreenshot: true }),
2796
+ reload: (opts) => runStep(
2797
+ "reload",
2798
+ async () => {
2799
+ if (driver.reload) {
2800
+ await run(driver.reload(opts));
2801
+ return;
2802
+ }
2803
+ if (driver.domChannel?.reload) {
2804
+ await driver.domChannel.reload();
2805
+ return;
2806
+ }
2807
+ await run(driver.evaluate("window.location.reload()"));
2808
+ },
2809
+ { captureScreenshot: true }
2810
+ ),
2811
+ url: () => runStep("url", () => getCurrentUrl()),
2812
+ waitForURL: (expected, opts) => runStep(
2813
+ `waitForURL(${expected instanceof RegExp ? String(expected) : JSON.stringify(expected)})`,
2814
+ () => run(coord.waitForURL(expected, opts))
2815
+ ),
2816
+ waitForResponse: (matcher, opts) => runStep(
2817
+ `waitForResponse(${typeof matcher === "function" ? "<predicate>" : describeMatcher(matcher)})`,
2818
+ () => run(optionalMethod("waitForResponse", driver.waitForResponse)(matcher, opts))
2819
+ ),
1744
2820
  takeScreenshot: (name) => runScreenshotStep(
1745
2821
  name ? `takeScreenshot(${name})` : "takeScreenshot",
1746
2822
  () => run(driver.takeScreenshot()),
1747
2823
  { name }
1748
2824
  ),
1749
- evaluate: (fn, ...args) => runStep("evaluate", () => run(driver.evaluate(fn, ...args))),
2825
+ evaluate: (fn, ...args) => runStep(
2826
+ formatEvaluateCommand(fn),
2827
+ () => run(driver.evaluate(fn, ...args))
2828
+ ),
1750
2829
  mockNetwork: (matcher, response) => runStep(
1751
2830
  "mockNetwork",
1752
2831
  () => run(optionalMethod("mockNetwork", driver.mockNetwork)(matcher, response)),
@@ -1770,12 +2849,22 @@ function createPromiseApp(driver, appId, config, recorder, options = {}) {
1770
2849
  () => run(optionalMethod("setNetworkConditions", driver.setNetworkConditions)(conditions)),
1771
2850
  { selector: conditions }
1772
2851
  ),
2852
+ setOffline: (offline) => runStep(
2853
+ `setOffline(${offline})`,
2854
+ () => run(optionalMethod("setOffline", driver.setNetworkConditions)({ offline })),
2855
+ { selector: { offline } }
2856
+ ),
1773
2857
  saveCookies: (path) => runStep("saveCookies", () => run(optionalMethod("saveCookies", driver.saveCookies)(path)), {
1774
2858
  selector: { path }
1775
2859
  }),
1776
2860
  loadCookies: (path) => runStep("loadCookies", () => run(optionalMethod("loadCookies", driver.loadCookies)(path)), {
1777
2861
  selector: { path }
1778
2862
  }),
2863
+ getCookies: (urls) => runStep("getCookies", () => run(optionalMethod("getCookies", driver.getCookies)(urls))),
2864
+ setCookies: (cookies) => runStep("setCookies", () => run(optionalMethod("setCookies", driver.setCookies)(cookies)), {
2865
+ selector: { count: cookies.length }
2866
+ }),
2867
+ clearCookies: () => runStep("clearCookies", () => run(optionalMethod("clearCookies", driver.clearCookies)())),
1779
2868
  saveAuthState: (path) => runStep(
1780
2869
  "saveAuthState",
1781
2870
  () => run(optionalMethod("saveAuthState", driver.saveAuthState)(path)),
@@ -1821,13 +2910,77 @@ function createPromiseApp(driver, appId, config, recorder, options = {}) {
1821
2910
  ),
1822
2911
  getJSErrors: () => runStep("getJSErrors", () => run(optionalMethod("getJSErrors", driver.getJSErrors)())),
1823
2912
  getHAR: () => runStep("getHAR", () => run(optionalMethod("getHAR", driver.getHAR)())),
2913
+ request: requestClient,
2914
+ newContext: (ctxOpts) => runStep(
2915
+ "newContext",
2916
+ async () => {
2917
+ const created = await run(
2918
+ optionalMethod("newContext", driver.createIsolatedContext)(ctxOpts)
2919
+ );
2920
+ let closed = false;
2921
+ const safeClose = async () => {
2922
+ if (closed) return;
2923
+ closed = true;
2924
+ await created.close();
2925
+ };
2926
+ options.onRegisterCleanup?.(safeClose);
2927
+ const childDriver = created.driver;
2928
+ const childApp = createPromiseApp(childDriver, appId, config, recorder, options);
2929
+ const childExpect = createPromiseExpect(
2930
+ childDriver,
2931
+ config,
2932
+ recorder,
2933
+ options.flowContext,
2934
+ options.visualRegression
2935
+ );
2936
+ return { app: childApp, expect: childExpect, close: safeClose };
2937
+ },
2938
+ { selector: ctxOpts }
2939
+ ),
2940
+ frame: (frameSelector) => {
2941
+ const scoped = (sel) => inFrame(frameSelector, sel);
2942
+ return {
2943
+ tap: (sel, opts) => appObj.tap(scoped(sel), opts),
2944
+ doubleTap: (sel, opts) => appObj.doubleTap(scoped(sel), opts),
2945
+ longPress: (sel, opts) => appObj.longPress(scoped(sel), opts),
2946
+ hover: (sel, opts) => appObj.hover(scoped(sel), opts),
2947
+ fill: (sel, value, opts) => appObj.fill(scoped(sel), value, opts),
2948
+ uploadFile: (sel, path) => appObj.uploadFile(scoped(sel), path),
2949
+ getText: (sel, opts) => appObj.getText(scoped(sel), opts),
2950
+ getAttribute: (sel, name, opts) => appObj.getAttribute(scoped(sel), name, opts),
2951
+ isVisible: (sel, opts) => appObj.isVisible(scoped(sel), opts),
2952
+ isEnabled: (sel, opts) => appObj.isEnabled(scoped(sel), opts),
2953
+ count: (sel, opts) => appObj.count(scoped(sel), opts),
2954
+ expect: (sel) => appExpect(scoped(sel))
2955
+ };
2956
+ },
1824
2957
  getPage: () => {
1825
2958
  if (!driver.getRawPage) {
1826
2959
  throw new DriverError({
1827
2960
  message: "getPage() is only available when running with a browser driver that exposes a raw page."
1828
2961
  });
1829
2962
  }
1830
- return driver.getRawPage();
2963
+ return wrapRawPageWithStepRecording(driver.getRawPage(), recorder);
2964
+ },
2965
+ cdp: () => {
2966
+ const raw = driver.getCdpSession?.();
2967
+ if (!raw) {
2968
+ throw new DriverError({
2969
+ message: "app.cdp() is only available on Chromium web drivers (Direct CDP or Playwright Chromium)."
2970
+ });
2971
+ }
2972
+ return {
2973
+ send: (method, params) => runStep(`cdp.${method}`, () => raw.send(method, params), {
2974
+ selector: params
2975
+ }),
2976
+ on: (event, listener) => raw.on(event, listener),
2977
+ get sessionId() {
2978
+ return raw.sessionId;
2979
+ },
2980
+ get browserContextId() {
2981
+ return raw.browserContextId;
2982
+ }
2983
+ };
1831
2984
  },
1832
2985
  enableVirtualAuthenticator: (opts) => runStep(
1833
2986
  "enableVirtualAuthenticator",
@@ -1849,6 +3002,16 @@ function createPromiseApp(driver, appId, config, recorder, options = {}) {
1849
3002
  "getVirtualCredentials",
1850
3003
  () => run(optionalMethod("getVirtualCredentials", driver.getVirtualCredentials)(authenticatorId))
1851
3004
  ),
3005
+ addVirtualCredential: (credential, authenticatorId) => runStep(
3006
+ "addVirtualCredential",
3007
+ () => run(
3008
+ optionalMethod("addVirtualCredential", driver.addVirtualCredential)(
3009
+ credential,
3010
+ authenticatorId
3011
+ )
3012
+ ),
3013
+ { selector: { credentialId: credential.credentialId, rpId: credential.rpId } }
3014
+ ),
1852
3015
  clearVirtualCredentials: (authenticatorId) => runStep(
1853
3016
  "clearVirtualCredentials",
1854
3017
  () => run(
@@ -1874,8 +3037,8 @@ function createPromiseApp(driver, appId, config, recorder, options = {}) {
1874
3037
  isVisible: (selector, opts) => {
1875
3038
  const timeout = opts?.timeout ?? 1e3;
1876
3039
  return run(
1877
- Effect5.gen(function* () {
1878
- const result = yield* Effect5.either(
3040
+ Effect6.gen(function* () {
3041
+ const result = yield* Effect6.either(
1879
3042
  waitForElement(
1880
3043
  driver,
1881
3044
  selector,
@@ -1889,6 +3052,7 @@ function createPromiseApp(driver, appId, config, recorder, options = {}) {
1889
3052
  );
1890
3053
  },
1891
3054
  isEnabled: (selector, opts) => runStep("isEnabled", () => run(coord.isElementEnabled(selector, opts)), { selector }),
3055
+ count: (selector, opts) => runStep("count", () => run(coord.count(selector, opts)), { selector }),
1892
3056
  // Web-first bridge & fast state helpers
1893
3057
  waitForIdle: (opts) => runStep("waitForIdle", async () => {
1894
3058
  if (driver.domChannel?.waitForIdle) {
@@ -1967,19 +3131,19 @@ function createPromiseApp(driver, appId, config, recorder, options = {}) {
1967
3131
  // WebView / hybrid context switching (low-level escape hatches)
1968
3132
  getContexts: () => runStep(
1969
3133
  "getContexts",
1970
- () => run((driver.getContexts ?? (() => Effect5.succeed(["NATIVE_APP"])))())
3134
+ () => run((driver.getContexts ?? (() => Effect6.succeed(["NATIVE_APP"])))())
1971
3135
  ),
1972
3136
  getCurrentContext: () => runStep(
1973
3137
  "getCurrentContext",
1974
- () => run((driver.getCurrentContext ?? (() => Effect5.succeed("NATIVE_APP")))())
3138
+ () => run((driver.getCurrentContext ?? (() => Effect6.succeed("NATIVE_APP")))())
1975
3139
  ),
1976
3140
  switchToContext: (contextId) => runStep(
1977
3141
  `switchToContext(${contextId})`,
1978
- () => run((driver.setContext ?? ((_id) => Effect5.void))(contextId))
3142
+ () => run((driver.setContext ?? ((_id) => Effect6.void))(contextId))
1979
3143
  ),
1980
3144
  switchToWebView: () => runStep("switchToWebView", async () => {
1981
3145
  const contexts = await run(
1982
- (driver.getContexts ?? (() => Effect5.succeed(["NATIVE_APP"])))()
3146
+ (driver.getContexts ?? (() => Effect6.succeed(["NATIVE_APP"])))()
1983
3147
  );
1984
3148
  const webview = contexts.find((c) => c.startsWith("WEBVIEW_"));
1985
3149
  if (!webview) {
@@ -1987,13 +3151,14 @@ function createPromiseApp(driver, appId, config, recorder, options = {}) {
1987
3151
  message: `No WebView context found. Available contexts: ${contexts.join(", ")}`
1988
3152
  });
1989
3153
  }
1990
- await run((driver.setContext ?? ((_id) => Effect5.void))(webview));
3154
+ await run((driver.setContext ?? ((_id) => Effect6.void))(webview));
1991
3155
  }),
1992
3156
  switchToNativeApp: () => runStep(
1993
3157
  "switchToNativeApp",
1994
- () => run((driver.setContext ?? ((_id) => Effect5.void))("NATIVE_APP"))
3158
+ () => run((driver.setContext ?? ((_id) => Effect6.void))("NATIVE_APP"))
1995
3159
  )
1996
3160
  };
3161
+ return appObj;
1997
3162
  }
1998
3163
 
1999
3164
  // src/drivers/playwright-parser.ts
@@ -2025,15 +3190,18 @@ function parseWebHierarchy(json) {
2025
3190
  }
2026
3191
 
2027
3192
  // src/drivers/raw-driver.ts
2028
- import { Context, Effect as Effect6 } from "effect";
3193
+ import { Context, Effect as Effect7 } from "effect";
2029
3194
  var RawDriver = class extends Context.Tag("RawDriver")() {
2030
3195
  };
2031
3196
 
2032
3197
  // src/drivers/playwright.ts
2033
3198
  import { spawn } from "child_process";
2034
3199
  import { createHash } from "crypto";
3200
+ import { mkdtempSync, rmSync } from "fs";
2035
3201
  import { readFile, writeFile } from "fs/promises";
2036
- import { Effect as Effect7, Layer } from "effect";
3202
+ import { tmpdir } from "os";
3203
+ import { join } from "path";
3204
+ import { Effect as Effect8, Layer } from "effect";
2037
3205
  import {
2038
3206
  chromium,
2039
3207
  firefox,
@@ -2082,18 +3250,12 @@ async function evaluateOnPage(activePage, script, args) {
2082
3250
  if (args.length === 1) {
2083
3251
  return await activePage.evaluate(script, args[0]);
2084
3252
  }
2085
- const fnSource = script.toString();
2086
- return await activePage.evaluate(
2087
- ({ src, params }) => {
2088
- const compiled = (0, eval)(`(${src})`);
2089
- return compiled(...params);
2090
- },
2091
- { src: fnSource, params: args }
2092
- );
3253
+ const serializedArgs = args.map((arg) => arg === void 0 ? "undefined" : JSON.stringify(arg)).join(", ");
3254
+ return await activePage.evaluate(`(${script.toString()})(${serializedArgs})`);
2093
3255
  }
2094
3256
  function resolveWarmBrowserKey(scope) {
2095
3257
  if (scope && scope.trim().length > 0) return scope.trim();
2096
- const cwdHash = createHash("sha1").update(process.cwd()).digest("hex").slice(0, 10);
3258
+ const cwdHash = createHash("sha256").update(process.cwd()).digest("hex").slice(0, 10);
2097
3259
  return `scope-${cwdHash}`;
2098
3260
  }
2099
3261
  var INSTANT_ANIMATIONS_INIT_SCRIPT = `
@@ -2125,19 +3287,29 @@ async function ensureWarmBrowserDaemon(config = {}) {
2125
3287
  } catch {
2126
3288
  }
2127
3289
  }
2128
- const port = allocatePort(9322);
3290
+ const port = await allocateFreePort(9322);
3291
+ const userDataDir = mkdtempSync(join(tmpdir(), "spana-warm-chrome-"));
2129
3292
  const execPath = config.executablePath ?? chromium.executablePath();
2130
3293
  const child = spawn(
2131
3294
  execPath,
2132
3295
  [
2133
3296
  ...config.headless !== false ? ["--headless=new"] : [],
2134
3297
  `--remote-debugging-port=${port}`,
3298
+ "--remote-debugging-address=127.0.0.1",
3299
+ `--user-data-dir=${userDataDir}`,
2135
3300
  "--no-first-run",
2136
3301
  "--no-default-browser-check",
3302
+ "--disable-background-networking",
2137
3303
  "--disable-background-timer-throttling",
2138
3304
  "--disable-backgrounding-occluded-windows",
2139
3305
  "--disable-renderer-backgrounding",
2140
3306
  "--disable-ipc-flooding-protection",
3307
+ "--disable-hang-monitor",
3308
+ "--disable-default-apps",
3309
+ "--disable-extensions",
3310
+ "--disable-sync",
3311
+ "--metrics-recording-only",
3312
+ "--disable-features=Translate,BackForwardCache,AcceptCHFrame,MediaRouter,OptimizationHints",
2141
3313
  ...config.headless !== false ? ["--disable-gpu"] : [],
2142
3314
  "about:blank"
2143
3315
  ],
@@ -2159,6 +3331,11 @@ async function ensureWarmBrowserDaemon(config = {}) {
2159
3331
  await new Promise((r) => setTimeout(r, 80));
2160
3332
  }
2161
3333
  if (!ready) {
3334
+ try {
3335
+ child.kill("SIGKILL");
3336
+ } catch {
3337
+ }
3338
+ rmSync(userDataDir, { recursive: true, force: true });
2162
3339
  throw new Error(`Warm Chromium daemon failed to start on ${cdpUrl}`);
2163
3340
  }
2164
3341
  registerWarmDaemon({
@@ -2167,6 +3344,7 @@ async function ensureWarmBrowserDaemon(config = {}) {
2167
3344
  host: "127.0.0.1",
2168
3345
  port,
2169
3346
  pid: child.pid,
3347
+ userDataDir,
2170
3348
  startedAt: (/* @__PURE__ */ new Date()).toISOString()
2171
3349
  });
2172
3350
  const browser = await chromium.connectOverCDP(cdpUrl);
@@ -2264,24 +3442,92 @@ function totalHarTime(timing) {
2264
3442
  const end = timing.responseEnd >= 0 ? timing.responseEnd : timing.responseStart >= 0 ? timing.responseStart : timing.requestStart >= 0 ? timing.requestStart : 0;
2265
3443
  return Math.max(Math.round(end), 0);
2266
3444
  }
3445
+ function selectorToFrameCss(frameSel) {
3446
+ if (typeof frameSel === "string") return frameSel;
3447
+ if (typeof frameSel === "object" && frameSel !== null) {
3448
+ if ("css" in frameSel && frameSel.css) return frameSel.css;
3449
+ if ("testID" in frameSel && frameSel.testID) return `[data-testid="${frameSel.testID}"]`;
3450
+ if ("accessibilityLabel" in frameSel && frameSel.accessibilityLabel) {
3451
+ return `[aria-label="${frameSel.accessibilityLabel}"], iframe[title="${frameSel.accessibilityLabel}"]`;
3452
+ }
3453
+ }
3454
+ return "iframe";
3455
+ }
3456
+ function resolvePlaywrightLocator(root, selector) {
3457
+ if (typeof selector === "string") {
3458
+ return root.getByLabel(selector, { exact: true });
3459
+ }
3460
+ if ("point" in selector) {
3461
+ throw new DriverError({
3462
+ message: "uploadFile() does not support point selectors on the web platform. Use testID, css, role, text, or accessibilityLabel."
3463
+ });
3464
+ }
3465
+ let scope = root;
3466
+ if (selector.frame) {
3467
+ scope = scope.frameLocator(selectorToFrameCss(selector.frame));
3468
+ }
3469
+ if (selector.within) {
3470
+ scope = resolvePlaywrightLocator(scope, selector.within);
3471
+ }
3472
+ let locator;
3473
+ if ("anyOf" in selector) {
3474
+ const branches = selector.anyOf.map((branch) => resolvePlaywrightLocator(scope, branch));
3475
+ locator = branches.reduce((acc, next) => acc.or(next));
3476
+ } else if ("css" in selector) {
3477
+ locator = scope.locator(selector.css);
3478
+ } else if ("role" in selector) {
3479
+ locator = scope.getByRole(selector.role, {
3480
+ ...selector.name !== void 0 ? { name: selector.name } : {},
3481
+ ...selector.exact !== void 0 ? { exact: selector.exact } : {},
3482
+ ...selector.level !== void 0 ? { level: selector.level } : {},
3483
+ ...selector.includeHidden !== void 0 ? { includeHidden: selector.includeHidden } : {}
3484
+ });
3485
+ } else if ("testID" in selector) {
3486
+ locator = scope.getByTestId(selector.testID);
3487
+ } else if ("accessibilityLabel" in selector) {
3488
+ locator = scope.getByLabel(selector.accessibilityLabel, { exact: true });
3489
+ } else {
3490
+ locator = scope.getByLabel(selector.text, { exact: true });
3491
+ }
3492
+ if (selector.hasText !== void 0) {
3493
+ locator = locator.filter({ hasText: selector.hasText });
3494
+ }
3495
+ if (selector.hasNotText !== void 0) {
3496
+ locator = locator.filter({ hasNotText: selector.hasNotText });
3497
+ }
3498
+ if (selector.has !== void 0) {
3499
+ locator = locator.filter({ has: resolvePlaywrightLocator(scope, selector.has) });
3500
+ }
3501
+ if (selector.hasNot !== void 0) {
3502
+ locator = locator.filter({ hasNot: resolvePlaywrightLocator(scope, selector.hasNot) });
3503
+ }
3504
+ if (selector.first) {
3505
+ locator = locator.first();
3506
+ } else if (selector.last) {
3507
+ locator = locator.last();
3508
+ } else if (typeof selector.nth === "number") {
3509
+ locator = locator.nth(selector.nth);
3510
+ }
3511
+ return locator;
3512
+ }
2267
3513
  function makePlaywrightDriver(config) {
2268
- return Effect7.gen(function* () {
3514
+ return Effect8.gen(function* () {
2269
3515
  const browserName = config.browser ?? "chromium";
2270
3516
  const ownsBrowser = !config.sharedBrowser && !config.cdpEndpoint && !config.wsEndpoint && !config.warmBrowser;
2271
- const browser = config.sharedBrowser ? config.sharedBrowser : config.wsEndpoint ? yield* Effect7.tryPromise({
3517
+ const browser = config.sharedBrowser ? config.sharedBrowser : config.wsEndpoint ? yield* Effect8.tryPromise({
2272
3518
  try: () => browserLaunchers[browserName].connect(config.wsEndpoint),
2273
3519
  catch: (e) => new DriverError({
2274
3520
  message: `Failed to connect to remote Playwright server (${config.wsEndpoint}): ${e}`
2275
3521
  })
2276
- }) : config.cdpEndpoint ? yield* Effect7.tryPromise({
3522
+ }) : config.cdpEndpoint ? yield* Effect8.tryPromise({
2277
3523
  try: () => chromium.connectOverCDP(config.cdpEndpoint),
2278
3524
  catch: (e) => new DriverError({
2279
3525
  message: `Failed to connect to browser over CDP (${config.cdpEndpoint}): ${e}`
2280
3526
  })
2281
- }) : config.warmBrowser && browserName === "chromium" ? yield* Effect7.tryPromise({
3527
+ }) : config.warmBrowser && browserName === "chromium" ? yield* Effect8.tryPromise({
2282
3528
  try: async () => (await ensureWarmBrowserDaemon(config)).browser,
2283
3529
  catch: (e) => new DriverError({ message: `Failed to connect to warm Chromium daemon: ${e}` })
2284
- }) : yield* Effect7.tryPromise({
3530
+ }) : yield* Effect8.tryPromise({
2285
3531
  try: () => browserLaunchers[browserName].launch({
2286
3532
  headless: config.headless ?? true,
2287
3533
  ...config.channel ? { channel: config.channel } : {},
@@ -2585,26 +3831,32 @@ function makePlaywrightDriver(config) {
2585
3831
  }
2586
3832
  if ("point" in selector) {
2587
3833
  throw new DriverError({
2588
- message: "uploadFile() does not support point selectors on the web platform. Use testID, text, or accessibilityLabel."
3834
+ message: "uploadFile() does not support point selectors on the web platform. Use testID, css, role, text, or accessibilityLabel."
2589
3835
  });
2590
3836
  }
2591
- if ("testID" in selector) {
2592
- await page.getByTestId(selector.testID).setInputFiles(path);
2593
- return;
2594
- }
2595
- if ("accessibilityLabel" in selector) {
2596
- await page.getByLabel(selector.accessibilityLabel, { exact: true }).setInputFiles(path);
2597
- return;
2598
- }
2599
- if ("text" in selector) {
2600
- try {
2601
- await page.getByLabel(selector.text, { exact: true }).setInputFiles(path);
3837
+ const hasModifiers = Boolean(
3838
+ selector.within || selector.frame || selector.hasText !== void 0 || selector.hasNotText !== void 0 || selector.nth !== void 0 || selector.first || selector.last
3839
+ );
3840
+ if (!hasModifiers) {
3841
+ if ("testID" in selector) {
3842
+ await page.getByTestId(selector.testID).setInputFiles(path);
2602
3843
  return;
2603
- } catch {
2604
- await page.getByText(selector.text, { exact: true }).setInputFiles(path);
3844
+ }
3845
+ if ("accessibilityLabel" in selector) {
3846
+ await page.getByLabel(selector.accessibilityLabel, { exact: true }).setInputFiles(path);
2605
3847
  return;
2606
3848
  }
3849
+ if ("text" in selector) {
3850
+ try {
3851
+ await page.getByLabel(selector.text, { exact: true }).setInputFiles(path);
3852
+ return;
3853
+ } catch {
3854
+ await page.getByText(selector.text, { exact: true }).setInputFiles(path);
3855
+ return;
3856
+ }
3857
+ }
2607
3858
  }
3859
+ await resolvePlaywrightLocator(page, selector).setInputFiles(path);
2608
3860
  };
2609
3861
  const applyContextSpeedOptions = async (ctx) => {
2610
3862
  if (config.instantAnimations && typeof ctx.addInitScript === "function") {
@@ -2752,7 +4004,7 @@ function makePlaywrightDriver(config) {
2752
4004
  updateHarPage(page);
2753
4005
  debugLog("beginFlow", flowName);
2754
4006
  };
2755
- yield* Effect7.tryPromise({
4007
+ yield* Effect8.tryPromise({
2756
4008
  try: () => createContextAndPage(config.storageState),
2757
4009
  catch: (e) => new DriverError({ message: `Failed to create page: ${e}` })
2758
4010
  });
@@ -2795,11 +4047,11 @@ function makePlaywrightDriver(config) {
2795
4047
  };
2796
4048
  const service = {
2797
4049
  ...domChannel ? { domChannel } : {},
2798
- beginFlow: (flowName) => Effect7.tryPromise({
4050
+ beginFlow: (flowName) => Effect8.tryPromise({
2799
4051
  try: () => beginFlow(flowName),
2800
4052
  catch: (e) => new DriverError({ message: `Failed to prepare flow ${flowName}: ${e}` })
2801
4053
  }),
2802
- dumpHierarchy: () => Effect7.tryPromise({
4054
+ dumpHierarchy: () => Effect8.tryPromise({
2803
4055
  try: async () => {
2804
4056
  const tree = await page.evaluate(`
2805
4057
  (function() {
@@ -2834,17 +4086,17 @@ function makePlaywrightDriver(config) {
2834
4086
  },
2835
4087
  catch: (e) => new DriverError({ message: `Failed to dump hierarchy: ${e}` })
2836
4088
  }),
2837
- tapAtCoordinate: (x, y) => Effect7.tryPromise({
4089
+ tapAtCoordinate: (x, y) => Effect8.tryPromise({
2838
4090
  try: async () => {
2839
4091
  await page.mouse.click(x, y);
2840
4092
  },
2841
4093
  catch: (e) => new DriverError({ message: `Failed to tap at (${x}, ${y}): ${e}` })
2842
4094
  }),
2843
- doubleTapAtCoordinate: (x, y) => Effect7.tryPromise({
4095
+ doubleTapAtCoordinate: (x, y) => Effect8.tryPromise({
2844
4096
  try: () => page.mouse.dblclick(x, y),
2845
4097
  catch: (e) => new DriverError({ message: `Failed to double tap at (${x}, ${y}): ${e}` })
2846
4098
  }),
2847
- longPressAtCoordinate: (x, y, duration) => Effect7.tryPromise({
4099
+ longPressAtCoordinate: (x, y, duration) => Effect8.tryPromise({
2848
4100
  try: async () => {
2849
4101
  await page.mouse.move(x, y);
2850
4102
  await page.mouse.down();
@@ -2853,7 +4105,7 @@ function makePlaywrightDriver(config) {
2853
4105
  },
2854
4106
  catch: (e) => new DriverError({ message: `Failed to long press at (${x}, ${y}): ${e}` })
2855
4107
  }),
2856
- swipe: (startX, startY, endX, endY, duration) => Effect7.tryPromise({
4108
+ swipe: (startX, startY, endX, endY, duration) => Effect8.tryPromise({
2857
4109
  try: async () => {
2858
4110
  await page.evaluate(`
2859
4111
  (function() {
@@ -2890,23 +4142,23 @@ function makePlaywrightDriver(config) {
2890
4142
  },
2891
4143
  catch: (e) => new DriverError({ message: `Failed to swipe: ${e}` })
2892
4144
  }),
2893
- inputText: (text) => Effect7.tryPromise({
4145
+ inputText: (text) => Effect8.tryPromise({
2894
4146
  try: () => page.keyboard.insertText(text),
2895
4147
  catch: (e) => new DriverError({ message: `Failed to input text: ${e}` })
2896
4148
  }),
2897
- pressKey: (key) => Effect7.tryPromise({
4149
+ pressKey: (key) => Effect8.tryPromise({
2898
4150
  try: () => page.keyboard.press(key),
2899
4151
  catch: (e) => new DriverError({ message: `Failed to press key ${key}: ${e}` })
2900
4152
  }),
2901
- hideKeyboard: () => Effect7.void,
2902
- takeScreenshot: () => Effect7.tryPromise({
4153
+ hideKeyboard: () => Effect8.void,
4154
+ takeScreenshot: () => Effect8.tryPromise({
2903
4155
  try: async () => {
2904
4156
  const buffer = await page.screenshot();
2905
4157
  return new Uint8Array(buffer);
2906
4158
  },
2907
4159
  catch: (e) => new DriverError({ message: `Failed to take screenshot: ${e}` })
2908
4160
  }),
2909
- getDeviceInfo: () => Effect7.tryPromise({
4161
+ getDeviceInfo: () => Effect8.tryPromise({
2910
4162
  try: async () => {
2911
4163
  const viewport = page.viewportSize() ?? { width: 1280, height: 720 };
2912
4164
  return {
@@ -2921,7 +4173,7 @@ function makePlaywrightDriver(config) {
2921
4173
  },
2922
4174
  catch: (e) => new DriverError({ message: `Failed to get device info: ${e}` })
2923
4175
  }),
2924
- launchApp: (url, opts) => Effect7.tryPromise({
4176
+ launchApp: (url, opts) => Effect8.tryPromise({
2925
4177
  try: async () => {
2926
4178
  const targetUrl = opts?.deepLink || url || config.baseUrl || "about:blank";
2927
4179
  if (opts?.clearState) {
@@ -2942,7 +4194,7 @@ function makePlaywrightDriver(config) {
2942
4194
  },
2943
4195
  catch: (e) => new DriverError({ message: `Failed to navigate to ${url}: ${e}` })
2944
4196
  }),
2945
- stopApp: (_id) => Effect7.tryPromise({
4197
+ stopApp: (_id) => Effect8.tryPromise({
2946
4198
  try: async () => {
2947
4199
  await page.goto("about:blank");
2948
4200
  updateHarPage(page);
@@ -2950,7 +4202,7 @@ function makePlaywrightDriver(config) {
2950
4202
  },
2951
4203
  catch: (e) => new DriverError({ message: `Failed to stop app: ${e}` })
2952
4204
  }),
2953
- killApp: (_id) => Effect7.tryPromise({
4205
+ killApp: (_id) => Effect8.tryPromise({
2954
4206
  try: async () => {
2955
4207
  const prefetched = prefetchedSlotPromise;
2956
4208
  prefetchedSlotPromise = void 0;
@@ -2973,14 +4225,14 @@ function makePlaywrightDriver(config) {
2973
4225
  },
2974
4226
  catch: (e) => new DriverError({ message: `Failed to kill app: ${e}` })
2975
4227
  }),
2976
- clearAppState: (_id) => Effect7.tryPromise({
4228
+ clearAppState: (_id) => Effect8.tryPromise({
2977
4229
  try: async () => {
2978
4230
  await clearStorage();
2979
4231
  debugLog("clearAppState");
2980
4232
  },
2981
4233
  catch: (e) => new DriverError({ message: `Failed to clear app state: ${e}` })
2982
4234
  }),
2983
- openLink: (url) => Effect7.tryPromise({
4235
+ openLink: (url) => Effect8.tryPromise({
2984
4236
  try: async () => {
2985
4237
  await page.goto(url, config.waitUntil ? { waitUntil: config.waitUntil } : void 0);
2986
4238
  updateHarPage(page);
@@ -2989,7 +4241,7 @@ function makePlaywrightDriver(config) {
2989
4241
  },
2990
4242
  catch: (e) => new DriverError({ message: `Failed to open link ${url}: ${e}` })
2991
4243
  }),
2992
- back: () => Effect7.tryPromise({
4244
+ back: () => Effect8.tryPromise({
2993
4245
  try: async () => {
2994
4246
  await page.goBack();
2995
4247
  updateHarPage(page);
@@ -2997,12 +4249,56 @@ function makePlaywrightDriver(config) {
2997
4249
  },
2998
4250
  catch: (e) => new DriverError({ message: `Failed to go back: ${e}` })
2999
4251
  }),
3000
- evaluate: (script, ...args) => Effect7.tryPromise({
4252
+ reload: (reloadOpts) => Effect8.tryPromise({
4253
+ try: async () => {
4254
+ const waitUntil = reloadOpts?.waitUntil ?? config.waitUntil;
4255
+ await page.reload(waitUntil ? { waitUntil } : void 0);
4256
+ updateHarPage(page);
4257
+ debugLog("reload", currentPageUrl(page));
4258
+ },
4259
+ catch: (e) => new DriverError({ message: `Failed to reload page: ${e}` })
4260
+ }),
4261
+ hoverAtCoordinate: (x, y) => Effect8.tryPromise({
4262
+ try: async () => {
4263
+ await page.mouse.move(x, y);
4264
+ },
4265
+ catch: (e) => new DriverError({ message: `Failed to hover at (${x}, ${y}): ${e}` })
4266
+ }),
4267
+ getUrl: () => Effect8.sync(() => currentPageUrl(page)),
4268
+ evaluate: (script, ...args) => Effect8.tryPromise({
3001
4269
  try: () => evaluateOnPage(page, script, args),
3002
4270
  catch: (e) => new DriverError({ message: `Evaluate failed: ${e}` })
3003
4271
  }),
3004
4272
  getRawPage: () => page,
3005
- enableVirtualAuthenticator: (opts) => Effect7.tryPromise({
4273
+ getCdpSession: () => {
4274
+ if (browserName !== "chromium") return void 0;
4275
+ return {
4276
+ send: async (method, params) => {
4277
+ const session = await ensureCdpSession();
4278
+ return await session.send(method, params);
4279
+ },
4280
+ on: (event, listener) => {
4281
+ let unsubscribed = false;
4282
+ let attachedSession;
4283
+ const wrapped = (params) => {
4284
+ if (!unsubscribed) listener(params ?? {});
4285
+ };
4286
+ void ensureCdpSession().then((session) => {
4287
+ if (unsubscribed) return;
4288
+ attachedSession = session;
4289
+ session.on(event, wrapped);
4290
+ }).catch(() => {
4291
+ });
4292
+ return () => {
4293
+ unsubscribed = true;
4294
+ if (attachedSession && typeof attachedSession.off === "function") {
4295
+ attachedSession.off(event, wrapped);
4296
+ }
4297
+ };
4298
+ }
4299
+ };
4300
+ },
4301
+ enableVirtualAuthenticator: (opts) => Effect8.tryPromise({
3006
4302
  try: async () => {
3007
4303
  const attached = await attachVirtualAuthenticatorOn(context, page, opts);
3008
4304
  activeAuthenticatorId = attached.authenticatorId;
@@ -3011,7 +4307,7 @@ function makePlaywrightDriver(config) {
3011
4307
  },
3012
4308
  catch: (e) => e instanceof DriverError ? e : new DriverError({ message: `Failed to enable virtual authenticator: ${e}` })
3013
4309
  }),
3014
- removeVirtualAuthenticator: (authenticatorId) => Effect7.tryPromise({
4310
+ removeVirtualAuthenticator: (authenticatorId) => Effect8.tryPromise({
3015
4311
  try: async () => {
3016
4312
  const id = authenticatorId ?? activeAuthenticatorId;
3017
4313
  if (!id) return;
@@ -3022,7 +4318,7 @@ function makePlaywrightDriver(config) {
3022
4318
  },
3023
4319
  catch: (e) => new DriverError({ message: `Failed to remove virtual authenticator: ${e}` })
3024
4320
  }),
3025
- getVirtualCredentials: (authenticatorId) => Effect7.tryPromise({
4321
+ getVirtualCredentials: (authenticatorId) => Effect8.tryPromise({
3026
4322
  try: async () => {
3027
4323
  const id = authenticatorId ?? activeAuthenticatorId;
3028
4324
  if (!id) return [];
@@ -3034,7 +4330,37 @@ function makePlaywrightDriver(config) {
3034
4330
  },
3035
4331
  catch: (e) => new DriverError({ message: `Failed to read virtual credentials: ${e}` })
3036
4332
  }),
3037
- clearVirtualCredentials: (authenticatorId) => Effect7.tryPromise({
4333
+ addVirtualCredential: (credential, authenticatorId) => Effect8.tryPromise({
4334
+ try: async () => {
4335
+ if (browserName !== "chromium") {
4336
+ throw new DriverError({
4337
+ message: "addVirtualCredential() is only supported on Chromium browsers."
4338
+ });
4339
+ }
4340
+ let id = authenticatorId ?? activeAuthenticatorId;
4341
+ if (!id) {
4342
+ const attached = await attachVirtualAuthenticatorOn(context, page);
4343
+ id = attached.authenticatorId;
4344
+ activeAuthenticatorId = id;
4345
+ }
4346
+ const session = await ensureCdpSession();
4347
+ await session.send("WebAuthn.addCredential", {
4348
+ authenticatorId: id,
4349
+ credential: {
4350
+ credentialId: credential.credentialId,
4351
+ isResidentCredential: credential.isResidentCredential,
4352
+ privateKey: credential.privateKey,
4353
+ signCount: credential.signCount ?? 0,
4354
+ ...credential.rpId !== void 0 ? { rpId: credential.rpId } : {},
4355
+ ...credential.userHandle !== void 0 ? { userHandle: credential.userHandle } : {},
4356
+ ...credential.userName !== void 0 ? { userName: credential.userName } : {}
4357
+ }
4358
+ });
4359
+ debugLog("addVirtualCredential", id, credential.credentialId);
4360
+ },
4361
+ catch: (e) => e instanceof DriverError ? e : new DriverError({ message: `Failed to import virtual credential: ${e}` })
4362
+ }),
4363
+ clearVirtualCredentials: (authenticatorId) => Effect8.tryPromise({
3038
4364
  try: async () => {
3039
4365
  const id = authenticatorId ?? activeAuthenticatorId;
3040
4366
  if (!id) return;
@@ -3044,7 +4370,7 @@ function makePlaywrightDriver(config) {
3044
4370
  },
3045
4371
  catch: (e) => new DriverError({ message: `Failed to clear virtual credentials: ${e}` })
3046
4372
  }),
3047
- mockNetwork: (matcher, response) => Effect7.tryPromise({
4373
+ mockNetwork: (matcher, response) => Effect8.tryPromise({
3048
4374
  try: async () => {
3049
4375
  buildMockResponse(response);
3050
4376
  const definition = { kind: "mock", matcher, response };
@@ -3054,7 +4380,7 @@ function makePlaywrightDriver(config) {
3054
4380
  },
3055
4381
  catch: (e) => new DriverError({ message: `Failed to mock network route: ${e}` })
3056
4382
  }),
3057
- blockNetwork: (matcher) => Effect7.tryPromise({
4383
+ blockNetwork: (matcher) => Effect8.tryPromise({
3058
4384
  try: async () => {
3059
4385
  const definition = { kind: "block", matcher };
3060
4386
  routeDefinitions.push(definition);
@@ -3063,7 +4389,7 @@ function makePlaywrightDriver(config) {
3063
4389
  },
3064
4390
  catch: (e) => new DriverError({ message: `Failed to block network route: ${e}` })
3065
4391
  }),
3066
- clearNetworkMocks: () => Effect7.tryPromise({
4392
+ clearNetworkMocks: () => Effect8.tryPromise({
3067
4393
  try: async () => {
3068
4394
  for (const appliedRoute of appliedRoutes) {
3069
4395
  await context.unroute(appliedRoute.matcher, appliedRoute.handler);
@@ -3074,7 +4400,7 @@ function makePlaywrightDriver(config) {
3074
4400
  },
3075
4401
  catch: (e) => new DriverError({ message: `Failed to clear network mocks: ${e}` })
3076
4402
  }),
3077
- setNetworkConditions: (conditions) => Effect7.tryPromise({
4403
+ setNetworkConditions: (conditions) => Effect8.tryPromise({
3078
4404
  try: async () => {
3079
4405
  currentNetworkConditions = { ...conditions };
3080
4406
  await applyNetworkConditions();
@@ -3082,7 +4408,7 @@ function makePlaywrightDriver(config) {
3082
4408
  },
3083
4409
  catch: (e) => new DriverError({ message: `Failed to set network conditions: ${e}` })
3084
4410
  }),
3085
- saveCookies: (path) => Effect7.tryPromise({
4411
+ saveCookies: (path) => Effect8.tryPromise({
3086
4412
  try: async () => {
3087
4413
  const cookies = await context.cookies();
3088
4414
  await writeFile(path, JSON.stringify(cookies, null, 2), "utf8");
@@ -3090,7 +4416,7 @@ function makePlaywrightDriver(config) {
3090
4416
  },
3091
4417
  catch: (e) => new DriverError({ message: `Failed to save cookies to ${path}: ${e}` })
3092
4418
  }),
3093
- loadCookies: (path) => Effect7.tryPromise({
4419
+ loadCookies: (path) => Effect8.tryPromise({
3094
4420
  try: async () => {
3095
4421
  const contents = await readFile(path, "utf8");
3096
4422
  const cookies = JSON.parse(contents);
@@ -3102,14 +4428,117 @@ function makePlaywrightDriver(config) {
3102
4428
  },
3103
4429
  catch: (e) => new DriverError({ message: `Failed to load cookies from ${path}: ${e}` })
3104
4430
  }),
3105
- saveAuthState: (path) => Effect7.tryPromise({
4431
+ getCookies: (urls) => Effect8.tryPromise({
4432
+ try: async () => {
4433
+ const cookies = await (urls && urls.length > 0 ? context.cookies(urls) : context.cookies());
4434
+ return cookies;
4435
+ },
4436
+ catch: (e) => new DriverError({ message: `Failed to read cookies: ${e}` })
4437
+ }),
4438
+ setCookies: (cookies) => Effect8.tryPromise({
4439
+ try: async () => {
4440
+ if (cookies.length === 0) return;
4441
+ await context.addCookies(cookies);
4442
+ },
4443
+ catch: (e) => new DriverError({ message: `Failed to set cookies: ${e}` })
4444
+ }),
4445
+ clearCookies: () => Effect8.tryPromise({
4446
+ try: async () => {
4447
+ await context.clearCookies();
4448
+ },
4449
+ catch: (e) => new DriverError({ message: `Failed to clear cookies: ${e}` })
4450
+ }),
4451
+ waitForResponse: (matcher, waitOpts) => Effect8.tryPromise({
4452
+ try: async () => {
4453
+ const timeout = waitOpts?.timeout ?? 15e3;
4454
+ const matches = (res) => {
4455
+ const info = {
4456
+ url: res.url(),
4457
+ status: res.status(),
4458
+ statusText: res.statusText(),
4459
+ headers: res.headers(),
4460
+ method: res.request().method(),
4461
+ body: () => res.text(),
4462
+ json: () => res.json()
4463
+ };
4464
+ const ok = typeof matcher === "function" ? matcher(info) : matcher instanceof RegExp ? matcher.test(info.url) : info.url.includes(matcher);
4465
+ return ok ? info : null;
4466
+ };
4467
+ return await new Promise((resolve2, reject) => {
4468
+ const watchedPages = /* @__PURE__ */ new Set();
4469
+ let settled = false;
4470
+ const onResponse = (res) => {
4471
+ if (settled) return;
4472
+ const hit = matches(res);
4473
+ if (hit) {
4474
+ cleanup();
4475
+ resolve2(hit);
4476
+ }
4477
+ };
4478
+ const attachPage = (p) => {
4479
+ if (watchedPages.has(p)) return;
4480
+ watchedPages.add(p);
4481
+ p.on("response", onResponse);
4482
+ };
4483
+ const onNewPage = (p) => {
4484
+ if (!settled) attachPage(p);
4485
+ };
4486
+ const cleanup = () => {
4487
+ if (settled) return;
4488
+ settled = true;
4489
+ clearTimeout(timer);
4490
+ context.off("page", onNewPage);
4491
+ for (const p of watchedPages) {
4492
+ p.off("response", onResponse);
4493
+ }
4494
+ watchedPages.clear();
4495
+ };
4496
+ const timer = setTimeout(() => {
4497
+ cleanup();
4498
+ reject(new Error(`Timed out waiting for response after ${timeout}ms`));
4499
+ }, timeout);
4500
+ for (const existingPage of context.pages()) {
4501
+ attachPage(existingPage);
4502
+ }
4503
+ attachPage(page);
4504
+ context.on("page", onNewPage);
4505
+ });
4506
+ },
4507
+ catch: (e) => new DriverError({ message: `waitForResponse() failed: ${e}` })
4508
+ }),
4509
+ createIsolatedContext: (ctxOpts) => Effect8.tryPromise({
4510
+ try: async () => {
4511
+ const childDriver = await Effect8.runPromise(
4512
+ makePlaywrightDriver({
4513
+ ...config,
4514
+ sharedBrowser: browser,
4515
+ freshContextPerFlow: false,
4516
+ warmBrowser: false,
4517
+ cdpEndpoint: void 0,
4518
+ wsEndpoint: void 0
4519
+ })
4520
+ );
4521
+ if (ctxOpts?.url) {
4522
+ await Effect8.runPromise(childDriver.openLink(ctxOpts.url));
4523
+ }
4524
+ return {
4525
+ driver: childDriver,
4526
+ close: async () => {
4527
+ await Effect8.runPromise(childDriver.killApp("isolated-context")).catch(() => {
4528
+ });
4529
+ }
4530
+ };
4531
+ },
4532
+ catch: (e) => new DriverError({ message: `createIsolatedContext() failed: ${e}` })
4533
+ }),
4534
+ saveAuthState: (path) => Effect8.tryPromise({
3106
4535
  try: async () => {
3107
4536
  await context.storageState({ path });
3108
4537
  debugLog("saveAuthState", path);
3109
4538
  },
3110
4539
  catch: (e) => new DriverError({ message: `Failed to save auth state to ${path}: ${e}` })
3111
4540
  }),
3112
- loadAuthState: (path) => Effect7.tryPromise({
4541
+ loadAuthState: (path) => Effect8.tryPromise({
3113
4542
  try: async () => {
3114
4543
  await replaceContext(path);
3115
4544
  updateHarPage(page);
@@ -3117,7 +4546,7 @@ function makePlaywrightDriver(config) {
3117
4546
  },
3118
4547
  catch: (e) => new DriverError({ message: `Failed to load auth state from ${path}: ${e}` })
3119
4548
  }),
3120
- downloadFile: (path) => Effect7.tryPromise({
4549
+ downloadFile: (path) => Effect8.tryPromise({
3121
4550
  try: async () => {
3122
4551
  const download = await nextDownload();
3123
4552
  await download.saveAs(path);
@@ -3125,14 +4554,16 @@ function makePlaywrightDriver(config) {
3125
4554
  },
3126
4555
  catch: (e) => new DriverError({ message: `Failed to download file to ${path}: ${e}` })
3127
4556
  }),
3128
- uploadFile: (selector, path) => Effect7.tryPromise({
4557
+ uploadFile: (selector, path) => Effect8.tryPromise({
3129
4558
  try: async () => {
3130
4559
  await setInputFiles(selector, path);
3131
- debugLog("uploadFile", path);
4560
+ debugLog("uploadFile", Array.isArray(path) ? path.join(", ") : path);
3132
4561
  },
3133
- catch: (e) => new DriverError({ message: `Failed to upload file ${path}: ${e}` })
4562
+ catch: (e) => new DriverError({
4563
+ message: `Failed to upload file ${Array.isArray(path) ? path.join(", ") : path}: ${e}`
4564
+ })
3134
4565
  }),
3135
- newTab: (url) => Effect7.tryPromise({
4566
+ newTab: (url) => Effect8.tryPromise({
3136
4567
  try: async () => {
3137
4568
  const nextPage = await context.newPage();
3138
4569
  attachPageDiagnostics(nextPage);
@@ -3147,7 +4578,7 @@ function makePlaywrightDriver(config) {
3147
4578
  },
3148
4579
  catch: (e) => new DriverError({ message: `Failed to open a new tab: ${e}` })
3149
4580
  }),
3150
- switchToTab: (index) => Effect7.tryPromise({
4581
+ switchToTab: (index) => Effect8.tryPromise({
3151
4582
  try: async () => {
3152
4583
  const openPages = context.pages();
3153
4584
  const nextPage = openPages[index];
@@ -3163,7 +4594,7 @@ function makePlaywrightDriver(config) {
3163
4594
  },
3164
4595
  catch: (e) => new DriverError({ message: `Failed to switch tabs: ${e}` })
3165
4596
  }),
3166
- closeTab: () => Effect7.tryPromise({
4597
+ closeTab: () => Effect8.tryPromise({
3167
4598
  try: async () => {
3168
4599
  const openPages = context.pages();
3169
4600
  if (openPages.length <= 1) {
@@ -3183,14 +4614,14 @@ function makePlaywrightDriver(config) {
3183
4614
  },
3184
4615
  catch: (e) => new DriverError({ message: `Failed to close the current tab: ${e}` })
3185
4616
  }),
3186
- getTabIds: () => Effect7.sync(() => {
4617
+ getTabIds: () => Effect8.sync(() => {
3187
4618
  const ids = context.pages().map((openPage) => getTabId(openPage));
3188
4619
  debugLog("getTabIds", ids.join(", "));
3189
4620
  return ids;
3190
4621
  }),
3191
- getConsoleLogs: () => Effect7.succeed([...consoleLogs]),
3192
- getJSErrors: () => Effect7.succeed([...jsErrors]),
3193
- getHAR: () => Effect7.sync(() => ({
4622
+ getConsoleLogs: () => Effect8.succeed([...consoleLogs]),
4623
+ getJSErrors: () => Effect8.succeed([...jsErrors]),
4624
+ getHAR: () => Effect8.sync(() => ({
3194
4625
  log: {
3195
4626
  version: "1.2",
3196
4627
  creator: {
@@ -3210,7 +4641,7 @@ function makePlaywrightDriver(config) {
3210
4641
  }
3211
4642
 
3212
4643
  // src/drivers/uiautomator2/driver.ts
3213
- import { Effect as Effect8 } from "effect";
4644
+ import { Effect as Effect9 } from "effect";
3214
4645
 
3215
4646
  // src/drivers/uiautomator2/client.ts
3216
4647
  var UiAutomator2Client = class {
@@ -3554,9 +4985,21 @@ var UiAutomator2Client = class {
3554
4985
 
3555
4986
  // src/drivers/uiautomator2/driver.ts
3556
4987
  function createUiAutomator2Driver(host, port, serial, packageName, driverOptions) {
3557
- return Effect8.gen(function* () {
4988
+ return Effect9.gen(function* () {
3558
4989
  const client = new UiAutomator2Client(host, port);
3559
4990
  let currentContext = "NATIVE_APP";
4991
+ let hasLaunchedOnce = false;
4992
+ const waitForAndroidReady = async (maxMs) => {
4993
+ const deadline = Date.now() + maxMs;
4994
+ while (Date.now() < deadline) {
4995
+ try {
4996
+ await client.getWindowSize();
4997
+ return;
4998
+ } catch {
4999
+ await new Promise((resolve2) => setTimeout(resolve2, 40));
5000
+ }
5001
+ }
5002
+ };
3560
5003
  const cdpChannel = driverOptions?.enableWebViewCdp === false ? void 0 : createAndroidWebViewCdpChannel({
3561
5004
  serial,
3562
5005
  packageName: packageName || void 0,
@@ -3566,7 +5009,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3566
5009
  if (driverOptions?.domChannel) channels.push(driverOptions.domChannel);
3567
5010
  if (cdpChannel) channels.push(cdpChannel);
3568
5011
  const domChannel = channels.length === 0 ? void 0 : channels.length === 1 ? channels[0] : createCompositeDomChannel(channels);
3569
- yield* Effect8.tryPromise({
5012
+ yield* Effect9.tryPromise({
3570
5013
  try: () => client.createSession(packageName),
3571
5014
  catch: (e) => new DriverError({
3572
5015
  message: `Failed to create UiAutomator2 session: ${e}`
@@ -3577,70 +5020,70 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3577
5020
  // -----------------------------------------------------------------------
3578
5021
  // Hierarchy
3579
5022
  // -----------------------------------------------------------------------
3580
- dumpHierarchy: () => Effect8.tryPromise({
5023
+ dumpHierarchy: () => Effect9.tryPromise({
3581
5024
  try: () => client.getSource(),
3582
5025
  catch: (e) => new DriverError({ message: `Failed to get page source: ${e}` })
3583
5026
  }),
3584
5027
  // -----------------------------------------------------------------------
3585
5028
  // Coordinate-level actions
3586
5029
  // -----------------------------------------------------------------------
3587
- tapAtCoordinate: (x, y) => Effect8.tryPromise({
5030
+ tapAtCoordinate: (x, y) => Effect9.tryPromise({
3588
5031
  try: () => client.performTap(x, y),
3589
5032
  catch: (e) => new DriverError({ message: `Tap failed: ${e}` })
3590
5033
  }),
3591
- doubleTapAtCoordinate: (x, y) => Effect8.tryPromise({
5034
+ doubleTapAtCoordinate: (x, y) => Effect9.tryPromise({
3592
5035
  try: async () => {
3593
5036
  await client.performTap(x, y);
3594
5037
  await client.performTap(x, y);
3595
5038
  },
3596
5039
  catch: (e) => new DriverError({ message: `Double tap failed: ${e}` })
3597
5040
  }),
3598
- longPressAtCoordinate: (x, y, duration) => Effect8.tryPromise({
5041
+ longPressAtCoordinate: (x, y, duration) => Effect9.tryPromise({
3599
5042
  try: () => client.performLongPress(x, y, duration),
3600
5043
  catch: (e) => new DriverError({ message: `Long press failed: ${e}` })
3601
5044
  }),
3602
- swipe: (sx, sy, ex, ey, dur) => Effect8.tryPromise({
5045
+ swipe: (sx, sy, ex, ey, dur) => Effect9.tryPromise({
3603
5046
  try: () => client.performSwipe(sx, sy, ex, ey, dur),
3604
5047
  catch: (e) => new DriverError({ message: `Swipe failed: ${e}` })
3605
5048
  }),
3606
- pinch: (cx, cy, scale, duration) => Effect8.tryPromise({
5049
+ pinch: (cx, cy, scale, duration) => Effect9.tryPromise({
3607
5050
  try: () => client.performPinch(cx, cy, scale, duration),
3608
5051
  catch: (e) => new DriverError({ message: `Pinch failed: ${e}` })
3609
5052
  }),
3610
- zoom: (cx, cy, scale, duration) => Effect8.tryPromise({
5053
+ zoom: (cx, cy, scale, duration) => Effect9.tryPromise({
3611
5054
  try: () => client.performZoom(cx, cy, scale, duration),
3612
5055
  catch: (e) => new DriverError({ message: `Zoom failed: ${e}` })
3613
5056
  }),
3614
- multiTouch: (sequences) => Effect8.tryPromise({
5057
+ multiTouch: (sequences) => Effect9.tryPromise({
3615
5058
  try: () => client.performMultiTouch(sequences),
3616
5059
  catch: (e) => new DriverError({ message: `Multi-touch failed: ${e}` })
3617
5060
  }),
3618
5061
  // -----------------------------------------------------------------------
3619
5062
  // Text input
3620
5063
  // -----------------------------------------------------------------------
3621
- inputText: (text) => Effect8.tryPromise({
5064
+ inputText: (text) => Effect9.tryPromise({
3622
5065
  try: () => client.sendKeys(text),
3623
5066
  catch: (e) => new DriverError({ message: `Input text failed: ${e}` })
3624
5067
  }),
3625
- pressKey: (key) => Effect8.tryPromise({
5068
+ pressKey: (key) => Effect9.tryPromise({
3626
5069
  try: () => client.pressKeyCode(parseInt(key, 10) || 0),
3627
5070
  catch: (e) => new DriverError({ message: `Press key failed: ${e}` })
3628
5071
  }),
3629
- hideKeyboard: () => Effect8.tryPromise({
5072
+ hideKeyboard: () => Effect9.tryPromise({
3630
5073
  try: () => client.hideKeyboard(),
3631
5074
  catch: (e) => new DriverError({ message: `Hide keyboard failed: ${e}` })
3632
5075
  }),
3633
5076
  // -----------------------------------------------------------------------
3634
5077
  // Queries
3635
5078
  // -----------------------------------------------------------------------
3636
- takeScreenshot: () => Effect8.tryPromise({
5079
+ takeScreenshot: () => Effect9.tryPromise({
3637
5080
  try: async () => {
3638
5081
  const base64 = await client.getScreenshot();
3639
- return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
5082
+ return new Uint8Array(Buffer.from(base64, "base64"));
3640
5083
  },
3641
5084
  catch: (e) => new DriverError({ message: `Screenshot failed: ${e}` })
3642
5085
  }),
3643
- getDeviceInfo: () => Effect8.tryPromise({
5086
+ getDeviceInfo: () => Effect9.tryPromise({
3644
5087
  try: async () => {
3645
5088
  const size = await client.getWindowSize();
3646
5089
  return {
@@ -3658,8 +5101,29 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3658
5101
  // -----------------------------------------------------------------------
3659
5102
  // App lifecycle
3660
5103
  // -----------------------------------------------------------------------
3661
- launchApp: (bundleId, opts) => Effect8.tryPromise({
5104
+ launchApp: (bundleId, opts) => Effect9.tryPromise({
3662
5105
  try: async () => {
5106
+ const canFastReset = hasLaunchedOnce && driverOptions?.fastWebViewReset !== false && domChannel?.isConnected() && !opts?.deepLink && !opts?.clearKeychain && !hasLaunchDeviceState(opts?.deviceState) && !(opts?.launchArguments && Object.keys(opts.launchArguments).length > 0);
5107
+ if (canFastReset) {
5108
+ try {
5109
+ if (opts?.clearState && domChannel.clearStorage) {
5110
+ await domChannel.clearStorage({
5111
+ localStorage: true,
5112
+ sessionStorage: true,
5113
+ cookies: true,
5114
+ indexedDB: true,
5115
+ capacitorPreferences: true
5116
+ });
5117
+ }
5118
+ if (domChannel.reload) {
5119
+ await domChannel.reload();
5120
+ } else {
5121
+ await domChannel.evaluate("window.location.reload()");
5122
+ }
5123
+ return;
5124
+ } catch {
5125
+ }
5126
+ }
3663
5127
  if (opts?.clearState) {
3664
5128
  adbClearApp(serial, bundleId);
3665
5129
  }
@@ -3673,12 +5137,12 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3673
5137
  }
3674
5138
  if (opts?.deepLink) {
3675
5139
  adbOpenLink(serial, opts.deepLink, bundleId);
3676
- await new Promise((resolve2) => setTimeout(resolve2, 500));
5140
+ await waitForAndroidReady(500);
3677
5141
  } else {
3678
5142
  adbForceStop(serial, bundleId);
3679
5143
  if (opts?.launchArguments && Object.keys(opts.launchArguments).length > 0) {
3680
- const { execFileSync } = await import("child_process");
3681
- const { findADB: findADB2 } = await import("./android-4NVTZMHL.js");
5144
+ const { execFileSync: execFileSync2 } = await import("child_process");
5145
+ const { findADB: findADB2 } = await import("./android-6BOQTMM3.js");
3682
5146
  const adb = findADB2();
3683
5147
  if (!adb) throw new Error("adb not found");
3684
5148
  const startArgs = [
@@ -3696,22 +5160,23 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3696
5160
  for (const [k, v] of Object.entries(opts.launchArguments)) {
3697
5161
  startArgs.push("--es", k, String(v));
3698
5162
  }
3699
- execFileSync(adb, startArgs, { stdio: "ignore" });
5163
+ execFileSync2(adb, startArgs, { stdio: "ignore" });
3700
5164
  } else {
3701
5165
  adbLaunchApp(serial, bundleId);
3702
5166
  }
5167
+ await waitForAndroidReady(800);
3703
5168
  }
3704
- await new Promise((resolve2) => setTimeout(resolve2, 1e3));
5169
+ hasLaunchedOnce = true;
3705
5170
  },
3706
5171
  catch: (e) => new DriverError({ message: `Launch app failed: ${e}` })
3707
5172
  }),
3708
- stopApp: (bundleId) => Effect8.tryPromise({
5173
+ stopApp: (bundleId) => Effect9.tryPromise({
3709
5174
  try: async () => {
3710
5175
  adbForceStop(serial, bundleId);
3711
5176
  },
3712
5177
  catch: (e) => new DriverError({ message: `Stop app failed: ${e}` })
3713
5178
  }),
3714
- killApp: (bundleId) => Effect8.tryPromise({
5179
+ killApp: (bundleId) => Effect9.tryPromise({
3715
5180
  try: async () => {
3716
5181
  await domChannel?.disconnect().catch(() => {
3717
5182
  });
@@ -3720,7 +5185,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3720
5185
  },
3721
5186
  catch: (e) => new DriverError({ message: `Kill app failed: ${e}` })
3722
5187
  }),
3723
- clearAppState: (bundleId) => Effect8.tryPromise({
5188
+ clearAppState: (bundleId) => Effect9.tryPromise({
3724
5189
  try: async () => {
3725
5190
  if (domChannel?.isConnected() && domChannel.clearStorage) {
3726
5191
  await domChannel.clearStorage({
@@ -3740,7 +5205,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3740
5205
  },
3741
5206
  catch: (e) => new DriverError({ message: `Clear app state failed: ${e}` })
3742
5207
  }),
3743
- resetFast: () => Effect8.tryPromise({
5208
+ resetFast: () => Effect9.tryPromise({
3744
5209
  try: async () => {
3745
5210
  if (!domChannel) {
3746
5211
  throw new Error("resetFast() requires a connected DOM channel (spana-bridge or CDP)");
@@ -3770,14 +5235,14 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3770
5235
  // -----------------------------------------------------------------------
3771
5236
  // Navigation
3772
5237
  // -----------------------------------------------------------------------
3773
- openLink: (url) => Effect8.tryPromise({
5238
+ openLink: (url) => Effect9.tryPromise({
3774
5239
  try: async () => {
3775
5240
  adbOpenLink(serial, url, packageName);
3776
5241
  await new Promise((resolve2) => setTimeout(resolve2, 1e3));
3777
5242
  },
3778
5243
  catch: (e) => new DriverError({ message: `Open link failed: ${e}` })
3779
5244
  }),
3780
- back: () => Effect8.tryPromise({
5245
+ back: () => Effect9.tryPromise({
3781
5246
  // KEYCODE_BACK = 4
3782
5247
  try: () => client.pressKeyCode(4),
3783
5248
  catch: (e) => new DriverError({ message: `Back failed: ${e}` })
@@ -3786,7 +5251,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3786
5251
  // Direct DOM evaluation via spana-bridge or Android WebView CDP,
3787
5252
  // falling back to UiAutomator2 /execute/sync when no DOM channel attaches.
3788
5253
  // -----------------------------------------------------------------------
3789
- evaluate: (script, ...args) => Effect8.tryPromise({
5254
+ evaluate: (script, ...args) => Effect9.tryPromise({
3790
5255
  try: async () => {
3791
5256
  if (domChannel) {
3792
5257
  try {
@@ -3812,7 +5277,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3812
5277
  },
3813
5278
  catch: (e) => new DriverError({ message: `evaluate() failed: ${e}` })
3814
5279
  }),
3815
- getContexts: () => Effect8.tryPromise({
5280
+ getContexts: () => Effect9.tryPromise({
3816
5281
  try: async () => {
3817
5282
  const contexts = /* @__PURE__ */ new Set(["NATIVE_APP"]);
3818
5283
  if (domChannel?.listTargets) {
@@ -3835,7 +5300,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3835
5300
  },
3836
5301
  catch: (e) => new DriverError({ message: `getContexts failed: ${e}` })
3837
5302
  }),
3838
- getCurrentContext: () => Effect8.tryPromise({
5303
+ getCurrentContext: () => Effect9.tryPromise({
3839
5304
  try: async () => {
3840
5305
  if (currentContext !== "NATIVE_APP") return currentContext;
3841
5306
  if (typeof client.getCurrentContext === "function") {
@@ -3849,7 +5314,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3849
5314
  },
3850
5315
  catch: (e) => new DriverError({ message: `getCurrentContext failed: ${e}` })
3851
5316
  }),
3852
- setContext: (contextId) => Effect8.tryPromise({
5317
+ setContext: (contextId) => Effect9.tryPromise({
3853
5318
  try: async () => {
3854
5319
  if (contextId === "NATIVE_APP") {
3855
5320
  currentContext = "NATIVE_APP";
@@ -3875,7 +5340,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3875
5340
  },
3876
5341
  catch: (e) => new DriverError({ message: `setContext failed: ${e}` })
3877
5342
  }),
3878
- mockNetwork: (matcher, response) => Effect8.tryPromise({
5343
+ mockNetwork: (matcher, response) => Effect9.tryPromise({
3879
5344
  try: async () => {
3880
5345
  if (!domChannel?.mockNetwork) {
3881
5346
  throw new Error("mockNetwork() on Android requires spana-bridge");
@@ -3884,7 +5349,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3884
5349
  },
3885
5350
  catch: (e) => new DriverError({ message: `mockNetwork failed: ${e}` })
3886
5351
  }),
3887
- blockNetwork: (matcher) => Effect8.tryPromise({
5352
+ blockNetwork: (matcher) => Effect9.tryPromise({
3888
5353
  try: async () => {
3889
5354
  if (!domChannel?.blockNetwork) {
3890
5355
  throw new Error("blockNetwork() on Android requires spana-bridge");
@@ -3893,7 +5358,7 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3893
5358
  },
3894
5359
  catch: (e) => new DriverError({ message: `blockNetwork failed: ${e}` })
3895
5360
  }),
3896
- clearNetworkMocks: () => Effect8.tryPromise({
5361
+ clearNetworkMocks: () => Effect9.tryPromise({
3897
5362
  try: async () => {
3898
5363
  if (domChannel?.clearNetworkMocks) {
3899
5364
  await domChannel.clearNetworkMocks();
@@ -3901,18 +5366,18 @@ function createUiAutomator2Driver(host, port, serial, packageName, driverOptions
3901
5366
  },
3902
5367
  catch: (e) => new DriverError({ message: `clearNetworkMocks failed: ${e}` })
3903
5368
  }),
3904
- getConsoleLogs: () => Effect8.tryPromise({
5369
+ getConsoleLogs: () => Effect9.tryPromise({
3905
5370
  try: async () => domChannel?.getConsoleLogs ? domChannel.getConsoleLogs() : [],
3906
5371
  catch: (e) => new DriverError({ message: `getConsoleLogs failed: ${e}` })
3907
5372
  }),
3908
- getJSErrors: () => Effect8.tryPromise({
5373
+ getJSErrors: () => Effect9.tryPromise({
3909
5374
  try: async () => domChannel?.getJSErrors ? domChannel.getJSErrors() : [],
3910
5375
  catch: (e) => new DriverError({ message: `getJSErrors failed: ${e}` })
3911
5376
  }),
3912
5377
  // -----------------------------------------------------------------------
3913
5378
  // Network conditions
3914
5379
  // -----------------------------------------------------------------------
3915
- setNetworkConditions: (conditions) => Effect8.tryPromise({
5380
+ setNetworkConditions: (conditions) => Effect9.tryPromise({
3916
5381
  try: async () => {
3917
5382
  const isEmulator = serial.startsWith("emulator-");
3918
5383
  const resolved = resolveNetworkConditions(conditions);
@@ -4159,7 +5624,7 @@ function parseAndroidHierarchy(xml) {
4159
5624
  }
4160
5625
 
4161
5626
  // src/drivers/wda/driver.ts
4162
- import { Effect as Effect9 } from "effect";
5627
+ import { Effect as Effect10 } from "effect";
4163
5628
 
4164
5629
  // src/drivers/wda/client.ts
4165
5630
  var WDAClient = class {
@@ -4594,9 +6059,21 @@ function isSessionError(error) {
4594
6059
  return msg.includes("session does not exist") || msg.includes("unable to connect") || msg.includes("no active session") || msg.includes("invalid session") || /status[:\s]*404/.test(msg);
4595
6060
  }
4596
6061
  function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth = 100, driverOptions) {
4597
- return Effect9.gen(function* () {
6062
+ return Effect10.gen(function* () {
4598
6063
  const client = new WDAClient(host, port);
4599
6064
  let currentContext = "NATIVE_APP";
6065
+ let hasLaunchedOnce = false;
6066
+ const waitForWdaReady = async (maxMs) => {
6067
+ const deadline = Date.now() + maxMs;
6068
+ while (Date.now() < deadline) {
6069
+ try {
6070
+ await client.getWindowSize();
6071
+ return;
6072
+ } catch {
6073
+ await sleep(40);
6074
+ }
6075
+ }
6076
+ };
4600
6077
  const inspectorChannel = createWebKitInspectorChannel({
4601
6078
  endpointUrl: driverOptions?.webkitInspectorUrl,
4602
6079
  port: driverOptions?.webkitInspectorPort,
@@ -4640,7 +6117,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4640
6117
  const activateSimulatorApp = async (targetBundleId) => {
4641
6118
  if (!targetBundleId) return;
4642
6119
  await client.activateApp(targetBundleId);
4643
- await sleep(1e3);
6120
+ await waitForWdaReady(400);
4644
6121
  };
4645
6122
  const openSimulatorUrl = async (url, targetBundleId = bundleId) => {
4646
6123
  if (!simulatorUdid) {
@@ -4650,7 +6127,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4650
6127
  try {
4651
6128
  await activateSimulatorApp(targetBundleId);
4652
6129
  await client.openUrl(url);
4653
- await sleep(1e3);
6130
+ await waitForWdaReady(400);
4654
6131
  return;
4655
6132
  } catch {
4656
6133
  try {
@@ -4662,7 +6139,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4662
6139
  await client.disableQuiescence();
4663
6140
  await activateSimulatorApp(targetBundleId);
4664
6141
  await client.openUrl(url);
4665
- await sleep(1e3);
6142
+ await waitForWdaReady(400);
4666
6143
  return;
4667
6144
  } catch {
4668
6145
  }
@@ -4703,23 +6180,23 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4703
6180
  let reusedWarmSession = false;
4704
6181
  if (driverOptions?.warmSessionId && typeof client.attachSession === "function") {
4705
6182
  client.attachSession(driverOptions.warmSessionId);
4706
- const alive = yield* Effect9.tryPromise({
6183
+ const alive = yield* Effect10.tryPromise({
4707
6184
  try: () => client.isSessionAlive(),
4708
6185
  catch: () => false
4709
- }).pipe(Effect9.catchAll(() => Effect9.succeed(false)));
6186
+ }).pipe(Effect10.catchAll(() => Effect10.succeed(false)));
4710
6187
  reusedWarmSession = alive;
4711
6188
  }
4712
6189
  if (!reusedWarmSession) {
4713
- const createdId = yield* Effect9.tryPromise({
6190
+ const createdId = yield* Effect10.tryPromise({
4714
6191
  try: () => createSessionWithRetry(bundleId || void 0),
4715
6192
  catch: (e) => new DriverError({ message: `Failed to create WDA session: ${e}` })
4716
6193
  });
4717
6194
  driverOptions?.onSessionCreated?.(createdId);
4718
- yield* Effect9.tryPromise({
6195
+ yield* Effect10.tryPromise({
4719
6196
  try: () => client.disableQuiescence(),
4720
6197
  catch: (e) => new DriverError({ message: `Failed to disable quiescence: ${e}` })
4721
6198
  });
4722
- yield* Effect9.tryPromise({
6199
+ yield* Effect10.tryPromise({
4723
6200
  try: () => client.setSnapshotMaxDepth(snapshotMaxDepth),
4724
6201
  catch: (e) => new DriverError({ message: `Failed to set snapshot depth: ${e}` })
4725
6202
  });
@@ -4729,27 +6206,27 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4729
6206
  // -----------------------------------------------------------------------
4730
6207
  // Hierarchy
4731
6208
  // -----------------------------------------------------------------------
4732
- dumpHierarchy: () => Effect9.tryPromise({
6209
+ dumpHierarchy: () => Effect10.tryPromise({
4733
6210
  try: () => withSessionRecovery(() => client.getSource()),
4734
6211
  catch: (e) => new DriverError({ message: `Failed to get page source: ${e}` })
4735
6212
  }),
4736
6213
  // -----------------------------------------------------------------------
4737
6214
  // Coordinate-level actions
4738
6215
  // -----------------------------------------------------------------------
4739
- tapAtCoordinate: (x, y) => Effect9.tryPromise({
6216
+ tapAtCoordinate: (x, y) => Effect10.tryPromise({
4740
6217
  try: () => withSessionRecovery(() => client.tap(x, y)),
4741
6218
  catch: (e) => new DriverError({ message: `Tap failed: ${e}` })
4742
6219
  }),
4743
- doubleTapAtCoordinate: (x, y) => Effect9.tryPromise({
6220
+ doubleTapAtCoordinate: (x, y) => Effect10.tryPromise({
4744
6221
  try: () => withSessionRecovery(() => client.doubleTap(x, y)),
4745
6222
  catch: (e) => new DriverError({ message: `Double tap failed: ${e}` })
4746
6223
  }),
4747
- longPressAtCoordinate: (x, y, duration) => Effect9.tryPromise({
6224
+ longPressAtCoordinate: (x, y, duration) => Effect10.tryPromise({
4748
6225
  // duration arrives in ms (spana convention) → convert to seconds for WDA
4749
6226
  try: () => withSessionRecovery(() => client.longPress(x, y, msToSec(duration))),
4750
6227
  catch: (e) => new DriverError({ message: `Long press failed: ${e}` })
4751
6228
  }),
4752
- swipe: (sx, sy, ex, ey, dur) => Effect9.tryPromise({
6229
+ swipe: (sx, sy, ex, ey, dur) => Effect10.tryPromise({
4753
6230
  // dur arrives in ms → convert to seconds for WDA.
4754
6231
  // Clamp Y to avoid iOS system gesture zones (home indicator / App Switcher).
4755
6232
  try: async () => {
@@ -4767,26 +6244,26 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4767
6244
  },
4768
6245
  catch: (e) => new DriverError({ message: `Swipe failed: ${e}` })
4769
6246
  }),
4770
- pinch: (cx, cy, scale, duration) => Effect9.tryPromise({
6247
+ pinch: (cx, cy, scale, duration) => Effect10.tryPromise({
4771
6248
  try: () => withSessionRecovery(() => client.pinch(cx, cy, scale, msToSec(duration))),
4772
6249
  catch: (e) => new DriverError({ message: `Pinch failed: ${e}` })
4773
6250
  }),
4774
- zoom: (cx, cy, scale, duration) => Effect9.tryPromise({
6251
+ zoom: (cx, cy, scale, duration) => Effect10.tryPromise({
4775
6252
  try: () => withSessionRecovery(() => client.zoom(cx, cy, scale, msToSec(duration))),
4776
6253
  catch: (e) => new DriverError({ message: `Zoom failed: ${e}` })
4777
6254
  }),
4778
- multiTouch: (sequences) => Effect9.tryPromise({
6255
+ multiTouch: (sequences) => Effect10.tryPromise({
4779
6256
  try: () => withSessionRecovery(() => client.multiTouch(sequences)),
4780
6257
  catch: (e) => new DriverError({ message: `Multi-touch failed: ${e}` })
4781
6258
  }),
4782
6259
  // -----------------------------------------------------------------------
4783
6260
  // Text input
4784
6261
  // -----------------------------------------------------------------------
4785
- inputText: (text) => Effect9.tryPromise({
6262
+ inputText: (text) => Effect10.tryPromise({
4786
6263
  try: () => withSessionRecovery(() => client.sendKeys(text)),
4787
6264
  catch: (e) => new DriverError({ message: `Input text failed: ${e}` })
4788
6265
  }),
4789
- pressKey: (key) => Effect9.tryPromise({
6266
+ pressKey: (key) => Effect10.tryPromise({
4790
6267
  // WDA uses named hardware buttons; map common names, fall back to home
4791
6268
  try: async () => {
4792
6269
  const buttonMap = {
@@ -4801,7 +6278,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4801
6278
  },
4802
6279
  catch: (e) => new DriverError({ message: `Press key failed: ${e}` })
4803
6280
  }),
4804
- hideKeyboard: () => Effect9.tryPromise({
6281
+ hideKeyboard: () => Effect10.tryPromise({
4805
6282
  // Dismiss keyboard by tapping above the keyboard area.
4806
6283
  // The previous approach (pressHome) backgrounds the app on iOS.
4807
6284
  try: async () => {
@@ -4814,11 +6291,11 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4814
6291
  // -----------------------------------------------------------------------
4815
6292
  // Queries
4816
6293
  // -----------------------------------------------------------------------
4817
- takeScreenshot: () => Effect9.tryPromise({
6294
+ takeScreenshot: () => Effect10.tryPromise({
4818
6295
  try: () => withSessionRecovery(() => client.getScreenshot()),
4819
6296
  catch: (e) => new DriverError({ message: `Screenshot failed: ${e}` })
4820
6297
  }),
4821
- getDeviceInfo: () => Effect9.tryPromise({
6298
+ getDeviceInfo: () => Effect10.tryPromise({
4822
6299
  try: async () => {
4823
6300
  const size = await withSessionRecovery(() => client.getWindowSize());
4824
6301
  return {
@@ -4836,15 +6313,40 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4836
6313
  // -----------------------------------------------------------------------
4837
6314
  // App lifecycle
4838
6315
  // -----------------------------------------------------------------------
4839
- launchApp: (appBundleId, opts) => Effect9.tryPromise({
6316
+ launchApp: (appBundleId, opts) => Effect10.tryPromise({
4840
6317
  try: async () => {
6318
+ const canFastReset = hasLaunchedOnce && driverOptions?.fastWebViewReset !== false && domChannel.isConnected() && !opts?.deepLink && !opts?.clearKeychain && !hasLaunchDeviceState(opts?.deviceState) && !(opts?.launchArguments && Object.keys(opts.launchArguments).length > 0);
6319
+ if (canFastReset) {
6320
+ try {
6321
+ if (opts?.clearState && domChannel.clearStorage) {
6322
+ await domChannel.clearStorage({
6323
+ localStorage: true,
6324
+ sessionStorage: true,
6325
+ cookies: true,
6326
+ indexedDB: true,
6327
+ capacitorPreferences: true
6328
+ });
6329
+ }
6330
+ if (domChannel.reload) {
6331
+ await domChannel.reload();
6332
+ } else {
6333
+ await domChannel.evaluate("window.location.reload()");
6334
+ }
6335
+ return;
6336
+ } catch {
6337
+ }
6338
+ }
4841
6339
  if (opts?.clearState && simulatorUdid) {
4842
6340
  terminateOnSimulator(simulatorUdid, appBundleId);
4843
6341
  try {
4844
- const { execSync: execSync2 } = await import("child_process");
4845
- execSync2(`xcrun simctl privacy ${simulatorUdid} reset all ${appBundleId}`, {
4846
- stdio: "ignore"
4847
- });
6342
+ const { execFileSync: execFileSync2 } = await import("child_process");
6343
+ execFileSync2(
6344
+ "xcrun",
6345
+ ["simctl", "privacy", simulatorUdid, "reset", "all", appBundleId],
6346
+ {
6347
+ stdio: "ignore"
6348
+ }
6349
+ );
4848
6350
  } catch {
4849
6351
  }
4850
6352
  }
@@ -4870,13 +6372,12 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4870
6372
  } catch {
4871
6373
  }
4872
6374
  }
4873
- await sleep(300);
4874
6375
  try {
4875
6376
  await client.launchApp(appBundleId);
4876
- await sleep(500);
6377
+ await waitForWdaReady(500);
4877
6378
  } catch {
4878
6379
  launchOnSimulator(simulatorUdid, appBundleId);
4879
- await sleep(500);
6380
+ await sleep(250);
4880
6381
  try {
4881
6382
  await client.deleteSession();
4882
6383
  } catch {
@@ -4888,13 +6389,15 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4888
6389
  }
4889
6390
  }
4890
6391
  }
6392
+ hasLaunchedOnce = true;
4891
6393
  return;
4892
6394
  }
4893
6395
  await (opts?.deepLink ? client.openUrl(opts.deepLink) : client.launchApp(appBundleId));
6396
+ hasLaunchedOnce = true;
4894
6397
  },
4895
6398
  catch: (e) => new DriverError({ message: `Launch app failed: ${e}` })
4896
6399
  }),
4897
- stopApp: (appBundleId) => Effect9.tryPromise({
6400
+ stopApp: (appBundleId) => Effect10.tryPromise({
4898
6401
  try: () => {
4899
6402
  if (simulatorUdid) {
4900
6403
  terminateOnSimulator(simulatorUdid, appBundleId);
@@ -4904,7 +6407,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4904
6407
  },
4905
6408
  catch: (e) => new DriverError({ message: `Stop app failed: ${e}` })
4906
6409
  }),
4907
- killApp: (appBundleId) => Effect9.tryPromise({
6410
+ killApp: (appBundleId) => Effect10.tryPromise({
4908
6411
  try: async () => {
4909
6412
  await domChannel.disconnect().catch(() => {
4910
6413
  });
@@ -4917,7 +6420,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4917
6420
  },
4918
6421
  catch: (e) => new DriverError({ message: `Kill app failed: ${e}` })
4919
6422
  }),
4920
- clearAppState: (appBundleId) => Effect9.tryPromise({
6423
+ clearAppState: (appBundleId) => Effect10.tryPromise({
4921
6424
  try: async () => {
4922
6425
  if (domChannel.isConnected() && domChannel.clearStorage) {
4923
6426
  await domChannel.clearStorage({
@@ -4940,7 +6443,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4940
6443
  },
4941
6444
  catch: (e) => new DriverError({ message: `Clear app state failed: ${e}` })
4942
6445
  }),
4943
- resetFast: () => Effect9.tryPromise({
6446
+ resetFast: () => Effect10.tryPromise({
4944
6447
  try: async () => {
4945
6448
  if (domChannel.clearStorage) {
4946
6449
  await domChannel.clearStorage({
@@ -4967,7 +6470,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4967
6470
  // -----------------------------------------------------------------------
4968
6471
  // Navigation
4969
6472
  // -----------------------------------------------------------------------
4970
- openLink: (url) => Effect9.tryPromise({
6473
+ openLink: (url) => Effect10.tryPromise({
4971
6474
  try: async () => {
4972
6475
  if (simulatorUdid) {
4973
6476
  await openSimulatorUrl(url);
@@ -4977,7 +6480,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4977
6480
  },
4978
6481
  catch: (e) => new DriverError({ message: `Open link failed: ${e}` })
4979
6482
  }),
4980
- back: () => Effect9.tryPromise({
6483
+ back: () => Effect10.tryPromise({
4981
6484
  // iOS has no hardware back button; pressing home is the closest
4982
6485
  // equivalent for dismissing the current context.
4983
6486
  try: () => client.pressHome(),
@@ -4987,13 +6490,13 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
4987
6490
  // Direct DOM evaluation via spana-bridge or WebKit Remote Inspector
4988
6491
  // (no Appium required)
4989
6492
  // -----------------------------------------------------------------------
4990
- evaluate: (script, ...args) => Effect9.tryPromise({
6493
+ evaluate: (script, ...args) => Effect10.tryPromise({
4991
6494
  try: () => domChannel.evaluate(script, ...args),
4992
6495
  catch: (e) => new DriverError({
4993
6496
  message: `iOS direct WDA evaluate() failed via ${domChannel.kind}: ${e instanceof Error ? e.message : e}. Ensure WKWebView.isInspectable = true (iOS 16.4+) with ios_webkit_debug_proxy running, or include spana-bridge in test builds.`
4994
6497
  })
4995
6498
  }),
4996
- getContexts: () => Effect9.tryPromise({
6499
+ getContexts: () => Effect10.tryPromise({
4997
6500
  try: async () => {
4998
6501
  const contexts = ["NATIVE_APP"];
4999
6502
  if (domChannel.listTargets) {
@@ -5012,8 +6515,8 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
5012
6515
  },
5013
6516
  catch: (e) => new DriverError({ message: `getContexts failed: ${e}` })
5014
6517
  }),
5015
- getCurrentContext: () => Effect9.succeed(currentContext),
5016
- setContext: (contextId) => Effect9.tryPromise({
6518
+ getCurrentContext: () => Effect10.succeed(currentContext),
6519
+ setContext: (contextId) => Effect10.tryPromise({
5017
6520
  try: async () => {
5018
6521
  if (contextId === "NATIVE_APP") {
5019
6522
  currentContext = "NATIVE_APP";
@@ -5033,7 +6536,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
5033
6536
  },
5034
6537
  catch: (e) => new DriverError({ message: `setContext failed: ${e}` })
5035
6538
  }),
5036
- mockNetwork: (matcher, response) => Effect9.tryPromise({
6539
+ mockNetwork: (matcher, response) => Effect10.tryPromise({
5037
6540
  try: async () => {
5038
6541
  if (!domChannel.mockNetwork) {
5039
6542
  throw new Error("mockNetwork() on iOS requires spana-bridge");
@@ -5042,7 +6545,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
5042
6545
  },
5043
6546
  catch: (e) => new DriverError({ message: `mockNetwork failed: ${e}` })
5044
6547
  }),
5045
- blockNetwork: (matcher) => Effect9.tryPromise({
6548
+ blockNetwork: (matcher) => Effect10.tryPromise({
5046
6549
  try: async () => {
5047
6550
  if (!domChannel.blockNetwork) {
5048
6551
  throw new Error("blockNetwork() on iOS requires spana-bridge");
@@ -5051,7 +6554,7 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
5051
6554
  },
5052
6555
  catch: (e) => new DriverError({ message: `blockNetwork failed: ${e}` })
5053
6556
  }),
5054
- clearNetworkMocks: () => Effect9.tryPromise({
6557
+ clearNetworkMocks: () => Effect10.tryPromise({
5055
6558
  try: async () => {
5056
6559
  if (domChannel.clearNetworkMocks) {
5057
6560
  await domChannel.clearNetworkMocks();
@@ -5059,18 +6562,18 @@ function createWDADriver(host, port, bundleId, simulatorUdid, snapshotMaxDepth =
5059
6562
  },
5060
6563
  catch: (e) => new DriverError({ message: `clearNetworkMocks failed: ${e}` })
5061
6564
  }),
5062
- getConsoleLogs: () => Effect9.tryPromise({
6565
+ getConsoleLogs: () => Effect10.tryPromise({
5063
6566
  try: async () => domChannel.getConsoleLogs ? domChannel.getConsoleLogs() : [],
5064
6567
  catch: (e) => new DriverError({ message: `getConsoleLogs failed: ${e}` })
5065
6568
  }),
5066
- getJSErrors: () => Effect9.tryPromise({
6569
+ getJSErrors: () => Effect10.tryPromise({
5067
6570
  try: async () => domChannel.getJSErrors ? domChannel.getJSErrors() : [],
5068
6571
  catch: (e) => new DriverError({ message: `getJSErrors failed: ${e}` })
5069
6572
  }),
5070
6573
  // -----------------------------------------------------------------------
5071
6574
  // Network simulation
5072
6575
  // -----------------------------------------------------------------------
5073
- setNetworkConditions: (conditions) => Effect9.tryPromise({
6576
+ setNetworkConditions: (conditions) => Effect10.tryPromise({
5074
6577
  try: async () => {
5075
6578
  if (!simulatorUdid) {
5076
6579
  throw new DriverError({
@@ -5193,7 +6696,7 @@ function parseIOSHierarchy(xml) {
5193
6696
  }
5194
6697
 
5195
6698
  // src/drivers/electron.ts
5196
- import { Effect as Effect10 } from "effect";
6699
+ import { Effect as Effect11 } from "effect";
5197
6700
  import {
5198
6701
  _electron,
5199
6702
  chromium as chromium2
@@ -5237,7 +6740,7 @@ var CLEAR_STORAGE_SCRIPT2 = `
5237
6740
  })();
5238
6741
  `;
5239
6742
  function makeElectronDriver(options) {
5240
- return Effect10.gen(function* () {
6743
+ return Effect11.gen(function* () {
5241
6744
  let electronApp;
5242
6745
  let cdpBrowser;
5243
6746
  let context;
@@ -5261,13 +6764,13 @@ function makeElectronDriver(options) {
5261
6764
  const resolvedCdpUrl = options.cdpUrl ?? (options.cdpPort && !options.entry && !options.executablePath ? `http://127.0.0.1:${options.cdpPort}` : void 0);
5262
6765
  if (resolvedCdpUrl) {
5263
6766
  const connect = options.connectOverCDP ?? chromium2.connectOverCDP.bind(chromium2);
5264
- cdpBrowser = yield* Effect10.tryPromise({
6767
+ cdpBrowser = yield* Effect11.tryPromise({
5265
6768
  try: () => connect(resolvedCdpUrl),
5266
6769
  catch: (e) => new DriverError({
5267
6770
  message: `Failed to connect to Electron over CDP (${resolvedCdpUrl}): ${e}`
5268
6771
  })
5269
6772
  });
5270
- page = yield* Effect10.tryPromise({
6773
+ page = yield* Effect11.tryPromise({
5271
6774
  try: async () => {
5272
6775
  const contexts = cdpBrowser.contexts();
5273
6776
  context = contexts[0];
@@ -5292,7 +6795,7 @@ function makeElectronDriver(options) {
5292
6795
  });
5293
6796
  }
5294
6797
  const launcher = options.launchElectron ?? _electron.launch.bind(_electron);
5295
- electronApp = yield* Effect10.tryPromise({
6798
+ electronApp = yield* Effect11.tryPromise({
5296
6799
  try: () => launcher({
5297
6800
  ...options.executablePath ? { executablePath: options.executablePath } : {},
5298
6801
  ...launchArgs.length > 0 ? { args: launchArgs } : {},
@@ -5301,7 +6804,7 @@ function makeElectronDriver(options) {
5301
6804
  }),
5302
6805
  catch: (e) => new DriverError({ message: `Failed to launch Electron app: ${e}` })
5303
6806
  });
5304
- page = yield* Effect10.tryPromise({
6807
+ page = yield* Effect11.tryPromise({
5305
6808
  try: async () => {
5306
6809
  const win = await electronApp.firstWindow();
5307
6810
  context = electronApp.context();
@@ -5331,26 +6834,26 @@ function makeElectronDriver(options) {
5331
6834
  };
5332
6835
  const service = {
5333
6836
  domChannel,
5334
- beginFlow: () => Effect10.sync(() => {
6837
+ beginFlow: () => Effect11.sync(() => {
5335
6838
  consoleLogs.length = 0;
5336
6839
  jsErrors.length = 0;
5337
6840
  }),
5338
- dumpHierarchy: () => Effect10.tryPromise({
6841
+ dumpHierarchy: () => Effect11.tryPromise({
5339
6842
  try: async () => {
5340
6843
  const tree = await page.evaluate(DOM_HIERARCHY_WALK_SCRIPT);
5341
6844
  return JSON.stringify(tree);
5342
6845
  },
5343
6846
  catch: (e) => new DriverError({ message: `Electron dumpHierarchy failed: ${e}` })
5344
6847
  }),
5345
- tapAtCoordinate: (x, y) => Effect10.tryPromise({
6848
+ tapAtCoordinate: (x, y) => Effect11.tryPromise({
5346
6849
  try: () => page.mouse.click(x, y),
5347
6850
  catch: (e) => new DriverError({ message: `Electron tap failed at (${x}, ${y}): ${e}` })
5348
6851
  }),
5349
- doubleTapAtCoordinate: (x, y) => Effect10.tryPromise({
6852
+ doubleTapAtCoordinate: (x, y) => Effect11.tryPromise({
5350
6853
  try: () => page.mouse.dblclick(x, y),
5351
6854
  catch: (e) => new DriverError({ message: `Electron doubleTap failed at (${x}, ${y}): ${e}` })
5352
6855
  }),
5353
- longPressAtCoordinate: (x, y, duration) => Effect10.tryPromise({
6856
+ longPressAtCoordinate: (x, y, duration) => Effect11.tryPromise({
5354
6857
  try: async () => {
5355
6858
  await page.mouse.move(x, y);
5356
6859
  await page.mouse.down();
@@ -5359,7 +6862,7 @@ function makeElectronDriver(options) {
5359
6862
  },
5360
6863
  catch: (e) => new DriverError({ message: `Electron longPress failed: ${e}` })
5361
6864
  }),
5362
- swipe: (startX, startY, endX, endY, duration) => Effect10.tryPromise({
6865
+ swipe: (startX, startY, endX, endY, duration) => Effect11.tryPromise({
5363
6866
  try: async () => {
5364
6867
  await page.mouse.move(startX, startY);
5365
6868
  await page.mouse.wheel(startX - endX, startY - endY);
@@ -5367,20 +6870,20 @@ function makeElectronDriver(options) {
5367
6870
  },
5368
6871
  catch: (e) => new DriverError({ message: `Electron swipe failed: ${e}` })
5369
6872
  }),
5370
- inputText: (text) => Effect10.tryPromise({
6873
+ inputText: (text) => Effect11.tryPromise({
5371
6874
  try: () => page.keyboard.insertText(text),
5372
6875
  catch: (e) => new DriverError({ message: `Electron inputText failed: ${e}` })
5373
6876
  }),
5374
- pressKey: (key) => Effect10.tryPromise({
6877
+ pressKey: (key) => Effect11.tryPromise({
5375
6878
  try: () => page.keyboard.press(key),
5376
6879
  catch: (e) => new DriverError({ message: `Electron pressKey failed: ${e}` })
5377
6880
  }),
5378
- hideKeyboard: () => Effect10.void,
5379
- takeScreenshot: () => Effect10.tryPromise({
6881
+ hideKeyboard: () => Effect11.void,
6882
+ takeScreenshot: () => Effect11.tryPromise({
5380
6883
  try: async () => new Uint8Array(await page.screenshot()),
5381
6884
  catch: (e) => new DriverError({ message: `Electron screenshot failed: ${e}` })
5382
6885
  }),
5383
- getDeviceInfo: () => Effect10.tryPromise({
6886
+ getDeviceInfo: () => Effect11.tryPromise({
5384
6887
  try: async () => {
5385
6888
  const viewport = page.viewportSize() ?? { width: 1280, height: 800 };
5386
6889
  return {
@@ -5395,7 +6898,7 @@ function makeElectronDriver(options) {
5395
6898
  },
5396
6899
  catch: (e) => new DriverError({ message: `Electron getDeviceInfo failed: ${e}` })
5397
6900
  }),
5398
- launchApp: (appRef, opts) => Effect10.tryPromise({
6901
+ launchApp: (appRef, opts) => Effect11.tryPromise({
5399
6902
  try: async () => {
5400
6903
  if (opts?.clearState) {
5401
6904
  await clearStorageAndCookies();
@@ -5407,8 +6910,8 @@ function makeElectronDriver(options) {
5407
6910
  },
5408
6911
  catch: (e) => new DriverError({ message: `Electron launchApp failed: ${e}` })
5409
6912
  }),
5410
- stopApp: () => Effect10.void,
5411
- killApp: () => Effect10.tryPromise({
6913
+ stopApp: () => Effect11.void,
6914
+ killApp: () => Effect11.tryPromise({
5412
6915
  try: async () => {
5413
6916
  await domChannel?.disconnect().catch(() => {
5414
6917
  });
@@ -5420,32 +6923,32 @@ function makeElectronDriver(options) {
5420
6923
  },
5421
6924
  catch: (e) => new DriverError({ message: `Electron killApp failed: ${e}` })
5422
6925
  }),
5423
- clearAppState: () => Effect10.tryPromise({
6926
+ clearAppState: () => Effect11.tryPromise({
5424
6927
  try: async () => {
5425
6928
  await clearStorageAndCookies();
5426
6929
  },
5427
6930
  catch: (e) => new DriverError({ message: `Electron clearAppState failed: ${e}` })
5428
6931
  }),
5429
- resetFast: () => Effect10.tryPromise({
6932
+ resetFast: () => Effect11.tryPromise({
5430
6933
  try: async () => {
5431
6934
  await clearStorageAndCookies();
5432
6935
  await page.reload();
5433
6936
  },
5434
6937
  catch: (e) => new DriverError({ message: `Electron resetFast failed: ${e}` })
5435
6938
  }),
5436
- openLink: (url) => Effect10.tryPromise({
6939
+ openLink: (url) => Effect11.tryPromise({
5437
6940
  try: async () => {
5438
6941
  await page.goto(url);
5439
6942
  },
5440
6943
  catch: (e) => new DriverError({ message: `Electron openLink failed: ${e}` })
5441
6944
  }),
5442
- back: () => Effect10.tryPromise({
6945
+ back: () => Effect11.tryPromise({
5443
6946
  try: async () => {
5444
6947
  await page.goBack();
5445
6948
  },
5446
6949
  catch: (e) => new DriverError({ message: `Electron back failed: ${e}` })
5447
6950
  }),
5448
- evaluate: (script, ...args) => Effect10.tryPromise({
6951
+ evaluate: (script, ...args) => Effect11.tryPromise({
5449
6952
  try: async () => {
5450
6953
  if (domChannel?.isConnected()) {
5451
6954
  return await domChannel.evaluate(script, ...args);
@@ -5463,7 +6966,7 @@ function makeElectronDriver(options) {
5463
6966
  },
5464
6967
  catch: (e) => new DriverError({ message: `Electron evaluate failed: ${e}` })
5465
6968
  }),
5466
- mockNetwork: (matcher, response) => Effect10.tryPromise({
6969
+ mockNetwork: (matcher, response) => Effect11.tryPromise({
5467
6970
  try: async () => {
5468
6971
  if (!context) throw new Error("No Electron BrowserContext available");
5469
6972
  await context.route(matcher, async (route) => {
@@ -5478,7 +6981,7 @@ function makeElectronDriver(options) {
5478
6981
  },
5479
6982
  catch: (e) => new DriverError({ message: `Electron mockNetwork failed: ${e}` })
5480
6983
  }),
5481
- blockNetwork: (matcher) => Effect10.tryPromise({
6984
+ blockNetwork: (matcher) => Effect11.tryPromise({
5482
6985
  try: async () => {
5483
6986
  if (!context) throw new Error("No Electron BrowserContext available");
5484
6987
  await context.route(matcher, async (route) => {
@@ -5488,7 +6991,7 @@ function makeElectronDriver(options) {
5488
6991
  },
5489
6992
  catch: (e) => new DriverError({ message: `Electron blockNetwork failed: ${e}` })
5490
6993
  }),
5491
- clearNetworkMocks: () => Effect10.tryPromise({
6994
+ clearNetworkMocks: () => Effect11.tryPromise({
5492
6995
  try: async () => {
5493
6996
  if (!context) return;
5494
6997
  for (const entry of appliedRoutes) {
@@ -5499,18 +7002,18 @@ function makeElectronDriver(options) {
5499
7002
  },
5500
7003
  catch: (e) => new DriverError({ message: `Electron clearNetworkMocks failed: ${e}` })
5501
7004
  }),
5502
- getConsoleLogs: () => Effect10.succeed([...consoleLogs]),
5503
- getJSErrors: () => Effect10.succeed([...jsErrors])
7005
+ getConsoleLogs: () => Effect11.succeed([...consoleLogs]),
7006
+ getJSErrors: () => Effect11.succeed([...jsErrors])
5504
7007
  };
5505
7008
  return service;
5506
7009
  });
5507
7010
  }
5508
7011
 
5509
7012
  // src/drivers/uiautomator2/installer.ts
5510
- import { execSync } from "child_process";
7013
+ import { execFileSync, spawn as spawn2 } from "child_process";
5511
7014
  import { existsSync, readdirSync } from "fs";
5512
7015
  import { createRequire } from "module";
5513
- import { dirname, resolve, join } from "path";
7016
+ import { dirname, resolve, join as join2 } from "path";
5514
7017
  import { fileURLToPath } from "url";
5515
7018
  var __dirname2 = fileURLToPath(new URL(".", import.meta.url));
5516
7019
  var require2 = createRequire(import.meta.url);
@@ -5539,7 +7042,7 @@ function findUiAutomator2APK() {
5539
7042
  );
5540
7043
  const testApk = files.find((f) => f.includes("androidTest") && f.endsWith(".apk"));
5541
7044
  if (serverApk && testApk) {
5542
- return { serverApk: join(dir, serverApk), testApk: join(dir, testApk) };
7045
+ return { serverApk: join2(dir, serverApk), testApk: join2(dir, testApk) };
5543
7046
  }
5544
7047
  }
5545
7048
  return null;
@@ -5568,10 +7071,23 @@ function startUiAutomator2Server(serial) {
5568
7071
  const adb = findADB();
5569
7072
  if (!adb) throw new Error("adb not found");
5570
7073
  try {
5571
- execSync(
5572
- `${adb} -s ${serial} shell am instrument -w -e disableAnalytics true io.appium.uiautomator2.server.test/androidx.test.runner.AndroidJUnitRunner &`,
5573
- { stdio: "ignore", timeout: 5e3 }
7074
+ const proc = spawn2(
7075
+ adb,
7076
+ [
7077
+ "-s",
7078
+ serial,
7079
+ "shell",
7080
+ "am",
7081
+ "instrument",
7082
+ "-w",
7083
+ "-e",
7084
+ "disableAnalytics",
7085
+ "true",
7086
+ "io.appium.uiautomator2.server.test/androidx.test.runner.AndroidJUnitRunner"
7087
+ ],
7088
+ { detached: true, stdio: "ignore" }
5574
7089
  );
7090
+ proc.unref();
5575
7091
  } catch {
5576
7092
  }
5577
7093
  }
@@ -5599,7 +7115,7 @@ async function setupUiAutomator2(serial, hostPort, options = {}) {
5599
7115
  const adb = findADB();
5600
7116
  if (adb) {
5601
7117
  try {
5602
- execSync(`${adb} -s ${serial} forward --remove tcp:${port}`, { stdio: "ignore" });
7118
+ execFileSync(adb, ["-s", serial, "forward", "--remove", `tcp:${port}`], { stdio: "ignore" });
5603
7119
  } catch {
5604
7120
  }
5605
7121
  }
@@ -5629,7 +7145,9 @@ async function setupUiAutomator2(serial, hostPort, options = {}) {
5629
7145
  if (warm) return;
5630
7146
  try {
5631
7147
  if (adb)
5632
- execSync(`${adb} -s ${serial} forward --remove tcp:${port}`, { stdio: "ignore" });
7148
+ execFileSync(adb, ["-s", serial, "forward", "--remove", `tcp:${port}`], {
7149
+ stdio: "ignore"
7150
+ });
5633
7151
  } catch {
5634
7152
  }
5635
7153
  releasePort(port);
@@ -5649,9 +7167,19 @@ export {
5649
7167
  hasLaunchDeviceState,
5650
7168
  deviceStateToAppiumCapabilities,
5651
7169
  buildIOSLaunchConfiguration,
7170
+ byRole,
7171
+ byCss,
7172
+ or,
7173
+ within,
7174
+ inFrame,
7175
+ nth,
7176
+ first,
7177
+ last,
7178
+ filterSelector,
5652
7179
  systemUI,
5653
7180
  isSystemUISelector,
5654
7181
  isTestIDSelector,
7182
+ isComposableDomSelector,
5655
7183
  splitGraphemes,
5656
7184
  flattenElements,
5657
7185
  invalidateWebViewFrameCache,
@@ -5661,6 +7189,7 @@ export {
5661
7189
  resolveElementAcrossChannels,
5662
7190
  createCoordinator,
5663
7191
  buildStorybookUrl,
7192
+ createPromiseExpect,
5664
7193
  createPromiseApp,
5665
7194
  parseWebHierarchy,
5666
7195
  resolveNetworkConditions,
@@ -5676,4 +7205,4 @@ export {
5676
7205
  makeElectronDriver,
5677
7206
  setupUiAutomator2
5678
7207
  };
5679
- //# sourceMappingURL=chunk-T5CROOR7.js.map
7208
+ //# sourceMappingURL=chunk-3UVSUVHW.js.map