@buoy-gg/highlight-updates 7.0.40 → 7.0.42

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 (110) hide show
  1. package/README.md +11 -67
  2. package/lib/commonjs/highlight-updates/HighlightUpdatesOverlay.js +1 -281
  3. package/lib/commonjs/highlight-updates/components/HighlightFilterView.js +1 -1474
  4. package/lib/commonjs/highlight-updates/components/HighlightUpdatesModal.js +1 -641
  5. package/lib/commonjs/highlight-updates/components/IdentifierBadge.js +1 -273
  6. package/lib/commonjs/highlight-updates/components/IsolatedRenderList.js +1 -188
  7. package/lib/commonjs/highlight-updates/components/ModalHeaderContent.js +1 -293
  8. package/lib/commonjs/highlight-updates/components/RenderCauseBadge.js +1 -508
  9. package/lib/commonjs/highlight-updates/components/RenderDetailView.js +1 -846
  10. package/lib/commonjs/highlight-updates/components/RenderHistoryViewer.js +1 -915
  11. package/lib/commonjs/highlight-updates/components/RenderListItem.js +1 -235
  12. package/lib/commonjs/highlight-updates/components/RendersCopySettingsView.js +1 -469
  13. package/lib/commonjs/highlight-updates/components/StatsDisplay.js +1 -73
  14. package/lib/commonjs/highlight-updates/types/copySettings.js +1 -107
  15. package/lib/commonjs/highlight-updates/utils/CommitProfiler.js +1 -446
  16. package/lib/commonjs/highlight-updates/utils/HighlightUpdatesController.js +1 -1920
  17. package/lib/commonjs/highlight-updates/utils/PerformanceLogger.js +26 -359
  18. package/lib/commonjs/highlight-updates/utils/ProfilerInterceptor.js +1 -371
  19. package/lib/commonjs/highlight-updates/utils/RenderCauseDetector.js +5 -1840
  20. package/lib/commonjs/highlight-updates/utils/RenderTracker.js +1 -952
  21. package/lib/commonjs/highlight-updates/utils/ViewTypeMapper.js +1 -264
  22. package/lib/commonjs/highlight-updates/utils/copySettingsStorage.js +1 -32
  23. package/lib/commonjs/highlight-updates/utils/devtoolsComponentNames.js +1 -188
  24. package/lib/commonjs/highlight-updates/utils/namedComposite.js +1 -41
  25. package/lib/commonjs/highlight-updates/utils/ownStateChanged.js +1 -103
  26. package/lib/commonjs/highlight-updates/utils/rawEventEmitter.js +1 -50
  27. package/lib/commonjs/highlight-updates/utils/rawEventEmitter.web.js +1 -0
  28. package/lib/commonjs/highlight-updates/utils/renderExportFormatter.js +1 -58
  29. package/lib/commonjs/highlight-updates/utils/rendersExportFormatter.js +1 -485
  30. package/lib/commonjs/highlight-updates/utils/screenElements.js +1 -1248
  31. package/lib/commonjs/highlight-updates/utils/tapMatch.js +1 -83
  32. package/lib/commonjs/highlight-updates/utils/testIDs.js +1 -68
  33. package/lib/commonjs/highlight-updates/utils/touchCapture.js +1 -277
  34. package/lib/commonjs/index.js +1 -429
  35. package/lib/commonjs/preset.js +1 -278
  36. package/lib/commonjs/sync/highlightUpdatesSyncAdapter.js +1 -235
  37. package/lib/module/highlight-updates/HighlightUpdatesOverlay.js +1 -274
  38. package/lib/module/highlight-updates/components/HighlightFilterView.js +1 -1468
  39. package/lib/module/highlight-updates/components/HighlightUpdatesModal.js +1 -634
  40. package/lib/module/highlight-updates/components/IdentifierBadge.js +1 -265
  41. package/lib/module/highlight-updates/components/IsolatedRenderList.js +1 -183
  42. package/lib/module/highlight-updates/components/ModalHeaderContent.js +1 -288
  43. package/lib/module/highlight-updates/components/RenderCauseBadge.js +1 -499
  44. package/lib/module/highlight-updates/components/RenderDetailView.js +1 -840
  45. package/lib/module/highlight-updates/components/RenderHistoryViewer.js +1 -908
  46. package/lib/module/highlight-updates/components/RenderListItem.js +1 -230
  47. package/lib/module/highlight-updates/components/RendersCopySettingsView.js +1 -465
  48. package/lib/module/highlight-updates/components/StatsDisplay.js +1 -70
  49. package/lib/module/highlight-updates/types/copySettings.js +1 -102
  50. package/lib/module/highlight-updates/utils/CommitProfiler.js +1 -442
  51. package/lib/module/highlight-updates/utils/HighlightUpdatesController.js +1 -1916
  52. package/lib/module/highlight-updates/utils/PerformanceLogger.js +26 -353
  53. package/lib/module/highlight-updates/utils/ProfilerInterceptor.js +1 -358
  54. package/lib/module/highlight-updates/utils/RenderCauseDetector.js +5 -1830
  55. package/lib/module/highlight-updates/utils/RenderTracker.js +1 -949
  56. package/lib/module/highlight-updates/utils/ViewTypeMapper.js +1 -255
  57. package/lib/module/highlight-updates/utils/copySettingsStorage.js +1 -26
  58. package/lib/module/highlight-updates/utils/devtoolsComponentNames.js +1 -178
  59. package/lib/module/highlight-updates/utils/namedComposite.js +1 -36
  60. package/lib/module/highlight-updates/utils/ownStateChanged.js +1 -98
  61. package/lib/module/highlight-updates/utils/rawEventEmitter.js +1 -46
  62. package/lib/module/highlight-updates/utils/rawEventEmitter.web.js +1 -0
  63. package/lib/module/highlight-updates/utils/renderExportFormatter.js +1 -54
  64. package/lib/module/highlight-updates/utils/rendersExportFormatter.js +1 -478
  65. package/lib/module/highlight-updates/utils/screenElements.js +1 -1242
  66. package/lib/module/highlight-updates/utils/tapMatch.js +1 -76
  67. package/lib/module/highlight-updates/utils/testIDs.js +1 -60
  68. package/lib/module/highlight-updates/utils/touchCapture.js +1 -270
  69. package/lib/module/index.js +1 -130
  70. package/lib/module/preset.js +1 -272
  71. package/lib/module/sync/highlightUpdatesSyncAdapter.js +1 -230
  72. package/lib/typescript/highlight-updates/utils/HighlightUpdatesController.d.ts +0 -26
  73. package/lib/typescript/highlight-updates/utils/rawEventEmitter.web.d.ts +3 -0
  74. package/lib/typescript/highlight-updates/utils/screenElements.d.ts +0 -19
  75. package/lib/web/index.mjs +38 -0
  76. package/package.json +34 -14
  77. package/lib/typescript/highlight-updates/HighlightUpdatesOverlay.d.ts.map +0 -1
  78. package/lib/typescript/highlight-updates/components/HighlightFilterView.d.ts.map +0 -1
  79. package/lib/typescript/highlight-updates/components/HighlightUpdatesModal.d.ts.map +0 -1
  80. package/lib/typescript/highlight-updates/components/IdentifierBadge.d.ts.map +0 -1
  81. package/lib/typescript/highlight-updates/components/IsolatedRenderList.d.ts.map +0 -1
  82. package/lib/typescript/highlight-updates/components/ModalHeaderContent.d.ts.map +0 -1
  83. package/lib/typescript/highlight-updates/components/RenderCauseBadge.d.ts.map +0 -1
  84. package/lib/typescript/highlight-updates/components/RenderDetailView.d.ts.map +0 -1
  85. package/lib/typescript/highlight-updates/components/RenderHistoryViewer.d.ts.map +0 -1
  86. package/lib/typescript/highlight-updates/components/RenderListItem.d.ts.map +0 -1
  87. package/lib/typescript/highlight-updates/components/RendersCopySettingsView.d.ts.map +0 -1
  88. package/lib/typescript/highlight-updates/components/StatsDisplay.d.ts.map +0 -1
  89. package/lib/typescript/highlight-updates/types/copySettings.d.ts.map +0 -1
  90. package/lib/typescript/highlight-updates/utils/CommitProfiler.d.ts.map +0 -1
  91. package/lib/typescript/highlight-updates/utils/HighlightUpdatesController.d.ts.map +0 -1
  92. package/lib/typescript/highlight-updates/utils/PerformanceLogger.d.ts.map +0 -1
  93. package/lib/typescript/highlight-updates/utils/ProfilerInterceptor.d.ts.map +0 -1
  94. package/lib/typescript/highlight-updates/utils/RenderCauseDetector.d.ts.map +0 -1
  95. package/lib/typescript/highlight-updates/utils/RenderTracker.d.ts.map +0 -1
  96. package/lib/typescript/highlight-updates/utils/ViewTypeMapper.d.ts.map +0 -1
  97. package/lib/typescript/highlight-updates/utils/copySettingsStorage.d.ts.map +0 -1
  98. package/lib/typescript/highlight-updates/utils/devtoolsComponentNames.d.ts.map +0 -1
  99. package/lib/typescript/highlight-updates/utils/namedComposite.d.ts.map +0 -1
  100. package/lib/typescript/highlight-updates/utils/ownStateChanged.d.ts.map +0 -1
  101. package/lib/typescript/highlight-updates/utils/rawEventEmitter.d.ts.map +0 -1
  102. package/lib/typescript/highlight-updates/utils/renderExportFormatter.d.ts.map +0 -1
  103. package/lib/typescript/highlight-updates/utils/rendersExportFormatter.d.ts.map +0 -1
  104. package/lib/typescript/highlight-updates/utils/screenElements.d.ts.map +0 -1
  105. package/lib/typescript/highlight-updates/utils/tapMatch.d.ts.map +0 -1
  106. package/lib/typescript/highlight-updates/utils/testIDs.d.ts.map +0 -1
  107. package/lib/typescript/highlight-updates/utils/touchCapture.d.ts.map +0 -1
  108. package/lib/typescript/index.d.ts.map +0 -1
  109. package/lib/typescript/preset.d.ts.map +0 -1
  110. package/lib/typescript/sync/highlightUpdatesSyncAdapter.d.ts.map +0 -1
@@ -1,1242 +1 @@
1
- "use strict";
2
-
3
- /**
4
- * On-device screen element discovery + in-JS tap.
5
- *
6
- * This powers the MCP "describe_screen" / "tap_element" tools. It walks the
7
- * live React fiber tree (all renderers), collects the meaningful / interactive
8
- * elements on the current screen, and measures each one's on-screen rect — the
9
- * same idea as the desktop screenshot tool's component-locate, but producing a
10
- * whole-screen list with normalized tap coordinates instead of a single crop.
11
- *
12
- * Tapping is done PURELY in JS: we resolve the target element, find the nearest
13
- * `onPress` handler up its fiber chain, and invoke it with a synthetic press
14
- * event. No screenshots, no OS-level touch injection, and it works on physical
15
- * devices — because Buoy runs INSIDE the app (unlike external simulator drivers
16
- * that have to inject an OS touch at a pixel coordinate).
17
- *
18
- * Fiber traversal is adapted from image-overlay/utils/fiberScanner.ts and
19
- * debug-borders/utils/fiberTreeTraversal.js; the fiber-access triad matches the
20
- * rest of highlight-updates (Fabric / Paper / RN-CLI-dev).
21
- */
22
-
23
- import { Dimensions, UIManager, findNodeHandle } from "react-native";
24
- import { isRectCenterOnScreen, scoreTapMatch } from "./tapMatch";
25
-
26
- /* eslint-disable @typescript-eslint/no-explicit-any */
27
-
28
- // --- React fiber tag / renderer plumbing ---------------------------------
29
-
30
- const HostComponent = 5;
31
- const OffscreenComponent = 22;
32
-
33
- // Component names that are pure infrastructure and never worth listing on
34
- // their own. Kept small on purpose — a candidate still needs a real signal
35
- // (onPress / testID / label / text / role) to be emitted, so this only
36
- // suppresses the *name* of wrappers that happen to also carry one.
37
- const INTERNAL_NAMES = new Set(["View", "RCTView", "ScrollView", "RCTScrollView", "RCTScrollContentView", "SafeAreaView", "RCTSafeAreaView", "AndroidHorizontalScrollContentView", "KeyboardAvoidingView", "Pressable", "PlatformPressable", "TouchableOpacity", "TouchableHighlight", "TouchableWithoutFeedback", "TouchableNativeFeedback", "AnimatedComponent", "Wrapper"]);
38
- function getReactDevToolsHook() {
39
- if (typeof global === "undefined") return null;
40
- return global.__REACT_DEVTOOLS_GLOBAL_HOOK__ ?? null;
41
- }
42
-
43
- /**
44
- * React commits observed since this counter was installed.
45
- *
46
- * `tapElement` reads it either side of firing a handler to say whether
47
- * ANYTHING re-rendered afterwards. Without that a tap that matched a button
48
- * on the screen BENEATH the current one (a stack keeps it mounted) came back
49
- * `tapped:true` — the handler really did run — and an agent then built its
50
- * next three turns on a sign-in that never happened. Zero commits inside the
51
- * settle window is the honest signal: the handler ran and the app did nothing
52
- * visible with it.
53
- *
54
- * Installed once and chained, the same way CommitProfiler wraps the hook;
55
- * counting is the only work it does on the commit path.
56
- */
57
- let commitCount = 0;
58
- let commitCounterInstalled = false;
59
- function ensureCommitCounter() {
60
- if (commitCounterInstalled) return;
61
- const hook = getReactDevToolsHook();
62
- if (!hook) return;
63
- const original = hook.onCommitFiberRoot;
64
- hook.onCommitFiberRoot = function (...args) {
65
- commitCount++;
66
- return typeof original === "function" ? original.apply(hook, args) : undefined;
67
- };
68
- commitCounterInstalled = true;
69
- }
70
-
71
- /** How long a tap waits to see the app react before reporting. */
72
- const TAP_SETTLE_MS = 250;
73
-
74
- /**
75
- * Per-walk memo of "is this fiber under Buoy's own overlay". Every candidate
76
- * asks, and they share ancestors, so the answer is cached along the path
77
- * walked rather than recomputed 400 levels deep per row.
78
- */
79
- function makeChromeCheck() {
80
- const memo = new Map();
81
- return fiber => {
82
- const path = [];
83
- let cur = fiber;
84
- let depth = 0;
85
- let inChrome = false;
86
- while (cur && depth < 400) {
87
- const known = memo.get(cur);
88
- if (known !== undefined) {
89
- inChrome = known;
90
- break;
91
- }
92
- if (getProps(cur)?.__buoyDevToolsRoot) {
93
- inChrome = true;
94
- memo.set(cur, true);
95
- break;
96
- }
97
- path.push(cur);
98
- cur = cur.return;
99
- depth++;
100
- }
101
- for (const f of path) memo.set(f, inChrome);
102
- return inChrome;
103
- };
104
- }
105
-
106
- /**
107
- * Collect fiber roots across ALL renderers. A single renderer id is not safe
108
- * to assume: secondary reconcilers (react-native-skia, react-native-svg, …)
109
- * register their own renderer, sometimes first as id 1, whose roots contain
110
- * none of the tappable app UI.
111
- */
112
- function getAllFiberRoots() {
113
- const hook = getReactDevToolsHook();
114
- if (!hook) return [];
115
- const roots = [];
116
- try {
117
- if (hook.renderers && typeof hook.renderers.forEach === "function") {
118
- hook.renderers.forEach((_r, rendererId) => {
119
- try {
120
- const set = hook.getFiberRoots?.(rendererId);
121
- if (set) set.forEach(root => roots.push(root));
122
- } catch {
123
- /* ignore a single renderer failing */
124
- }
125
- });
126
- }
127
- if (roots.length === 0 && hook.getFiberRoots) {
128
- const legacy = hook.getFiberRoots(1);
129
- if (legacy) legacy.forEach(root => roots.push(root));
130
- }
131
- } catch {
132
- /* ignore */
133
- }
134
- return roots;
135
- }
136
- function isHiddenOffscreen(fiber) {
137
- return fiber.tag === OffscreenComponent && fiber.memoizedState !== null;
138
- }
139
- function isInactiveScreen(fiber) {
140
- // react-native-screens: activityState 0/1 = inactive/transitioning.
141
- const as = fiber.memoizedProps?.activityState;
142
- if (as === 0 || as === 1) return true;
143
- // pagers
144
- if (fiber.memoizedProps?.isPageFocused === false) return true;
145
- return false;
146
- }
147
- function traverseFiberTree(fiber, callback, depth = 0, visited = new Set()) {
148
- if (!fiber || visited.has(fiber) || depth > 500) return;
149
- visited.add(fiber);
150
- if (isHiddenOffscreen(fiber) || isInactiveScreen(fiber)) {
151
- // Prune the whole subtree, but keep walking siblings.
152
- if (fiber.sibling) traverseFiberTree(fiber.sibling, callback, depth, visited);
153
- return;
154
- }
155
- callback(fiber);
156
- if (fiber.child) traverseFiberTree(fiber.child, callback, depth + 1, visited);
157
- if (fiber.sibling) traverseFiberTree(fiber.sibling, callback, depth, visited);
158
- }
159
-
160
- // --- Fiber → host instance / name / props --------------------------------
161
-
162
- /** Get a measurable public instance from a host fiber's stateNode. */
163
- function getPublicInstance(stateNode) {
164
- if (!stateNode) return null;
165
- const node = stateNode;
166
- if (node.canonical?.publicInstance) return node.canonical.publicInstance;
167
- if (node.canonical && typeof node.canonical.measure === "function") {
168
- return node.canonical;
169
- }
170
- if (typeof node.measure === "function" || typeof node.measureInWindow === "function") {
171
- return node;
172
- }
173
- return null;
174
- }
175
- function getNativeTag(stateNode) {
176
- if (stateNode == null) return null;
177
- const n = stateNode;
178
- if (typeof n.__nativeTag === "number") return n.__nativeTag;
179
- if (typeof n._nativeTag === "number") return n._nativeTag;
180
- if (typeof n.nativeTag === "number") return n.nativeTag;
181
- if (n.canonical) {
182
- if (typeof n.canonical.__nativeTag === "number") return n.canonical.__nativeTag;
183
- if (typeof n.canonical._nativeTag === "number") return n.canonical._nativeTag;
184
- if (typeof n.canonical.nativeTag === "number") return n.canonical.nativeTag;
185
- }
186
- return null;
187
- }
188
-
189
- /** The first host node in a fiber's own subtree (self first, then descendants). */
190
- function findHostInstance(fiber) {
191
- const selfInst = getPublicInstance(fiber.stateNode);
192
- if (selfInst) {
193
- return {
194
- instance: selfInst,
195
- nativeTag: getNativeTag(fiber.stateNode),
196
- stateNode: fiber.stateNode
197
- };
198
- }
199
-
200
- // DFS restricted to this fiber's subtree (child + siblings-of-children).
201
- const stack = [];
202
- if (fiber.child) stack.push(fiber.child);
203
- let guard = 0;
204
- while (stack.length > 0 && guard < 4000) {
205
- guard++;
206
- const f = stack.pop();
207
- if (!f) continue;
208
- const inst = getPublicInstance(f.stateNode);
209
- if (inst) return {
210
- instance: inst,
211
- nativeTag: getNativeTag(f.stateNode),
212
- stateNode: f.stateNode
213
- };
214
- if (f.child) stack.push(f.child);
215
- if (f.sibling) stack.push(f.sibling);
216
- }
217
- return null;
218
- }
219
-
220
- /**
221
- * Walk up from a fiber to the nearest ScrollView-like instance (exposes
222
- * scrollTo). Mirrors HighlightUpdatesController.findScrollAncestor.
223
- */
224
- function findScrollAncestor(fiber) {
225
- let cur = fiber;
226
- let guard = 0;
227
- while (cur && guard++ < 200) {
228
- const inst = cur.stateNode;
229
- if (inst && typeof inst.scrollTo === "function") {
230
- const nativeRef = typeof inst.getNativeScrollRef === "function" && inst.getNativeScrollRef() || null;
231
- const innerNode = typeof inst.getInnerViewNode === "function" && inst.getInnerViewNode() || typeof inst.getScrollableNode === "function" && inst.getScrollableNode() || inst;
232
- return {
233
- instance: inst,
234
- nativeRef,
235
- innerNode
236
- };
237
- }
238
- cur = cur.return;
239
- }
240
- return null;
241
- }
242
-
243
- /**
244
- * Best-effort scroll of an ancestor ScrollView so the target sits near the top
245
- * of its viewport. Returns true only if a scroll was issued. Never throws.
246
- * Ported from HighlightUpdatesController.scrollDescendantIntoView.
247
- */
248
- async function scrollIntoView(targetFiber, publicInstance, stateNode, margin) {
249
- try {
250
- const ancestor = findScrollAncestor(targetFiber);
251
- if (!ancestor) return false;
252
- const inst = publicInstance;
253
- let top = null;
254
-
255
- // measureLayout can invoke NEITHER callback on some architectures — race
256
- // every call against a short timeout so the await can't hang.
257
- const withTimeout = run => new Promise(resolve => {
258
- let done = false;
259
- const settle = v => {
260
- if (done) return;
261
- done = true;
262
- resolve(v);
263
- };
264
- const timer = setTimeout(() => settle(null), 600);
265
- try {
266
- run(v => {
267
- clearTimeout(timer);
268
- settle(v);
269
- });
270
- } catch {
271
- clearTimeout(timer);
272
- settle(null);
273
- }
274
- });
275
-
276
- // Fabric: ref.measureLayout against the inner view ref.
277
- if (ancestor.nativeRef && typeof inst.measureLayout === "function") {
278
- top = await withTimeout(resolve => inst.measureLayout(ancestor.nativeRef, (_left, t) => resolve(t), () => resolve(null)));
279
- }
280
-
281
- // Legacy: UIManager.measureLayout with numeric node handles.
282
- if (top == null) {
283
- const targetHandle = findNodeHandle(publicInstance);
284
- const innerHandle = typeof ancestor.innerNode === "number" ? ancestor.innerNode : findNodeHandle(ancestor.innerNode);
285
- if (targetHandle != null && innerHandle != null) {
286
- top = await withTimeout(resolve => UIManager.measureLayout(targetHandle, innerHandle, () => resolve(null), (_left, t) => resolve(t)));
287
- }
288
- }
289
- if (top == null) return false;
290
- ancestor.instance.scrollTo({
291
- y: Math.max(0, top - margin),
292
- animated: false
293
- });
294
- await new Promise(r => setTimeout(r, 120)); // let scroll + layout settle
295
- return true;
296
- } catch {
297
- return false;
298
- }
299
- }
300
- function getComponentName(fiber) {
301
- const t = fiber?.type;
302
- if (!t) return null;
303
- if (typeof t === "string") return t;
304
- return t.displayName || t.name || null;
305
- }
306
-
307
- /** Walk up to the nearest user-defined component name (skips host/internal). */
308
- function getOwningComponentName(fiber) {
309
- let cur = fiber?._debugOwner || fiber?.return;
310
- let depth = 0;
311
- while (cur && depth < 30) {
312
- depth++;
313
- const name = getComponentName(cur);
314
- if (name && !INTERNAL_NAMES.has(name) && typeof cur.type !== "string") {
315
- return name;
316
- }
317
- cur = cur.return;
318
- }
319
- return null;
320
- }
321
- function getProps(fiber) {
322
- return fiber?.memoizedProps ?? fiber?.pendingProps ?? null;
323
- }
324
-
325
- /**
326
- * The text of a `children` value, INCLUDING one assembled from several pieces.
327
- *
328
- * `<Text>{value} {label}</Text>` compiles to `children: ["1,450", " ", "Points"]`
329
- * and `Check Back Soon{"\n"}For Available Offers` to three strings. This used
330
- * to accept a lone string or number and nothing else, so EVERY composed label
331
- * in an app was invisible to describeScreen, tapElement and waitFor — while
332
- * native accessibility, which concatenates the same children, could read them.
333
- * Measured on a live QA run: five waits failed against an empty state that was
334
- * on screen the whole time, and the agent then reported the app was missing
335
- * one; a points balance could not be found by its own number.
336
- *
337
- * Nested React ELEMENTS are not walked here — `collectDescendantText` owns
338
- * that, with its stop-at-a-nested-button rule — so this stays a leaf join, and
339
- * adjacent pieces are concatenated exactly as React renders them.
340
- */
341
- function flattenText(value, depth = 0) {
342
- if (typeof value === "string") return value;
343
- if (typeof value === "number" && Number.isFinite(value)) return String(value);
344
- if (Array.isArray(value) && depth < 4) {
345
- const parts = [];
346
- for (const child of value) {
347
- const part = flattenText(child, depth + 1);
348
- if (part) parts.push(part);
349
- }
350
- return parts.length > 0 ? parts.join("") : undefined;
351
- }
352
- return undefined;
353
- }
354
-
355
- /** What a person reads: newlines and runs of spaces collapse to one space. */
356
- function normalizeVisibleText(value) {
357
- return value.replace(/\s+/g, " ").trim();
358
- }
359
- function getVisibleText(props) {
360
- if (!props) return undefined;
361
- const pick = v => {
362
- const flat = flattenText(v);
363
- if (flat === undefined) return undefined;
364
- const text = normalizeVisibleText(flat);
365
- return text ? text.slice(0, 80) : undefined;
366
- };
367
- return pick(props.children) ?? pick(props.title) ?? pick(props.label) ?? pick(props.placeholder) ?? undefined;
368
- }
369
-
370
- /**
371
- * Gather visible text from a fiber's descendants (its own label), stopping at
372
- * nested interactive subtrees so a button doesn't absorb another button's text.
373
- * Lets an icon-button whose label is a child <Text> (e.g. a dial icon) still be
374
- * matched/shown by that label — the button host measures even when the inner
375
- * Text host doesn't.
376
- */
377
- function collectDescendantText(root, maxDepth) {
378
- const parts = [];
379
- const visit = (f, depth) => {
380
- if (!f || depth > maxDepth || parts.length >= 4) return;
381
- // Don't cross into a nested interactive element (another button's label).
382
- if (f !== root) {
383
- const p = getProps(f);
384
- if (p && (typeof p.onPress === "function" || typeof p.onLongPress === "function")) return;
385
- }
386
- const t = getVisibleText(getProps(f));
387
- if (t && !parts.includes(t)) parts.push(t);
388
- if (f.child) visit(f.child, depth + 1);
389
- if (f !== root && f.sibling) visit(f.sibling, depth); // siblings stay in subtree
390
- };
391
- if (root.child) visit(root.child, 1);
392
- const joined = parts.join(" ").trim();
393
- return joined ? joined.slice(0, 80) : undefined;
394
- }
395
-
396
- /** Nearest onPress / onLongPress handlers at or above a fiber. */
397
-
398
- function findPressHandler(fiber) {
399
- let cur = fiber;
400
- let depth = 0;
401
- let press = null;
402
- let longPress = null;
403
- while (cur && depth < 25 && !(press && longPress)) {
404
- const p = getProps(cur);
405
- if (p) {
406
- if (!press && typeof p.onPress === "function") press = p.onPress;
407
- if (!longPress && typeof p.onLongPress === "function") longPress = p.onLongPress;
408
- }
409
- cur = cur.return;
410
- depth++;
411
- }
412
- if (press) return {
413
- handler: press,
414
- kind: "onPress",
415
- longPress: longPress ?? undefined
416
- };
417
- return longPress ? {
418
- handler: longPress,
419
- kind: "onLongPress"
420
- } : null;
421
- }
422
-
423
- // --- Measurement ----------------------------------------------------------
424
-
425
- /** Absolute on-screen rect in points (or null), with a hang guard. */
426
- function measureInstance(instance) {
427
- return new Promise(resolve => {
428
- let settled = false;
429
- const done = r => {
430
- if (settled) return;
431
- settled = true;
432
- resolve(r);
433
- };
434
- // Detached / off-screen nodes can fire neither callback.
435
- setTimeout(() => done(null), 1000);
436
- try {
437
- if (typeof instance.measureInWindow === "function") {
438
- instance.measureInWindow((x, y, width, height) => {
439
- if (width > 0 && height > 0) done({
440
- x,
441
- y,
442
- width,
443
- height
444
- });else done(null);
445
- });
446
- } else if (typeof instance.measure === "function") {
447
- instance.measure((_x, _y, width, height, pageX, pageY) => {
448
- if (width > 0 && height > 0 && pageX != null && pageY != null) {
449
- done({
450
- x: pageX,
451
- y: pageY,
452
- width,
453
- height
454
- });
455
- } else {
456
- done(null);
457
- }
458
- });
459
- } else {
460
- done(null);
461
- }
462
- } catch {
463
- done(null);
464
- }
465
- });
466
- }
467
-
468
- // --- Public types ---------------------------------------------------------
469
-
470
- // Internal record carries the live fiber refs that `describeScreen`'s
471
- // serializable result drops.
472
-
473
- // --- Collection -----------------------------------------------------------
474
-
475
- function collectCandidates() {
476
- const roots = getAllFiberRoots();
477
- if (roots.length === 0) return [];
478
- const out = [];
479
- /**
480
- * De-dup indexes. Two fibers resolving to the same host node collapse to one
481
- * row — a Pressable and its inner View, but ALSO the same native view reached
482
- * twice by the walk, which produces two different `instance` objects for one
483
- * `nativeTag`. Measured on a live QA run: a 141-row screen dump held 70
484
- * distinct elements, every one listed twice, and the agent told the user
485
- * their layout had duplicate elements. Keyed both ways so either collision
486
- * collapses, and as Maps because the old `out.find(…)` was a linear scan per
487
- * candidate on a list that can run to hundreds.
488
- */
489
- const byInstance = new Map();
490
- const byTag = new Map();
491
- const inBuoyChrome = makeChromeCheck();
492
- for (const root of roots) {
493
- traverseFiberTree(root.current, fiber => {
494
- const props = getProps(fiber);
495
- if (!props) return;
496
- const hasPress = typeof props.onPress === "function" || typeof props.onLongPress === "function";
497
- const hasValue = typeof props.onValueChange === "function";
498
- const hasText = typeof props.onChangeText === "function";
499
- const testID = props.testID || undefined;
500
- const label = props.accessibilityLabel || undefined;
501
- const role = props.accessibilityRole || props.role || undefined;
502
- let text = getVisibleText(props);
503
- const roleInteractive = role === "button" || role === "link" || role === "menuitem" || role === "tab" || role === "switch" || role === "checkbox";
504
-
505
- // A fiber earns a row only if it carries a real signal.
506
- if (!hasPress && !hasValue && !hasText && !testID && !label && !text && !roleInteractive) {
507
- return;
508
- }
509
-
510
- // Resolve how this element is driven. A value/text control is a leaf
511
- // (Switch/Slider/TextInput) whose OWN handler wins over an ancestor
512
- // onPress; otherwise fall back to the nearest onPress up the tree.
513
- let press = null;
514
- let valueControl = null;
515
- let textControl = null;
516
- if (hasValue) {
517
- const current = props.value;
518
- const numeric = typeof current === "number" || typeof props.minimumValue === "number";
519
- valueControl = {
520
- handler: props.onValueChange,
521
- kind: numeric ? "slider" : "toggle",
522
- current,
523
- min: typeof props.minimumValue === "number" ? props.minimumValue : undefined,
524
- max: typeof props.maximumValue === "number" ? props.maximumValue : undefined
525
- };
526
- } else if (hasText) {
527
- textControl = {
528
- handler: props.onChangeText,
529
- current: typeof props.value === "string" ? props.value : undefined
530
- };
531
- } else {
532
- press = findPressHandler(fiber);
533
- }
534
- const rawName = getComponentName(fiber);
535
- // Prefer a user component name over a bare host/internal wrapper name.
536
- let name = rawName ?? "Unknown";
537
- if (!rawName || INTERNAL_NAMES.has(rawName) || typeof fiber.type === "string") {
538
- name = getOwningComponentName(fiber) ?? rawName ?? "Unknown";
539
- }
540
- const host = findHostInstance(fiber);
541
- if (!host && !testID) return; // unmeasurable & unnamed → skip
542
-
543
- // Interactive element with no own text/label (icon button, dial icon) —
544
- // adopt a descendant <Text> as its label so it's matchable by that text.
545
- if (!text && !label && hasPress) {
546
- text = collectDescendantText(fiber, 6);
547
- }
548
- const instance = host?.instance ?? null;
549
- const nativeTag = host?.nativeTag ?? null;
550
- const existing = (instance ? byInstance.get(instance) : undefined) ?? (nativeTag != null ? byTag.get(nativeTag) : undefined);
551
- if (existing) {
552
- // Keep the more interactive / better-labelled of the two.
553
- if (!existing.press && press) existing.press = press;else if (existing.press && press?.longPress && !existing.press.longPress) {
554
- existing.press.longPress = press.longPress;
555
- }
556
- if (!existing.valueControl && valueControl) existing.valueControl = valueControl;
557
- if (!existing.textControl && textControl) existing.textControl = textControl;
558
- if (!existing.testID && testID) existing.testID = testID;
559
- if (!existing.label && label) existing.label = label;
560
- if (!existing.text && text) existing.text = text;
561
- // Index the alias too, so a third sighting through either key finds it.
562
- if (instance && !byInstance.has(instance)) byInstance.set(instance, existing);
563
- if (nativeTag != null && !byTag.has(nativeTag)) byTag.set(nativeTag, existing);
564
- return;
565
- }
566
- const candidate = {
567
- nativeTag,
568
- name,
569
- role,
570
- testID,
571
- label,
572
- text,
573
- instance,
574
- stateNode: host?.stateNode ?? null,
575
- fiber,
576
- press,
577
- valueControl,
578
- textControl,
579
- rect: null,
580
- buoy: inBuoyChrome(fiber)
581
- };
582
- out.push(candidate);
583
- if (instance) byInstance.set(instance, candidate);
584
- if (nativeTag != null) byTag.set(nativeTag, candidate);
585
- });
586
- }
587
- return out;
588
- }
589
-
590
- /**
591
- * Whether the caller named THIS element, rather than described one like it.
592
- * An exact nativeTag or testID is a deliberate choice, and is honoured even
593
- * inside Buoy's own chrome — that is how a test or an editor agent drives a
594
- * Buoy tool on purpose. A fuzzy `query` is not.
595
- */
596
- function explicitlyTargets(c, params) {
597
- if (params.nativeTag != null) return c.nativeTag === params.nativeTag;
598
- if (params.testID && c.testID) return c.testID.toLowerCase() === params.testID.toLowerCase();
599
- return false;
600
- }
601
-
602
- /**
603
- * The app under test, not the tool looking at it.
604
- *
605
- * Buoy runs INSIDE the app, so its own sheet is in the same fiber tree as the
606
- * screens it inspects — and Ask Buoy's activity log echoes whatever the model
607
- * is searching for back as visible text. Left in, that echo was the best
608
- * match for the next fuzzy tap or wait, so every text-driven action landed on
609
- * Buoy's own panel and nothing in the app moved. The agent diagnosed it
610
- * itself, four chats in ("every text-based tap and wait I've done this
611
- * session has been landing on Buoy's panel"), and still could not escape it.
612
- *
613
- * `includeBuoy` lists the chrome for callers that want it; an exact id gets
614
- * through regardless (see `explicitlyTargets`).
615
- */
616
- function appCandidates(params) {
617
- const all = collectCandidates();
618
- if (params.includeBuoy) return all;
619
- return all.filter(c => !c.buoy || explicitlyTargets(c, params));
620
- }
621
- async function measureCandidates(candidates) {
622
- await Promise.all(candidates.map(async c => {
623
- if (c.instance) c.rect = await measureInstance(c.instance);
624
- }));
625
- }
626
-
627
- // --- describeScreen -------------------------------------------------------
628
-
629
- export async function describeScreen(params = {}) {
630
- const all = collectCandidates();
631
- const candidates = params.includeBuoy ? all : all.filter(c => !c.buoy);
632
- const hiddenBuoy = all.length - candidates.length;
633
- await measureCandidates(candidates);
634
- const win = Dimensions.get("window");
635
- const screenW = Math.round(win.width) || 1;
636
- const screenH = Math.round(win.height) || 1;
637
- const elements = [];
638
- for (const c of candidates) {
639
- const r = c.rect;
640
- // Keep on-screen elements; drop rect-less rows unless they carry a testID.
641
- if (!r && !c.testID) continue;
642
- let tap;
643
- let frame;
644
- if (r) {
645
- const cx = r.x + r.width / 2;
646
- const cy = r.y + r.height / 2;
647
- // Drop previous Expo Router screens (centers well outside the window).
648
- // Keep a 10% slack so the floating menu / home-indicator-clipped rows stay.
649
- if (cy < -screenH * 0.1 || cy > screenH * 1.1 || cx < -screenW * 0.1 || cx > screenW * 1.1) {
650
- continue;
651
- }
652
- tap = {
653
- x: round2(cx / screenW),
654
- y: round2(cy / screenH)
655
- };
656
- frame = {
657
- x: round2(r.x / screenW),
658
- y: round2(r.y / screenH),
659
- width: round2(r.width / screenW),
660
- height: round2(r.height / screenH)
661
- };
662
- }
663
- const control = c.valueControl ? c.valueControl.kind : c.textControl ? "text" : undefined;
664
- const value = c.valueControl ? c.valueControl.current : c.textControl?.current;
665
- elements.push({
666
- nativeTag: c.nativeTag,
667
- name: c.name,
668
- role: c.role,
669
- testID: c.testID,
670
- label: c.label,
671
- text: c.text,
672
- interactive: !!(c.press || c.valueControl || c.textControl),
673
- longPressable: c.press && (c.press.kind === "onLongPress" || c.press.longPress) ? true : undefined,
674
- control,
675
- value,
676
- tap,
677
- frame
678
- });
679
- }
680
-
681
- // Reading order: top-to-bottom, then left-to-right.
682
- elements.sort((a, b) => {
683
- const ay = a.tap?.y ?? 2;
684
- const by = b.tap?.y ?? 2;
685
- if (Math.abs(ay - by) > 0.02) return ay - by;
686
- return (a.tap?.x ?? 2) - (b.tap?.x ?? 2);
687
- });
688
- return {
689
- screen: {
690
- width: screenW,
691
- height: screenH
692
- },
693
- count: elements.length,
694
- elements,
695
- ...(hiddenBuoy > 0 ? {
696
- hiddenBuoy
697
- } : {})
698
- };
699
- }
700
- function round2(n) {
701
- return Math.round(n * 100) / 100;
702
- }
703
-
704
- // --- tapElement -----------------------------------------------------------
705
-
706
- function fieldsOf(c) {
707
- return {
708
- nativeTag: c.nativeTag,
709
- testID: c.testID,
710
- label: c.label,
711
- text: c.text,
712
- name: c.name
713
- };
714
- }
715
- function matchScore(c, params) {
716
- return scoreTapMatch(fieldsOf(c), params);
717
- }
718
- function tapPoint(rect, screenW, screenH) {
719
- if (!rect || !screenW || !screenH) return undefined;
720
- return {
721
- x: (rect.x + rect.width / 2) / screenW,
722
- y: (rect.y + rect.height / 2) / screenH
723
- };
724
- }
725
- function makeSyntheticPressEvent(rect) {
726
- const pageX = rect ? rect.x + rect.width / 2 : 0;
727
- const pageY = rect ? rect.y + rect.height / 2 : 0;
728
- const nativeEvent = {
729
- locationX: rect ? rect.width / 2 : 0,
730
- locationY: rect ? rect.height / 2 : 0,
731
- pageX,
732
- pageY,
733
- timestamp: 0,
734
- target: null,
735
- identifier: 1,
736
- touches: [],
737
- changedTouches: []
738
- };
739
- return {
740
- nativeEvent,
741
- persist: () => {},
742
- preventDefault: () => {},
743
- stopPropagation: () => {},
744
- isDefaultPrevented: () => false,
745
- isPropagationStopped: () => false,
746
- target: null,
747
- currentTarget: null,
748
- type: "press",
749
- timeStamp: 0
750
- };
751
- }
752
- export async function tapElement(params) {
753
- const candidates = appCandidates(params);
754
- if (candidates.length === 0) {
755
- return {
756
- tapped: false,
757
- reason: "No React fiber roots / elements found on screen."
758
- };
759
- }
760
-
761
- // Rank; only elements with a reachable press handler are tappable.
762
- const ranked = candidates.map(c => ({
763
- c,
764
- score: matchScore(c, params)
765
- })).filter(r => r.score > 0).sort((a, b) => b.score - a.score);
766
- const isInteractive = c => !!(c.press || c.valueControl || c.textControl);
767
- if (ranked.length === 0) {
768
- return {
769
- tapped: false,
770
- reason: "No element matched. Call describe_screen to see available elements (match by testID, text, or name).",
771
- candidates: candidates.filter(isInteractive).slice(0, 12).map(c => ({
772
- nativeTag: c.nativeTag,
773
- name: c.name,
774
- testID: c.testID,
775
- text: c.text
776
- }))
777
- };
778
- }
779
-
780
- // Measure the top matches so an on-screen DialIcon beats an off-screen nav
781
- // chip whose testID happens to contain the same substring.
782
- const win = Dimensions.get("window");
783
- const screenW = win.width || 1;
784
- const screenH = win.height || 1;
785
- const top = ranked.slice(0, 15);
786
- await Promise.all(top.map(async r => {
787
- if (r.c.instance && !r.c.rect) r.c.rect = await measureInstance(r.c.instance);
788
- }));
789
- for (const r of top) {
790
- r.score = scoreTapMatch({
791
- ...fieldsOf(r.c),
792
- tap: tapPoint(r.c.rect, screenW, screenH)
793
- }, params);
794
- }
795
- top.sort((a, b) => b.score - a.score);
796
-
797
- // Fall back to the FULL ranked list for an interactive match — the top-15
798
- // re-score is only a tiebreak, and on a busy screen the pressable match can
799
- // sit below 15 text-score peers.
800
- const target = top.find(r => isInteractive(r.c)) ?? ranked.find(r => isInteractive(r.c)) ?? top[0];
801
- const c = target.c;
802
-
803
- // Everything else that matched just as well. A fuzzy "SIGN IN" on a stack
804
- // that still has the home screen mounted underneath has two equal answers,
805
- // and the caller has to know that before trusting whichever one fired.
806
- const sameControl = (a, b) => a.press && a.press.handler === b.press?.handler || a.valueControl && a.valueControl.handler === b.valueControl?.handler || a.textControl && a.textControl.handler === b.textControl?.handler;
807
- const alsoMatched = top.filter(r => r !== target && isInteractive(r.c) && r.score === target.score)
808
- // The label Text inside the tapped button matches its own button's text
809
- // and inherits its onPress: same control, not a rival.
810
- .filter(r => !sameControl(r.c, c)).filter((r, i, arr) => arr.findIndex(o => sameControl(o.c, r.c)) === i).slice(0, 3).map(r => ({
811
- nativeTag: r.c.nativeTag,
812
- name: r.c.name,
813
- testID: r.c.testID,
814
- text: r.c.text,
815
- tap: tapPoint(r.c.rect, screenW, screenH)
816
- }));
817
- if (!isInteractive(c)) {
818
- return {
819
- tapped: false,
820
- reason: `Matched "${c.name}"${c.text ? ` ("${c.text}")` : ""} but it has no onPress / onValueChange / onChangeText handler (e.g. a react-native-gesture-handler GestureDetector). This element can't be driven in JS.`,
821
- matched: {
822
- nativeTag: c.nativeTag,
823
- name: c.name,
824
- testID: c.testID,
825
- label: c.label,
826
- text: c.text,
827
- via: "onPress"
828
- }
829
- };
830
- }
831
-
832
- // Measure the target so we can decide whether to scroll it on-screen (and,
833
- // for a press, give the synthetic event real coordinates).
834
- if (c.instance && !c.rect) c.rect = await measureInstance(c.instance);
835
-
836
- // Bring it into view if it's off-screen and scrolling is wanted. The action
837
- // doesn't NEED this (handlers are invoked directly), but it keeps the element
838
- // visible for the human watching / a follow-up describe.
839
- let scrolled = false;
840
- // A failed measure (rect == null) counts as off-screen: the node may be in
841
- // a virtualized list that hasn't materialized it, and scrolling can help.
842
- const offScreen = c.rect == null || !isRectCenterOnScreen(c.rect, screenW, screenH);
843
- if (offScreen && params.scrollIntoView !== false && c.instance) {
844
- scrolled = await scrollIntoView(c.fiber, c.instance, c.stateNode, 80);
845
- if (scrolled) c.rect = await measureInstance(c.instance); // fresh coords
846
- }
847
- const base = {
848
- nativeTag: c.nativeTag,
849
- name: c.name,
850
- testID: c.testID,
851
- label: c.label,
852
- text: c.text
853
- };
854
-
855
- // Fire, then watch. The handler is the app's own; what it did — or did
856
- // not do — shows up as commits (or none) in the settle window.
857
- ensureCommitCounter();
858
- // Read BEFORE the handler runs: a synchronous setState commits inside it.
859
- const c0 = commitCount;
860
- const t0 = Date.now();
861
- const fired = async matched => {
862
- await new Promise(resolve => setTimeout(resolve, TAP_SETTLE_MS));
863
- return {
864
- tapped: true,
865
- scrolled,
866
- matched,
867
- effect: {
868
- commits: commitCount - c0,
869
- observedMs: Date.now() - t0
870
- },
871
- ...(alsoMatched.length ? {
872
- alsoMatched
873
- } : {})
874
- };
875
- };
876
- try {
877
- if (c.press) {
878
- if (params.longPress) {
879
- const lp = c.press.kind === "onLongPress" ? c.press.handler : c.press.longPress;
880
- if (!lp) {
881
- return {
882
- tapped: false,
883
- scrolled,
884
- reason: `Matched "${c.name}"${c.text ? ` ("${c.text}")` : ""} but it has no onLongPress handler — call tap_element without longPress to tap it normally.`,
885
- matched: {
886
- ...base,
887
- via: "onPress"
888
- }
889
- };
890
- }
891
- lp(makeSyntheticPressEvent(c.rect));
892
- return await fired({
893
- ...base,
894
- via: "onLongPress"
895
- });
896
- }
897
- c.press.handler(makeSyntheticPressEvent(c.rect));
898
- return await fired({
899
- ...base,
900
- via: c.press.kind
901
- });
902
- }
903
- if (c.valueControl) {
904
- const vc = c.valueControl;
905
- let next;
906
- if (vc.kind === "toggle") {
907
- next = typeof params.value === "boolean" ? params.value : !vc.current;
908
- } else {
909
- const min = vc.min ?? 0;
910
- const max = vc.max ?? 1;
911
- if (typeof params.value === "number") {
912
- next = Math.min(max, Math.max(min, params.value));
913
- } else {
914
- // No target given → move to the far end so the change is visible.
915
- next = vc.current === max ? min : max;
916
- }
917
- }
918
- vc.handler(next);
919
- return await fired({
920
- ...base,
921
- via: "onValueChange",
922
- value: next
923
- });
924
- }
925
- // textControl
926
- const next = params.text ?? (typeof params.value === "string" ? params.value : "");
927
- c.textControl.handler(next);
928
- return await fired({
929
- ...base,
930
- via: "onChangeText",
931
- value: next
932
- });
933
- } catch (e) {
934
- return {
935
- tapped: false,
936
- scrolled,
937
- reason: `handler threw: ${e instanceof Error ? e.message : String(e)}`,
938
- matched: {
939
- ...base,
940
- via: c.press ? c.press.kind : c.valueControl ? "onValueChange" : "onChangeText"
941
- }
942
- };
943
- }
944
- }
945
-
946
- // --- waitFor --------------------------------------------------------------
947
-
948
- const WAIT_DEFAULT_MS = 5_000;
949
- const WAIT_MAX_MS = 30_000;
950
- const WAIT_MIN_POLL_MS = 50;
951
- const WAIT_DEFAULT_POLL_MS = 150;
952
-
953
- /**
954
- * Block until an element appears (or disappears), then report how long it took.
955
- *
956
- * WHY THIS EXISTS. `navigate` returns the moment the route is pushed, not when
957
- * the new screen has data on it, so "go to /shop then tap Fire Grill" reliably
958
- * tapped a loading skeleton. A remote driver solves that with a wait step
959
- * (MCP's `run_flow` has `waitFor`/`waitMs`); anything driving the tools from
960
- * INSIDE the app had nothing, and its only option was to re-run
961
- * `describeScreen` in a loop — which for an agent means burning turns against a
962
- * step budget, and for a Scenario means a fixed sleep that is either flaky or
963
- * slow.
964
- *
965
- * MATCHING IS `tapElement`'S, EXACTLY. Same `scoreTapMatch`, same fields, so
966
- * "wait for X" and "tap X" can never disagree about what X is. A wait that
967
- * resolves on an element the tap then cannot find is worse than no wait.
968
- *
969
- * PRESENCE MEANS ON SCREEN. An identity scan alone would resolve against a
970
- * previous Expo Router screen still mounted behind the current one — the exact
971
- * false positive `describeScreen` drops by rect. So a candidate that matches by
972
- * name is measured before it counts, and only the matches are measured: the
973
- * per-poll cost stays one fiber walk plus a handful of `measureInWindow`
974
- * calls, not a full `describeScreen`.
975
- *
976
- * The poll floor is deliberate. This runs on the JS thread the app is drawing
977
- * on, and a caller asking for `pollMs: 0` would starve the very render it is
978
- * waiting for.
979
- */
980
- export async function waitFor(params) {
981
- // Coerced, not optional-chained: a model sends `query: 1450` often enough,
982
- // and `.trim()` on a number throws before the wait ever starts.
983
- const hasTarget = params.nativeTag != null || !!String(params.testID ?? "").trim() || !!String(params.query ?? "").trim();
984
- if (!hasTarget) {
985
- return {
986
- ok: false,
987
- waitedMs: 0,
988
- polls: 0,
989
- reason: "Nothing to wait for — pass nativeTag, testID or query."
990
- };
991
- }
992
- const timeoutMs = Math.min(Math.max(params.timeoutMs ?? WAIT_DEFAULT_MS, 0), WAIT_MAX_MS);
993
- const pollMs = Math.max(params.pollMs ?? WAIT_DEFAULT_POLL_MS, WAIT_MIN_POLL_MS);
994
- const wantGone = params.gone === true;
995
- const started = Date.now();
996
- let polls = 0;
997
- for (;;) {
998
- polls += 1;
999
- const {
1000
- hit,
1001
- closest
1002
- } = await findOnScreen(params);
1003
- if (wantGone ? !hit : !!hit) {
1004
- return {
1005
- ok: true,
1006
- waitedMs: Date.now() - started,
1007
- polls,
1008
- matched: hit ?? undefined
1009
- };
1010
- }
1011
- if (Date.now() - started >= timeoutMs) {
1012
- const nearMisses = closest?.length ? closest : undefined;
1013
- // Say which of the two failures this is. "Nothing is called that" and
1014
- // "it exists but is not visible" need opposite next moves, and a caller
1015
- // that cannot tell them apart tries the same wait with new words.
1016
- const why = wantGone ? `Still on screen after ${timeoutMs}ms.` : nearMisses ? `Not on screen after ${timeoutMs}ms — ${nearMisses.length === 1 ? "one element" : `${nearMisses.length} elements`} matched but ${nearMisses.some(n => n.onScreen) ? "not well enough" : "none is visible"}. See \`closest\`; do not retry with different words, call describeScreen.` : `Not on screen after ${timeoutMs}ms, and nothing matched those words at all. Call describeScreen to see what is there.`;
1017
- return {
1018
- ok: false,
1019
- waitedMs: Date.now() - started,
1020
- polls,
1021
- reason: why,
1022
- matched: hit ?? undefined,
1023
- closest: nearMisses
1024
- };
1025
- }
1026
- await new Promise(resolve => setTimeout(resolve, pollMs));
1027
- }
1028
- }
1029
-
1030
- /** One scan: rank by identity, then confirm the best match is really visible. */
1031
- async function findOnScreen(params) {
1032
- const ranked = appCandidates(params).map(c => ({
1033
- c,
1034
- score: matchScore(c, params)
1035
- })).filter(r => r.score > 0).sort((a, b) => b.score - a.score)
1036
- // Only the plausible few get measured; a broad query can match dozens.
1037
- .slice(0, 8);
1038
- if (ranked.length === 0) return {
1039
- hit: null,
1040
- closest: undefined
1041
- };
1042
- await measureCandidates(ranked.map(r => r.c));
1043
- const win = Dimensions.get("window");
1044
- const screenW = Math.round(win.width) || 1;
1045
- const screenH = Math.round(win.height) || 1;
1046
- let hit = null;
1047
- for (const {
1048
- c
1049
- } of ranked) {
1050
- if (!isRectCenterOnScreen(c.rect, screenW, screenH)) continue;
1051
- hit = {
1052
- nativeTag: c.nativeTag,
1053
- name: c.name,
1054
- testID: c.testID,
1055
- label: c.label,
1056
- text: c.text,
1057
- interactive: !!(c.press || c.valueControl || c.textControl)
1058
- };
1059
- break;
1060
- }
1061
-
1062
- // Built from the same measured ranking, so a failed wait can say what it
1063
- // nearly matched and whether that thing was visible.
1064
- const closest = ranked.slice(0, 3).map(({
1065
- c
1066
- }) => ({
1067
- name: c.name,
1068
- testID: c.testID,
1069
- text: c.text,
1070
- onScreen: isRectCenterOnScreen(c.rect, screenW, screenH)
1071
- }));
1072
- return {
1073
- hit,
1074
- closest
1075
- };
1076
- }
1077
-
1078
- // --- resolveTouchTarget ---------------------------------------------------
1079
-
1080
- /**
1081
- * What a recorded touch landed on, in the vocabulary `tapElement` searches by.
1082
- *
1083
- * Deliberately the SAME fields `describeScreen` emits: a macro recorded from a
1084
- * human's finger has to replay through `tapElement`, and the only way to
1085
- * guarantee that is for the recorder to name the element exactly the way the
1086
- * matcher will look for it. Anything richer here is a selector that records
1087
- * fine and then can't be found again.
1088
- */
1089
-
1090
- /**
1091
- * Resolve the native tag from a raw touch event to the element a HUMAN would
1092
- * say they tapped.
1093
- *
1094
- * Synchronous on purpose. The tag arrives on `topTouchStart`, and by the time
1095
- * an async resolve came back the press handler may already have navigated —
1096
- * leaving the recorder to name the element on the screen it moved TO. Everything
1097
- * here is a fiber walk (no measure), which is what makes that affordable.
1098
- *
1099
- * Returns null when the tag belongs to nothing interesting (the background, a
1100
- * scroll surface): the recorder treats that as "not a step", which is exactly
1101
- * right — a tap on empty space is not something to replay.
1102
- */
1103
- /**
1104
- * Is this fiber inside Buoy's own overlay?
1105
- *
1106
- * `FloatingDevTools` marks its single root View with `__buoyDevToolsRoot`, and
1107
- * everything the tool draws — the bubble, the dial, every modal, every tool
1108
- * overlay — is under it. Walking the whole chain (rather than a fixed depth) is
1109
- * the point: a control deep inside a tool's modal is still the tool.
1110
- */
1111
- function isBuoyChrome(fiber) {
1112
- let cur = fiber;
1113
- let depth = 0;
1114
- while (cur && depth < 400) {
1115
- if (getProps(cur)?.__buoyDevToolsRoot) return true;
1116
- cur = cur.return;
1117
- depth++;
1118
- }
1119
- return false;
1120
- }
1121
-
1122
- /**
1123
- * Climb from the node that was touched to the element that OWNS the press.
1124
- *
1125
- * A finger lands on the deepest host view, which for a button is the `<Text>`
1126
- * inside it. That Text is a legitimate candidate — `findPressHandler` walks up
1127
- * and finds the button's `onPress`, so it looks drivable — but it carries the
1128
- * TEXT's identity: no testID, and "visible text" that is whatever string
1129
- * happens to be in that node.
1130
- *
1131
- * Left alone, every recorded step is named after a fragment of copy and
1132
- * replayed by fuzzy-matching that fragment. In the Poké Mart flow, all six
1133
- * steps came back as `Text` with no testID at all, so "tap the Charizard row"
1134
- * was recorded as "The signature. Flame-broiled, wings on, worth the wait." —
1135
- * the brittlest possible selector, chosen when `shop-item-charizard` was one
1136
- * fiber up.
1137
- *
1138
- * So we walk to the fiber that DECLARES `onPress` and take the candidate there.
1139
- * Stopping at the declaring fiber matters: keep climbing and a row inside a
1140
- * pressable list resolves to the list.
1141
- */
1142
- function preferHandlerOwner(match, byFiber) {
1143
- // Already the owner (or a Switch/TextInput, whose handler is its own).
1144
- const own = getProps(match.fiber);
1145
- if (typeof own?.onPress === "function" || typeof own?.onValueChange === "function" || typeof own?.onChangeText === "function") {
1146
- return match;
1147
- }
1148
-
1149
- // 1. Find the fiber that actually declares the handler.
1150
- let declaring = null;
1151
- let cur = match.fiber?.return;
1152
- let depth = 0;
1153
- while (cur && depth < 25) {
1154
- if (typeof getProps(cur)?.onPress === "function") {
1155
- declaring = cur;
1156
- break;
1157
- }
1158
- cur = cur.return;
1159
- depth++;
1160
- }
1161
- if (!declaring) return match;
1162
-
1163
- // 2. Take the candidate AT that fiber, or the first one above it.
1164
- //
1165
- // Stopping exactly at the declaring fiber isn't enough: a `<Pressable>`
1166
- // declares onPress but is de-duped into the component that renders it
1167
- // (`PrimaryButton`), and de-duping keeps the OUTERMOST fiber of everything
1168
- // sharing a host instance — which is where the testID ends up. Climbing a
1169
- // few levels past the handler is what turns "Text: Add to bag" into
1170
- // "PrimaryButton [testID=shop-add-to-bag]". The bound keeps a row inside a
1171
- // pressable list from resolving to the list.
1172
- let probe = declaring;
1173
- for (let i = 0; i < 6 && probe; i++) {
1174
- const candidate = byFiber.get(probe);
1175
- if (candidate) return candidate;
1176
- probe = probe.return;
1177
- }
1178
- return match;
1179
- }
1180
- export function resolveTouchTarget(nativeTag) {
1181
- const candidates = collectCandidates();
1182
- if (candidates.length === 0) return null;
1183
- const byFiber = new Map();
1184
- for (const c of candidates) byFiber.set(c.fiber, c);
1185
-
1186
- // Fast path: the touched host IS a candidate's host.
1187
- const direct = candidates.find(c => c.nativeTag === nativeTag);
1188
-
1189
- // Otherwise find the touched fiber and walk up to the nearest candidate. The
1190
- // touch lands on the deepest host view (the <Text> inside the button), so the
1191
- // interesting element is almost always an ancestor.
1192
- let touched = null;
1193
- if (!direct) {
1194
- for (const root of getAllFiberRoots()) {
1195
- traverseFiberTree(root.current, fiber => {
1196
- if (touched) return;
1197
- if (fiber.stateNode && getNativeTag(fiber.stateNode) === nativeTag) {
1198
- touched = fiber;
1199
- }
1200
- });
1201
- if (touched) break;
1202
- }
1203
- }
1204
- let match = direct ?? null;
1205
- if (!match && touched) {
1206
- let cur = touched;
1207
- let depth = 0;
1208
- // Prefer an ancestor that is actually drivable; fall back to the nearest
1209
- // named one so an unlabeled tap still records something a human can read.
1210
- let named = null;
1211
- while (cur && depth < 25) {
1212
- const c = byFiber.get(cur);
1213
- if (c) {
1214
- if (c.press || c.valueControl || c.textControl) {
1215
- match = c;
1216
- break;
1217
- }
1218
- if (!named) named = c;
1219
- }
1220
- cur = cur.return;
1221
- depth++;
1222
- }
1223
- if (!match) match = named;
1224
- }
1225
- if (!match) return null;
1226
- match = preferHandlerOwner(match, byFiber);
1227
- if (!match.press && !match.valueControl && !match.textControl) return null;
1228
- // Buoy's own chrome is not part of the app under test. Without this, the tap
1229
- // that stops a recording is recorded as its final step.
1230
- if (isBuoyChrome(match.fiber)) return null;
1231
- const control = match.valueControl ? match.valueControl.kind : match.textControl ? "text" : "press";
1232
- return {
1233
- nativeTag: match.nativeTag,
1234
- name: match.name,
1235
- role: match.role,
1236
- testID: match.testID,
1237
- label: match.label,
1238
- text: match.text,
1239
- control,
1240
- value: match.valueControl ? match.valueControl.current : match.textControl ? match.textControl.current : undefined
1241
- };
1242
- }
1
+ "use strict";import{getDOMControlProps as ee,getDOMNodeHandle as te,getDOMPublicInstance as ne,isDOMElement as oe}from"@buoy-gg/shared-ui/utils";import{Dimensions as k,UIManager as re,findNodeHandle as E}from"react-native";import{isRectCenterOnScreen as V,scoreTapMatch as H}from"./tapMatch";const Ne=5;const ie=22;const F=new Set(["View","RCTView","ScrollView","RCTScrollView","RCTScrollContentView","SafeAreaView","RCTSafeAreaView","AndroidHorizontalScrollContentView","KeyboardAvoidingView","Pressable","PlatformPressable","TouchableOpacity","TouchableHighlight","TouchableWithoutFeedback","TouchableNativeFeedback","AnimatedComponent","Wrapper"]);function $(){if(typeof global==="undefined")return null;return global.__REACT_DEVTOOLS_GLOBAL_HOOK__??null}let L=0;let W=false;function se(){if(W)return;const e=$();if(!e)return;const t=e.onCommitFiberRoot;e.onCommitFiberRoot=function(...n){L++;return typeof t==="function"?t.apply(e,n):void 0};W=true}const le=250;function ae(){const e=new Map;return t=>{const n=[];let r=t;let l=0;let s=false;while(r&&l<400){const u=e.get(r);if(u!==void 0){s=u;break}if(b(r)?.__buoyDevToolsRoot){s=true;e.set(r,true);break}n.push(r);r=r.return;l++}for(const u of n)e.set(u,s);return s}}function B(){const e=$();if(!e)return[];const t=[];try{if(e.renderers&&typeof e.renderers.forEach==="function"){e.renderers.forEach((n,r)=>{try{const l=e.getFiberRoots?.(r);if(l)l.forEach(s=>t.push(s))}catch{}})}if(t.length===0&&e.getFiberRoots){const n=e.getFiberRoots(1);if(n)n.forEach(r=>t.push(r))}}catch{}return t}function ce(e){return e.tag===ie&&e.memoizedState!==null}function ue(e){const t=e.memoizedProps?.activityState;if(t===0||t===1)return true;if(e.memoizedProps?.isPageFocused===false)return true;return false}function S(e,t,n=0,r=new Set){if(!e||r.has(e)||n>500)return;r.add(e);if(ce(e)||ue(e)){if(e.sibling)S(e.sibling,t,n,r);return}t(e);if(e.child)S(e.child,t,n+1,r);if(e.sibling)S(e.sibling,t,n,r)}function z(e){const t=ne(e);if(t)return t;if(!e)return null;const n=e;if(n.canonical?.publicInstance)return n.canonical.publicInstance;if(n.canonical&&typeof n.canonical.measure==="function"){return n.canonical}if(typeof n.measure==="function"||typeof n.measureInWindow==="function"){return n}return null}function R(e){const t=te(e);if(t!==null)return t;if(e==null)return null;const n=e;if(typeof n.__nativeTag==="number")return n.__nativeTag;if(typeof n._nativeTag==="number")return n._nativeTag;if(typeof n.nativeTag==="number")return n.nativeTag;if(n.canonical){if(typeof n.canonical.__nativeTag==="number")return n.canonical.__nativeTag;if(typeof n.canonical._nativeTag==="number")return n.canonical._nativeTag;if(typeof n.canonical.nativeTag==="number")return n.canonical.nativeTag}return null}function fe(e){const t=z(e.stateNode);if(t){return{instance:t,nativeTag:R(e.stateNode),stateNode:e.stateNode}}const n=[];if(e.child)n.push(e.child);let r=0;while(n.length>0&&r<4e3){r++;const l=n.pop();if(!l)continue;const s=z(l.stateNode);if(s)return{instance:s,nativeTag:R(l.stateNode),stateNode:l.stateNode};if(l.child)n.push(l.child);if(l.sibling)n.push(l.sibling)}return null}function de(e){let t=e;let n=0;while(t&&n++<200){const r=t.stateNode;if(r&&typeof r.scrollTo==="function"){const l=typeof r.getNativeScrollRef==="function"&&r.getNativeScrollRef()||null;const s=typeof r.getInnerViewNode==="function"&&r.getInnerViewNode()||typeof r.getScrollableNode==="function"&&r.getScrollableNode()||r;return{instance:r,nativeRef:l,innerNode:s}}t=t.return}return null}async function he(e,t,n,r){try{if(oe(n)){n.scrollIntoView({block:"nearest",inline:"nearest",behavior:"instant"});await new Promise(a=>setTimeout(a,16));return true}const l=de(e);if(!l)return false;const s=t;let u=null;const o=a=>new Promise(i=>{let f=false;const h=y=>{if(f)return;f=true;i(y)};const g=setTimeout(()=>h(null),600);try{a(y=>{clearTimeout(g);h(y)})}catch{clearTimeout(g);h(null)}});if(l.nativeRef&&typeof s.measureLayout==="function"){u=await o(a=>s.measureLayout(l.nativeRef,(i,f)=>a(f),()=>a(null)))}if(u==null){const a=E(t);const i=typeof l.innerNode==="number"?l.innerNode:E(l.innerNode);if(a!=null&&i!=null){u=await o(f=>re.measureLayout(a,i,()=>f(null),(h,g)=>f(g)))}}if(u==null)return false;l.instance.scrollTo({y:Math.max(0,u-r),animated:false});await new Promise(a=>setTimeout(a,120));return true}catch{return false}}function U(e){const t=e?.type;if(!t)return null;if(typeof t==="string")return t;return t.displayName||t.name||null}function ge(e){let t=e?._debugOwner||e?.return;let n=0;while(t&&n<30){n++;const r=U(t);if(r&&!F.has(r)&&typeof t.type!=="string"){return r}t=t.return}return null}function b(e){return ee(e?.stateNode,e?.memoizedProps??e?.pendingProps??null)}function j(e,t=0){if(typeof e==="string")return e;if(typeof e==="number"&&Number.isFinite(e))return String(e);if(Array.isArray(e)&&t<4){const n=[];for(const r of e){const l=j(r,t+1);if(l)n.push(l)}return n.length>0?n.join(""):void 0}return void 0}function me(e){return e.replace(/\s+/g," ").trim()}function G(e){if(!e)return void 0;const t=n=>{const r=j(n);if(r===void 0)return void 0;const l=me(r);return l?l.slice(0,80):void 0};return t(e.children)??t(e.title)??t(e.label)??t(e.placeholder)??void 0}function pe(e,t){const n=[];const r=(s,u)=>{if(!s||u>t||n.length>=4)return;if(s!==e){const a=b(s);if(a&&(typeof a.onPress==="function"||typeof a.onLongPress==="function"))return}const o=G(b(s));if(o&&!n.includes(o))n.push(o);if(s.child)r(s.child,u+1);if(s!==e&&s.sibling)r(s.sibling,u)};if(e.child)r(e.child,1);const l=n.join(" ").trim();return l?l.slice(0,80):void 0}function ye(e){let t=e;let n=0;let r=null;let l=null;while(t&&n<25&&!(r&&l)){const s=b(t);if(s){if(!r&&typeof s.onPress==="function")r=s.onPress;if(!l&&typeof s.onLongPress==="function")l=s.onLongPress}t=t.return;n++}if(r)return{handler:r,kind:"onPress",longPress:l??void 0};return l?{handler:l,kind:"onLongPress"}:null}function M(e){return new Promise(t=>{let n=false;const r=l=>{if(n)return;n=true;t(l)};setTimeout(()=>r(null),1e3);try{if(typeof e.measureInWindow==="function"){e.measureInWindow((l,s,u,o)=>{if(u>0&&o>0)r({x:l,y:s,width:u,height:o});else r(null)})}else if(typeof e.measure==="function"){e.measure((l,s,u,o,a,i)=>{if(u>0&&o>0&&a!=null&&i!=null){r({x:a,y:i,width:u,height:o})}else{r(null)}})}else{r(null)}}catch{r(null)}})}const we=new Set(["RCTActivityIndicatorView","AndroidProgressBar"]);function A(){const e=B();if(e.length===0)return[];const t=[];const n=new Map;const r=new Map;const l=ae();for(const s of e){S(s.current,u=>{const o=b(u);if(!o)return;const a=typeof o.onPress==="function"||typeof o.onLongPress==="function";const i=typeof o.onValueChange==="function";const f=typeof o.onChangeText==="function";const h=o.testID||void 0;const g=o.accessibilityLabel||void 0;const y=o.accessibilityRole||o.role||void 0;let p=G(o);const P=y==="button"||y==="link"||y==="menuitem"||y==="tab"||y==="switch"||y==="checkbox";const _=typeof u.type==="string"&&we.has(u.type)&&o.animating!==false;if(!a&&!i&&!f&&!h&&!g&&!p&&!P&&!_){return}let v=null;let c=null;let d=null;if(i){const O=o.value;const Z=typeof O==="number"||typeof o.minimumValue==="number";c={handler:o.onValueChange,kind:Z?"slider":"toggle",current:O,min:typeof o.minimumValue==="number"?o.minimumValue:void 0,max:typeof o.maximumValue==="number"?o.maximumValue:void 0}}else if(f){d={handler:o.onChangeText,current:typeof o.value==="string"?o.value:void 0}}else{v=ye(u)}const w=U(u);let I=w??"Unknown";if(!w||F.has(w)||typeof u.type==="string"){I=ge(u)??w??"Unknown"}const T=fe(u);if(!T&&!h)return;if(!p&&!g&&a){p=pe(u,6)}const x=T?.instance??null;const C=T?.nativeTag??null;const m=(x?n.get(x):void 0)??(C!=null?r.get(C):void 0);if(m){if(!m.press&&v)m.press=v;else if(m.press&&v?.longPress&&!m.press.longPress){m.press.longPress=v.longPress}if(!m.valueControl&&c)m.valueControl=c;if(!m.textControl&&d)m.textControl=d;if(!m.testID&&h)m.testID=h;if(!m.label&&g)m.label=g;if(!m.text&&p)m.text=p;if(x&&!n.has(x))n.set(x,m);if(C!=null&&!r.has(C))r.set(C,m);return}const N={nativeTag:C,name:I,role:y??(_?"progressbar":void 0),testID:h,label:g,text:p,instance:x,stateNode:T?.stateNode??null,fiber:u,press:v,valueControl:c,textControl:d,rect:null,buoy:l(u)};t.push(N);if(x)n.set(x,N);if(C!=null)r.set(C,N)})}return t}function ve(e,t){if(t.nativeTag!=null)return e.nativeTag===t.nativeTag;if(t.testID&&e.testID)return e.testID.toLowerCase()===t.testID.toLowerCase();return false}function q(e){const t=A();if(e.includeBuoy)return t;return t.filter(n=>!n.buoy||ve(n,e))}async function K(e){await Promise.all(e.map(async t=>{if(t.instance)t.rect=await M(t.instance)}))}export async function describeScreen(e={}){const t=A();const n=e.includeBuoy?t:t.filter(a=>!a.buoy);const r=t.length-n.length;await K(n);const l=k.get("window");const s=Math.round(l.width)||1;const u=Math.round(l.height)||1;const o=[];for(const a of n){const i=a.rect;if(!i&&!a.testID)continue;let f;let h;if(i){const p=i.x+i.width/2;const P=i.y+i.height/2;if(P<-u*.1||P>u*1.1||p<-s*.1||p>s*1.1){continue}f={x:D(p/s),y:D(P/u)};h={x:D(i.x/s),y:D(i.y/u),width:D(i.width/s),height:D(i.height/u)}}const g=a.valueControl?a.valueControl.kind:a.textControl?"text":void 0;const y=a.valueControl?a.valueControl.current:a.textControl?.current;o.push({nativeTag:a.nativeTag,name:a.name,role:a.role,testID:a.testID,label:a.label,text:a.text,interactive:!!(a.press||a.valueControl||a.textControl),longPressable:a.press&&(a.press.kind==="onLongPress"||a.press.longPress)?true:void 0,control:g,value:y,tap:f,frame:h})}o.sort((a,i)=>{const f=a.tap?.y??2;const h=i.tap?.y??2;if(Math.abs(f-h)>.02)return f-h;return(a.tap?.x??2)-(i.tap?.x??2)});return{screen:{width:s,height:u},count:o.length,elements:o,...r>0?{hiddenBuoy:r}:{}}}function D(e){return Math.round(e*100)/100}function X(e){return{nativeTag:e.nativeTag,testID:e.testID,label:e.label,text:e.text,name:e.name}}function J(e,t){return H(X(e),t)}function Y(e,t,n){if(!e||!t||!n)return void 0;return{x:(e.x+e.width/2)/t,y:(e.y+e.height/2)/n}}function Q(e){const t=e?e.x+e.width/2:0;const n=e?e.y+e.height/2:0;const r={locationX:e?e.width/2:0,locationY:e?e.height/2:0,pageX:t,pageY:n,timestamp:0,target:null,identifier:1,touches:[],changedTouches:[]};return{nativeEvent:r,persist:()=>{},preventDefault:()=>{},stopPropagation:()=>{},isDefaultPrevented:()=>false,isPropagationStopped:()=>false,target:null,currentTarget:null,type:"press",timeStamp:0}}export async function tapElement(e){const t=q(e);if(t.length===0){return{tapped:false,reason:"No React fiber roots / elements found on screen."}}const n=t.map(c=>({c,score:J(c,e)})).filter(c=>c.score>0).sort((c,d)=>d.score-c.score);const r=c=>!!(c.press||c.valueControl||c.textControl);if(n.length===0){return{tapped:false,reason:"No element matched. Call describe_screen to see available elements (match by testID, text, or name).",candidates:t.filter(r).slice(0,12).map(c=>({nativeTag:c.nativeTag,name:c.name,testID:c.testID,text:c.text}))}}const l=k.get("window");const s=l.width||1;const u=l.height||1;const o=n.slice(0,15);await Promise.all(o.map(async c=>{if(c.c.instance&&!c.c.rect)c.c.rect=await M(c.c.instance)}));for(const c of o){c.score=H({...X(c.c),tap:Y(c.c.rect,s,u)},e)}o.sort((c,d)=>d.score-c.score);const a=o.find(c=>r(c.c))??n.find(c=>r(c.c))??o[0];const i=a.c;const f=(c,d)=>c.press&&c.press.handler===d.press?.handler||c.valueControl&&c.valueControl.handler===d.valueControl?.handler||c.textControl&&c.textControl.handler===d.textControl?.handler;const h=o.filter(c=>c!==a&&r(c.c)&&c.score===a.score).filter(c=>!f(c.c,i)).filter((c,d,w)=>w.findIndex(I=>f(I.c,c.c))===d).slice(0,3).map(c=>({nativeTag:c.c.nativeTag,name:c.c.name,testID:c.c.testID,text:c.c.text,tap:Y(c.c.rect,s,u)}));if(!r(i)){return{tapped:false,reason:`Matched "${i.name}"${i.text?` ("${i.text}")`:""} but it has no onPress / onValueChange / onChangeText handler (e.g. a react-native-gesture-handler GestureDetector). This element can't be driven in JS.`,matched:{nativeTag:i.nativeTag,name:i.name,testID:i.testID,label:i.label,text:i.text,via:"onPress"}}}if(i.instance&&!i.rect)i.rect=await M(i.instance);let g=false;const y=i.rect==null||!V(i.rect,s,u);if(y&&e.scrollIntoView!==false&&i.instance){g=await he(i.fiber,i.instance,i.stateNode,80);if(g)i.rect=await M(i.instance)}const p={nativeTag:i.nativeTag,name:i.name,testID:i.testID,label:i.label,text:i.text};se();const P=L;const _=Date.now();const v=async c=>{await new Promise(d=>setTimeout(d,le));return{tapped:true,scrolled:g,matched:c,effect:{commits:L-P,observedMs:Date.now()-_},...h.length?{alsoMatched:h}:{}}};try{if(i.press){if(e.longPress){const d=i.press.kind==="onLongPress"?i.press.handler:i.press.longPress;if(!d){return{tapped:false,scrolled:g,reason:`Matched "${i.name}"${i.text?` ("${i.text}")`:""} but it has no onLongPress handler \u2014 call tap_element without longPress to tap it normally.`,matched:{...p,via:"onPress"}}}d(Q(i.rect));return await v({...p,via:"onLongPress"})}i.press.handler(Q(i.rect));return await v({...p,via:i.press.kind})}if(i.valueControl){const d=i.valueControl;let w;if(d.kind==="toggle"){w=typeof e.value==="boolean"?e.value:!d.current}else{const I=d.min??0;const T=d.max??1;if(typeof e.value==="number"){w=Math.min(T,Math.max(I,e.value))}else{w=d.current===T?I:T}}d.handler(w);return await v({...p,via:"onValueChange",value:w})}const c=e.text??(typeof e.value==="string"?e.value:"");i.textControl.handler(c);return await v({...p,via:"onChangeText",value:c})}catch(c){return{tapped:false,scrolled:g,reason:`handler threw: ${c instanceof Error?c.message:String(c)}`,matched:{...p,via:i.press?i.press.kind:i.valueControl?"onValueChange":"onChangeText"}}}}const Te=5e3;const xe=3e4;const Ce=50;const be=150;export async function waitFor(e){const t=e.nativeTag!=null||!!String(e.testID??"").trim()||!!String(e.query??"").trim();if(!t){return{ok:false,waitedMs:0,polls:0,reason:"Nothing to wait for \u2014 pass nativeTag, testID or query."}}const n=Math.min(Math.max(e.timeoutMs??Te,0),xe);const r=Math.max(e.pollMs??be,Ce);const l=e.gone===true;const s=Date.now();let u=0;for(;;){u+=1;const{hit:o,closest:a}=await Pe(e);if(l?!o:!!o){return{ok:true,waitedMs:Date.now()-s,polls:u,matched:o??void 0}}if(Date.now()-s>=n){const i=a?.length?a:void 0;const f=l?`Still on screen after ${n}ms.`:i?`Not on screen after ${n}ms \u2014 ${i.length===1?"one element":`${i.length} elements`} matched but ${i.some(h=>h.onScreen)?"not well enough":"none is visible"}. See \`closest\`; do not retry with different words, call describeScreen.`:`Not on screen after ${n}ms, and nothing matched those words at all. Call describeScreen to see what is there.`;return{ok:false,waitedMs:Date.now()-s,polls:u,reason:f,matched:o??void 0,closest:i}}await new Promise(i=>setTimeout(i,r))}}async function Pe(e){const t=q(e).map(o=>({c:o,score:J(o,e)})).filter(o=>o.score>0).sort((o,a)=>a.score-o.score).slice(0,8);if(t.length===0)return{hit:null,closest:void 0};await K(t.map(o=>o.c));const n=k.get("window");const r=Math.round(n.width)||1;const l=Math.round(n.height)||1;let s=null;for(const{c:o}of t){if(!V(o.rect,r,l))continue;s={nativeTag:o.nativeTag,name:o.name,testID:o.testID,label:o.label,text:o.text,interactive:!!(o.press||o.valueControl||o.textControl)};break}const u=t.slice(0,3).map(({c:o})=>({name:o.name,testID:o.testID,text:o.text,onScreen:V(o.rect,r,l)}));return{hit:s,closest:u}}function Ie(e){let t=e;let n=0;while(t&&n<400){if(b(t)?.__buoyDevToolsRoot)return true;t=t.return;n++}return false}function De(e,t){const n=b(e.fiber);if(typeof n?.onPress==="function"||typeof n?.onValueChange==="function"||typeof n?.onChangeText==="function"){return e}let r=null;let l=e.fiber?.return;let s=0;while(l&&s<25){if(typeof b(l)?.onPress==="function"){r=l;break}l=l.return;s++}if(!r)return e;let u=r;for(let o=0;o<6&&u;o++){const a=t.get(u);if(a)return a;u=u.return}return e}export function resolveTouchTarget(e){const t=A();if(t.length===0)return null;const n=new Map;for(const o of t)n.set(o.fiber,o);const r=t.find(o=>o.nativeTag===e);let l=null;if(!r){for(const o of B()){S(o.current,a=>{if(l)return;if(a.stateNode&&R(a.stateNode)===e){l=a}});if(l)break}}let s=r??null;if(!s&&l){let o=l;let a=0;let i=null;while(o&&a<25){const f=n.get(o);if(f){if(f.press||f.valueControl||f.textControl){s=f;break}if(!i)i=f}o=o.return;a++}if(!s)s=i}if(!s)return null;s=De(s,n);if(!s.press&&!s.valueControl&&!s.textControl)return null;if(Ie(s.fiber))return null;const u=s.valueControl?s.valueControl.kind:s.textControl?"text":"press";return{nativeTag:s.nativeTag,name:s.name,role:s.role,testID:s.testID,label:s.label,text:s.text,control:u,value:s.valueControl?s.valueControl.current:s.textControl?s.textControl.current:void 0}}