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
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  allocatePort,
3
3
  releasePort
4
- } from "./chunk-OBCFACUW.js";
4
+ } from "./chunk-JPZCZHL4.js";
5
5
  import {
6
6
  adbShell,
7
7
  findADB
8
- } from "./chunk-H27IBIGA.js";
8
+ } from "./chunk-2AFWVHQK.js";
9
9
 
10
10
  // src/errors.ts
11
11
  import { Schema } from "effect";
@@ -97,8 +97,10 @@ function domMatchToElement(match, screenBounds) {
97
97
  return {
98
98
  ...match.id !== void 0 ? { id: match.id } : {},
99
99
  ...match.text !== void 0 ? { text: match.text } : {},
100
+ ...match.textContent !== void 0 ? { textContent: match.textContent } : {},
100
101
  ...match.value !== void 0 ? { value: match.value } : {},
101
102
  ...match.accessibilityLabel !== void 0 ? { accessibilityLabel: match.accessibilityLabel } : {},
103
+ ...match.accessibleDescription !== void 0 ? { accessibleDescription: match.accessibleDescription } : {},
102
104
  ...match.tag !== void 0 ? { elementType: match.tag } : {},
103
105
  bounds: screenBounds ?? {
104
106
  x: Math.round(match.rect.x),
@@ -125,10 +127,230 @@ function buildEvaluateExpression(script, args = []) {
125
127
  }
126
128
  return script;
127
129
  }
130
+ function serializeSelectorForDom(sel) {
131
+ if (sel instanceof RegExp) {
132
+ return { __spanaRegex: sel.source, flags: sel.flags };
133
+ }
134
+ if (Array.isArray(sel)) {
135
+ return sel.map((item) => serializeSelectorForDom(item));
136
+ }
137
+ if (sel && typeof sel === "object") {
138
+ const out = {};
139
+ for (const [k, v] of Object.entries(sel)) {
140
+ if (v !== void 0) {
141
+ out[k] = serializeSelectorForDom(v);
142
+ }
143
+ }
144
+ return out;
145
+ }
146
+ return sel;
147
+ }
128
148
  var SHARED_DOM_TRAVERSAL_HELPERS = `
149
+ function matchSpec(actual, spec, exact) {
150
+ var str = String(actual || "");
151
+ if (spec && typeof spec === "object" && typeof spec.__spanaRegex === "string") {
152
+ try { return new RegExp(spec.__spanaRegex, spec.flags || "").test(str); } catch (e) { return false; }
153
+ }
154
+ var needle = String(spec == null ? "" : spec);
155
+ if (exact) return str.trim() === needle.trim();
156
+ return str.toLowerCase().indexOf(needle.toLowerCase()) !== -1;
157
+ }
158
+ function getImplicitRole(el) {
159
+ if (!el || !el.getAttribute) return "";
160
+ var explicit = (el.getAttribute("role") || "").trim().toLowerCase();
161
+ if (explicit) return explicit.split(/\\s+/)[0] || "";
162
+ var tag = el.tagName ? el.tagName.toUpperCase() : "";
163
+ if (tag === "BUTTON") return "button";
164
+ if (tag === "A") return el.hasAttribute("href") ? "link" : "";
165
+ if (tag === "TEXTAREA") return "textbox";
166
+ if (tag === "SELECT") return (el.hasAttribute("multiple") || Number(el.getAttribute("size") || 0) > 1) ? "listbox" : "combobox";
167
+ if (tag === "OPTION") return "option";
168
+ if (tag === "IMG") return el.getAttribute("alt") === "" ? "presentation" : "img";
169
+ if (tag === "DIALOG") return "dialog";
170
+ if (tag === "NAV") return "navigation";
171
+ if (tag === "MAIN") return "main";
172
+ if (tag === "HEADER") return "banner";
173
+ if (tag === "FOOTER") return "contentinfo";
174
+ if (tag === "ASIDE") return "complementary";
175
+ if (tag === "UL" || tag === "OL") return "list";
176
+ if (tag === "LI") return "listitem";
177
+ if (tag === "TABLE") return "table";
178
+ if (tag === "TR") return "row";
179
+ if (tag === "TD") return "cell";
180
+ if (tag === "TH") return "columnheader";
181
+ if (tag === "ARTICLE") return "article";
182
+ if (tag === "FORM") return "form";
183
+ if (tag === "PROGRESS") return "progressbar";
184
+ if (tag === "HR") return "separator";
185
+ if (tag === "SECTION") return (el.hasAttribute("aria-label") || el.hasAttribute("aria-labelledby")) ? "region" : "";
186
+ if (/^H[1-6]$/.test(tag)) return "heading";
187
+ if (tag === "INPUT") {
188
+ var t = (el.getAttribute("type") || "text").toLowerCase();
189
+ if (t === "button" || t === "submit" || t === "reset" || t === "image") return "button";
190
+ if (t === "checkbox") return "checkbox";
191
+ if (t === "radio") return "radio";
192
+ if (t === "search") return "searchbox";
193
+ if (t === "number") return "spinbutton";
194
+ if (t === "range") return "slider";
195
+ if (t === "hidden") return "";
196
+ return "textbox";
197
+ }
198
+ return "";
199
+ }
200
+ function visibleTextOf(node, allowHiddenRoot, skipControl) {
201
+ if (!node) return "";
202
+ if (node.nodeType === 3) return node.nodeValue || "";
203
+ if (node.nodeType !== 1 && node.nodeType !== 11) return "";
204
+ if (node.nodeType === 1) {
205
+ if (skipControl && node === skipControl) return "";
206
+ var t = node.tagName ? node.tagName.toUpperCase() : "";
207
+ if (t === "SCRIPT" || t === "STYLE" || t === "NOSCRIPT" || t === "TEMPLATE") return "";
208
+ if (skipControl && (t === "SELECT" || t === "TEXTAREA" || t === "INPUT")) return "";
209
+ if (!allowHiddenRoot) {
210
+ if (node.getAttribute && node.getAttribute("aria-hidden") === "true") return "";
211
+ var win = (node.ownerDocument && node.ownerDocument.defaultView) || window;
212
+ if (win && win.getComputedStyle) {
213
+ var st = win.getComputedStyle(node);
214
+ if (st && (st.display === "none" || st.visibility === "hidden" || st.visibility === "collapse")) {
215
+ return "";
216
+ }
217
+ }
218
+ }
219
+ }
220
+ var out = [];
221
+ if (node.shadowRoot) {
222
+ var stxt = visibleTextOf(node.shadowRoot, false, skipControl);
223
+ if (stxt) out.push(stxt);
224
+ }
225
+ var kids = node.childNodes || [];
226
+ for (var i = 0; i < kids.length; i++) {
227
+ var k = visibleTextOf(kids[i], false, skipControl);
228
+ if (k) out.push(k);
229
+ }
230
+ return out.join(" ").replace(/\\s+/g, " ").trim();
231
+ }
232
+ function isAriaHidden(el) {
233
+ if (!el) return true;
234
+ var win = (el.ownerDocument && el.ownerDocument.defaultView) || window;
235
+ var cur = el;
236
+ var guard = 0;
237
+ while (cur && guard++ < 32) {
238
+ if (cur.getAttribute) {
239
+ if (cur.getAttribute("aria-hidden") === "true") return true;
240
+ if (cur.hasAttribute && cur.hasAttribute("inert")) return true;
241
+ }
242
+ if (cur.nodeType === 1 && win && win.getComputedStyle) {
243
+ var cs = win.getComputedStyle(cur);
244
+ if (cs && cs.display === "none") return true;
245
+ }
246
+ var root = typeof cur.getRootNode === "function" ? cur.getRootNode() : null;
247
+ cur = cur.parentElement || (root && root.host) || null;
248
+ }
249
+ if (typeof el.checkVisibility === "function") {
250
+ try {
251
+ if (!el.checkVisibility({ visibilityProperty: true })) return true;
252
+ } catch (e) {}
253
+ } else if (win && win.getComputedStyle) {
254
+ var selfCs = win.getComputedStyle(el);
255
+ if (selfCs && (selfCs.visibility === "hidden" || selfCs.visibility === "collapse")) return true;
256
+ }
257
+ return false;
258
+ }
259
+ function headingLevelOf(el) {
260
+ if (!el) return null;
261
+ var explicit = el.getAttribute && el.getAttribute("aria-level");
262
+ if (explicit) {
263
+ var parsed = parseInt(explicit, 10);
264
+ if (!isNaN(parsed)) return parsed;
265
+ }
266
+ var tag = el.tagName ? el.tagName.toUpperCase() : "";
267
+ var m = /^H([1-6])$/.exec(tag);
268
+ return m ? parseInt(m[1], 10) : null;
269
+ }
270
+ function getAccessibleName(el) {
271
+ if (!el) return "";
272
+ var doc = el.ownerDocument || document;
273
+ var labelledBy = el.getAttribute && el.getAttribute("aria-labelledby");
274
+ if (labelledBy) {
275
+ var parts = [];
276
+ var ids = labelledBy.trim().split(/\\s+/);
277
+ for (var i = 0; i < ids.length; i++) {
278
+ var ref = doc.getElementById ? doc.getElementById(ids[i]) : null;
279
+ if (ref) {
280
+ var rt = visibleTextOf(ref, true, null);
281
+ if (rt) parts.push(rt);
282
+ }
283
+ }
284
+ if (parts.length > 0) return parts.join(" ").replace(/\\s+/g, " ").trim();
285
+ }
286
+ var ariaLabel = el.getAttribute && el.getAttribute("aria-label");
287
+ if (ariaLabel && ariaLabel.trim()) return ariaLabel.trim();
288
+ var tag = el.tagName ? el.tagName.toUpperCase() : "";
289
+ if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") {
290
+ if (el.id && doc.querySelector) {
291
+ try {
292
+ var escId = typeof CSS !== "undefined" && CSS.escape ? CSS.escape(el.id) : el.id;
293
+ var forLbl = doc.querySelector('label[for="' + escId + '"]');
294
+ if (forLbl) {
295
+ var ft = visibleTextOf(forLbl, false, el);
296
+ if (ft) return ft;
297
+ }
298
+ } catch (e) {}
299
+ }
300
+ if (el.closest) {
301
+ var wrapLbl = el.closest("label");
302
+ if (wrapLbl) {
303
+ var wt = visibleTextOf(wrapLbl, false, el);
304
+ if (wt) return wt;
305
+ }
306
+ }
307
+ var itype = tag === "INPUT" ? (el.getAttribute("type") || "text").toLowerCase() : "";
308
+ if ((itype === "button" || itype === "submit" || itype === "reset") && el.value) {
309
+ return String(el.value).trim();
310
+ }
311
+ var ph = el.getAttribute && el.getAttribute("placeholder");
312
+ if (ph && ph.trim()) return ph.trim();
313
+ }
314
+ if (tag === "IMG") {
315
+ var alt = el.getAttribute && el.getAttribute("alt");
316
+ if (alt && alt.trim()) return alt.trim();
317
+ }
318
+ var txt = visibleTextOf(el, false, null);
319
+ if (txt) return txt;
320
+ var title = el.getAttribute && el.getAttribute("title");
321
+ return title ? title.trim() : "";
322
+ }
323
+ function getAccessibleDescription(el) {
324
+ if (!el) return "";
325
+ var doc = el.ownerDocument || document;
326
+ var describedBy = el.getAttribute && el.getAttribute("aria-describedby");
327
+ if (describedBy) {
328
+ var parts = [];
329
+ var ids = describedBy.trim().split(/\\s+/);
330
+ for (var i = 0; i < ids.length; i++) {
331
+ var ref = doc.getElementById ? doc.getElementById(ids[i]) : null;
332
+ if (ref) {
333
+ var rt = visibleTextOf(ref, true, null);
334
+ if (rt) parts.push(rt);
335
+ }
336
+ }
337
+ if (parts.length > 0) return parts.join(" ").replace(/\\s+/g, " ").trim();
338
+ }
339
+ var ariaDesc = el.getAttribute && el.getAttribute("aria-description");
340
+ if (ariaDesc && ariaDesc.trim()) return ariaDesc.trim();
341
+ var title = el.getAttribute && el.getAttribute("title");
342
+ if (title && title.trim()) {
343
+ var accName = getAccessibleName(el);
344
+ if (accName && accName !== title.trim()) return title.trim();
345
+ }
346
+ return "";
347
+ }
129
348
  function collectRoots(root, offsetX, offsetY, inShadow, inIframe, out) {
130
349
  if (!root) return;
131
350
  out.push({ root: root, offsetX: offsetX, offsetY: offsetY, inShadow: inShadow, inIframe: inIframe });
351
+ if (root.shadowRoot) {
352
+ collectRoots(root.shadowRoot, offsetX, offsetY, true, inIframe, out);
353
+ }
132
354
  var nodes = root.querySelectorAll ? root.querySelectorAll("*") : [];
133
355
  for (var i = 0; i < nodes.length; i++) {
134
356
  var el = nodes[i];
@@ -146,14 +368,16 @@ var SHARED_DOM_TRAVERSAL_HELPERS = `
146
368
  }
147
369
  }
148
370
  }
149
- function findTextInRoot(root, needle, ctx, pushHit) {
371
+ function findTextInRoot(root, needle, exact, ctx, pushHit) {
150
372
  var doc = root.ownerDocument || (root.nodeType === 9 ? root : document);
151
373
  if (doc && typeof doc.createTreeWalker === "function" && typeof NodeFilter !== "undefined") {
152
374
  var walker = doc.createTreeWalker(root, NodeFilter.SHOW_TEXT);
153
375
  var txtNode;
154
376
  while ((txtNode = walker.nextNode())) {
155
- var val = (txtNode.nodeValue || "").trim().toLowerCase();
156
- if (val && val.indexOf(needle) !== -1 && txtNode.parentElement) {
377
+ var rawVal = (txtNode.nodeValue || "").trim();
378
+ var val = rawVal.toLowerCase();
379
+ var ok = exact ? rawVal === needle : (val && val.indexOf(needle.toLowerCase()) !== -1);
380
+ if (ok && txtNode.parentElement) {
157
381
  pushHit(txtNode.parentElement, ctx);
158
382
  }
159
383
  }
@@ -161,8 +385,9 @@ var SHARED_DOM_TRAVERSAL_HELPERS = `
161
385
  var inputs = root.querySelectorAll("input, button");
162
386
  for (var ii = 0; ii < inputs.length; ii++) {
163
387
  var inp = inputs[ii];
164
- var inputVal = String(inp.value || "").toLowerCase();
165
- if (inputVal && inputVal.indexOf(needle) !== -1) {
388
+ var rawInp = String(inp.value || "").trim();
389
+ var inpOk = exact ? rawInp === needle : (rawInp && rawInp.toLowerCase().indexOf(needle.toLowerCase()) !== -1);
390
+ if (inpOk) {
166
391
  pushHit(inp, ctx);
167
392
  }
168
393
  }
@@ -176,14 +401,64 @@ var SHARED_DOM_TRAVERSAL_HELPERS = `
176
401
  for (var c = 0; c < node.childNodes.length; c++) {
177
402
  if (node.childNodes[c].nodeType === 3) directText += node.childNodes[c].textContent || "";
178
403
  }
179
- var trimmedDirect = directText.trim().toLowerCase();
180
- var inpVal = (node.tagName === "INPUT" || node.tagName === "BUTTON") ? String(node.value || "").toLowerCase() : "";
181
- if ((trimmedDirect && trimmedDirect.indexOf(needle) !== -1) || (inpVal && inpVal.indexOf(needle) !== -1)) {
404
+ var trimmedDirect = directText.trim();
405
+ var inpVal = (node.tagName === "INPUT" || node.tagName === "BUTTON") ? String(node.value || "").trim() : "";
406
+ var directOk = exact ? trimmedDirect === needle : (trimmedDirect && trimmedDirect.toLowerCase().indexOf(needle.toLowerCase()) !== -1);
407
+ var inputOk = exact ? inpVal === needle : (inpVal && inpVal.toLowerCase().indexOf(needle.toLowerCase()) !== -1);
408
+ if (directOk || inputOk) {
182
409
  pushHit(node, ctx);
183
410
  }
184
411
  }
185
412
  }
186
- function findAcrossRoots(sel) {
413
+ function findRoleInRoot(root, roleLower, nameSpec, exact, ctx, pushHit, includeHidden, level) {
414
+ if (!root || !root.querySelectorAll) return;
415
+ var candidates = root.querySelectorAll("*");
416
+ for (var i = 0; i < candidates.length; i++) {
417
+ var el = candidates[i];
418
+ if (getImplicitRole(el) !== roleLower) continue;
419
+ if (!includeHidden && isAriaHidden(el)) continue;
420
+ if (level !== undefined && level !== null && headingLevelOf(el) !== Number(level)) continue;
421
+ if (nameSpec !== undefined && nameSpec !== null) {
422
+ var accName = getAccessibleName(el);
423
+ if (!matchSpec(accName, nameSpec, Boolean(exact))) continue;
424
+ }
425
+ pushHit(el, ctx);
426
+ }
427
+ }
428
+ function applyModifiersAndSlice(hits, sel) {
429
+ if (!sel || typeof sel !== "object" || "point" in sel) return hits;
430
+ var filtered = hits;
431
+ if (sel.hasText !== undefined) {
432
+ filtered = filtered.filter(function(h) {
433
+ var txt = (h.el.innerText || h.el.textContent || h.el.value || getAccessibleName(h.el) || "");
434
+ return matchSpec(txt, sel.hasText, false);
435
+ });
436
+ }
437
+ if (sel.hasNotText !== undefined) {
438
+ filtered = filtered.filter(function(h) {
439
+ var txt = (h.el.innerText || h.el.textContent || h.el.value || getAccessibleName(h.el) || "");
440
+ return !matchSpec(txt, sel.hasNotText, false);
441
+ });
442
+ }
443
+ if (sel.has !== undefined) {
444
+ filtered = filtered.filter(function(h) {
445
+ return findInScope(sel.has, h.el, h.offsetX, h.offsetY, h.inShadow, h.inIframe).length > 0;
446
+ });
447
+ }
448
+ if (sel.hasNot !== undefined) {
449
+ filtered = filtered.filter(function(h) {
450
+ return findInScope(sel.hasNot, h.el, h.offsetX, h.offsetY, h.inShadow, h.inIframe).length === 0;
451
+ });
452
+ }
453
+ if (sel.first) return filtered.length > 0 ? [filtered[0]] : [];
454
+ if (sel.last) return filtered.length > 0 ? [filtered[filtered.length - 1]] : [];
455
+ if (typeof sel.nth === "number") {
456
+ var idx = sel.nth < 0 ? filtered.length + sel.nth : sel.nth;
457
+ return idx >= 0 && idx < filtered.length ? [filtered[idx]] : [];
458
+ }
459
+ return filtered;
460
+ }
461
+ function findInScope(sel, scopeRoot, baseOffsetX, baseOffsetY, baseInShadow, baseInIframe) {
187
462
  var hits = [];
188
463
  var seen = typeof Set !== "undefined" ? new Set() : null;
189
464
  function pushHit(el, ctx) {
@@ -198,53 +473,135 @@ var SHARED_DOM_TRAVERSAL_HELPERS = `
198
473
  if (atPt) pushHit(atPt, { offsetX: 0, offsetY: 0, inShadow: false, inIframe: false });
199
474
  return hits;
200
475
  }
476
+ // Frame scoping: find matching <iframe> first, then search inside its contentDocument
477
+ if (typeof sel === "object" && sel !== null && sel.frame) {
478
+ var frameHits = findInScope(sel.frame, scopeRoot, baseOffsetX, baseOffsetY, baseInShadow, baseInIframe);
479
+ var innerSel = Object.assign({}, sel);
480
+ delete innerSel.frame;
481
+ for (var fi = 0; fi < frameHits.length; fi++) {
482
+ var fEl = frameHits[fi].el;
483
+ if (fEl && fEl.tagName === "IFRAME") {
484
+ try {
485
+ var fDoc = fEl.contentDocument;
486
+ if (fDoc) {
487
+ var fRect = fEl.getBoundingClientRect();
488
+ var sub = findInScope(innerSel, fDoc, frameHits[fi].offsetX + fRect.left, frameHits[fi].offsetY + fRect.top, frameHits[fi].inShadow, true);
489
+ for (var si = 0; si < sub.length; si++) pushHit(sub[si].el, sub[si]);
490
+ }
491
+ } catch (e) {}
492
+ }
493
+ }
494
+ return hits;
495
+ }
496
+ // Parent scoping: resolve 'within' first, then search inside each matched container
497
+ if (typeof sel === "object" && sel !== null && sel.within) {
498
+ var parentHits = findInScope(sel.within, scopeRoot, baseOffsetX, baseOffsetY, baseInShadow, baseInIframe);
499
+ var childSel = Object.assign({}, sel);
500
+ delete childSel.within;
501
+ delete childSel.hasText;
502
+ delete childSel.hasNotText;
503
+ delete childSel.has;
504
+ delete childSel.hasNot;
505
+ delete childSel.first;
506
+ delete childSel.last;
507
+ delete childSel.nth;
508
+ var combined = [];
509
+ var cSeen = typeof Set !== "undefined" ? new Set() : null;
510
+ for (var pi = 0; pi < parentHits.length; pi++) {
511
+ var ph = parentHits[pi];
512
+ var subHits = findInScope(childSel, ph.el, ph.offsetX, ph.offsetY, ph.inShadow, ph.inIframe);
513
+ for (var ci = 0; ci < subHits.length; ci++) {
514
+ if (cSeen && cSeen.has(subHits[ci].el)) continue;
515
+ if (cSeen) cSeen.add(subHits[ci].el);
516
+ combined.push(subHits[ci]);
517
+ }
518
+ }
519
+ return applyModifiersAndSlice(combined, sel);
520
+ }
521
+ // Logical OR composition (anyOf): union deduplicated hits across branches
522
+ if (typeof sel === "object" && sel !== null && Array.isArray(sel.anyOf)) {
523
+ for (var bi = 0; bi < sel.anyOf.length; bi++) {
524
+ var branchHits = findInScope(sel.anyOf[bi], scopeRoot, baseOffsetX, baseOffsetY, baseInShadow, baseInIframe);
525
+ for (var bh = 0; bh < branchHits.length; bh++) {
526
+ pushHit(branchHits[bh].el, branchHits[bh]);
527
+ }
528
+ }
529
+ return applyModifiersAndSlice(hits, sel);
530
+ }
531
+
201
532
  var esc = function(v) {
202
533
  return typeof CSS !== "undefined" && CSS.escape ? CSS.escape(v) : String(v).replace(/\\\\/g, "\\\\\\\\").replace(/"/g, '\\\\"');
203
534
  };
204
- var mainCtx = { root: document, offsetX: 0, offsetY: 0, inShadow: false, inIframe: false };
535
+ var mainCtx = { root: scopeRoot, offsetX: baseOffsetX, offsetY: baseOffsetY, inShadow: baseInShadow, inIframe: baseInIframe };
536
+ var hasModifiers = typeof sel === "object" && sel !== null && (sel.hasText !== undefined || sel.hasNotText !== undefined || sel.has !== undefined || sel.hasNot !== undefined || sel.first || sel.last || typeof sel.nth === "number");
537
+
205
538
  // O(1)-ish Light-DOM fast path: avoids scanning thousands of nodes with querySelectorAll("*")
206
- // on large SPAs unless Shadow DOM / iframe piercing is actually needed!
207
- if (document.querySelectorAll) {
539
+ // unless Shadow DOM / iframe piercing is needed or no Light-DOM match exists.
540
+ if (scopeRoot && scopeRoot.querySelectorAll && !hasModifiers) {
208
541
  if (typeof sel === "object" && sel !== null && "testID" in sel) {
209
542
  var fastTid = esc(sel.testID);
210
- var fastFound = document.querySelectorAll('[data-testid="' + fastTid + '"], [testID="' + fastTid + '"]');
543
+ var fastFound = scopeRoot.querySelectorAll('[data-testid="' + fastTid + '"], [testID="' + fastTid + '"]');
211
544
  if (fastFound.length > 0) {
212
- for (var fi = 0; fi < fastFound.length; fi++) pushHit(fastFound[fi], mainCtx);
545
+ for (var fi2 = 0; fi2 < fastFound.length; fi2++) pushHit(fastFound[fi2], mainCtx);
213
546
  return hits;
214
547
  }
548
+ } else if (typeof sel === "object" && sel !== null && "css" in sel) {
549
+ try {
550
+ var fastCss = scopeRoot.querySelectorAll(sel.css);
551
+ if (fastCss.length > 0) {
552
+ for (var fc = 0; fc < fastCss.length; fc++) pushHit(fastCss[fc], mainCtx);
553
+ return hits;
554
+ }
555
+ } catch (e) {}
215
556
  } else if (typeof sel === "object" && sel !== null && "accessibilityLabel" in sel) {
216
557
  var fastLbl = esc(sel.accessibilityLabel);
217
- var fastFoundLbl = document.querySelectorAll('[aria-label="' + fastLbl + '"]');
558
+ var fastFoundLbl = scopeRoot.querySelectorAll('[aria-label="' + fastLbl + '"]');
218
559
  if (fastFoundLbl.length > 0) {
219
560
  for (var fj = 0; fj < fastFoundLbl.length; fj++) pushHit(fastFoundLbl[fj], mainCtx);
220
561
  return hits;
221
562
  }
563
+ } else if (typeof sel === "object" && sel !== null && "role" in sel) {
564
+ findRoleInRoot(scopeRoot, String(sel.role).toLowerCase(), sel.name, sel.exact, mainCtx, pushHit, sel.includeHidden, sel.level);
565
+ if (hits.length > 0) return hits;
222
566
  } else if (typeof sel === "string" || (typeof sel === "object" && sel !== null && "text" in sel)) {
223
- var fastNeedle = (typeof sel === "string" ? sel : sel.text).toLowerCase();
224
- findTextInRoot(document, fastNeedle, mainCtx, pushHit);
567
+ var fastNeedle = typeof sel === "string" ? sel : sel.text;
568
+ var fastExact = typeof sel === "object" && sel !== null && Boolean(sel.exact);
569
+ findTextInRoot(scopeRoot, fastNeedle, fastExact, mainCtx, pushHit);
225
570
  if (hits.length > 0) return hits;
226
571
  }
227
572
  }
573
+
228
574
  var roots = [];
229
- collectRoots(document, 0, 0, false, false, roots);
230
- for (var r = 1; r < roots.length; r++) {
575
+ collectRoots(scopeRoot, baseOffsetX, baseOffsetY, baseInShadow, baseInIframe, roots);
576
+ for (var r = 0; r < roots.length; r++) {
231
577
  var ctx = roots[r];
232
578
  var root = ctx.root;
233
- if (!root.querySelectorAll) continue;
579
+ if (!root || !root.querySelectorAll) continue;
234
580
  if (typeof sel === "object" && sel !== null && "testID" in sel) {
235
581
  var tid = esc(sel.testID);
236
582
  var found = root.querySelectorAll('[data-testid="' + tid + '"], [testID="' + tid + '"]');
237
583
  for (var i = 0; i < found.length; i++) pushHit(found[i], ctx);
584
+ } else if (typeof sel === "object" && sel !== null && "css" in sel) {
585
+ try {
586
+ var foundCss = root.querySelectorAll(sel.css);
587
+ for (var ci2 = 0; ci2 < foundCss.length; ci2++) pushHit(foundCss[ci2], ctx);
588
+ } catch (e) {}
238
589
  } else if (typeof sel === "object" && sel !== null && "accessibilityLabel" in sel) {
239
590
  var lbl = esc(sel.accessibilityLabel);
240
591
  var foundLbl = root.querySelectorAll('[aria-label="' + lbl + '"]');
241
592
  for (var j = 0; j < foundLbl.length; j++) pushHit(foundLbl[j], ctx);
593
+ } else if (typeof sel === "object" && sel !== null && "role" in sel) {
594
+ findRoleInRoot(root, String(sel.role).toLowerCase(), sel.name, sel.exact, ctx, pushHit, sel.includeHidden, sel.level);
242
595
  } else if (typeof sel === "string" || (typeof sel === "object" && sel !== null && "text" in sel)) {
243
- var needle = (typeof sel === "string" ? sel : sel.text).toLowerCase();
244
- findTextInRoot(root, needle, ctx, pushHit);
596
+ var needle = typeof sel === "string" ? sel : sel.text;
597
+ var isExact = typeof sel === "object" && sel !== null && Boolean(sel.exact);
598
+ findTextInRoot(root, needle, isExact, ctx, pushHit);
245
599
  }
246
600
  }
247
- return hits;
601
+ return applyModifiersAndSlice(hits, sel);
602
+ }
603
+ function findAcrossRoots(sel) {
604
+ return findInScope(sel, document, 0, 0, false, false);
248
605
  }
249
606
  function isClickable(el) {
250
607
  var tag = el.tagName;
@@ -289,13 +646,22 @@ var SHARED_DOM_TRAVERSAL_HELPERS = `
289
646
  }
290
647
  return el;
291
648
  }
649
+ function labelControlOf(node) {
650
+ var cur = node;
651
+ var guard = 0;
652
+ while (cur && guard++ < 8) {
653
+ if (cur.tagName === "LABEL") return cur.control || null;
654
+ cur = cur.parentElement;
655
+ }
656
+ return null;
657
+ }
292
658
  function isSameOrDescendant(target, candidate) {
293
659
  if (!target || !candidate) return false;
294
660
  if (target === candidate) return true;
295
661
  try {
296
662
  if (typeof target.contains === "function" && target.contains(candidate)) return true;
297
- if (typeof candidate.contains === "function" && candidate.contains(target)) return true;
298
663
  } catch (e) {}
664
+ if (labelControlOf(candidate) === target) return true;
299
665
  var cur = candidate;
300
666
  var guard = 0;
301
667
  while (cur && guard++ < 24) {
@@ -309,6 +675,31 @@ var SHARED_DOM_TRAVERSAL_HELPERS = `
309
675
  }
310
676
  return false;
311
677
  }
678
+ function describeEl(el) {
679
+ if (!el) return "(unknown)";
680
+ var tag = el.tagName ? el.tagName.toLowerCase() : "element";
681
+ var idPart = el.id ? "#" + el.id : "";
682
+ var cls = typeof el.className === "string" ? el.className.trim().split(/\\s+/).filter(Boolean).slice(0, 3).join(".") : "";
683
+ var clsPart = cls ? "." + cls : "";
684
+ var txt = (el.innerText || el.textContent || "").replace(/\\s+/g, " ").trim();
685
+ if (txt.length > 40) txt = txt.slice(0, 37) + "...";
686
+ return "<" + tag + idPart + clsPart + (txt ? ">" + txt + "</" + tag + ">" : ">");
687
+ }
688
+ function getHitTestBlocker(hit) {
689
+ var el = hit.el;
690
+ var rect = el.getBoundingClientRect();
691
+ var vw = (window.visualViewport && window.visualViewport.width) || window.innerWidth || document.documentElement.clientWidth || 0;
692
+ var vh = (window.visualViewport && window.visualViewport.height) || window.innerHeight || document.documentElement.clientHeight || 0;
693
+ var cx = rect.left + hit.offsetX + rect.width / 2;
694
+ var cy = rect.top + hit.offsetY + rect.height / 2;
695
+ if (vw > 0 && vh > 0 && (cx < 0 || cy < 0 || cx > vw || cy > vh)) {
696
+ return "outside viewport";
697
+ }
698
+ var topEl = deepElementFromPoint(document, cx, cy);
699
+ if (!topEl) return null;
700
+ if (isSameOrDescendant(el, topEl)) return null;
701
+ return describeEl(topEl);
702
+ }
312
703
  function isHitTestClear(hit) {
313
704
  var el = hit.el;
314
705
  var rect = el.getBoundingClientRect();
@@ -339,6 +730,36 @@ var SHARED_DOM_TRAVERSAL_HELPERS = `
339
730
  }
340
731
  return false;
341
732
  }
733
+ function scrollToUnobscure(hit) {
734
+ var el = hit.el;
735
+ if (typeof el.scrollIntoView !== "function") return false;
736
+ var blocks = ["center", "end", "start", "nearest"];
737
+ for (var i = 0; i < blocks.length; i++) {
738
+ try {
739
+ el.scrollIntoView({ block: blocks[i], inline: "center", behavior: "instant" });
740
+ } catch (e) {
741
+ try { el.scrollIntoView(true); } catch (e2) {}
742
+ }
743
+ if (isHitTestClear(hit)) return true;
744
+ }
745
+ return false;
746
+ }
747
+ function hasActiveAnimation(el) {
748
+ var cur = el;
749
+ var depth = 0;
750
+ while (cur && depth++ < 8) {
751
+ if (typeof cur.getAnimations === "function") {
752
+ try {
753
+ var anims = cur.getAnimations();
754
+ for (var i = 0; i < anims.length; i++) {
755
+ if (anims[i] && anims[i].playState === "running") return true;
756
+ }
757
+ } catch (e) {}
758
+ }
759
+ cur = cur.parentElement;
760
+ }
761
+ return false;
762
+ }
342
763
  function isVisible(el, rect) {
343
764
  if (rect.width <= 0 || rect.height <= 0) return false;
344
765
  var win = (el.ownerDocument && el.ownerDocument.defaultView) || window;
@@ -360,12 +781,20 @@ var SHARED_DOM_TRAVERSAL_HELPERS = `
360
781
  ? String(el.value ?? "")
361
782
  : undefined;
362
783
  var text = (el.innerText || el.textContent || "").trim() || undefined;
784
+ var normTextContent = (el.textContent || "").replace(/\\s+/g, " ").trim() || undefined;
785
+ var accName = getAccessibleName(el) || undefined;
786
+ var accDesc = getAccessibleDescription(el) || undefined;
787
+ var role = getImplicitRole(el) || undefined;
363
788
  return {
364
789
  id: el.getAttribute("data-testid") || el.getAttribute("testID") || undefined,
365
790
  tag: tag,
791
+ role: role,
366
792
  text: text,
793
+ textContent: normTextContent,
367
794
  value: val,
368
795
  accessibilityLabel: el.getAttribute("aria-label") || undefined,
796
+ accessibleName: accName,
797
+ accessibleDescription: accDesc,
369
798
  rect: { x: rect.x + hit.offsetX, y: rect.y + hit.offsetY, width: rect.width, height: rect.height },
370
799
  scrollX: window.scrollX || window.pageXOffset || 0,
371
800
  scrollY: window.scrollY || window.pageYOffset || 0,
@@ -383,14 +812,14 @@ var SHARED_DOM_TRAVERSAL_HELPERS = `
383
812
  }
384
813
  `;
385
814
  function buildDomQueryScript(selector) {
386
- const serialized = JSON.stringify(selector);
815
+ const serialized = JSON.stringify(serializeSelectorForDom(selector));
387
816
  return `(function(sel) {
388
817
  ${SHARED_DOM_TRAVERSAL_HELPERS}
389
818
  return findAcrossRoots(sel).map(toMatch);
390
819
  })(${serialized})`;
391
820
  }
392
821
  function buildDomScrollIntoViewScript(selector) {
393
- const serialized = JSON.stringify(selector);
822
+ const serialized = JSON.stringify(serializeSelectorForDom(selector));
394
823
  return `(function(sel) {
395
824
  ${SHARED_DOM_TRAVERSAL_HELPERS}
396
825
  var hits = findAcrossRoots(sel);
@@ -404,7 +833,7 @@ function buildDomScrollIntoViewScript(selector) {
404
833
  })(${serialized})`;
405
834
  }
406
835
  function buildDomTapScript(selector) {
407
- const serialized = JSON.stringify(selector);
836
+ const serialized = JSON.stringify(serializeSelectorForDom(selector));
408
837
  return `(function(sel) {
409
838
  ${SHARED_DOM_TRAVERSAL_HELPERS}
410
839
  var hits = findAcrossRoots(sel);
@@ -428,19 +857,27 @@ function buildDomTapScript(selector) {
428
857
  return true;
429
858
  })(${serialized})`;
430
859
  }
860
+ function defaultActionStableFrames() {
861
+ const envVal = process.env["SPANA_ACTION_STABLE_FRAMES"];
862
+ if (envVal !== void 0) {
863
+ const parsed = Number.parseInt(envVal, 10);
864
+ if (Number.isFinite(parsed) && parsed >= 0) return parsed;
865
+ }
866
+ return 2;
867
+ }
431
868
  function buildDomWaitForSelectorScript(selector, opts = {}) {
432
- const serialized = JSON.stringify(selector);
869
+ const serialized = JSON.stringify(serializeSelectorForDom(selector));
433
870
  const timeoutMs = Math.max(10, Math.round(opts.timeoutMs ?? 5e3));
434
871
  const forAction = Boolean(opts.forAction);
435
872
  const failFastWhenIdle = Boolean(opts.failFastWhenIdle);
436
873
  const idleQuietMs = Math.max(50, Math.round(opts.idleQuietMs ?? 250));
437
- const stableFrames = opts.stableFrames !== void 0 ? Math.max(0, Math.round(opts.stableFrames)) : forAction ? 1 : 0;
874
+ const stableFrames = opts.stableFrames !== void 0 ? Math.max(0, Math.round(opts.stableFrames)) : forAction ? defaultActionStableFrames() : 0;
438
875
  const checkHitTest = opts.checkHitTest !== void 0 ? Boolean(opts.checkHitTest) : forAction;
439
876
  const waitForAppReady = opts.waitForAppReady !== void 0 ? Boolean(opts.waitForAppReady) : true;
440
877
  return `(function(sel, timeoutMs, forAction, failFastWhenIdle, idleQuietMs, reqStableFrames, checkHitTest, waitForAppReady) {
441
878
  ${SHARED_DOM_TRAVERSAL_HELPERS}
442
879
  var instantAnim = Boolean(typeof document !== "undefined" && document.getElementById && document.getElementById("__spana_instant_anim"));
443
- var stableFrames = instantAnim ? 0 : reqStableFrames;
880
+ var explicitStableFrames = instantAnim ? 0 : reqStableFrames;
444
881
 
445
882
  function findCandidates() {
446
883
  if (waitForAppReady && !isAppReady()) return null;
@@ -461,20 +898,33 @@ function buildDomWaitForSelectorScript(selector, opts = {}) {
461
898
  if (!ready) return null;
462
899
  if (!forAction) return ready.map(function(r) { return r.match; });
463
900
  var target = ready[ready.length - 1];
464
- ensureInViewport(target.hit);
465
- if (checkHitTest && !isHitTestClear(target.hit)) return null;
901
+ var didScroll = ensureInViewport(target.hit);
902
+ if (checkHitTest && !isHitTestClear(target.hit)) {
903
+ if (scrollToUnobscure(target.hit)) {
904
+ didScroll = true;
905
+ }
906
+ if (!isHitTestClear(target.hit)) return null;
907
+ }
466
908
  var updated = toMatch(target.hit);
467
909
  if (!updated.visible || !updated.enabled) return null;
468
- return { hits: ready, target: target, match: updated };
910
+ return { hits: ready, target: target, match: updated, didScroll: didScroll };
469
911
  }
470
912
 
471
- // Fast synchronous exit when no multi-frame stability check is needed
472
- if (!forAction || stableFrames <= 0 || typeof requestAnimationFrame !== "function") {
473
- var imm = checkActionableNow();
474
- if (imm) {
475
- if (!forAction) return imm;
476
- return [imm.match];
477
- }
913
+ function neededStableFrames(candidate) {
914
+ if (!forAction || typeof requestAnimationFrame !== "function") return 0;
915
+ if (explicitStableFrames >= 0) return explicitStableFrames;
916
+ // Smart auto stability: 0 rAF wait on static, unobstructed elements;
917
+ // wait 2 frames if CSS animations/transitions are running or 1 frame right after scroll.
918
+ if (hasActiveAnimation(candidate.target.hit.el)) return 2;
919
+ if (candidate.didScroll) return 1;
920
+ return 0;
921
+ }
922
+
923
+ // Fast synchronous exit when target is already actionable and needs 0 stability frames
924
+ var imm = checkActionableNow();
925
+ if (imm) {
926
+ if (!forAction) return imm;
927
+ if (neededStableFrames(imm) <= 0) return [imm.match];
478
928
  }
479
929
 
480
930
  return new Promise(function(resolve) {
@@ -518,14 +968,15 @@ function buildDomWaitForSelectorScript(selector, opts = {}) {
518
968
 
519
969
  function verifyStability(candidate) {
520
970
  if (done || checkingStability) return;
521
- if (!forAction || stableFrames <= 0 || typeof requestAnimationFrame !== "function") {
971
+ var framesToWait = neededStableFrames(candidate);
972
+ if (!forAction || framesToWait <= 0 || typeof requestAnimationFrame !== "function") {
522
973
  finish(forAction ? [candidate.match] : candidate);
523
974
  return;
524
975
  }
525
976
  checkingStability = true;
526
977
  var el = candidate.target.hit.el;
527
978
  var lastRect = candidate.match.rect;
528
- var remainingFrames = stableFrames;
979
+ var remainingFrames = framesToWait;
529
980
 
530
981
  function step() {
531
982
  if (done) return;
@@ -553,7 +1004,7 @@ function buildDomWaitForSelectorScript(selector, opts = {}) {
553
1004
  return;
554
1005
  }
555
1006
  } else {
556
- remainingFrames = stableFrames;
1007
+ remainingFrames = framesToWait;
557
1008
  lastRect = cur.rect;
558
1009
  }
559
1010
  rafId = requestAnimationFrame(step);
@@ -610,7 +1061,7 @@ function buildDomWaitForSelectorScript(selector, opts = {}) {
610
1061
  })(${serialized}, ${timeoutMs}, ${forAction}, ${failFastWhenIdle}, ${idleQuietMs}, ${stableFrames}, ${checkHitTest}, ${waitForAppReady})`;
611
1062
  }
612
1063
  function buildDomWaitForHiddenScript(selector, opts = {}) {
613
- const serialized = JSON.stringify(selector);
1064
+ const serialized = JSON.stringify(serializeSelectorForDom(selector));
614
1065
  const timeoutMs = Math.max(10, Math.round(opts.timeoutMs ?? 5e3));
615
1066
  return `(function(sel, timeoutMs) {
616
1067
  ${SHARED_DOM_TRAVERSAL_HELPERS}
@@ -664,55 +1115,87 @@ function buildDomWaitForHiddenScript(selector, opts = {}) {
664
1115
  })(${serialized}, ${timeoutMs})`;
665
1116
  }
666
1117
  function buildDomWaitForMatchScript(selector, opts) {
667
- const serialized = JSON.stringify(selector);
1118
+ const serialized = JSON.stringify(serializeSelectorForDom(selector));
668
1119
  const timeoutMs = Math.max(10, Math.round(opts.timeoutMs ?? 5e3));
669
1120
  const kind = JSON.stringify(opts.kind);
670
1121
  const expected = JSON.stringify(opts.expected ?? null);
1122
+ const expectedCount = JSON.stringify(opts.expectedCount ?? null);
671
1123
  const attributeName = JSON.stringify(opts.attributeName ?? null);
672
1124
  const patternSource = JSON.stringify(opts.patternSource ?? null);
673
1125
  const patternFlags = JSON.stringify(opts.patternFlags ?? "");
674
- return `(function(sel, timeoutMs, kind, expected, attributeName, patternSource, patternFlags) {
1126
+ const negate = Boolean(opts.negate);
1127
+ return `(function(sel, timeoutMs, kind, expected, expectedCount, attributeName, patternSource, patternFlags, negate) {
675
1128
  ${SHARED_DOM_TRAVERSAL_HELPERS}
676
1129
  var lastActual = undefined;
677
1130
  var regex = patternSource !== null ? new RegExp(patternSource, patternFlags) : null;
678
1131
 
679
1132
  function evaluateMatch() {
1133
+ if (kind === "url") {
1134
+ var href = String(window.location.href || "");
1135
+ lastActual = href;
1136
+ var urlOk = regex
1137
+ ? regex.test(href)
1138
+ : (expected !== null && (href === expected || href.indexOf(String(expected)) !== -1));
1139
+ if (negate ? !urlOk : urlOk) return { matched: true, actual: href };
1140
+ return null;
1141
+ }
680
1142
  var hits = findAcrossRoots(sel);
1143
+ if (kind === "count") {
1144
+ var visibleCount = 0;
1145
+ for (var ci = 0; ci < hits.length; ci++) {
1146
+ if (toMatch(hits[ci]).visible) visibleCount += 1;
1147
+ }
1148
+ lastActual = String(visibleCount);
1149
+ var countOk = visibleCount === expectedCount;
1150
+ if (negate ? !countOk : countOk) return { matched: true, actual: String(visibleCount) };
1151
+ return null;
1152
+ }
1153
+ var anyVisible = false;
681
1154
  for (var i = hits.length - 1; i >= 0; i--) {
682
1155
  var m = toMatch(hits[i]);
683
1156
  if (!m.visible) continue;
684
- if (kind === "text") {
685
- lastActual = m.text;
686
- if (m.text === expected) return { matched: true, actual: m.text };
1157
+ anyVisible = true;
1158
+ var matched = false;
1159
+ var actualVal = undefined;
1160
+ if (kind === "focused") {
1161
+ var isFoc = Boolean(m.focused);
1162
+ actualVal = isFoc ? "focused" : "not focused";
1163
+ matched = isFoc;
1164
+ } else if (kind === "accessibleName") {
1165
+ var acc = m.accessibleName || "";
1166
+ actualVal = acc;
1167
+ matched = regex ? regex.test(acc) : (expected === null ? acc.length > 0 : acc.trim() === String(expected).trim());
1168
+ } else if (kind === "accessibleDescription") {
1169
+ var accD = m.accessibleDescription || "";
1170
+ actualVal = accD;
1171
+ matched = regex ? regex.test(accD) : (expected === null ? accD.length > 0 : accD.trim() === String(expected).trim());
1172
+ } else if (kind === "text") {
1173
+ var normTxt = m.textContent !== undefined ? m.textContent : (m.text || "");
1174
+ actualVal = normTxt;
1175
+ matched = normTxt === (expected !== null ? String(expected).replace(/\\s+/g, " ").trim() : expected);
687
1176
  } else if (kind === "containsText") {
688
- var actual = m.text || "";
689
- lastActual = m.text;
690
- if (expected !== null && actual.toLowerCase().indexOf(String(expected).toLowerCase()) !== -1) {
691
- return { matched: true, actual: m.text };
692
- }
1177
+ var actual = m.textContent !== undefined ? m.textContent : (m.text || "");
1178
+ actualVal = actual;
1179
+ matched = expected !== null && actual.toLowerCase().indexOf(String(expected).replace(/\\s+/g, " ").trim().toLowerCase()) !== -1;
693
1180
  } else if (kind === "matchesText") {
694
- var actualRe = m.text || "";
695
- lastActual = m.text;
696
- if (regex && regex.test(actualRe)) {
697
- return { matched: true, actual: m.text };
698
- }
1181
+ var actualRe = m.textContent !== undefined ? m.textContent : (m.text || "");
1182
+ actualVal = actualRe;
1183
+ matched = Boolean(regex && regex.test(actualRe));
699
1184
  } else if (kind === "value") {
700
1185
  var val = m.value !== undefined ? m.value : "";
701
- lastActual = val;
702
- if (val === expected) return { matched: true, actual: val };
1186
+ actualVal = val;
1187
+ matched = val === expected;
703
1188
  } else if (kind === "attribute" && attributeName !== null) {
704
1189
  var attrVal = m.attributes ? m.attributes[attributeName] : undefined;
705
- lastActual = attrVal;
706
- if (expected === null ? attrVal !== undefined : attrVal === expected) {
707
- return { matched: true, actual: attrVal };
708
- }
1190
+ actualVal = attrVal;
1191
+ matched = expected === null ? attrVal !== undefined : attrVal === expected;
709
1192
  } else if (kind === "accessibilityLabel") {
710
1193
  var lbl = m.accessibilityLabel;
711
- lastActual = lbl;
712
- if (expected === null ? (lbl !== undefined && lbl.length > 0) : lbl === expected) {
713
- return { matched: true, actual: lbl };
714
- }
1194
+ actualVal = lbl;
1195
+ matched = expected === null ? (lbl !== undefined && lbl.length > 0) : lbl === expected;
715
1196
  }
1197
+ lastActual = actualVal;
1198
+ if (negate ? !matched : matched) return { matched: true, actual: actualVal };
716
1199
  }
717
1200
  return null;
718
1201
  }
@@ -736,6 +1219,11 @@ function buildDomWaitForMatchScript(selector, opts) {
736
1219
  if (typeof document !== "undefined") {
737
1220
  document.removeEventListener("input", onChange, true);
738
1221
  document.removeEventListener("change", onChange, true);
1222
+ document.removeEventListener("focusin", onChange, true);
1223
+ }
1224
+ if (typeof window !== "undefined") {
1225
+ window.removeEventListener("popstate", onChange);
1226
+ window.removeEventListener("hashchange", onChange);
739
1227
  }
740
1228
  resolve(res);
741
1229
  }
@@ -756,11 +1244,16 @@ function buildDomWaitForMatchScript(selector, opts) {
756
1244
  finish(finalRes || { matched: false, actual: lastActual });
757
1245
  }, timeoutMs);
758
1246
 
759
- fallbackInterval = setInterval(onChange, 120);
1247
+ fallbackInterval = setInterval(onChange, kind === "url" ? 50 : 100);
760
1248
 
761
1249
  if (typeof document !== "undefined") {
762
1250
  document.addEventListener("input", onChange, true);
763
1251
  document.addEventListener("change", onChange, true);
1252
+ document.addEventListener("focusin", onChange, true);
1253
+ }
1254
+ if (typeof window !== "undefined") {
1255
+ window.addEventListener("popstate", onChange);
1256
+ window.addEventListener("hashchange", onChange);
764
1257
  }
765
1258
 
766
1259
  if (typeof MutationObserver !== "undefined") {
@@ -776,18 +1269,21 @@ function buildDomWaitForMatchScript(selector, opts) {
776
1269
  }
777
1270
  }
778
1271
  });
779
- })(${serialized}, ${timeoutMs}, ${kind}, ${expected}, ${attributeName}, ${patternSource}, ${patternFlags})`;
1272
+ })(${serialized}, ${timeoutMs}, ${kind}, ${expected}, ${expectedCount}, ${attributeName}, ${patternSource}, ${patternFlags}, ${negate})`;
780
1273
  }
781
1274
  function buildDomFillScript(selector, value, opts = {}) {
782
- const serializedSel = JSON.stringify(selector);
1275
+ const serializedSel = JSON.stringify(serializeSelectorForDom(selector));
783
1276
  const serializedVal = JSON.stringify(value);
784
1277
  const timeoutMs = Math.max(10, Math.round(opts.timeoutMs ?? 5e3));
785
1278
  const checkHitTest = opts.checkHitTest !== void 0 ? Boolean(opts.checkHitTest) : true;
786
1279
  return `(function(sel, val, timeoutMs, checkHitTest) {
787
1280
  ${SHARED_DOM_TRAVERSAL_HELPERS}
788
- function applyFill(el) {
1281
+ function writeValue(el) {
789
1282
  if (typeof el.focus === "function") { try { el.focus(); } catch (e) {} }
790
1283
  var tag = el.tagName;
1284
+ // Rich-text contenteditable editors (TipTap/ProseMirror/Lexical/Slate) require native keyboard input;
1285
+ // return false so coordinator falls back cleanly to real tap + SelectAll + Input.insertText.
1286
+ if (el.isContentEditable) return false;
791
1287
  if (tag === "INPUT" || tag === "TEXTAREA") {
792
1288
  var proto = tag === "TEXTAREA"
793
1289
  ? (window.HTMLTextAreaElement && window.HTMLTextAreaElement.prototype)
@@ -798,10 +1294,12 @@ function buildDomFillScript(selector, value, opts = {}) {
798
1294
  } else {
799
1295
  el.value = val;
800
1296
  }
1297
+ // Reset React's internal _valueTracker so synthetic controlled onChange always fires
1298
+ if (el._valueTracker && typeof el._valueTracker.setValue === "function") {
1299
+ try { el._valueTracker.setValue(val === "" ? " " : ""); } catch (e) {}
1300
+ }
801
1301
  } else if (tag === "SELECT") {
802
1302
  el.value = val;
803
- } else if (el.isContentEditable) {
804
- el.textContent = val;
805
1303
  } else {
806
1304
  el.value = val;
807
1305
  }
@@ -811,21 +1309,50 @@ function buildDomFillScript(selector, value, opts = {}) {
811
1309
  return true;
812
1310
  }
813
1311
 
814
- function tryNow() {
815
- if (!isAppReady()) return false;
1312
+ function findEditableNow() {
1313
+ if (!isAppReady()) return null;
816
1314
  var hits = findAcrossRoots(sel);
817
1315
  for (var i = hits.length - 1; i >= 0; i--) {
818
1316
  var h = hits[i];
819
1317
  var m = toMatch(h);
820
1318
  if (!m.visible || !m.enabled) continue;
821
1319
  ensureInViewport(h);
822
- if (checkHitTest && !isHitTestClear(h)) continue;
823
- return applyFill(h.el);
1320
+ if (checkHitTest && !isHitTestClear(h)) {
1321
+ scrollToUnobscure(h);
1322
+ if (!isHitTestClear(h)) continue;
1323
+ }
1324
+ return h.el;
824
1325
  }
825
- return false;
1326
+ return null;
1327
+ }
1328
+
1329
+ function verifyAndRetryFill(attemptsLeft) {
1330
+ var el = findEditableNow();
1331
+ if (!el) return Promise.resolve(false);
1332
+ if (el.isContentEditable) return Promise.resolve(false);
1333
+ if (!writeValue(el)) return Promise.resolve(false);
1334
+ return new Promise(function(resolve) {
1335
+ // Let React/Vue microtask + single paint flush settle, then verify value survived remount/re-render
1336
+ setTimeout(function() {
1337
+ var latest = findEditableNow() || el;
1338
+ if (latest && latest.isConnected && String(latest.value == null ? "" : latest.value) === val) {
1339
+ resolve(true);
1340
+ return;
1341
+ }
1342
+ if (attemptsLeft > 1) {
1343
+ verifyAndRetryFill(attemptsLeft - 1).then(resolve);
1344
+ } else {
1345
+ resolve(false);
1346
+ }
1347
+ }, 12);
1348
+ });
826
1349
  }
827
1350
 
828
- if (tryNow()) return true;
1351
+ var immEl = findEditableNow();
1352
+ if (immEl) {
1353
+ if (immEl.isContentEditable) return false;
1354
+ return verifyAndRetryFill(3);
1355
+ }
829
1356
 
830
1357
  return new Promise(function(resolve) {
831
1358
  var done = false;
@@ -833,6 +1360,7 @@ function buildDomFillScript(selector, value, opts = {}) {
833
1360
  var timeoutTimer = null;
834
1361
  var fallbackInterval = null;
835
1362
  var scheduled = false;
1363
+ var filling = false;
836
1364
 
837
1365
  function finish(ok) {
838
1366
  if (done) return;
@@ -844,16 +1372,25 @@ function buildDomFillScript(selector, value, opts = {}) {
844
1372
  }
845
1373
 
846
1374
  function onChange() {
847
- if (done || scheduled) return;
1375
+ if (done || scheduled || filling) return;
848
1376
  scheduled = true;
849
1377
  Promise.resolve().then(function() {
850
1378
  scheduled = false;
851
- if (!done && tryNow()) finish(true);
1379
+ if (done || filling) return;
1380
+ var target = findEditableNow();
1381
+ if (!target) return;
1382
+ if (target.isContentEditable) { finish(false); return; }
1383
+ filling = true;
1384
+ verifyAndRetryFill(3).then(function(ok) { finish(ok); });
852
1385
  });
853
1386
  }
854
1387
 
855
1388
  timeoutTimer = setTimeout(function() {
856
- finish(tryNow());
1389
+ if (filling) return;
1390
+ var target = findEditableNow();
1391
+ if (!target || target.isContentEditable) { finish(false); return; }
1392
+ filling = true;
1393
+ verifyAndRetryFill(2).then(function(ok) { finish(ok); });
857
1394
  }, timeoutMs);
858
1395
 
859
1396
  fallbackInterval = setInterval(onChange, 40);
@@ -873,6 +1410,546 @@ function buildDomFillScript(selector, value, opts = {}) {
873
1410
  });
874
1411
  })(${serializedSel}, ${serializedVal}, ${timeoutMs}, ${checkHitTest})`;
875
1412
  }
1413
+ var SPANA_RUNTIME_MISSING_SENTINEL = "__SPANA_RT_MISSING__";
1414
+ var SPANA_INJECTED_RUNTIME_SCRIPT = `(function() {
1415
+ if (typeof window === "undefined" || window.__spanaRt) return true;
1416
+ ${SHARED_DOM_TRAVERSAL_HELPERS}
1417
+
1418
+ function query(sel) {
1419
+ return findAcrossRoots(sel).map(toMatch);
1420
+ }
1421
+
1422
+ function scrollIntoView(sel) {
1423
+ var hits = findAcrossRoots(sel);
1424
+ if (hits.length === 0) return null;
1425
+ var hit = hits[hits.length - 1];
1426
+ if (typeof hit.el.scrollIntoView === "function") {
1427
+ try { hit.el.scrollIntoView({ block: "center", inline: "center", behavior: "instant" }); }
1428
+ catch (e) { try { hit.el.scrollIntoView(true); } catch (e2) {} }
1429
+ }
1430
+ return toMatch(hit);
1431
+ }
1432
+
1433
+ function tap(sel) {
1434
+ var hits = findAcrossRoots(sel);
1435
+ if (hits.length === 0) return false;
1436
+ var hit = hits[hits.length - 1];
1437
+ var el = hit.el;
1438
+ if (typeof el.scrollIntoView === "function") {
1439
+ try { el.scrollIntoView({ block: "center", inline: "center", behavior: "instant" }); } catch (e) {}
1440
+ }
1441
+ var rect = el.getBoundingClientRect();
1442
+ var cx = rect.left + rect.width / 2;
1443
+ var cy = rect.top + rect.height / 2;
1444
+ var init = { bubbles: true, cancelable: true, composed: true, clientX: cx, clientY: cy };
1445
+ try { el.dispatchEvent(new PointerEvent("pointerdown", init)); } catch (e) {}
1446
+ try { el.dispatchEvent(new MouseEvent("mousedown", init)); } catch (e) {}
1447
+ if (typeof el.focus === "function") { try { el.focus(); } catch (e) {} }
1448
+ try { el.dispatchEvent(new PointerEvent("pointerup", init)); } catch (e) {}
1449
+ try { el.dispatchEvent(new MouseEvent("mouseup", init)); } catch (e) {}
1450
+ if (typeof el.click === "function") { el.click(); }
1451
+ else { el.dispatchEvent(new MouseEvent("click", init)); }
1452
+ return true;
1453
+ }
1454
+
1455
+ function waitForSelector(sel, opts) {
1456
+ opts = opts || {};
1457
+ var timeoutMs = Math.max(10, Math.round(opts.timeoutMs != null ? opts.timeoutMs : 5000));
1458
+ var forAction = Boolean(opts.forAction);
1459
+ var failFastWhenIdle = Boolean(opts.failFastWhenIdle);
1460
+ var idleQuietMs = Math.max(50, Math.round(opts.idleQuietMs != null ? opts.idleQuietMs : 250));
1461
+ var reqStableFrames = opts.stableFrames !== undefined ? Math.max(0, Math.round(opts.stableFrames)) : (forAction ? 2 : 0);
1462
+ var checkHitTest = opts.checkHitTest !== undefined ? Boolean(opts.checkHitTest) : forAction;
1463
+ var waitForAppReady = opts.waitForAppReady !== undefined ? Boolean(opts.waitForAppReady) : true;
1464
+ var instantAnim = Boolean(typeof document !== "undefined" && document.getElementById && document.getElementById("__spana_instant_anim"));
1465
+ var explicitStableFrames = instantAnim ? 0 : reqStableFrames;
1466
+
1467
+ function findCandidates() {
1468
+ if (waitForAppReady && !isAppReady()) return null;
1469
+ var rawHits = findAcrossRoots(sel);
1470
+ var ready = [];
1471
+ for (var i = 0; i < rawHits.length; i++) {
1472
+ var h = rawHits[i];
1473
+ var m = toMatch(h);
1474
+ if (!m.visible) continue;
1475
+ if (forAction && !m.enabled) continue;
1476
+ ready.push({ hit: h, match: m });
1477
+ }
1478
+ return ready.length > 0 ? ready : null;
1479
+ }
1480
+
1481
+ function checkActionableNow() {
1482
+ var ready = findCandidates();
1483
+ if (!ready) return null;
1484
+ if (!forAction) return ready.map(function(r) { return r.match; });
1485
+ var target = ready[ready.length - 1];
1486
+ var didScroll = ensureInViewport(target.hit);
1487
+ if (checkHitTest && !isHitTestClear(target.hit)) {
1488
+ if (scrollToUnobscure(target.hit)) {
1489
+ didScroll = true;
1490
+ }
1491
+ if (!isHitTestClear(target.hit)) return null;
1492
+ }
1493
+ var updated = toMatch(target.hit);
1494
+ if (!updated.visible || !updated.enabled) return null;
1495
+ return { hits: ready, target: target, match: updated, didScroll: didScroll };
1496
+ }
1497
+
1498
+ function neededStableFrames(candidate) {
1499
+ if (!forAction || typeof requestAnimationFrame !== "function") return 0;
1500
+ if (explicitStableFrames >= 0) return explicitStableFrames;
1501
+ if (hasActiveAnimation(candidate.target.hit.el)) return 2;
1502
+ if (candidate.didScroll) return 1;
1503
+ return 0;
1504
+ }
1505
+
1506
+ var imm = checkActionableNow();
1507
+ if (imm) {
1508
+ if (!forAction) return imm;
1509
+ if (neededStableFrames(imm) <= 0) return [imm.match];
1510
+ }
1511
+
1512
+ return new Promise(function(resolve) {
1513
+ var done = false;
1514
+ var observer = null;
1515
+ var timeoutTimer = null;
1516
+ var fallbackInterval = null;
1517
+ var idleTimer = null;
1518
+ var rafId = null;
1519
+ var checkingStability = false;
1520
+
1521
+ function finish(result) {
1522
+ if (done) return;
1523
+ done = true;
1524
+ if (observer) { try { observer.disconnect(); } catch (e) {} }
1525
+ if (timeoutTimer) clearTimeout(timeoutTimer);
1526
+ if (fallbackInterval) clearInterval(fallbackInterval);
1527
+ if (idleTimer) clearTimeout(idleTimer);
1528
+ if (rafId !== null && typeof cancelAnimationFrame === "function") {
1529
+ try { cancelAnimationFrame(rafId); } catch (e) {}
1530
+ }
1531
+ resolve(result);
1532
+ }
1533
+
1534
+ function armIdleTimer() {
1535
+ if (!failFastWhenIdle) return;
1536
+ if (idleTimer) clearTimeout(idleTimer);
1537
+ idleTimer = setTimeout(function() {
1538
+ if (document.readyState === "complete" && (!waitForAppReady || isAppReady())) {
1539
+ var hit = checkActionableNow();
1540
+ finish(hit ? (forAction ? [hit.match] : hit) : []);
1541
+ } else {
1542
+ armIdleTimer();
1543
+ }
1544
+ }, idleQuietMs);
1545
+ }
1546
+
1547
+ function verifyStability(candidate) {
1548
+ if (done || checkingStability) return;
1549
+ var framesToWait = neededStableFrames(candidate);
1550
+ if (!forAction || framesToWait <= 0 || typeof requestAnimationFrame !== "function") {
1551
+ finish(forAction ? [candidate.match] : candidate);
1552
+ return;
1553
+ }
1554
+ checkingStability = true;
1555
+ var el = candidate.target.hit.el;
1556
+ var lastRect = candidate.match.rect;
1557
+ var remainingFrames = framesToWait;
1558
+
1559
+ function step() {
1560
+ if (done) return;
1561
+ if (!el.isConnected) { checkingStability = false; return; }
1562
+ if (checkHitTest && !isHitTestClear(candidate.target.hit)) { checkingStability = false; return; }
1563
+ var cur = toMatch(candidate.target.hit);
1564
+ if (!cur.visible || !cur.enabled) { checkingStability = false; return; }
1565
+ var dx = Math.abs(cur.rect.x - lastRect.x);
1566
+ var dy = Math.abs(cur.rect.y - lastRect.y);
1567
+ var dw = Math.abs(cur.rect.width - lastRect.width);
1568
+ var dh = Math.abs(cur.rect.height - lastRect.height);
1569
+ if (dx <= 1 && dy <= 1 && dw <= 1 && dh <= 1) {
1570
+ remainingFrames -= 1;
1571
+ if (remainingFrames <= 0) { finish([cur]); return; }
1572
+ } else {
1573
+ remainingFrames = framesToWait;
1574
+ lastRect = cur.rect;
1575
+ }
1576
+ rafId = requestAnimationFrame(step);
1577
+ }
1578
+ rafId = requestAnimationFrame(step);
1579
+ }
1580
+
1581
+ function attempt() {
1582
+ if (done || checkingStability) return;
1583
+ var hit = checkActionableNow();
1584
+ if (hit) {
1585
+ if (forAction) verifyStability(hit);
1586
+ else finish(hit);
1587
+ return;
1588
+ }
1589
+ armIdleTimer();
1590
+ }
1591
+
1592
+ var scheduled = false;
1593
+ function scheduleAttempt() {
1594
+ if (done || scheduled || checkingStability) return;
1595
+ scheduled = true;
1596
+ Promise.resolve().then(function() { scheduled = false; attempt(); });
1597
+ }
1598
+
1599
+ timeoutTimer = setTimeout(function() {
1600
+ var finalHit = checkActionableNow();
1601
+ finish(finalHit ? (forAction ? [finalHit.match] : finalHit) : []);
1602
+ }, timeoutMs);
1603
+ fallbackInterval = setInterval(attempt, forAction ? 40 : 120);
1604
+ if (typeof MutationObserver !== "undefined") {
1605
+ var root = document.documentElement || document.body || document;
1606
+ if (root) {
1607
+ observer = new MutationObserver(scheduleAttempt);
1608
+ observer.observe(root, { childList: true, subtree: true, attributes: true, characterData: true });
1609
+ }
1610
+ }
1611
+ attempt();
1612
+ });
1613
+ }
1614
+
1615
+ function waitForHidden(sel, opts) {
1616
+ opts = opts || {};
1617
+ var timeoutMs = Math.max(10, Math.round(opts.timeoutMs != null ? opts.timeoutMs : 5000));
1618
+ function isHiddenNow() {
1619
+ var hits = findAcrossRoots(sel);
1620
+ for (var i = 0; i < hits.length; i++) {
1621
+ if (toMatch(hits[i]).visible) return false;
1622
+ }
1623
+ return true;
1624
+ }
1625
+ if (isHiddenNow()) return true;
1626
+ return new Promise(function(resolve) {
1627
+ var done = false;
1628
+ var observer = null;
1629
+ var timeoutTimer = null;
1630
+ var fallbackInterval = null;
1631
+ function finish(val) {
1632
+ if (done) return;
1633
+ done = true;
1634
+ if (observer) { try { observer.disconnect(); } catch (e) {} }
1635
+ if (timeoutTimer) clearTimeout(timeoutTimer);
1636
+ if (fallbackInterval) clearInterval(fallbackInterval);
1637
+ resolve(val);
1638
+ }
1639
+ function onChange() { if (isHiddenNow()) finish(true); }
1640
+ timeoutTimer = setTimeout(function() { finish(isHiddenNow()); }, timeoutMs);
1641
+ fallbackInterval = setInterval(onChange, 120);
1642
+ if (typeof MutationObserver !== "undefined") {
1643
+ var root = document.documentElement || document.body || document;
1644
+ if (root) {
1645
+ observer = new MutationObserver(onChange);
1646
+ observer.observe(root, { childList: true, subtree: true, attributes: true, characterData: true });
1647
+ }
1648
+ }
1649
+ });
1650
+ }
1651
+
1652
+ function waitForMatch(sel, opts) {
1653
+ opts = opts || {};
1654
+ var timeoutMs = Math.max(10, Math.round(opts.timeoutMs != null ? opts.timeoutMs : 5000));
1655
+ var kind = opts.kind;
1656
+ var expected = opts.expected !== undefined ? opts.expected : null;
1657
+ var expectedCount = opts.expectedCount !== undefined ? opts.expectedCount : null;
1658
+ var attributeName = opts.attributeName !== undefined ? opts.attributeName : null;
1659
+ var patternSource = opts.patternSource !== undefined ? opts.patternSource : null;
1660
+ var patternFlags = opts.patternFlags || "";
1661
+ var negate = Boolean(opts.negate);
1662
+ var lastActual = undefined;
1663
+ var regex = patternSource !== null ? new RegExp(patternSource, patternFlags) : null;
1664
+
1665
+ function evaluateMatch() {
1666
+ if (kind === "url") {
1667
+ var href = typeof window !== "undefined" && window.location ? String(window.location.href || "") : "";
1668
+ lastActual = href;
1669
+ var urlOk = regex
1670
+ ? regex.test(href)
1671
+ : (expected !== null && (href === expected || href.indexOf(String(expected)) !== -1));
1672
+ if (negate ? !urlOk : urlOk) return { matched: true, actual: href };
1673
+ return null;
1674
+ }
1675
+
1676
+ var hits = findAcrossRoots(sel);
1677
+
1678
+ if (kind === "count") {
1679
+ var visibleCount = 0;
1680
+ for (var ci = 0; ci < hits.length; ci++) {
1681
+ if (toMatch(hits[ci]).visible) visibleCount++;
1682
+ }
1683
+ lastActual = String(visibleCount);
1684
+ var countOk = expectedCount !== null && visibleCount === expectedCount;
1685
+ if (negate ? !countOk : countOk) {
1686
+ return { matched: true, actual: String(visibleCount) };
1687
+ }
1688
+ return null;
1689
+ }
1690
+
1691
+ for (var i = hits.length - 1; i >= 0; i--) {
1692
+ var m = toMatch(hits[i]);
1693
+ if (!m.visible) continue;
1694
+ var matched = false;
1695
+ var actualVal = undefined;
1696
+ if (kind === "text") {
1697
+ var normTxt = m.textContent !== undefined ? m.textContent : (m.text || "");
1698
+ actualVal = normTxt;
1699
+ matched = normTxt === (expected !== null ? String(expected).replace(/\\s+/g, " ").trim() : expected);
1700
+ } else if (kind === "containsText") {
1701
+ var actual = m.textContent !== undefined ? m.textContent : (m.text || "");
1702
+ actualVal = actual;
1703
+ matched = expected !== null && actual.toLowerCase().indexOf(String(expected).replace(/\\s+/g, " ").trim().toLowerCase()) !== -1;
1704
+ } else if (kind === "matchesText") {
1705
+ var actualRe = m.textContent !== undefined ? m.textContent : (m.text || "");
1706
+ actualVal = actualRe;
1707
+ matched = Boolean(regex && regex.test(actualRe));
1708
+ } else if (kind === "value") {
1709
+ var val = m.value !== undefined ? m.value : "";
1710
+ actualVal = val;
1711
+ matched = val === expected;
1712
+ } else if (kind === "attribute" && attributeName !== null) {
1713
+ var attrVal = m.attributes ? m.attributes[attributeName] : undefined;
1714
+ actualVal = attrVal;
1715
+ matched = expected === null ? attrVal !== undefined : attrVal === expected;
1716
+ } else if (kind === "accessibilityLabel") {
1717
+ var lbl = m.accessibilityLabel;
1718
+ actualVal = lbl;
1719
+ matched = expected === null ? (lbl !== undefined && lbl.length > 0) : lbl === expected;
1720
+ } else if (kind === "accessibleName") {
1721
+ var accName = m.accessibleName || m.accessibilityLabel || m.text || "";
1722
+ actualVal = accName;
1723
+ matched = regex ? regex.test(accName) : (expected === null ? accName.length > 0 : accName.trim() === String(expected).trim());
1724
+ } else if (kind === "accessibleDescription") {
1725
+ var accDesc = m.accessibleDescription || "";
1726
+ actualVal = accDesc;
1727
+ matched = regex ? regex.test(accDesc) : (expected === null ? accDesc.length > 0 : accDesc.trim() === String(expected).trim());
1728
+ } else if (kind === "focused") {
1729
+ actualVal = m.focused ? "focused" : "not focused";
1730
+ matched = Boolean(m.focused);
1731
+ }
1732
+ lastActual = actualVal;
1733
+ if (negate ? !matched : matched) return { matched: true, actual: actualVal };
1734
+ }
1735
+ return null;
1736
+ }
1737
+
1738
+ var immediate = evaluateMatch();
1739
+ if (immediate) return immediate;
1740
+
1741
+ return new Promise(function(resolve) {
1742
+ var done = false;
1743
+ var observer = null;
1744
+ var timeoutTimer = null;
1745
+ var fallbackInterval = null;
1746
+ var scheduled = false;
1747
+ function finish(res) {
1748
+ if (done) return;
1749
+ done = true;
1750
+ if (observer) { try { observer.disconnect(); } catch (e) {} }
1751
+ if (timeoutTimer) clearTimeout(timeoutTimer);
1752
+ if (fallbackInterval) clearInterval(fallbackInterval);
1753
+ if (typeof document !== "undefined") {
1754
+ document.removeEventListener("input", onChange, true);
1755
+ document.removeEventListener("change", onChange, true);
1756
+ document.removeEventListener("focusin", onChange, true);
1757
+ document.removeEventListener("focusout", onChange, true);
1758
+ }
1759
+ if (typeof window !== "undefined") {
1760
+ window.removeEventListener("popstate", onChange);
1761
+ window.removeEventListener("hashchange", onChange);
1762
+ }
1763
+ resolve(res);
1764
+ }
1765
+ function onChange() {
1766
+ if (done || scheduled) return;
1767
+ scheduled = true;
1768
+ Promise.resolve().then(function() {
1769
+ scheduled = false;
1770
+ if (done) return;
1771
+ var res = evaluateMatch();
1772
+ if (res) finish(res);
1773
+ });
1774
+ }
1775
+ timeoutTimer = setTimeout(function() {
1776
+ var finalRes = evaluateMatch();
1777
+ finish(finalRes || { matched: false, actual: lastActual });
1778
+ }, timeoutMs);
1779
+ fallbackInterval = setInterval(onChange, kind === "url" ? 50 : 120);
1780
+ if (typeof document !== "undefined") {
1781
+ document.addEventListener("input", onChange, true);
1782
+ document.addEventListener("change", onChange, true);
1783
+ document.addEventListener("focusin", onChange, true);
1784
+ document.addEventListener("focusout", onChange, true);
1785
+ }
1786
+ if (typeof window !== "undefined") {
1787
+ window.addEventListener("popstate", onChange);
1788
+ window.addEventListener("hashchange", onChange);
1789
+ }
1790
+ if (typeof MutationObserver !== "undefined") {
1791
+ var root = document.documentElement || document.body || document;
1792
+ if (root) {
1793
+ observer = new MutationObserver(onChange);
1794
+ observer.observe(root, { childList: true, subtree: true, attributes: true, characterData: true });
1795
+ }
1796
+ }
1797
+ });
1798
+ }
1799
+
1800
+ function fill(sel, val, opts) {
1801
+ opts = opts || {};
1802
+ var timeoutMs = Math.max(10, Math.round(opts.timeoutMs != null ? opts.timeoutMs : 5000));
1803
+ var checkHitTest = opts.checkHitTest !== undefined ? Boolean(opts.checkHitTest) : true;
1804
+ function writeValue(el) {
1805
+ if (el.isContentEditable) return false;
1806
+ if (typeof el.focus === "function") { try { el.focus(); } catch (e) {} }
1807
+ var tag = el.tagName;
1808
+ if (tag === "INPUT" || tag === "TEXTAREA") {
1809
+ var win = (el.ownerDocument && el.ownerDocument.defaultView) || window;
1810
+ var proto = tag === "TEXTAREA"
1811
+ ? (win.HTMLTextAreaElement && win.HTMLTextAreaElement.prototype)
1812
+ : (win.HTMLInputElement && win.HTMLInputElement.prototype);
1813
+ var desc = proto ? Object.getOwnPropertyDescriptor(proto, "value") : null;
1814
+ if (desc && typeof desc.set === "function") desc.set.call(el, val);
1815
+ else el.value = val;
1816
+ if (el._valueTracker && typeof el._valueTracker.setValue === "function") {
1817
+ try { el._valueTracker.setValue(val === "" ? " " : ""); } catch (e) {}
1818
+ }
1819
+ } else if (tag === "SELECT") {
1820
+ el.value = val;
1821
+ } else {
1822
+ el.value = val;
1823
+ }
1824
+ try { el.dispatchEvent(new InputEvent("input", { bubbles: true, cancelable: true, data: val, inputType: "insertText" })); }
1825
+ catch (e) { el.dispatchEvent(new Event("input", { bubbles: true, cancelable: true })); }
1826
+ el.dispatchEvent(new Event("change", { bubbles: true, cancelable: true }));
1827
+ return true;
1828
+ }
1829
+ function findEditableNow() {
1830
+ if (!isAppReady()) return null;
1831
+ var hits = findAcrossRoots(sel);
1832
+ for (var i = hits.length - 1; i >= 0; i--) {
1833
+ var h = hits[i];
1834
+ var m = toMatch(h);
1835
+ if (!m.visible || !m.enabled) continue;
1836
+ ensureInViewport(h);
1837
+ if (checkHitTest && !isHitTestClear(h)) {
1838
+ scrollToUnobscure(h);
1839
+ if (!isHitTestClear(h)) continue;
1840
+ }
1841
+ return h.el;
1842
+ }
1843
+ return null;
1844
+ }
1845
+ function verifyAndRetryFill(attemptsLeft) {
1846
+ var el = findEditableNow();
1847
+ if (!el || el.isContentEditable) return Promise.resolve(false);
1848
+ if (!writeValue(el)) return Promise.resolve(false);
1849
+ return new Promise(function(resolve) {
1850
+ setTimeout(function() {
1851
+ var latest = findEditableNow() || el;
1852
+ if (latest && latest.isConnected && String(latest.value == null ? "" : latest.value) === val) {
1853
+ resolve(true);
1854
+ return;
1855
+ }
1856
+ if (attemptsLeft > 1) {
1857
+ verifyAndRetryFill(attemptsLeft - 1).then(resolve);
1858
+ } else {
1859
+ resolve(false);
1860
+ }
1861
+ }, 12);
1862
+ });
1863
+ }
1864
+ var immEl = findEditableNow();
1865
+ if (immEl) {
1866
+ if (immEl.isContentEditable) return false;
1867
+ return verifyAndRetryFill(3);
1868
+ }
1869
+ return new Promise(function(resolve) {
1870
+ var done = false;
1871
+ var observer = null;
1872
+ var timeoutTimer = null;
1873
+ var fallbackInterval = null;
1874
+ var scheduled = false;
1875
+ var filling = false;
1876
+ function finish(ok) {
1877
+ if (done) return;
1878
+ done = true;
1879
+ if (observer) { try { observer.disconnect(); } catch (e) {} }
1880
+ if (timeoutTimer) clearTimeout(timeoutTimer);
1881
+ if (fallbackInterval) clearInterval(fallbackInterval);
1882
+ resolve(ok);
1883
+ }
1884
+ function onChange() {
1885
+ if (done || scheduled || filling) return;
1886
+ scheduled = true;
1887
+ Promise.resolve().then(function() {
1888
+ scheduled = false;
1889
+ if (done || filling) return;
1890
+ var target = findEditableNow();
1891
+ if (!target) return;
1892
+ if (target.isContentEditable) { finish(false); return; }
1893
+ filling = true;
1894
+ verifyAndRetryFill(3).then(function(ok) { finish(ok); });
1895
+ });
1896
+ }
1897
+ timeoutTimer = setTimeout(function() {
1898
+ if (filling) return;
1899
+ var target = findEditableNow();
1900
+ if (!target || target.isContentEditable) { finish(false); return; }
1901
+ filling = true;
1902
+ verifyAndRetryFill(2).then(function(ok) { finish(ok); });
1903
+ }, timeoutMs);
1904
+ fallbackInterval = setInterval(onChange, 40);
1905
+ if (typeof MutationObserver !== "undefined") {
1906
+ var root = document.documentElement || document.body || document;
1907
+ if (root) {
1908
+ observer = new MutationObserver(onChange);
1909
+ observer.observe(root, { childList: true, subtree: true, attributes: true, characterData: true });
1910
+ }
1911
+ }
1912
+ });
1913
+ }
1914
+
1915
+ window.__spanaRt = {
1916
+ query: query,
1917
+ scrollIntoView: scrollIntoView,
1918
+ tap: tap,
1919
+ waitForSelector: waitForSelector,
1920
+ waitForHidden: waitForHidden,
1921
+ waitForMatch: waitForMatch,
1922
+ fill: fill
1923
+ };
1924
+ return true;
1925
+ })();`;
1926
+ function buildDomActionabilityDiagScript(selector) {
1927
+ const serialized = JSON.stringify(serializeSelectorForDom(selector));
1928
+ return `(function(sel) {
1929
+ ${SHARED_DOM_TRAVERSAL_HELPERS}
1930
+ var hits = findAcrossRoots(sel);
1931
+ if (hits.length === 0) return { found: false };
1932
+ var target = hits[hits.length - 1];
1933
+ var m = toMatch(target);
1934
+ if (!m.visible) return { found: true, visible: false, enabled: m.enabled };
1935
+ if (!m.enabled) return { found: true, visible: true, enabled: false };
1936
+ var blocker = getHitTestBlocker(target);
1937
+ return { found: true, visible: true, enabled: true, obstructedBy: blocker || undefined };
1938
+ })(${serialized})`;
1939
+ }
1940
+ function buildDomFindElementScript(selector) {
1941
+ const serialized = JSON.stringify(serializeSelectorForDom(selector));
1942
+ return `(function(sel) {
1943
+ ${SHARED_DOM_TRAVERSAL_HELPERS}
1944
+ var hits = findAcrossRoots(sel);
1945
+ if (hits.length === 0) return null;
1946
+ return hits[hits.length - 1].el;
1947
+ })(${serialized})`;
1948
+ }
1949
+ function buildInjectedCallScript(method, ...args) {
1950
+ const serializedArgs = args.map((arg) => JSON.stringify(serializeSelectorForDom(arg))).join(",");
1951
+ return `window.__spanaRt?window.__spanaRt.${method}(${serializedArgs}):${JSON.stringify(SPANA_RUNTIME_MISSING_SENTINEL)}`;
1952
+ }
876
1953
 
877
1954
  // src/core/target-matrix.ts
878
1955
  var TARGET_CHANNEL_MATRIX = {
@@ -1197,6 +2274,26 @@ var CdpDomChannel = class {
1197
2274
  getChildSessions() {
1198
2275
  return Array.from(this.childSessions.values());
1199
2276
  }
2277
+ useInjectedRuntime = false;
2278
+ enableInjectedRuntime(enabled = true) {
2279
+ this.useInjectedRuntime = enabled;
2280
+ }
2281
+ async invokeDom(sessionId, method, args, fallbackScript, timeoutMs) {
2282
+ if (!this.useInjectedRuntime) {
2283
+ return this.evaluateOnSessionWithTimeout(sessionId, fallbackScript(), timeoutMs);
2284
+ }
2285
+ const callExpr = buildInjectedCallScript(method, ...args);
2286
+ const res = await this.evaluateOnSessionWithTimeout(
2287
+ sessionId,
2288
+ callExpr,
2289
+ timeoutMs
2290
+ );
2291
+ if (res !== SPANA_RUNTIME_MISSING_SENTINEL) {
2292
+ return res;
2293
+ }
2294
+ await this.evaluateOnSessionWithTimeout(sessionId, SPANA_INJECTED_RUNTIME_SCRIPT, timeoutMs);
2295
+ return this.evaluateOnSessionWithTimeout(sessionId, callExpr, timeoutMs);
2296
+ }
1200
2297
  setFrameOffsetResolver(resolver) {
1201
2298
  this.frameOffsetResolver = resolver;
1202
2299
  }
@@ -1225,18 +2322,19 @@ var CdpDomChannel = class {
1225
2322
  });
1226
2323
  });
1227
2324
  }
1228
- async sendCommand(method, params = {}, sessionId) {
2325
+ async sendCommand(method, params = {}, sessionId, timeoutMs) {
1229
2326
  if (!this.isConnected()) {
1230
2327
  await this.connect();
1231
2328
  }
1232
2329
  const ws = this.ws;
1233
2330
  const id = this.nextId++;
1234
2331
  const resolvedSessionId = sessionId === void 0 ? this.activeSessionId : sessionId;
2332
+ const effectiveTimeout = timeoutMs ?? this.timeoutMs;
1235
2333
  return new Promise((resolve, reject) => {
1236
2334
  const timer = setTimeout(() => {
1237
2335
  this.pending.delete(id);
1238
- reject(new Error(`CDP command "${method}" timed out after ${this.timeoutMs}ms`));
1239
- }, this.timeoutMs);
2336
+ reject(new Error(`CDP command "${method}" timed out after ${effectiveTimeout}ms`));
2337
+ }, effectiveTimeout);
1240
2338
  this.pending.set(id, { resolve, reject, timer });
1241
2339
  const payload = { id, method, params };
1242
2340
  if (resolvedSessionId) {
@@ -1245,7 +2343,7 @@ var CdpDomChannel = class {
1245
2343
  ws.send(JSON.stringify(payload));
1246
2344
  });
1247
2345
  }
1248
- async evaluateOnSession(sessionId, script, ...args) {
2346
+ async evaluateOnSessionWithTimeout(sessionId, script, timeoutMs, args = []) {
1249
2347
  const expression = buildEvaluateExpression(script, args);
1250
2348
  const response = await this.sendCommand(
1251
2349
  "Runtime.evaluate",
@@ -1254,7 +2352,8 @@ var CdpDomChannel = class {
1254
2352
  returnByValue: true,
1255
2353
  awaitPromise: true
1256
2354
  },
1257
- sessionId
2355
+ sessionId,
2356
+ timeoutMs
1258
2357
  );
1259
2358
  if (response?.exceptionDetails) {
1260
2359
  const detail = response.exceptionDetails.exception?.description ?? response.exceptionDetails.text ?? "Evaluation threw an exception";
@@ -1267,6 +2366,9 @@ var CdpDomChannel = class {
1267
2366
  }
1268
2367
  return response?.result?.value;
1269
2368
  }
2369
+ async evaluateOnSession(sessionId, script, ...args) {
2370
+ return this.evaluateOnSessionWithTimeout(sessionId, script, void 0, args);
2371
+ }
1270
2372
  async evaluate(script, ...args) {
1271
2373
  return this.evaluateOnSession(void 0, script, ...args);
1272
2374
  }
@@ -1283,14 +2385,21 @@ var CdpDomChannel = class {
1283
2385
  }));
1284
2386
  }
1285
2387
  async query(selector) {
1286
- const script = buildDomQueryScript(selector);
1287
- const result = await this.evaluate(script);
2388
+ const fallback = () => buildDomQueryScript(selector);
2389
+ const result = await this.invokeDom(
2390
+ void 0,
2391
+ "query",
2392
+ [selector],
2393
+ fallback
2394
+ );
1288
2395
  if (Array.isArray(result) && result.length > 0) return result;
1289
2396
  if (this.childSessions.size === 0) return [];
1290
2397
  for (const child of this.childSessions.values()) {
1291
- const childRes = await this.evaluateOnSession(
2398
+ const childRes = await this.invokeDom(
1292
2399
  child.sessionId,
1293
- script
2400
+ "query",
2401
+ [selector],
2402
+ fallback
1294
2403
  ).catch(() => []);
1295
2404
  if (Array.isArray(childRes) && childRes.length > 0) {
1296
2405
  return this.applyChildOffset(childRes, child);
@@ -1299,22 +2408,37 @@ var CdpDomChannel = class {
1299
2408
  return [];
1300
2409
  }
1301
2410
  async waitForSelector(selector, opts) {
2411
+ const rpcTimeout = Math.max((opts?.timeoutMs ?? 5e3) + 5e3, this.timeoutMs);
2412
+ const fallback = () => buildDomWaitForSelectorScript(selector, opts);
1302
2413
  if (this.childSessions.size === 0) {
1303
- const result = await this.evaluate(
1304
- buildDomWaitForSelectorScript(selector, opts)
2414
+ const result = await this.invokeDom(
2415
+ void 0,
2416
+ "waitForSelector",
2417
+ [selector, opts ?? {}],
2418
+ fallback,
2419
+ rpcTimeout
1305
2420
  );
1306
2421
  return Array.isArray(result) ? result : [];
1307
2422
  }
1308
2423
  const immediate = await this.query(selector);
1309
2424
  const filtered = immediate.filter((m) => m.visible && (!opts?.forAction || m.enabled));
1310
2425
  if (filtered.length > 0 && !opts?.forAction) return filtered;
1311
- const script = buildDomWaitForSelectorScript(selector, opts);
1312
2426
  const racers = [
1313
- this.evaluate(script).catch(() => []),
2427
+ this.invokeDom(
2428
+ void 0,
2429
+ "waitForSelector",
2430
+ [selector, opts ?? {}],
2431
+ fallback,
2432
+ rpcTimeout
2433
+ ).catch(() => []),
1314
2434
  ...Array.from(this.childSessions.values()).map(async (child) => {
1315
- const res = await this.evaluateOnSession(child.sessionId, script).catch(
1316
- () => []
1317
- );
2435
+ const res = await this.invokeDom(
2436
+ child.sessionId,
2437
+ "waitForSelector",
2438
+ [selector, opts ?? {}],
2439
+ fallback,
2440
+ rpcTimeout
2441
+ ).catch(() => []);
1318
2442
  return Array.isArray(res) && res.length > 0 ? this.applyChildOffset(res, child) : [];
1319
2443
  })
1320
2444
  ];
@@ -1339,26 +2463,51 @@ var CdpDomChannel = class {
1339
2463
  });
1340
2464
  }
1341
2465
  async waitForHidden(selector, opts) {
1342
- const script = buildDomWaitForHiddenScript(selector, opts);
1343
- const mainHidden = Boolean(await this.evaluate(script));
2466
+ const rpcTimeout = Math.max((opts?.timeoutMs ?? 5e3) + 5e3, this.timeoutMs);
2467
+ const fallback = () => buildDomWaitForHiddenScript(selector, opts);
2468
+ const mainHidden = Boolean(
2469
+ await this.invokeDom(
2470
+ void 0,
2471
+ "waitForHidden",
2472
+ [selector, opts ?? {}],
2473
+ fallback,
2474
+ rpcTimeout
2475
+ )
2476
+ );
1344
2477
  if (!mainHidden || this.childSessions.size === 0) return mainHidden;
1345
2478
  for (const child of this.childSessions.values()) {
1346
2479
  const ok = Boolean(
1347
- await this.evaluateOnSession(child.sessionId, script).catch(() => true)
2480
+ await this.invokeDom(
2481
+ child.sessionId,
2482
+ "waitForHidden",
2483
+ [selector, opts ?? {}],
2484
+ fallback,
2485
+ rpcTimeout
2486
+ ).catch(() => true)
1348
2487
  );
1349
2488
  if (!ok) return false;
1350
2489
  }
1351
2490
  return true;
1352
2491
  }
1353
2492
  async waitForMatch(selector, opts) {
1354
- const script = buildDomWaitForMatchScript(selector, opts);
1355
- const result = await this.evaluate(script);
2493
+ const rpcTimeout = Math.max((opts?.timeoutMs ?? 5e3) + 5e3, this.timeoutMs);
2494
+ const fallback = () => buildDomWaitForMatchScript(selector, opts);
2495
+ const result = await this.invokeDom(
2496
+ void 0,
2497
+ "waitForMatch",
2498
+ [selector, opts],
2499
+ fallback,
2500
+ rpcTimeout
2501
+ );
1356
2502
  if (result && typeof result === "object" && result.matched) return result;
1357
2503
  if (this.childSessions.size > 0) {
1358
2504
  for (const child of this.childSessions.values()) {
1359
- const childRes = await this.evaluateOnSession(
2505
+ const childRes = await this.invokeDom(
1360
2506
  child.sessionId,
1361
- script
2507
+ "waitForMatch",
2508
+ [selector, opts],
2509
+ fallback,
2510
+ rpcTimeout
1362
2511
  ).catch(() => ({ matched: false }));
1363
2512
  if (childRes?.matched) return childRes;
1364
2513
  }
@@ -1366,38 +2515,64 @@ var CdpDomChannel = class {
1366
2515
  return result && typeof result === "object" ? result : { matched: false };
1367
2516
  }
1368
2517
  async fillDom(selector, value, opts) {
1369
- const script = buildDomFillScript(selector, value, opts);
1370
- const mainFilled = Boolean(await this.evaluate(script));
2518
+ const rpcTimeout = Math.max((opts?.timeoutMs ?? 5e3) + 5e3, this.timeoutMs);
2519
+ const fallback = () => buildDomFillScript(selector, value, opts);
2520
+ const mainFilled = Boolean(
2521
+ await this.invokeDom(
2522
+ void 0,
2523
+ "fill",
2524
+ [selector, value, opts ?? {}],
2525
+ fallback,
2526
+ rpcTimeout
2527
+ )
2528
+ );
1371
2529
  if (mainFilled || this.childSessions.size === 0) return mainFilled;
1372
2530
  for (const child of this.childSessions.values()) {
1373
2531
  const ok = Boolean(
1374
- await this.evaluateOnSession(child.sessionId, script).catch(() => false)
2532
+ await this.invokeDom(
2533
+ child.sessionId,
2534
+ "fill",
2535
+ [selector, value, opts ?? {}],
2536
+ fallback,
2537
+ rpcTimeout
2538
+ ).catch(() => false)
1375
2539
  );
1376
2540
  if (ok) return true;
1377
2541
  }
1378
2542
  return false;
1379
2543
  }
1380
2544
  async tapDom(selector) {
1381
- const script = buildDomTapScript(selector);
1382
- const mainTapped = Boolean(await this.evaluate(script));
2545
+ const fallback = () => buildDomTapScript(selector);
2546
+ const mainTapped = Boolean(
2547
+ await this.invokeDom(void 0, "tap", [selector], fallback)
2548
+ );
1383
2549
  if (mainTapped || this.childSessions.size === 0) return mainTapped;
1384
2550
  for (const child of this.childSessions.values()) {
1385
2551
  const ok = Boolean(
1386
- await this.evaluateOnSession(child.sessionId, script).catch(() => false)
2552
+ await this.invokeDom(child.sessionId, "tap", [selector], fallback).catch(
2553
+ () => false
2554
+ )
1387
2555
  );
1388
2556
  if (ok) return true;
1389
2557
  }
1390
2558
  return false;
1391
2559
  }
1392
2560
  async scrollIntoView(selector) {
1393
- const script = buildDomScrollIntoViewScript(selector);
1394
- const result = await this.evaluate(script);
2561
+ const fallback = () => buildDomScrollIntoViewScript(selector);
2562
+ const result = await this.invokeDom(
2563
+ void 0,
2564
+ "scrollIntoView",
2565
+ [selector],
2566
+ fallback
2567
+ );
1395
2568
  if (result) return result;
1396
2569
  if (this.childSessions.size > 0) {
1397
2570
  for (const child of this.childSessions.values()) {
1398
- const childRes = await this.evaluateOnSession(
2571
+ const childRes = await this.invokeDom(
1399
2572
  child.sessionId,
1400
- script
2573
+ "scrollIntoView",
2574
+ [selector],
2575
+ fallback
1401
2576
  ).catch(() => null);
1402
2577
  if (childRes) {
1403
2578
  const adjusted = await this.applyChildOffset([childRes], child);
@@ -1432,7 +2607,7 @@ function createCdpDomChannel(options) {
1432
2607
  }
1433
2608
 
1434
2609
  // src/channels/android-cdp.ts
1435
- import { execSync } from "child_process";
2610
+ import { execFileSync } from "child_process";
1436
2611
  function parseAndroidWebViewSockets(procNetUnixOutput) {
1437
2612
  const seen = /* @__PURE__ */ new Set();
1438
2613
  const sockets = [];
@@ -1481,13 +2656,13 @@ var AndroidWebViewCdpChannel = class {
1481
2656
  }
1482
2657
  execAdb(args) {
1483
2658
  if (this.options.runAdb) {
1484
- return this.options.runAdb(args);
2659
+ return this.options.runAdb(args.join(" "));
1485
2660
  }
1486
2661
  const adb = findADB();
1487
2662
  if (!adb) {
1488
2663
  throw new Error("adb not found on PATH or ANDROID_HOME");
1489
2664
  }
1490
- return execSync(`${adb} ${args}`, { encoding: "utf-8" });
2665
+ return execFileSync(adb, args, { encoding: "utf-8" });
1491
2666
  }
1492
2667
  isConnected() {
1493
2668
  return this.cdp?.isConnected() ?? false;
@@ -1521,7 +2696,13 @@ var AndroidWebViewCdpChannel = class {
1521
2696
  this.forwardedPort = port;
1522
2697
  this.activeSocketName = socketName;
1523
2698
  try {
1524
- this.execAdb(`-s ${this.options.serial} forward tcp:${port} localabstract:${socketName}`);
2699
+ this.execAdb([
2700
+ "-s",
2701
+ this.options.serial,
2702
+ "forward",
2703
+ `tcp:${port}`,
2704
+ `localabstract:${socketName}`
2705
+ ]);
1525
2706
  this.cdp = new CdpDomChannel({
1526
2707
  endpointUrl: `http://127.0.0.1:${port}`,
1527
2708
  timeoutMs: this.options.timeoutMs,
@@ -1585,7 +2766,7 @@ var AndroidWebViewCdpChannel = class {
1585
2766
  const port = this.forwardedPort;
1586
2767
  this.forwardedPort = null;
1587
2768
  try {
1588
- this.execAdb(`-s ${this.options.serial} forward --remove tcp:${port}`);
2769
+ this.execAdb(["-s", this.options.serial, "forward", "--remove", `tcp:${port}`]);
1589
2770
  } catch {
1590
2771
  }
1591
2772
  if (this.allocatedByUs) {
@@ -1601,7 +2782,7 @@ function createAndroidWebViewCdpChannel(options) {
1601
2782
  }
1602
2783
 
1603
2784
  // src/channels/apple-webinspector.ts
1604
- import { execSync as execSync2 } from "child_process";
2785
+ import { execSync } from "child_process";
1605
2786
  import { randomUUID } from "crypto";
1606
2787
  import { existsSync, readdirSync } from "fs";
1607
2788
  import { createConnection } from "net";
@@ -1706,7 +2887,7 @@ function findSimulatorWebInspectorSocket(udid) {
1706
2887
  if (existsSync(envSock)) return envSock;
1707
2888
  }
1708
2889
  try {
1709
- const out = execSync2("launchctl getenv SIMULATOR_WEBINSPECTOR_SOCKET 2>/dev/null || true", {
2890
+ const out = execSync("launchctl getenv SIMULATOR_WEBINSPECTOR_SOCKET 2>/dev/null || true", {
1710
2891
  encoding: "utf-8",
1711
2892
  timeout: 2e3
1712
2893
  }).trim();
@@ -1897,7 +3078,7 @@ var AppleWebInspectorClient = class {
1897
3078
  };
1898
3079
 
1899
3080
  // src/channels/webkit-inspector.ts
1900
- import { execSync as execSync3, spawn } from "child_process";
3081
+ import { execSync as execSync2, spawn } from "child_process";
1901
3082
  var WS_OPEN2 = 1;
1902
3083
  function defaultWebSocketFactory2(url) {
1903
3084
  return new WebSocket(url);
@@ -1938,7 +3119,7 @@ function selectWebKitTarget(targets, bundleId) {
1938
3119
  }
1939
3120
  function isWebKitDebugProxyInstalled() {
1940
3121
  try {
1941
- execSync3("which ios_webkit_debug_proxy", { stdio: "ignore" });
3122
+ execSync2("which ios_webkit_debug_proxy", { stdio: "ignore" });
1942
3123
  return true;
1943
3124
  } catch {
1944
3125
  return false;
@@ -3151,6 +4332,10 @@ export {
3151
4332
  buildDomWaitForHiddenScript,
3152
4333
  buildDomWaitForMatchScript,
3153
4334
  buildDomFillScript,
4335
+ SPANA_INJECTED_RUNTIME_SCRIPT,
4336
+ buildDomActionabilityDiagScript,
4337
+ buildDomFindElementScript,
4338
+ buildInjectedCallScript,
3154
4339
  TARGET_CHANNEL_MATRIX,
3155
4340
  resolveElectrobunEngine,
3156
4341
  resolveTargetDescriptor,
@@ -3175,4 +4360,4 @@ export {
3175
4360
  resolveElectrobunLaunchPlan,
3176
4361
  makeElectrobunDriver
3177
4362
  };
3178
- //# sourceMappingURL=chunk-T3EBOYLS.js.map
4363
+ //# sourceMappingURL=chunk-UEWZ2EXL.js.map