@bugsee/react-native 0.0.0-stage → 7.0.0-beta2

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 (250) hide show
  1. package/BugseeReactNative.podspec +95 -0
  2. package/LICENSE +21 -0
  3. package/README.md +557 -2
  4. package/android/build.gradle +162 -0
  5. package/android/consumer-rules.pro +2 -0
  6. package/android/src/main/AndroidManifest.xml +33 -0
  7. package/android/src/main/java/com/bugsee/reactnative/AppearanceBridge.java +82 -0
  8. package/android/src/main/java/com/bugsee/reactnative/AttributeBridge.java +209 -0
  9. package/android/src/main/java/com/bugsee/reactnative/BreadcrumbFilterBridge.java +443 -0
  10. package/android/src/main/java/com/bugsee/reactnative/BridgeJson.java +168 -0
  11. package/android/src/main/java/com/bugsee/reactnative/BugseeModule.java +1869 -0
  12. package/android/src/main/java/com/bugsee/reactnative/BugseeOptionEnums.java +136 -0
  13. package/android/src/main/java/com/bugsee/reactnative/BugseePackage.java +42 -0
  14. package/android/src/main/java/com/bugsee/reactnative/BugseeReactNativeWrapper.java +200 -0
  15. package/android/src/main/java/com/bugsee/reactnative/BugseeStatusMapper.java +66 -0
  16. package/android/src/main/java/com/bugsee/reactnative/BugseeTokens.java +22 -0
  17. package/android/src/main/java/com/bugsee/reactnative/ConsoleEchoDedup.java +202 -0
  18. package/android/src/main/java/com/bugsee/reactnative/CreatedReports.java +127 -0
  19. package/android/src/main/java/com/bugsee/reactnative/DataRequestBridge.java +375 -0
  20. package/android/src/main/java/com/bugsee/reactnative/ExceptionBridge.java +88 -0
  21. package/android/src/main/java/com/bugsee/reactnative/ExceptionExecutors.java +33 -0
  22. package/android/src/main/java/com/bugsee/reactnative/LogFilterBridge.java +375 -0
  23. package/android/src/main/java/com/bugsee/reactnative/NetworkEvents.java +227 -0
  24. package/android/src/main/java/com/bugsee/reactnative/NetworkFilterBridge.java +498 -0
  25. package/android/src/main/java/com/bugsee/reactnative/PluginEndpoint.java +48 -0
  26. package/android/src/main/java/com/bugsee/reactnative/ReactNativeWebException.java +19 -0
  27. package/android/src/main/java/com/bugsee/reactnative/ReactNativeWrapperInitProvider.java +61 -0
  28. package/android/src/main/java/com/bugsee/reactnative/ReactRootOriginTracker.java +867 -0
  29. package/android/src/main/java/com/bugsee/reactnative/ReportArgs.java +58 -0
  30. package/android/src/main/java/com/bugsee/reactnative/ReportHandlerBridge.java +336 -0
  31. package/android/src/main/java/com/bugsee/reactnative/ReportHandlerDeadlines.java +57 -0
  32. package/android/src/main/java/com/bugsee/reactnative/ReportOps.java +287 -0
  33. package/android/src/main/java/com/bugsee/reactnative/SecureRectanglePulls.java +113 -0
  34. package/android/src/main/java/com/bugsee/reactnative/SecureRectangleStore.java +692 -0
  35. package/android/src/main/java/com/bugsee/reactnative/SpanHandles.java +143 -0
  36. package/android/src/main/java/com/bugsee/reactnative/WrapperChannelHolder.java +137 -0
  37. package/android/src/main/java/com/bugsee/reactnative/WrapperEventBus.java +110 -0
  38. package/android/src/main/java/com/bugsee/reactnative/WrapperRegistrar.java +54 -0
  39. package/app.plugin.js +4 -0
  40. package/ios/BGSRNConsoleCapture.h +52 -0
  41. package/ios/BGSRNConsoleCapture.mm +344 -0
  42. package/ios/BugseeModule.h +25 -0
  43. package/ios/BugseeModule.mm +2728 -0
  44. package/ios/Package.swift +71 -0
  45. package/ios/Support/Package.resolved +14 -0
  46. package/ios/Support/Package.swift +44 -0
  47. package/ios/Support/Sources/BugseeRNSupport/BGSRNAttributes.m +52 -0
  48. package/ios/Support/Sources/BugseeRNSupport/BGSRNCreatedReportOps.m +236 -0
  49. package/ios/Support/Sources/BugseeRNSupport/BGSRNCreatedReports.m +184 -0
  50. package/ios/Support/Sources/BugseeRNSupport/BGSRNDataRequestBridge.m +431 -0
  51. package/ios/Support/Sources/BugseeRNSupport/BGSRNErrorMessage.m +40 -0
  52. package/ios/Support/Sources/BugseeRNSupport/BGSRNEventBus.m +70 -0
  53. package/ios/Support/Sources/BugseeRNSupport/BGSRNExceptions.m +63 -0
  54. package/ios/Support/Sources/BugseeRNSupport/BGSRNGuardedEmit.mm +32 -0
  55. package/ios/Support/Sources/BugseeRNSupport/BGSRNJSON.m +40 -0
  56. package/ios/Support/Sources/BugseeRNSupport/BGSRNLaunchHold.m +147 -0
  57. package/ios/Support/Sources/BugseeRNSupport/BGSRNMainThread.m +23 -0
  58. package/ios/Support/Sources/BugseeRNSupport/BGSRNNetworkEvents.m +159 -0
  59. package/ios/Support/Sources/BugseeRNSupport/BGSRNNetworkFilter.m +155 -0
  60. package/ios/Support/Sources/BugseeRNSupport/BGSRNPluginEndpoint.m +21 -0
  61. package/ios/Support/Sources/BugseeRNSupport/BGSRNReactRootOriginTracker.m +63 -0
  62. package/ios/Support/Sources/BugseeRNSupport/BGSRNReactWindow.m +251 -0
  63. package/ios/Support/Sources/BugseeRNSupport/BGSRNReportArgs.m +47 -0
  64. package/ios/Support/Sources/BugseeRNSupport/BGSRNReportDeadlines.m +8 -0
  65. package/ios/Support/Sources/BugseeRNSupport/BGSRNReportHandlerBridge.m +308 -0
  66. package/ios/Support/Sources/BugseeRNSupport/BGSRNReportOps.m +345 -0
  67. package/ios/Support/Sources/BugseeRNSupport/BGSRNSecureRectangles.m +508 -0
  68. package/ios/Support/Sources/BugseeRNSupport/BGSRNSettleOnce.m +62 -0
  69. package/ios/Support/Sources/BugseeRNSupport/BGSRNSpanHandles.m +136 -0
  70. package/ios/Support/Sources/BugseeRNSupport/BGSRNStatusMapper.m +18 -0
  71. package/ios/Support/Sources/BugseeRNSupport/BGSRNTokens.m +9 -0
  72. package/ios/Support/Sources/BugseeRNSupport/BGSRNValues.m +5 -0
  73. package/ios/Support/Sources/BugseeRNSupport/BGSRNWrapper.m +54 -0
  74. package/ios/Support/Sources/BugseeRNSupport/BGSRNWrapperChannelHolder.m +59 -0
  75. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNAttributes.h +63 -0
  76. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNCreatedReportOps.h +51 -0
  77. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNCreatedReports.h +81 -0
  78. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNDataRequestBridge.h +118 -0
  79. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNErrorMessage.h +30 -0
  80. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNEventBus.h +45 -0
  81. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNExceptions.h +31 -0
  82. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNGuardedEmit.h +31 -0
  83. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNJSON.h +25 -0
  84. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNLaunchHold.h +86 -0
  85. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNMainThread.h +32 -0
  86. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNNetworkEvents.h +28 -0
  87. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNNetworkFilter.h +28 -0
  88. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNPluginEndpoint.h +17 -0
  89. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNReactRootOriginTracker.h +48 -0
  90. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNReactWindow.h +135 -0
  91. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNReportArgs.h +17 -0
  92. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNReportDeadlines.h +37 -0
  93. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNReportHandlerBridge.h +94 -0
  94. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNReportOps.h +86 -0
  95. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNSecureRectangles.h +198 -0
  96. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNSettleOnce.h +25 -0
  97. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNSpanHandles.h +49 -0
  98. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNStatusMapper.h +26 -0
  99. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNTokens.h +14 -0
  100. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNValues.h +18 -0
  101. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNWrapper.h +40 -0
  102. package/ios/Support/Sources/BugseeRNSupport/include/BGSRNWrapperChannelHolder.h +74 -0
  103. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNAttributesTests.m +194 -0
  104. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNCreatedReportOpsTests.m +274 -0
  105. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNCreatedReportsTests.m +240 -0
  106. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNDataRequestBridgeTests.m +685 -0
  107. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNErrorMessageTests.m +102 -0
  108. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNEventBusTests.m +136 -0
  109. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNExceptionsTests.m +68 -0
  110. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNFakeReport.h +41 -0
  111. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNFakeReport.m +166 -0
  112. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNGuardedEmitTests.mm +85 -0
  113. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNJSONTests.m +281 -0
  114. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNLaunchHoldTests.m +230 -0
  115. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNMainThreadTests.m +97 -0
  116. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNNetworkEventsTests.m +99 -0
  117. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNNetworkFilterTests.m +134 -0
  118. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNPluginEndpointTests.m +38 -0
  119. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNReactRootOriginTrackerTests.m +210 -0
  120. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNReactWindowTests.m +548 -0
  121. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNReportArgsTests.m +51 -0
  122. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNReportDeadlinesTests.m +22 -0
  123. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNReportHandlerBridgeTests.m +382 -0
  124. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNReportOpsTests.m +295 -0
  125. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNSecureRectanglesTests.m +568 -0
  126. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNSettleOnceTests.m +134 -0
  127. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNSpanHandlesTests.m +153 -0
  128. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNStatusMapperTests.m +81 -0
  129. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNValuesTests.m +32 -0
  130. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNWrapperChannelHolderTests.m +205 -0
  131. package/ios/Support/Tests/BugseeRNSupportTests/BGSRNWrapperTests.m +66 -0
  132. package/ios/react-native-spm-prefix.h +10 -0
  133. package/native-versions.json +10 -0
  134. package/package.json +62 -3
  135. package/plugin/build/bundle-phase.d.ts +41 -0
  136. package/plugin/build/bundle-phase.js +116 -0
  137. package/plugin/build/bundle-phase.js.map +1 -0
  138. package/plugin/build/dsym-script.d.ts +32 -0
  139. package/plugin/build/dsym-script.js +159 -0
  140. package/plugin/build/dsym-script.js.map +1 -0
  141. package/plugin/build/endpoint.d.ts +30 -0
  142. package/plugin/build/endpoint.js +69 -0
  143. package/plugin/build/endpoint.js.map +1 -0
  144. package/plugin/build/gradle.d.ts +65 -0
  145. package/plugin/build/gradle.js +1066 -0
  146. package/plugin/build/gradle.js.map +1 -0
  147. package/plugin/build/index.d.ts +85 -0
  148. package/plugin/build/index.js +217 -0
  149. package/plugin/build/index.js.map +1 -0
  150. package/plugin/build/manifest.d.ts +48 -0
  151. package/plugin/build/manifest.js +69 -0
  152. package/plugin/build/manifest.js.map +1 -0
  153. package/plugin/build/native-versions.baked.json +4 -0
  154. package/plugin/build/native-versions.d.ts +10 -0
  155. package/plugin/build/native-versions.js +27 -0
  156. package/plugin/build/native-versions.js.map +1 -0
  157. package/plugin/build/pbx-string.d.ts +8 -0
  158. package/plugin/build/pbx-string.js +31 -0
  159. package/plugin/build/pbx-string.js.map +1 -0
  160. package/plugin/build/podfile.d.ts +3 -0
  161. package/plugin/build/podfile.js +28 -0
  162. package/plugin/build/podfile.js.map +1 -0
  163. package/plugin/build/properties.d.ts +19 -0
  164. package/plugin/build/properties.js +41 -0
  165. package/plugin/build/properties.js.map +1 -0
  166. package/plugin/build/scheme.d.ts +20 -0
  167. package/plugin/build/scheme.js +107 -0
  168. package/plugin/build/scheme.js.map +1 -0
  169. package/react-native.config.js +26 -0
  170. package/scripts/bugsee-sourcemaps.gradle +201 -0
  171. package/scripts/bugsee-xcode.sh +83 -0
  172. package/scripts/compose-then-inject.js +113 -0
  173. package/scripts/hermes-sourcemaps.js +634 -0
  174. package/scripts/hermesc-preserve-js.cmd +6 -0
  175. package/scripts/hermesc-preserve-js.js +200 -0
  176. package/scripts/hermesc-preserve-js.sh +7 -0
  177. package/src/NativeBugsee.ts +622 -0
  178. package/src/apm/notify.ts +58 -0
  179. package/src/apm/span.ts +403 -0
  180. package/src/apm/types.ts +57 -0
  181. package/src/appearance/report.ts +171 -0
  182. package/src/architecture.ts +48 -0
  183. package/src/attributes/errors.ts +39 -0
  184. package/src/attributes/validate.ts +150 -0
  185. package/src/breadcrumbs/add.ts +58 -0
  186. package/src/breadcrumbs/data.ts +33 -0
  187. package/src/breadcrumbs/filter.ts +215 -0
  188. package/src/breadcrumbs/types.ts +64 -0
  189. package/src/bridge/json.ts +110 -0
  190. package/src/console/capture.ts +180 -0
  191. package/src/console/dedup.ts +175 -0
  192. package/src/data/validate.ts +259 -0
  193. package/src/errorName.ts +32 -0
  194. package/src/exceptions/ErrorBoundary.tsx +92 -0
  195. package/src/exceptions/RootErrorReporter.tsx +61 -0
  196. package/src/exceptions/debugIds.ts +118 -0
  197. package/src/exceptions/handlers.ts +236 -0
  198. package/src/exceptions/options.ts +85 -0
  199. package/src/exceptions/payload.ts +456 -0
  200. package/src/exceptions/report.ts +170 -0
  201. package/src/exceptions/sha1.ts +148 -0
  202. package/src/exceptions/stack.ts +355 -0
  203. package/src/index.ts +962 -0
  204. package/src/logs/filter.ts +90 -0
  205. package/src/logs/log.ts +36 -0
  206. package/src/network/add.ts +165 -0
  207. package/src/network/filter.ts +198 -0
  208. package/src/options/AndroidLaunchOptions.ts +78 -0
  209. package/src/options/BugseeLaunchOptions.ts +190 -0
  210. package/src/options/IOSLaunchOptions.ts +57 -0
  211. package/src/options/android-options-manifest.json +646 -0
  212. package/src/options/createDefaultLaunchOptions.ts +29 -0
  213. package/src/options/endpoint.ts +58 -0
  214. package/src/options/enums.ts +104 -0
  215. package/src/options/ios-enums.json +19 -0
  216. package/src/options/keys.ts +39 -0
  217. package/src/options/option-enums.json +34 -0
  218. package/src/options/option-keys.json +107 -0
  219. package/src/report/BugseeReport.ts +264 -0
  220. package/src/report/CreatedReport.ts +127 -0
  221. package/src/report/dispatcher.ts +95 -0
  222. package/src/report/errors.ts +48 -0
  223. package/src/report/fields.ts +40 -0
  224. package/src/report/types.ts +157 -0
  225. package/src/report/validate.ts +197 -0
  226. package/src/secure/BugseeSecure.tsx +202 -0
  227. package/src/secure/ancestry.ts +622 -0
  228. package/src/secure/drivers.ts +342 -0
  229. package/src/secure/followEvents.ts +57 -0
  230. package/src/secure/hold.ts +99 -0
  231. package/src/secure/measureLoop.ts +323 -0
  232. package/src/secure/nativeAnimation.ts +1005 -0
  233. package/src/secure/rectangles.ts +93 -0
  234. package/src/secure/registry.ts +237 -0
  235. package/src/secure/surface.ts +83 -0
  236. package/src/secure/tracker.ts +723 -0
  237. package/src/secure/transition.ts +488 -0
  238. package/src/secure/unit.ts +22 -0
  239. package/src/status.ts +16 -0
  240. package/src/version.ts +9 -0
  241. package/src/viewtree/anchor.tsx +105 -0
  242. package/src/viewtree/constants.ts +20 -0
  243. package/src/viewtree/fiber.ts +251 -0
  244. package/src/viewtree/requests.ts +347 -0
  245. package/src/viewtree/walk.ts +902 -0
  246. package/src/wrapper/channel.ts +33 -0
  247. package/src/wrapper/collect.ts +52 -0
  248. package/src/wrapper/events.ts +45 -0
  249. package/src/wrapper/identity.ts +54 -0
  250. package/src/wrapper/lifecycle-events.ts +89 -0
@@ -0,0 +1,902 @@
1
+ /**
2
+ * Turns a React fiber tree into a privacy-safe "managed view tree": a plain,
3
+ * serialisable description of what is on screen, with no text content and no
4
+ * prop other than `testID`/`nativeID` ever read off a fiber (and, per the
5
+ * plan's payload contract, `testID`/`nativeID` only on host nodes).
6
+ *
7
+ * Pure on purpose: no import of `react` or `react-native`. Everything this
8
+ * module needs to know about the host platform, the renderer and the two
9
+ * component identities it must treat specially (the secure boundary and the
10
+ * wrap component) arrives through `WalkEnv`, so this file is testable with
11
+ * nothing but plain objects (see `__tests__/fakeFibers.ts`) and stays true
12
+ * whether it is walking a fake tree or a real one.
13
+ *
14
+ * The walk itself is iterative (an explicit stack, not recursion): a fiber
15
+ * tree is untrusted input as far as this module is concerned (it did not
16
+ * build it), and a long transparent chain — thousands of Fragments, or a
17
+ * pathological `Suspense`/context nesting — must not exhaust the JS call
18
+ * stack the way naive recursion would. Cycles (a `.child` or `.sibling` that
19
+ * loops back on itself) are detected with a visited set rather than assumed
20
+ * away, and `.child`/`.sibling`/`.return` being `undefined` or some other
21
+ * non-object value is tolerated the same as `null` throughout.
22
+ */
23
+ import { MODAL_HOST_TYPE } from '../secure/surface';
24
+ import { FiberTag } from './fiber';
25
+ import type { FiberLike, WindowRect } from './fiber';
26
+
27
+ export const VH_WALK_BUDGET_MS = 250;
28
+ export const VH_MAX_NODES = 2000;
29
+ // React trees are deep: every composite (provider, navigator, screen wrapper)
30
+ // is a level. One Expo Router stack screen alone reached depth 59 before any
31
+ // app view, so Android's native cap of 64 cut whole screens. The walk is
32
+ // iterative and bounded by the node, visit and time budgets, so depth only
33
+ // guards the payload: 200 levels is about 405 levels of JSON nesting, below
34
+ // the 512 that some JSON parsers refuse.
35
+ export const VH_MAX_DEPTH = 200;
36
+ export const VH_TAG_MAX_LENGTH = 99;
37
+ export const VH_IOS_DECIMALS = 2;
38
+
39
+ // Not part of the public contract: a ceiling on the total number of fibers
40
+ // *visited* (emitted or not — Fragments, providers, HostText, wrappers...).
41
+ // Generous relative to VH_MAX_NODES, since most visited fibers are never
42
+ // emitted, but it exists so a pathological shape (a very long transparent
43
+ // chain, a wide fan-out, or either under a frozen `now()`) cannot make the
44
+ // walk do unbounded work even though it can no longer overflow the stack.
45
+ const VH_FIBER_VISIT_BUDGET = VH_MAX_NODES * 8;
46
+
47
+ // A defensive bound on `fiberRootOf`-adjacent list-walks this module itself
48
+ // does (see `hasVisibleContentChild`): never more than a sanity check on a
49
+ // sibling chain, so a cyclic `.sibling` there cannot hang either.
50
+ const SIBLING_PEEK_CAP = 10_000;
51
+
52
+ export interface ManagedNode {
53
+ id: string;
54
+ class_name: string;
55
+ bounds: [number, number, number, number];
56
+ options: {
57
+ kind: 'root' | 'surface' | 'composite' | 'host';
58
+ secure?: true;
59
+ tag?: string;
60
+ native_id?: string;
61
+ };
62
+ subitems?: ManagedNode[];
63
+ truncated?: true;
64
+ }
65
+
66
+ export interface WalkEnv {
67
+ measure(fiber: FiberLike): WindowRect | null;
68
+ /** True for the fiber that is the `<BugseeSecure>` boundary itself. */
69
+ isSecureBoundary(fiber: FiberLike): boolean;
70
+ /** True for the wrap component's own fiber, or the anchor it renders. */
71
+ isWrapper(fiber: FiberLike): boolean;
72
+ platform: 'android' | 'ios';
73
+ scale: number;
74
+ originX: number;
75
+ originY: number;
76
+ /**
77
+ * Display origin of the `<Modal>` whose host has React tag `surface`, when
78
+ * known. `measureInWindow` inside a Modal is relative to the Modal's own
79
+ * content, so its subtree must not take the request's origin. Asked at
80
+ * most once per Modal per walk; a `null` answer keeps the enclosing
81
+ * origin for that subtree.
82
+ */
83
+ originForSurface?: (surface: number) => Origin | null;
84
+ /** Native tag of a host fiber's public instance, when measurable. */
85
+ nativeTagOf?: (fiber: FiberLike) => number | null;
86
+ /** ms; the budget is measured from this function's first call. */
87
+ now(): number;
88
+ }
89
+
90
+ type Bounds = [number, number, number, number];
91
+
92
+ /** Where `measureInWindow`'s (0, 0) sits, in the units `bounds` are in. */
93
+ export interface Origin {
94
+ x: number;
95
+ y: number;
96
+ }
97
+
98
+ interface Ctx {
99
+ env: WalkEnv;
100
+ startedAt: number;
101
+ emittedCount: number;
102
+ fiberVisits: number;
103
+ /** Why doesn't matter beyond this: every stop, whatever tripped it, marks whichever fiber was mid-visit truncated the same way (see the payload contract — "depth, node cap or budget" are one case, not three). */
104
+ stopped: boolean;
105
+ /** Set the moment any node (host, composite, surface or root) is marked `truncated`, so the root can carry it too regardless of where it happened. */
106
+ anyTruncated: boolean;
107
+ /** Every fiber visited so far, across every root — a repeat means a cycle, not a legitimate second visit (a well-formed tree never revisits a fiber). */
108
+ visited: Set<FiberLike>;
109
+ /** Each `<Modal>` surface's origin for this walk, asked of `originForSurface` once. */
110
+ surfaceOrigins: Map<number, Origin | null>;
111
+ }
112
+
113
+ /** The children collected for one fiber (or one fiber root), plus whether that list is known to be incomplete. */
114
+ interface Frame {
115
+ nodes: ManagedNode[];
116
+ truncated: boolean;
117
+ }
118
+
119
+ type Task =
120
+ | { kind: 'visit'; fiber: FiberLike; secure: boolean; depthRemaining: number; frame: Frame; origin: Origin }
121
+ | {
122
+ kind: 'finishHost';
123
+ frame: Frame;
124
+ parentFrame: Frame;
125
+ className: string;
126
+ bounds: Bounds;
127
+ secureHere: boolean;
128
+ tagOpts: TagOpts;
129
+ depthCut: boolean;
130
+ }
131
+ | { kind: 'finishComposite'; frame: Frame; parentFrame: Frame; className: string; secureHere: boolean }
132
+ | { kind: 'finishFlatten'; frame: Frame; parentFrame: Frame };
133
+
134
+ type TagOpts = { tag?: string; native_id?: string };
135
+
136
+ function isObject(value: unknown): value is object {
137
+ return value !== null && typeof value === 'object';
138
+ }
139
+
140
+ /** Loose on purpose: a malformed fiber's link being `undefined` (or anything else non-object) ends a walk the same way `null` does. */
141
+ function linkOf(value: unknown): FiberLike | null {
142
+ return isObject(value) ? (value as unknown as FiberLike) : null;
143
+ }
144
+
145
+ function round2(value: number): number {
146
+ return Math.round(value * 100) / 100;
147
+ }
148
+
149
+ function androidBounds(rect: WindowRect, env: WalkEnv, originX: number, originY: number): Bounds {
150
+ return [
151
+ Math.round(rect.x * env.scale) + originX,
152
+ Math.round(rect.y * env.scale) + originY,
153
+ Math.round(rect.width * env.scale),
154
+ Math.round(rect.height * env.scale),
155
+ ];
156
+ }
157
+
158
+ function iosBounds(rect: WindowRect, env: WalkEnv, originX: number, originY: number): Bounds {
159
+ return [
160
+ round2(rect.x + originX),
161
+ round2(rect.y + originY),
162
+ round2(rect.width),
163
+ round2(rect.height),
164
+ ];
165
+ }
166
+
167
+ /**
168
+ * The origin `fiber`'s children are measured from: a `<Modal>` host starts a
169
+ * surface of its own (its subtree is relative to the Modal's content), every
170
+ * other fiber passes `origin` down unchanged. The Modal host itself is
171
+ * measured in its parent's surface, so its own bounds keep `origin`.
172
+ */
173
+ function childOriginOf(fiber: FiberLike, origin: Origin, ctx: Ctx): Origin {
174
+ if (!isModalHost(fiber)) {
175
+ return origin;
176
+ }
177
+ const { env } = ctx;
178
+ const tag = env.nativeTagOf?.(fiber) ?? null;
179
+ if (tag === null || env.originForSurface === undefined) {
180
+ return origin;
181
+ }
182
+ if (!ctx.surfaceOrigins.has(tag)) {
183
+ ctx.surfaceOrigins.set(tag, env.originForSurface(tag));
184
+ }
185
+ return ctx.surfaceOrigins.get(tag) ?? origin;
186
+ }
187
+
188
+ /** Whether `fiber` is a `<Modal>` host. A throwing `.type` getter is not one (`safeHostClassName` names it). */
189
+ function isModalHost(fiber: FiberLike): boolean {
190
+ try {
191
+ return fiber.type === MODAL_HOST_TYPE;
192
+ } catch {
193
+ return false;
194
+ }
195
+ }
196
+
197
+ function toBounds(rect: WindowRect, env: WalkEnv, origin: Origin): Bounds {
198
+ return env.platform === 'android'
199
+ ? androidBounds(rect, env, origin.x, origin.y)
200
+ : iosBounds(rect, env, origin.x, origin.y);
201
+ }
202
+
203
+ function unionBounds(boxes: readonly Bounds[], env: WalkEnv): Bounds {
204
+ // Every call site only builds a composite, surface or root node (and thus
205
+ // only ever calls this) once it already knows there is at least one child
206
+ // to draw bounds from, so `boxes` is never empty here.
207
+ const first = boxes[0] as Bounds;
208
+ let minX = first[0];
209
+ let minY = first[1];
210
+ let maxX = first[0] + first[2];
211
+ let maxY = first[1] + first[3];
212
+ for (let i = 1; i < boxes.length; i += 1) {
213
+ const box = boxes[i] as Bounds;
214
+ minX = Math.min(minX, box[0]);
215
+ minY = Math.min(minY, box[1]);
216
+ maxX = Math.max(maxX, box[0] + box[2]);
217
+ maxY = Math.max(maxY, box[1] + box[3]);
218
+ }
219
+ const bounds: Bounds = [minX, minY, maxX - minX, maxY - minY];
220
+ return env.platform === 'ios' ? (bounds.map(round2) as Bounds) : bounds;
221
+ }
222
+
223
+ /** `displayName`, then `name`, then `'Anonymous'` — never the fiber's props. */
224
+ function nameOf(candidate: unknown): string {
225
+ if (typeof candidate === 'function' || (typeof candidate === 'object' && candidate !== null)) {
226
+ const named = candidate as { displayName?: unknown; name?: unknown };
227
+ if (typeof named.displayName === 'string' && named.displayName.length > 0) {
228
+ return named.displayName;
229
+ }
230
+ if (typeof named.name === 'string' && named.name.length > 0) {
231
+ return named.name;
232
+ }
233
+ }
234
+ return 'Anonymous';
235
+ }
236
+
237
+ /** The object's own `displayName`, if it has a non-empty string one — `null` otherwise. Factored out of `preferOuterName` so a multi-level unwrap (`memo(forwardRef(fn))`, see `compositeClassName`) can check each level's own `displayName` before falling all the way through to the innermost function's `.name`. */
238
+ function displayNameOf(value: unknown): string | null {
239
+ if (typeof value === 'object' && value !== null) {
240
+ const displayName = (value as { displayName?: unknown }).displayName;
241
+ if (typeof displayName === 'string' && displayName.length > 0) {
242
+ return displayName;
243
+ }
244
+ }
245
+ return null;
246
+ }
247
+
248
+ /** A manually-set `displayName` on the outer (wrapper) object wins over the inner component's own name — the same preference `getComponentNameFromType` and DevTools use. */
249
+ function preferOuterName(outer: unknown, inner: unknown): string {
250
+ return displayNameOf(outer) ?? nameOf(inner);
251
+ }
252
+
253
+ /**
254
+ * ForwardRef and Memo/SimpleMemo unwrap to the component they wrap — but the
255
+ * two shapes React actually builds are different, verified against a real
256
+ * fiber tree (`__tests__/realFiberNaming.test.ts`) and against
257
+ * `updateMemoComponent`/`updateMemoComponent`'s SimpleMemo downgrade in the
258
+ * bundled renderer:
259
+ * - `ForwardRef` (11): `fiber.type` is the wrapper `{ $$typeof, render }`.
260
+ * - `Memo` (14): `fiber.type` is the wrapper `{ $$typeof, type, compare }` —
261
+ * React only downgrades a *plain-function, comparator-less* `memo(...)` to
262
+ * SimpleMemo; a class component, a custom `compare`, or `defaultProps`
263
+ * keeps the fiber at this tag, with the wrapped component on `.type.type`.
264
+ * - `SimpleMemo` (15): React reassigns `fiber.type` to the inner function
265
+ * *directly* the first time such a fiber renders; the memo wrapper itself
266
+ * survives only on `fiber.elementType`.
267
+ *
268
+ * `memo(forwardRef(fn))` (a very common React Native pattern) is a Memo
269
+ * fiber that does NOT downgrade (its wrapped type, a ForwardRef wrapper
270
+ * object, is not a plain function) — so `.type.type` is the ForwardRef
271
+ * wrapper `{ $$typeof, render }` itself, not `fn`. Left alone, naming that
272
+ * wrapper object the same way as any other "inner" value gives
273
+ * `'Anonymous'` (it has no `.name`, and usually no `.displayName` either).
274
+ * DevTools' own `resolveFiberType` unwraps this one level further, the same
275
+ * way it already unwraps a bare ForwardRef fiber, so this does too: any
276
+ * `displayName` set on the Memo wrapper wins first, then any `displayName`
277
+ * set on the ForwardRef wrapper itself, then finally `fn`'s own name.
278
+ */
279
+ function compositeClassName(fiber: FiberLike): string {
280
+ if (fiber.tag === FiberTag.ForwardRef) {
281
+ const render = (fiber.type as { render?: unknown } | null)?.render;
282
+ return preferOuterName(fiber.type, render);
283
+ }
284
+ if (fiber.tag === FiberTag.Memo) {
285
+ const inner = (fiber.type as { type?: unknown } | null)?.type;
286
+ if (typeof inner === 'object' && inner !== null && 'render' in inner) {
287
+ const render = (inner as { render?: unknown }).render;
288
+ return displayNameOf(fiber.type) ?? displayNameOf(inner) ?? nameOf(render);
289
+ }
290
+ return preferOuterName(fiber.type, inner);
291
+ }
292
+ if (fiber.tag === FiberTag.SimpleMemo) {
293
+ return preferOuterName(fiber.elementType, fiber.type);
294
+ }
295
+ return nameOf(fiber.type);
296
+ }
297
+
298
+ /**
299
+ * `compositeClassName` guarded against a throwing `displayName`/`name`/
300
+ * `render`/`type` getter anywhere along its (potentially multi-level) read
301
+ * path: falls back to `'Anonymous'` rather than losing the whole node (see
302
+ * `runWalk`'s per-fiber `try` for the rest of the "one throw drops only its
303
+ * own contribution" contract — this is the one call within it that gets its
304
+ * own dedicated fallback, per the review, rather than the generic one).
305
+ */
306
+ function safeCompositeClassName(fiber: FiberLike): string {
307
+ try {
308
+ return compositeClassName(fiber);
309
+ } catch {
310
+ return 'Anonymous';
311
+ }
312
+ }
313
+
314
+ /** Real host types are always strings (the native component name). Anything else is a malformed or hostile fiber, and `String(x)` would run an arbitrary `toString` this module has no business invoking. Also guarded against a throwing `.type` getter, same reasoning as `safeCompositeClassName`. */
315
+ function safeHostClassName(fiber: FiberLike): string {
316
+ try {
317
+ return typeof fiber.type === 'string' ? fiber.type : 'Unknown';
318
+ } catch {
319
+ return 'Unknown';
320
+ }
321
+ }
322
+
323
+ type Kind = 'host' | 'composite' | 'transparent';
324
+
325
+ function classify(tag: number): Kind {
326
+ switch (tag) {
327
+ case FiberTag.HostComponent:
328
+ return 'host';
329
+ case FiberTag.FunctionComponent:
330
+ case FiberTag.ClassComponent:
331
+ case FiberTag.ForwardRef:
332
+ case FiberTag.Memo:
333
+ case FiberTag.SimpleMemo:
334
+ return 'composite';
335
+ default:
336
+ // Fragment, Mode, ContextConsumer, ContextProvider, HostPortal,
337
+ // HostRoot, Profiler, Suspense: none of these are visual on their own,
338
+ // so their children are flattened into whichever ancestor node ends up
339
+ // containing them. Offscreen and LegacyHidden are handled before this
340
+ // is ever called (see `isHidden`).
341
+ return 'transparent';
342
+ }
343
+ }
344
+
345
+ /**
346
+ * Offscreen/LegacyHidden visibility is not a prop: React's own commit phase
347
+ * reads `memoizedState` for it (see `FiberLike.memoizedState`'s doc comment
348
+ * in `fiber.ts`) — hidden while it holds a `{ baseLanes, cachePool }` object,
349
+ * visible once it is `null` again. This never touches `memoizedProps`.
350
+ *
351
+ * Fails closed: `LegacyHidden` is an unstable, internal-only tag with no
352
+ * shape this module has verified against a real renderer, so it is always
353
+ * treated as hidden — privacy over completeness for a tag OSS React does not
354
+ * even expose. For `Offscreen`, anything other than exactly `null` (the one
355
+ * value React's own "visible" branch produces) is likewise treated as
356
+ * hidden, so an unrecognised future shape drops the subtree instead of
357
+ * showing it.
358
+ */
359
+ function isHidden(fiber: FiberLike): boolean {
360
+ if (fiber.tag === FiberTag.LegacyHidden) {
361
+ return true;
362
+ }
363
+ return fiber.memoizedState !== null;
364
+ }
365
+
366
+ /** Reads `testID`/`nativeID` and nothing else — the only props this module ever touches, only for host nodes (the plan's payload contract), and only when the node is not secure. Never throws: a throwing prop getter yields no tag, not a crashed walk. */
367
+ function tagOptions(fiber: FiberLike): TagOpts {
368
+ try {
369
+ const props = fiber.memoizedProps as { testID?: unknown; nativeID?: unknown } | null | undefined;
370
+ const out: TagOpts = {};
371
+ const testID = props?.testID;
372
+ if (typeof testID === 'string' && testID.length <= VH_TAG_MAX_LENGTH) {
373
+ out.tag = testID;
374
+ }
375
+ const nativeID = props?.nativeID;
376
+ if (typeof nativeID === 'string' && nativeID.length <= VH_TAG_MAX_LENGTH) {
377
+ out.native_id = nativeID;
378
+ }
379
+ return out;
380
+ } catch {
381
+ return {};
382
+ }
383
+ }
384
+
385
+ function safeNow(env: WalkEnv): number {
386
+ try {
387
+ // `Number.isFinite` (unlike the global `isFinite`) never coerces its
388
+ // argument — it is already `false` for anything that is not a plain
389
+ // finite number, including every non-number value, so a separate
390
+ // `typeof value === 'number'` guard ahead of it would only ever agree.
391
+ const value = env.now();
392
+ return Number.isFinite(value) ? value : 0;
393
+ } catch {
394
+ return 0;
395
+ }
396
+ }
397
+
398
+ function safeMeasure(env: WalkEnv, fiber: FiberLike): WindowRect | null {
399
+ try {
400
+ return env.measure(fiber);
401
+ } catch {
402
+ return null;
403
+ }
404
+ }
405
+
406
+ /**
407
+ * Fails closed (N2): a throwing `env.isSecureBoundary` is treated as though
408
+ * the boundary *is* there, not as though it were absent. This is the one
409
+ * `safe*` wrapper in this file whose failure mode does not default to "skip
410
+ * it" — every other guarded call degrades to a smaller payload (no tag, no
411
+ * measurement, not the wrapper), but defaulting *this* one to "not secure"
412
+ * would mean a throwing predicate leaks `testID`/`nativeID` from whatever is
413
+ * inside `<BugseeSecure>`, which is a privacy regression, not merely a
414
+ * smaller payload. Consistent with `isHidden`'s own fail-closed stance for
415
+ * Offscreen/LegacyHidden.
416
+ */
417
+ function safeIsSecureBoundary(env: WalkEnv, fiber: FiberLike): boolean {
418
+ try {
419
+ return env.isSecureBoundary(fiber);
420
+ } catch {
421
+ return true;
422
+ }
423
+ }
424
+
425
+ /**
426
+ * A throwing `env.isWrapper` is treated as "this is not the wrap component",
427
+ * which is the *opposite* failure direction from `safeIsSecureBoundary`
428
+ * above, deliberately: `isWrapper` decides whether to skip a node while
429
+ * still keeping its children (`pushFlatten`), never whether to withhold
430
+ * anything, so there is no privacy reason to fail toward "yes, treat this as
431
+ * the wrapper" — and doing so would be actively wrong, since the wrapper's
432
+ * *content* (the anchor's children) is the one thing the walk must not lose
433
+ * just because a predicate broke. Failing to `false` here means the fiber is
434
+ * simply emitted as a normal node instead — nothing is dropped, unlike a
435
+ * failure in `safeIsSecureBoundary`, where failing "open" would drop
436
+ * privacy protection instead of dropping data.
437
+ */
438
+ function safeIsWrapper(env: WalkEnv, fiber: FiberLike): boolean {
439
+ try {
440
+ return env.isWrapper(fiber);
441
+ } catch {
442
+ return false;
443
+ }
444
+ }
445
+
446
+ /**
447
+ * Whether a depth cut at `firstChild` would actually hide anything: a host
448
+ * whose only child is `HostText` (`<Text>plain string</Text>`, the common
449
+ * case) never emits that child anyway, so cutting it off is not a loss worth
450
+ * flagging. Only looks at `.tag` and `.sibling` — never `.child` (that would
451
+ * defeat the point of not recursing) and never a prop.
452
+ *
453
+ * Bounded and cycle-safe: an inconclusive walk (a cyclic or implausibly long
454
+ * sibling chain) reports "yes, something real might be there" rather than
455
+ * silently swallowing a truncation that may be genuine.
456
+ */
457
+ function hasVisibleContentChild(firstChild: FiberLike): boolean {
458
+ const seen = new Set<FiberLike>();
459
+ let child: FiberLike | null = firstChild;
460
+ let steps = 0;
461
+ while (child !== null) {
462
+ if (steps >= SIBLING_PEEK_CAP || seen.has(child)) {
463
+ return true;
464
+ }
465
+ seen.add(child);
466
+ if (child.tag !== FiberTag.HostText) {
467
+ return true;
468
+ }
469
+ child = linkOf(child.sibling);
470
+ steps += 1;
471
+ }
472
+ return false;
473
+ }
474
+
475
+ function checkStop(ctx: Ctx): boolean {
476
+ if (ctx.stopped) {
477
+ return true;
478
+ }
479
+ const overTimeBudget = safeNow(ctx.env) - ctx.startedAt > VH_WALK_BUDGET_MS;
480
+ const overNodeBudget = ctx.emittedCount >= VH_MAX_NODES;
481
+ const overFiberVisitBudget = ctx.fiberVisits > VH_FIBER_VISIT_BUDGET;
482
+ if (overTimeBudget || overNodeBudget || overFiberVisitBudget) {
483
+ ctx.stopped = true;
484
+ return true;
485
+ }
486
+ return false;
487
+ }
488
+
489
+ // Every node's real `id` is assigned by `renumberPreorder`, unconditionally,
490
+ // once the whole tree is built — nothing before that point reads a node's
491
+ // `id`, so `makeNode` never takes one; it always starts a node off with this
492
+ // same placeholder, which final id it ends up with is simply not this
493
+ // function's concern.
494
+ const PLACEHOLDER_ID = '';
495
+
496
+ function makeNode(
497
+ className: string,
498
+ kind: ManagedNode['options']['kind'],
499
+ bounds: Bounds,
500
+ secure: boolean,
501
+ tagOpts: TagOpts,
502
+ children: ManagedNode[],
503
+ truncated: boolean,
504
+ ctx: Ctx,
505
+ ): ManagedNode {
506
+ const options: ManagedNode['options'] = { kind };
507
+ if (secure) {
508
+ options.secure = true;
509
+ } else {
510
+ if (tagOpts.tag !== undefined) {
511
+ options.tag = tagOpts.tag;
512
+ }
513
+ if (tagOpts.native_id !== undefined) {
514
+ options.native_id = tagOpts.native_id;
515
+ }
516
+ }
517
+ const node: ManagedNode = { id: PLACEHOLDER_ID, class_name: className, bounds, options };
518
+ if (children.length > 0) {
519
+ node.subitems = children;
520
+ }
521
+ if (truncated) {
522
+ node.truncated = true;
523
+ ctx.anyTruncated = true;
524
+ }
525
+ return node;
526
+ }
527
+
528
+ /** Pushes the work to flatten `fiber`'s children directly into `parentFrame` — used for every "this fiber emits nothing of its own" case (transparent tags, the wrap component/anchor, a visible Offscreen/LegacyHidden, and an unmeasurable host promoting its children per the plan's "no measurable host" rule). */
529
+ function pushFlatten(
530
+ stack: Task[],
531
+ fiber: FiberLike,
532
+ secure: boolean,
533
+ depthRemaining: number,
534
+ parentFrame: Frame,
535
+ origin: Origin,
536
+ ): void {
537
+ const child = linkOf(fiber.child);
538
+ if (child === null) {
539
+ return;
540
+ }
541
+ const frame: Frame = { nodes: [], truncated: false };
542
+ stack.push({ kind: 'finishFlatten', frame, parentFrame });
543
+ stack.push({ kind: 'visit', fiber: child, secure, depthRemaining, frame, origin });
544
+ }
545
+
546
+ /**
547
+ * Walks every fiber reachable from `rootFiber` (its siblings included, so it
548
+ * can be called directly on what a fiber root's `.current` is), collecting
549
+ * emitted nodes into `outerFrame`. Iterative: an explicit stack instead of
550
+ * recursion, so neither a long transparent chain nor a cycle can exhaust the
551
+ * JS call stack or loop forever.
552
+ */
553
+ function runWalk(rootFiber: FiberLike, ctx: Ctx, outerFrame: Frame): void {
554
+ const rootOrigin: Origin = { x: ctx.env.originX, y: ctx.env.originY };
555
+ const stack: Task[] = [
556
+ { kind: 'visit', fiber: rootFiber, secure: false, depthRemaining: VH_MAX_DEPTH, frame: outerFrame, origin: rootOrigin },
557
+ ];
558
+
559
+ while (stack.length > 0) {
560
+ const task = stack.pop() as Task;
561
+
562
+ if (task.kind === 'finishFlatten') {
563
+ task.parentFrame.nodes.push(...task.frame.nodes);
564
+ task.parentFrame.truncated = task.parentFrame.truncated || task.frame.truncated;
565
+ continue;
566
+ }
567
+
568
+ if (task.kind === 'finishHost') {
569
+ const truncatedHere = task.depthCut || task.frame.truncated;
570
+ const node = makeNode(task.className, 'host', task.bounds, task.secureHere, task.tagOpts, task.frame.nodes, truncatedHere, ctx);
571
+ task.parentFrame.nodes.push(node);
572
+ continue;
573
+ }
574
+
575
+ if (task.kind === 'finishComposite') {
576
+ if (task.frame.nodes.length === 0) {
577
+ // Nothing measurable under this composite (or a depth cut that never
578
+ // got to recurse at all): it contributes no node of its own, so
579
+ // whatever was cut bubbles to whichever ancestor DOES get emitted,
580
+ // instead of being reported on a composite that was never there.
581
+ task.parentFrame.truncated = task.parentFrame.truncated || task.frame.truncated;
582
+ continue;
583
+ }
584
+ const node = makeNode(
585
+ task.className,
586
+ 'composite',
587
+ unionBounds(
588
+ task.frame.nodes.map((n) => n.bounds),
589
+ ctx.env,
590
+ ),
591
+ task.secureHere,
592
+ {},
593
+ task.frame.nodes,
594
+ task.frame.truncated,
595
+ ctx,
596
+ );
597
+ task.parentFrame.nodes.push(node);
598
+ continue;
599
+ }
600
+
601
+ // Exhaustive given `Task`'s declared shape: 'finishFlatten', 'finishHost'
602
+ // and 'finishComposite' are handled (and `continue`d past) above,
603
+ // leaving only 'visit' — checked explicitly, rather than assumed by
604
+ // falling through, so a `Task` built with any other `kind` is caught
605
+ // here instead of silently being treated as a fiber to visit.
606
+ if ((task as { kind: unknown }).kind !== 'visit') {
607
+ throw new Error('unreachable view-tree task kind');
608
+ }
609
+ const { fiber, secure, depthRemaining, frame, origin } = task;
610
+
611
+ // N5 (fix round 2): everything from here on reads fields off `fiber`
612
+ // itself — `.tag`, `.sibling`, `.child`, `.type`, `.elementType`,
613
+ // `.memoizedState`, and (inside `safeCompositeClassName`/`nameOf`) a
614
+ // `displayName`/`name`/`render` getter one or two levels down. A fiber
615
+ // tree is untrusted input (this module did not build it), so any one of
616
+ // those can be a throwing getter without the whole walk being allowed to
617
+ // die for it. This `try` is scoped to exactly one fiber's own visit: if
618
+ // it throws, only THIS fiber's contribution is lost (`frame.truncated`
619
+ // is set on the frame it would have contributed to, and the loop moves
620
+ // on) — every sibling already pushed, and every ancestor's pending
621
+ // `finish*` task lower on the stack, is unaffected and still runs
622
+ // normally afterward. `safeCompositeClassName`/`safeHostClassName`
623
+ // additionally catch their own, narrower throw first, so a bad
624
+ // `displayName` alone degrades to `'Anonymous'`/`'Unknown'` on an
625
+ // otherwise-normal node instead of losing the node at all — this outer
626
+ // `try` is the backstop for everything neither of those, nor
627
+ // `safeMeasure`/`safeIsSecureBoundary`/`safeIsWrapper`/`tagOptions`
628
+ // (each already self-guarded), catches on its own.
629
+ try {
630
+ if (ctx.visited.has(fiber)) {
631
+ // A repeat visit only happens via a `.child`/`.sibling` cycle in a
632
+ // well-formed walk (nothing legitimate revisits the same fiber): stop
633
+ // this path rather than loop forever, and say so.
634
+ frame.truncated = true;
635
+ continue;
636
+ }
637
+ ctx.visited.add(fiber);
638
+
639
+ // The sibling chain continues after this fiber (and everything it
640
+ // produces) is fully resolved — pushed now, ahead of whatever this
641
+ // fiber itself pushes next, so the LIFO stack only reaches it once
642
+ // this fiber's own subtree is done. Skipped once the walk has already
643
+ // stopped (a budget tripped by an earlier fiber): pushing it would
644
+ // only have it immediately self-terminate via `checkStop` the moment
645
+ // it is popped, one sibling at a time — checking here instead drops
646
+ // the whole remaining sibling chain in one step, not `O(siblings)`.
647
+ // Not marking `frame.truncated` here on the skip: `checkStop(ctx)`,
648
+ // two lines below, already returns `true` immediately whenever
649
+ // `ctx.stopped` is set (its very first check), which marks this same
650
+ // `frame` truncated for THIS fiber regardless — doing it here too
651
+ // would only be the identical write a second time, not a different
652
+ // outcome for anything this walk produces.
653
+ const sibling = linkOf(fiber.sibling);
654
+ if (sibling !== null && !ctx.stopped) {
655
+ stack.push({ kind: 'visit', fiber: sibling, secure, depthRemaining, frame, origin });
656
+ }
657
+
658
+ ctx.fiberVisits += 1;
659
+ if (checkStop(ctx)) {
660
+ frame.truncated = true;
661
+ continue;
662
+ }
663
+
664
+ if (fiber.tag === FiberTag.HostText) {
665
+ continue;
666
+ }
667
+
668
+ const secureHere = secure || safeIsSecureBoundary(ctx.env, fiber);
669
+
670
+ if (safeIsWrapper(ctx.env, fiber)) {
671
+ pushFlatten(stack, fiber, secureHere, depthRemaining, frame, origin);
672
+ continue;
673
+ }
674
+
675
+ if (fiber.tag === FiberTag.Offscreen || fiber.tag === FiberTag.LegacyHidden) {
676
+ if (isHidden(fiber)) {
677
+ continue;
678
+ }
679
+ pushFlatten(stack, fiber, secureHere, depthRemaining, frame, origin);
680
+ continue;
681
+ }
682
+
683
+ const kind = classify(fiber.tag);
684
+
685
+ if (kind === 'transparent') {
686
+ pushFlatten(stack, fiber, secureHere, depthRemaining, frame, origin);
687
+ continue;
688
+ }
689
+
690
+ if (kind === 'host') {
691
+ const childOrigin = childOriginOf(fiber, origin, ctx);
692
+ const rect = safeMeasure(ctx.env, fiber);
693
+ if (rect === null) {
694
+ // No measurable host here — promote whatever children it has
695
+ // (as if this fiber were transparent) rather than dropping a
696
+ // subtree that might still have something to show underneath.
697
+ pushFlatten(stack, fiber, secureHere, depthRemaining, frame, childOrigin);
698
+ continue;
699
+ }
700
+
701
+ ctx.emittedCount += 1;
702
+
703
+ const child = linkOf(fiber.child);
704
+ const atDepthLimit = child !== null && depthRemaining <= 1;
705
+ const depthCut = atDepthLimit && hasVisibleContentChild(child as FiberLike);
706
+ const bounds = toBounds(rect, ctx.env, origin);
707
+ const tagOpts = secureHere ? {} : tagOptions(fiber);
708
+ const className = safeHostClassName(fiber);
709
+
710
+ if (child !== null && !atDepthLimit) {
711
+ const childFrame: Frame = { nodes: [], truncated: false };
712
+ stack.push({ kind: 'finishHost', frame: childFrame, parentFrame: frame, className, bounds, secureHere, tagOpts, depthCut: false });
713
+ stack.push({
714
+ kind: 'visit',
715
+ fiber: child,
716
+ secure: secureHere,
717
+ depthRemaining: depthRemaining - 1,
718
+ frame: childFrame,
719
+ origin: childOrigin,
720
+ });
721
+ } else {
722
+ stack.push({
723
+ kind: 'finishHost',
724
+ frame: { nodes: [], truncated: false },
725
+ parentFrame: frame,
726
+ className,
727
+ bounds,
728
+ secureHere,
729
+ tagOpts,
730
+ depthCut,
731
+ });
732
+ }
733
+ continue;
734
+ }
735
+
736
+ if (kind === 'composite') {
737
+ ctx.emittedCount += 1;
738
+
739
+ const child = linkOf(fiber.child);
740
+ const atDepthLimit = child !== null && depthRemaining <= 1;
741
+ const depthCut = atDepthLimit && hasVisibleContentChild(child as FiberLike);
742
+ const className = safeCompositeClassName(fiber);
743
+
744
+ if (child !== null && !atDepthLimit) {
745
+ const childFrame: Frame = { nodes: [], truncated: false };
746
+ stack.push({ kind: 'finishComposite', frame: childFrame, parentFrame: frame, className, secureHere });
747
+ stack.push({ kind: 'visit', fiber: child, secure: secureHere, depthRemaining: depthRemaining - 1, frame: childFrame, origin });
748
+ } else {
749
+ stack.push({
750
+ kind: 'finishComposite',
751
+ frame: { nodes: [], truncated: depthCut },
752
+ parentFrame: frame,
753
+ className,
754
+ secureHere,
755
+ });
756
+ }
757
+ continue;
758
+ }
759
+
760
+ // Exhaustive given `classify`'s declared return type: 'transparent' is
761
+ // handled above, leaving only 'host' and 'composite'. Reached only if
762
+ // a change to `classify` stops honouring that.
763
+ throw new Error('unreachable view-tree fiber kind');
764
+ } catch {
765
+ frame.truncated = true;
766
+ continue;
767
+ }
768
+ }
769
+ }
770
+
771
+ /** Renumbers every node's `id` to its preorder index in the final, already-emitted tree — decoupled from however many candidate fibers were visited and dropped along the way, so ids stay gap-free ("0" for the root, then depth-first) as the plan requires. */
772
+ function renumberPreorder(root: ManagedNode): void {
773
+ let counter = 0;
774
+ const visit = (node: ManagedNode): void => {
775
+ node.id = String(counter);
776
+ counter += 1;
777
+ if (node.subitems) {
778
+ for (const child of node.subitems) {
779
+ visit(child);
780
+ }
781
+ }
782
+ };
783
+ visit(root);
784
+ }
785
+
786
+ /**
787
+ * Builds the single "ReactNative" root of the managed view tree, with one
788
+ * "ReactSurface" child per fiber root that has anything measurable under it.
789
+ * Returns null when nothing was emitted at all (nothing mounted, nothing
790
+ * measurable, or every root was empty) — including the one case this cannot
791
+ * distinguish from that: an all-composite chain cut off past `VH_MAX_DEPTH`
792
+ * with no host anywhere in it. There is no node left to *carry* `truncated`
793
+ * in that case (every composite in the chain contributes nothing of its own
794
+ * and bubbles the cut further up, all the way past the root), and inventing
795
+ * a placeholder node just to hold the flag would mean fabricating a `bounds`
796
+ * rectangle with nothing real to draw it from — worse than the information
797
+ * loss it would be covering for. `depth truncation on an all-composite chain
798
+ * drops content well past VH_MAX_DEPTH` (`walk.test.ts`) pins this as
799
+ * accepted, known behaviour rather than an untested gap.
800
+ *
801
+ * Never throws, even on hostile input (not just a malformed-but-plain fiber
802
+ * tree): every call out to `env` and into a fiber's own props/type/name is
803
+ * individually guarded (see `safeMeasure`/`safeIsSecureBoundary`/
804
+ * `safeIsWrapper`/`tagOptions`/`safeHostClassName`/`safeCompositeClassName`,
805
+ * and `runWalk`'s own per-fiber `try`, which keeps one throwing fiber from
806
+ * losing more than its own contribution). What is left here is the outer
807
+ * backstop per root — covering `root.current` itself, read inside this
808
+ * `try`, not before it — for whatever none of those anticipated; a root that
809
+ * still hits something unanticipated is reported truncated instead of
810
+ * losing the whole tree (the other roots, and whatever that root already
811
+ * emitted before the throw, still stand).
812
+ */
813
+ export function buildViewTree(roots: readonly { current: FiberLike }[], env: WalkEnv): ManagedNode | null {
814
+ const ctx: Ctx = {
815
+ env,
816
+ startedAt: safeNow(env),
817
+ emittedCount: 0,
818
+ fiberVisits: 0,
819
+ stopped: false,
820
+ anyTruncated: false,
821
+ visited: new Set<FiberLike>(),
822
+ surfaceOrigins: new Map<number, Origin | null>(),
823
+ };
824
+
825
+ const surfaces: ManagedNode[] = [];
826
+
827
+ // Reserved up front, not as each is committed: the root and every surface
828
+ // are ancestors open for the whole walk beneath them, exactly the case
829
+ // that let the node cap overshoot when only emitted nodes were counted,
830
+ // post hoc, as `makeNode` ran.
831
+ ctx.emittedCount += 1 + roots.length;
832
+
833
+ for (const root of roots) {
834
+ if (!isObject(root)) {
835
+ continue;
836
+ }
837
+
838
+ const frame: Frame = { nodes: [], truncated: false };
839
+ try {
840
+ // Reading `.current` inside the `try` too, not just calling `runWalk`
841
+ // (N5/I6(a)): a throwing `.current` getter, or `root` itself being a
842
+ // revoked `Proxy`, used to escape this function uncaught — the same
843
+ // "never throws even on hostile input" gap `fiberRootOf` had before
844
+ // N1. `runWalk` no longer needs a broad defence of its own for
845
+ // anything fiber-shaped: every fiber-field read inside it is now
846
+ // individually guarded, most of them narrowly enough that only the
847
+ // one fiber that broke loses its own contribution rather than the
848
+ // whole root (see `runWalk`'s per-fiber `try`). What remains here is
849
+ // the outer backstop for `.current` itself and for whatever neither
850
+ // of those anticipated — a `linkOf(...) === null` (a legitimately
851
+ // absent or malformed root) is not an error and does not enter it.
852
+ const rootFiber = linkOf((root as { current?: unknown }).current);
853
+ if (rootFiber !== null) {
854
+ runWalk(rootFiber, ctx, frame);
855
+ }
856
+ } catch {
857
+ frame.truncated = true;
858
+ }
859
+
860
+ if (frame.nodes.length === 0) {
861
+ if (frame.truncated) {
862
+ ctx.anyTruncated = true;
863
+ }
864
+ continue;
865
+ }
866
+
867
+ const surface = makeNode(
868
+ 'ReactSurface',
869
+ 'surface',
870
+ unionBounds(
871
+ frame.nodes.map((n) => n.bounds),
872
+ env,
873
+ ),
874
+ false,
875
+ {},
876
+ frame.nodes,
877
+ frame.truncated,
878
+ ctx,
879
+ );
880
+ surfaces.push(surface);
881
+ }
882
+
883
+ if (surfaces.length === 0) {
884
+ return null;
885
+ }
886
+
887
+ const root = makeNode(
888
+ 'ReactNative',
889
+ 'root',
890
+ unionBounds(
891
+ surfaces.map((s) => s.bounds),
892
+ env,
893
+ ),
894
+ false,
895
+ {},
896
+ surfaces,
897
+ ctx.stopped || ctx.anyTruncated,
898
+ ctx,
899
+ );
900
+ renumberPreorder(root);
901
+ return root;
902
+ }