@scalebun/react-native 2.0.0 → 2.0.1

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 (70) hide show
  1. package/android/src/main/java/com/scalebun/rn/ota/BundleDownloader.kt +10 -0
  2. package/android/src/main/java/com/scalebun/rn/ota/DeviceIntegrity.kt +75 -0
  3. package/android/src/main/java/com/scalebun/rn/ota/ScaleBunOtaModule.kt +18 -3
  4. package/android/src/main/java/com/scalebun/rn/ota/SlotManager.kt +62 -1
  5. package/android/src/main/java/com/scalebun/rn/ota/TlsPinning.kt +118 -0
  6. package/android/src/oldarch/java/com/scalebun/rn/ota/ScaleBunOtaSpec.kt +2 -0
  7. package/dist/scalebun.full.js +840 -114
  8. package/dist/scalebun.slim.js +838 -112
  9. package/ios/ReplaySdk.swift +65 -2
  10. package/lib/commonjs/bootstrap/SDKBootstrapper.js +30 -0
  11. package/lib/commonjs/core/config/schema.js +16 -0
  12. package/lib/commonjs/core/constants/version.js +1 -1
  13. package/lib/commonjs/features/journey/ScaleBunDebugRoot.js +293 -5
  14. package/lib/commonjs/features/journey/ScaleBunScrollView.js +28 -0
  15. package/lib/commonjs/features/journey/autoInstrumentScroll.js +161 -0
  16. package/lib/commonjs/features/journey/interactionProtocol.js +131 -10
  17. package/lib/commonjs/features/journey/scrollContext.js +146 -0
  18. package/lib/commonjs/features/journey/targetGeometry.js +164 -0
  19. package/lib/commonjs/features/journey/touchTarget.js +152 -24
  20. package/lib/commonjs/features/journey/uiState.js +81 -1
  21. package/lib/commonjs/features/navigation/AutoScreenDetector.js +74 -5
  22. package/lib/commonjs/features/ota/OtaOrchestrator.js +69 -22
  23. package/lib/commonjs/features/session/SessionManager.js +63 -0
  24. package/lib/commonjs/public/ScaleBunFacade.js +18 -16
  25. package/lib/module/bootstrap/SDKBootstrapper.js +30 -0
  26. package/lib/module/core/config/schema.js +16 -0
  27. package/lib/module/core/constants/version.js +1 -1
  28. package/lib/module/features/journey/ScaleBunDebugRoot.js +295 -7
  29. package/lib/module/features/journey/ScaleBunScrollView.js +28 -0
  30. package/lib/module/features/journey/autoInstrumentScroll.js +155 -0
  31. package/lib/module/features/journey/interactionProtocol.js +128 -8
  32. package/lib/module/features/journey/scrollContext.js +135 -0
  33. package/lib/module/features/journey/targetGeometry.js +155 -0
  34. package/lib/module/features/journey/touchTarget.js +151 -24
  35. package/lib/module/features/journey/uiState.js +78 -1
  36. package/lib/module/features/navigation/AutoScreenDetector.js +74 -5
  37. package/lib/module/features/ota/OtaOrchestrator.js +69 -22
  38. package/lib/module/features/session/SessionManager.js +63 -0
  39. package/lib/module/public/ScaleBunFacade.js +18 -16
  40. package/lib/typescript/core/config/schema.d.ts +2 -0
  41. package/lib/typescript/core/constants/version.d.ts +1 -1
  42. package/lib/typescript/features/journey/autoInstrumentScroll.d.ts +46 -0
  43. package/lib/typescript/features/journey/interactionProtocol.d.ts +139 -1
  44. package/lib/typescript/features/journey/scrollContext.d.ts +85 -0
  45. package/lib/typescript/features/journey/targetGeometry.d.ts +114 -0
  46. package/lib/typescript/features/journey/touchTarget.d.ts +148 -15
  47. package/lib/typescript/features/journey/uiState.d.ts +39 -0
  48. package/lib/typescript/features/navigation/AutoScreenDetector.d.ts +48 -2
  49. package/lib/typescript/features/ota/OtaOrchestrator.d.ts +7 -0
  50. package/lib/typescript/features/session/SessionManager.d.ts +55 -0
  51. package/lib/typescript/public/types.d.ts +10 -0
  52. package/lib/typescript/specs/NativeScaleBunOta.d.ts +2 -0
  53. package/package.json +2 -2
  54. package/src/bootstrap/SDKBootstrapper.ts +40 -0
  55. package/src/core/config/schema.ts +18 -0
  56. package/src/core/constants/version.ts +1 -1
  57. package/src/features/journey/ScaleBunDebugRoot.tsx +288 -7
  58. package/src/features/journey/ScaleBunScrollView.tsx +29 -0
  59. package/src/features/journey/autoInstrumentScroll.ts +155 -0
  60. package/src/features/journey/interactionProtocol.ts +188 -10
  61. package/src/features/journey/scrollContext.ts +137 -0
  62. package/src/features/journey/targetGeometry.ts +176 -0
  63. package/src/features/journey/touchTarget.ts +237 -26
  64. package/src/features/journey/uiState.ts +80 -1
  65. package/src/features/navigation/AutoScreenDetector.ts +65 -5
  66. package/src/features/ota/OtaOrchestrator.ts +76 -22
  67. package/src/features/session/SessionManager.ts +113 -0
  68. package/src/public/ScaleBunFacade.ts +18 -16
  69. package/src/public/types.ts +10 -0
  70. package/src/specs/NativeScaleBunOta.ts +3 -0
@@ -9,29 +9,165 @@
9
9
  * WHY THE FIBER. There is no DOM. The only place a tapped view's identity exists in JS is the React
10
10
  * fiber hanging off the touch event (`_targetInst`), which carries `memoizedProps` — where
11
11
  * `accessibilityLabel` and `testID` live. This is a React internal, so every access is defensive and
12
- * the whole thing degrades to `null` rather than throwing: a analytics label is never worth a crash.
12
+ * the whole thing degrades to `null` rather than throwing: an analytics label is never worth a crash.
13
13
  *
14
- * IDENTITY PREFERENCE, strongest first:
15
- * 1. `accessibilityLabel`authored to describe the control, and already required for a11y.
16
- * 2. `testID` — authored to identify the control, stable across copy changes.
17
- * 3. a literal string child — the button's visible caption.
18
- * 4. the nearest named component — coarse, but far better than nothing.
14
+ * ─────────────────────────────────────────────────────────────────────────────────────────────
15
+ * RN-2THE IDENTITY LADDER USED TO CAPTURE USER TEXT, AND THAT IS A PRIVACY DEFECT, NOT A
16
+ * TRADE-OFF.
17
+ *
18
+ * The previous preference order was:
19
+ *
20
+ * 1. accessibilityLabel 2. testID 3. a literal string child 4. nearest component
21
+ *
22
+ * Ranks 1 and 3 are FREE TEXT authored for humans, and in a real app they routinely contain user
23
+ * data. An accessible order row is labelled "Order 1042 for mohamed@scalebun.com". A pay button
24
+ * reads "Pay EGP 1,442". A contact row's caption is a person's name. Rank 1 was preferred over
25
+ * `testID`, so the leakiest source won whenever it existed.
26
+ *
27
+ * Two separate harms, and the second is easy to miss:
28
+ *
29
+ * PRIVACY. `describeTouchTarget`'s output is persisted as the interaction's `target`. So names,
30
+ * email addresses and amounts were being written into an analytics store, under a field nobody
31
+ * would think to audit for PII. The same product already found 27 rows in `replay_events`
32
+ * carrying email addresses through a different route; this was a second one.
33
+ *
34
+ * CORRECTNESS. `target` is an AGGREGATION KEY. Keyed on text that varies per user, a single
35
+ * button produces one bucket per person — so the grouping this feature exists to provide is
36
+ * destroyed precisely in the screens that matter most. A leaky key is also a useless key.
37
+ *
38
+ * SO THE LADDER IS NOW DERIVED FROM CODE, NEVER FROM CONTENT:
39
+ *
40
+ * 1. `testID` — authored to identify, stable across copy edits, and by convention never
41
+ * user data. The strongest signal and now the first.
42
+ * 2. `path` — the component-name chain from the tapped node upward, e.g.
43
+ * `CartScreen>OrderRow>Pressable`. Structural: it changes when the code
44
+ * changes, not when the data does. This is what makes the ladder useful in
45
+ * the overwhelming majority of apps, which have no testIDs — without it,
46
+ * removing free text would have meant removing identity.
47
+ * 3. `component` — the nearest named component alone. Coarse, but a code identifier.
48
+ *
49
+ * Free text is still RESOLVABLE, because a team that has audited its own labels may legitimately
50
+ * want them, but it is opt-in per call (`includeText`) and it is NEVER what
51
+ * `describeTouchTarget` returns. Default-off matters more than the option: a default that leaks
52
+ * is a leak, whatever the documentation says.
53
+ *
54
+ * WHY THIS SHIPS WITH RN-1 (persistence) RATHER THAN AFTER IT. RN-1 makes the resolved target
55
+ * actually reach the backend. Landing that first would persist the leaky ladder and create a
56
+ * historical PII problem to clean up; landing the sanitised ladder first and persistence second
57
+ * leaves a window where the feature looks broken. They are one change.
58
+ * ─────────────────────────────────────────────────────────────────────────────────────────────
19
59
  */
20
60
 
21
61
  export interface TouchTarget {
22
- accessibilityLabel?: string;
62
+ /** Authored identifier. Safe to persist and to aggregate on. */
23
63
  testID?: string;
24
- text?: string;
64
+ /**
65
+ * Structural path of component names, tapped node first, e.g. `Pressable<OrderRow<CartScreen`.
66
+ * Derived from the code's shape, so it never contains user data.
67
+ */
68
+ path?: string;
69
+ /** Nearest named component. A code identifier, safe. */
25
70
  component?: string;
71
+ /**
72
+ * FREE TEXT — may contain user data. Populated ONLY when `includeText` is requested, and never
73
+ * returned by `describeTouchTarget`. Treat as unsafe to persist without an audit.
74
+ */
75
+ accessibilityLabel?: string;
76
+ /** FREE TEXT — the visible caption. Same warning as `accessibilityLabel`. */
77
+ text?: string;
78
+ /**
79
+ * RN-13 — the host node the IDENTITY was taken from, so a rect read off it describes the
80
+ * same element the tap was attributed to.
81
+ *
82
+ * This is the reason the node is captured during the identity walk rather than by a second,
83
+ * independent walk: two walks can disagree about which ancestor is "the control", and a rect
84
+ * belonging to a different element than the name is worse than no rect at all — it would make
85
+ * `heat ∈ target` answer confidently about the wrong box.
86
+ *
87
+ * Deliberately NOT serialisable and never persisted. Callers read a rectangle off it and
88
+ * discard it; nothing downstream should hold a React internal.
89
+ */
90
+ node?: unknown;
91
+ /**
92
+ * RN-3 — every ancestor host instance from the tapped node upward, INNERMOST FIRST.
93
+ *
94
+ * Collected on the identity walk rather than by a second traversal, for the same reason the
95
+ * rect's node is: two walks can disagree about the chain, and attributing a tap to the wrong
96
+ * scroller's offset places it by how far a DIFFERENT container had scrolled. Order is the
97
+ * contract — `nearestRecordedOffset` takes the first ancestor that has an offset, because that
98
+ * is the scroller the content under the finger actually moved with.
99
+ *
100
+ * Like `node`, these are React internals: read a native tag off them and discard.
101
+ */
102
+ ancestors?: unknown[];
103
+ /**
104
+ * RN-4 — the list row's own identity, for FREE.
105
+ *
106
+ * MEASURED BEFORE IT WAS DESIGNED, because the obvious fix was to make every app author a
107
+ * testID per row and that would have been a large, permanent burden on every integration. It is
108
+ * unnecessary. React Native's `VirtualizedList` builds each cell as
109
+ *
110
+ * const key = VirtualizedList._keyExtractor(item, ii, this.props); // line 797
111
+ * <CellRenderer cellKey={key} index={ii} key={key} ... /> // line 817
112
+ *
113
+ * so the app's OWN `keyExtractor` output — which every correct list already provides, because
114
+ * React requires keys — sits on the cell fiber as an ordinary prop. The walk that resolves
115
+ * identity already passes that fiber and simply never read it.
116
+ *
117
+ * `cellKey` is preferred over the fiber's `key` field: it is the same value, but reached
118
+ * through `memoizedProps` like every other prop this module reads, rather than through a React
119
+ * internal whose exposure is not part of any contract.
120
+ *
121
+ * WHY THIS MATTERS MORE THAN AN ORDINARY LABEL. A virtualised list REUSES native views: row 40
122
+ * scrolls into the view row 1 vacated. Without the cell key those two taps share a native
123
+ * identity and a screen position, so they merge — one hotspot on a row nobody in particular
124
+ * tapped. `itemIndex` is carried alongside precisely so the recycling is visible: the same index
125
+ * with a different key is a recycled slot, and that is a fact worth being able to prove rather
126
+ * than infer.
127
+ */
128
+ itemKey?: string;
129
+ /** The cell's position in the list at render time. See `itemKey` for why both are kept. */
130
+ itemIndex?: number;
131
+ }
132
+
133
+ /** Where a resolved identity came from — so a consumer can tell an authored id from a guess. */
134
+ export type TargetIdentitySource = 'testID' | 'path' | 'component' | 'none';
135
+
136
+ export interface ResolveTouchTargetOptions {
137
+ /** How far up the tree to look. */
138
+ maxDepth?: number;
139
+ /**
140
+ * Collect `accessibilityLabel` and the visible caption.
141
+ *
142
+ * OFF BY DEFAULT AND MEANT TO STAY THAT WAY. Turning it on means user-authored text may be
143
+ * carried out of the app, so it belongs to a team that has audited its own labels — not to a
144
+ * default. Even when on, the text is never used as the identity.
145
+ */
146
+ includeText?: boolean;
26
147
  }
27
148
 
28
149
  /** How far up the tree to look before giving up. Deep enough for a wrapped button, cheap enough to run on every tap. */
29
150
  const MAX_DEPTH = 12;
30
151
  /** Labels longer than this are truncated — a caption, not a paragraph. */
31
152
  const MAX_LEN = 60;
153
+ /**
154
+ * How many component names the structural path may hold.
155
+ *
156
+ * Four is enough to separate two same-named controls in different containers
157
+ * (`Pressable<OrderRow<CartScreen` vs `Pressable<SuggestionRow<CartScreen`) without letting the
158
+ * key drift every time someone adds a wrapper view higher up. A path that changes on unrelated
159
+ * refactors is a key that silently splits its own history.
160
+ */
161
+ const MAX_PATH_SEGMENTS = 4;
32
162
 
33
163
  interface FiberLike {
34
164
  memoizedProps?: Record<string, unknown> | null;
165
+ /**
166
+ * The host instance. On the New Architecture this is a ReactFabricHostComponent, which is
167
+ * the only thing in reach that can report a rectangle SYNCHRONOUSLY — see targetGeometry.ts
168
+ * for why an asynchronous measurement is unusable for a per-tap rect.
169
+ */
170
+ stateNode?: unknown;
35
171
  elementType?: unknown;
36
172
  type?: unknown;
37
173
  return?: FiberLike | null;
@@ -56,7 +192,7 @@ function componentName(f: FiberLike): string | undefined {
56
192
  return n.slice(0, MAX_LEN);
57
193
  }
58
194
 
59
- /** First literal string child, e.g. <Text>Buy now</Text>. */
195
+ /** First literal string child, e.g. <Text>Buy now</Text>. FREE TEXT — see the header. */
60
196
  function textChild(props: Record<string, unknown> | null | undefined): string | undefined {
61
197
  if (!props) return undefined;
62
198
  const c = props.children;
@@ -76,10 +212,11 @@ function fiberOf(event: unknown): FiberLike | null {
76
212
  const e = event as Record<string, unknown>;
77
213
  const direct = e._targetInst;
78
214
  if (direct && typeof direct === 'object') return direct as FiberLike;
79
- // Newer RN exposes the instance handle on the target node instead.
80
- const target = e.target as Record<string, unknown> | undefined;
81
- if (target && typeof target === 'object') {
82
- const handle = target._internalFiberInstanceHandleDEV ?? target._internalInstanceHandle;
215
+ const target = (e.target ?? (e.nativeEvent as Record<string, unknown> | undefined)?.target) as
216
+ | Record<string, unknown>
217
+ | undefined;
218
+ if (target) {
219
+ const handle = target._internalInstanceHandle ?? target._targetInst;
83
220
  if (handle && typeof handle === 'object') return handle as FiberLike;
84
221
  }
85
222
  return null;
@@ -88,41 +225,115 @@ function fiberOf(event: unknown): FiberLike | null {
88
225
  /**
89
226
  * Walk up from the touched fiber collecting the best identity available.
90
227
  *
91
- * Keeps walking after a hit so a wrapper's `testID` can still be picked up when the leaf only had text,
92
- * but stops as soon as BOTH an accessibilityLabel and a testID are known — nothing above can improve on
93
- * that pair.
228
+ * Keeps walking after a hit so a wrapper's `testID` can still be picked up when the leaf had none,
229
+ * and stops as soon as a `testID` is known AND the path is full — nothing above can improve on that.
94
230
  */
95
- export function resolveTouchTarget(event: unknown, maxDepth = MAX_DEPTH): TouchTarget | null {
231
+ export function resolveTouchTarget(
232
+ event: unknown,
233
+ optsOrMaxDepth: ResolveTouchTargetOptions | number = {},
234
+ ): TouchTarget | null {
235
+ /* Number form kept for the previous signature `resolveTouchTarget(event, maxDepth)`. */
236
+ const opts: ResolveTouchTargetOptions =
237
+ typeof optsOrMaxDepth === 'number' ? { maxDepth: optsOrMaxDepth } : optsOrMaxDepth;
238
+ const maxDepth = opts.maxDepth ?? MAX_DEPTH;
239
+
96
240
  let f = fiberOf(event);
97
241
  if (!f) return null;
98
242
  const out: TouchTarget = {};
243
+ const segments: string[] = [];
244
+ const ancestors: unknown[] = [];
99
245
  let depth = 0;
100
246
  try {
101
247
  while (f && depth < maxDepth) {
102
248
  const props = f.memoizedProps;
103
249
  if (props) {
104
- out.accessibilityLabel ??= str(props.accessibilityLabel);
250
+ const beforeTestId = out.testID;
105
251
  out.testID ??= str(props.testID);
106
- out.text ??= textChild(props);
252
+ /* The node is pinned to the fiber that supplied the testID — the CONTROL, not the
253
+ deepest node hit. A Text inside a Pressable is a tap on the Pressable, so the rect
254
+ has to be the Pressable's or the containment test would be run against the caption. */
255
+ if (!beforeTestId && out.testID) out.node = f.stateNode;
256
+ /* The nearest enclosing cell wins: nested lists mean a row can sit inside another
257
+ row, and the innermost is the one the finger is actually in. `??=` keeps the first
258
+ seen while walking outward, which is the innermost. */
259
+ if (typeof props.cellKey === 'string' && props.cellKey) {
260
+ out.itemKey ??= str(props.cellKey);
261
+ if (typeof props.index === 'number' && Number.isFinite(props.index)) {
262
+ out.itemIndex ??= props.index;
263
+ }
264
+ }
265
+ if (opts.includeText) {
266
+ out.accessibilityLabel ??= str(props.accessibilityLabel);
267
+ out.text ??= textChild(props);
268
+ }
269
+ }
270
+ /* Host instances only — a composite fiber has no native tag, so keeping them would pad
271
+ the chain with entries no scroller could ever match. */
272
+ if (f.stateNode) ancestors.push(f.stateNode);
273
+ const name = componentName(f);
274
+ if (name) {
275
+ out.component ??= name;
276
+ /* Consecutive duplicates collapse: a component that renders itself through a memo or a
277
+ forwardRef appears twice in the fiber chain and would otherwise pad the path with a
278
+ repetition that carries no information. */
279
+ if (segments[segments.length - 1] !== name && segments.length < MAX_PATH_SEGMENTS) {
280
+ segments.push(name);
281
+ }
107
282
  }
108
- out.component ??= componentName(f);
109
- if (out.accessibilityLabel && out.testID) break;
283
+ if (out.testID && segments.length >= MAX_PATH_SEGMENTS) break;
110
284
  f = f.return ?? null;
111
285
  depth++;
112
286
  }
113
287
  } catch {
114
288
  /* React internals shifted under us — return whatever was gathered so far */
115
289
  }
116
- return out.accessibilityLabel || out.testID || out.text || out.component ? out : null;
290
+
291
+ /* Tapped node first, so the most specific segment leads and a truncated path is still anchored
292
+ to the thing actually touched. */
293
+ if (segments.length) out.path = segments.join('<');
294
+
295
+ /* No authored testID anywhere, so identity came from the structural path. Anchor the rect to
296
+ the node that was actually touched — imperfect (it may be the caption rather than the
297
+ control) but honest, and better than no geometry for the majority of apps, which author no
298
+ testIDs. `targetSource` records which case this was, so a consumer can weight it. */
299
+ if (!out.node) out.node = fiberOf(event)?.stateNode;
300
+
301
+ if (ancestors.length) out.ancestors = ancestors;
302
+
303
+ return out.testID || out.path || out.component || out.accessibilityLabel || out.text || out.itemKey
304
+ ? out
305
+ : null;
117
306
  }
118
307
 
119
308
  /**
120
- * One short human label for the tapped thing, or undefined when nothing identified it.
309
+ * One short, STABLE, non-identifying label for the tapped thing.
121
310
  *
122
- * This is what ends up grouping the Events explorer, so it must be STABLE: a11y label and testID are
123
- * authored and rarely change, whereas visible text moves with copy edits hence the ordering.
311
+ * This is what ends up grouping the Events explorer and what gets persisted as the interaction's
312
+ * target, so it must satisfy two constraints at once: stable across copy edits, and free of user
313
+ * data. Both rule out visible text, which is why the free-text fields are not consulted here even
314
+ * when they have been resolved — see the RN-2 note in the header.
124
315
  */
125
316
  export function describeTouchTarget(t: TouchTarget | null): string | undefined {
126
317
  if (!t) return undefined;
127
- return t.accessibilityLabel || t.testID || t.text || t.component;
318
+ return t.testID || t.path || t.component;
319
+ }
320
+
321
+ /**
322
+ * The identity plus WHERE IT CAME FROM.
323
+ *
324
+ * A consumer cannot treat an authored `testID` and a structural `path` as equally trustworthy: the
325
+ * first is a promise from the app's authors that this control is this control, the second is an
326
+ * inference that breaks when the tree is refactored. Returning the source lets the accounting lane
327
+ * say WHY a tap could not be attributed, instead of reporting a missing target and leaving the
328
+ * reader to guess whether the control had no identity or the walk failed.
329
+ */
330
+ export function targetIdentity(t: TouchTarget | null): {
331
+ id?: string;
332
+ source: TargetIdentitySource;
333
+ } {
334
+ if (!t) return { source: 'none' };
335
+ if (t.testID) return { id: t.testID, source: 'testID' };
336
+ if (t.path) return { id: t.path, source: 'path' };
337
+ if (t.component) return { id: t.component, source: 'component' };
338
+ return { source: 'none' };
128
339
  }
@@ -50,7 +50,10 @@ const clean = (s: string): string =>
50
50
  export function setUiState(name: string, value: string): void {
51
51
  const n = clean(name);
52
52
  const v = clean(value);
53
- if (n && v) declared.set(n, v);
53
+ if (!n || !v) return;
54
+ if (declared.get(n) === v) return;
55
+ declared.set(n, v);
56
+ notifyChanged();
54
57
  }
55
58
 
56
59
  /**
@@ -62,8 +65,10 @@ export function setUiState(name: string, value: string): void {
62
65
  * screen.
63
66
  */
64
67
  export function clearUiState(name?: string): void {
68
+ const before = declared.size;
65
69
  if (name === undefined) declared.clear();
66
70
  else declared.delete(clean(name));
71
+ if (declared.size !== before) notifyChanged();
67
72
  }
68
73
 
69
74
  /**
@@ -87,3 +92,77 @@ export function uiStateSignature(): string | undefined {
87
92
  }
88
93
  return signature || undefined;
89
94
  }
95
+
96
+ /**
97
+ * RN-11 — TELL SOMEONE THE STATE CHANGED, so a frame can exist for it.
98
+ *
99
+ * THE GAP. Declaring a state used to mutate a Map and nothing else. Nothing captured a frame, so
100
+ * the visual for a declared state existed only if a screenshot happened to be taken for some other
101
+ * reason — a navigation, a timer, or the interaction capture that fires AFTER the touch and
102
+ * photographs the outcome. A state could therefore be recorded as a fact with no picture of it
103
+ * anywhere, or with a picture of the state that replaced it.
104
+ *
105
+ * The native capture reasons are NAVIGATION, MANUAL, INTERACTION and TIMER. None of them is "the
106
+ * UI changed shape", which is exactly the moment a heatmap needs a frame.
107
+ *
108
+ * FIRING ON A REAL CHANGE ONLY, AND WHY THAT IS THE SDK'S JOB. The advice above says to call
109
+ * `setUiState` when the state changes rather than on every render — but that is advice to the
110
+ * host, not a guarantee. A component that declares its state inside render is ordinary React, and
111
+ * trusting the caller would mean a screenshot per render: a performance disaster in exactly the
112
+ * apps that instrument most carefully. So a redundant set — same dimension, same value — is now a
113
+ * no-op, and the change test lives here where it cannot be got wrong by a host.
114
+ *
115
+ * COALESCED, because a transition usually declares several dimensions in one tick ("drawer:open"
116
+ * and "overlay:visible" belong to one visual change). Notifying per call would capture the
117
+ * intermediate shapes, which are states the user never saw.
118
+ *
119
+ * The listener is deliberately NOT given the signature. A subscriber that wants it calls
120
+ * `uiStateSignature()` at the moment it acts, which is the value that will actually be attached
121
+ * to the next tap; handing over a snapshot invites acting on a state that has already moved on.
122
+ */
123
+ export type UiStateChangeListener = () => void;
124
+
125
+ const listeners = new Set<UiStateChangeListener>();
126
+ let pending: ReturnType<typeof setTimeout> | null = null;
127
+
128
+ /**
129
+ * Subscribe to declared-state changes. Returns an unsubscribe.
130
+ *
131
+ * Registration is idempotent per function reference, so a component that re-subscribes on every
132
+ * render does not accumulate listeners — a leak that would only show up in long sessions.
133
+ */
134
+ export function onUiStateChange(listener: UiStateChangeListener): () => void {
135
+ listeners.add(listener);
136
+ return () => {
137
+ listeners.delete(listener);
138
+ };
139
+ }
140
+
141
+ /** Drop every listener and any pending notification. For teardown between sessions. */
142
+ export function resetUiStateListeners(): void {
143
+ listeners.clear();
144
+ if (pending !== null) {
145
+ clearTimeout(pending);
146
+ pending = null;
147
+ }
148
+ }
149
+
150
+ /** For assertions that a re-subscribing caller has not leaked. */
151
+ export function uiStateListenerCount(): number {
152
+ return listeners.size;
153
+ }
154
+
155
+ function notifyChanged(): void {
156
+ if (pending !== null) return;
157
+ pending = setTimeout(() => {
158
+ pending = null;
159
+ for (const listener of listeners) {
160
+ try {
161
+ listener();
162
+ } catch {
163
+ /* One bad subscriber must not stop the others, and must never surface to the host: a
164
+ screenshot is not worth an app crash. */
165
+ }
166
+ }
167
+ }, 0);
168
+ }
@@ -49,6 +49,15 @@ export class AutoScreenDetector {
49
49
  private _manualScreen: string | null = null;
50
50
  private _manualScreenTs = 0;
51
51
  private _autoScreen: string | null = null;
52
+ /**
53
+ * When `_autoScreen` was last written.
54
+ *
55
+ * Needed so `getCurrentScreen()` can prefer whichever source spoke MOST RECENTLY.
56
+ * Without a timestamp the only comparison available was "is the manual value still
57
+ * fresh", which is a different question and gave the wrong answer — see the note on
58
+ * `_currentScreen()`.
59
+ */
60
+ private _autoScreenTs = 0;
52
61
  /** `name#key` of the last auto-detected screen VISIT — see _extractActiveVisit. */
53
62
  private _autoVisitSig: string | null = null;
54
63
  private _navigationRef: any = null;
@@ -124,6 +133,7 @@ export class AutoScreenDetector {
124
133
  if (this.isManualScreenActive()) return;
125
134
  if (name !== this._autoScreen) {
126
135
  this._autoScreen = name;
136
+ this._autoScreenTs = Date.now();
127
137
  this._autoVisitSig = name; // native lifecycle carries no route key — name-only visit
128
138
  this._emitScreenChange(name, 'heuristic');
129
139
  }
@@ -131,8 +141,19 @@ export class AutoScreenDetector {
131
141
  }
132
142
 
133
143
  /**
134
- * Check if a manual screen is currently active.
135
- * Used by auto-detection to yield to manual overrides.
144
+ * Should a WRITER defer to the manual screen right now?
145
+ *
146
+ * THIS IS A PRECEDENCE GATE, NOT A VALIDITY TEST, and conflating the two was a real
147
+ * bug. Its job is what the cooldown constant says: for a short window after a manual
148
+ * beacon fires, an auto source must not overwrite it — the poller runs every 1500 ms
149
+ * and would otherwise clobber a fresh declaration with whatever it inferred.
150
+ *
151
+ * `getCurrentScreen()` used to reuse this as "is the manual screen still the current
152
+ * screen", which made a declared screen READABLE for only 2000 ms. Nothing called
153
+ * `setManualScreen` in production, so the effect was latent — but the moment the
154
+ * `<ScaleBunScreen>` beacon was wired to it (RN-8), every tap more than two seconds
155
+ * after a screen mounted would have lost its name, which is very nearly every tap. A
156
+ * fix that introduced that would have been worse than the gap it closed.
136
157
  */
137
158
  isManualScreenActive(): boolean {
138
159
  if (!this._manualScreen) return false;
@@ -196,6 +217,7 @@ export class AutoScreenDetector {
196
217
  const visit = this._extractActiveVisit(state);
197
218
  if (visit && this._visitSig(visit) !== this._autoVisitSig) {
198
219
  this._autoScreen = visit.name;
220
+ this._autoScreenTs = Date.now();
199
221
  this._autoVisitSig = this._visitSig(visit);
200
222
  this._emitScreenChange(visit.name, 'navRef');
201
223
  }
@@ -216,6 +238,7 @@ export class AutoScreenDetector {
216
238
  const visit = this._extractActiveVisit(state);
217
239
  if (visit) {
218
240
  this._autoScreen = visit.name;
241
+ this._autoScreenTs = Date.now();
219
242
  this._autoVisitSig = this._visitSig(visit);
220
243
  this._emitScreenChange(visit.name, 'navRef');
221
244
  }
@@ -261,6 +284,7 @@ export class AutoScreenDetector {
261
284
  const visit = this._extractActiveVisit(state);
262
285
  if (visit && this._visitSig(visit) !== this._autoVisitSig) {
263
286
  this._autoScreen = visit.name;
287
+ this._autoScreenTs = Date.now();
264
288
  this._autoVisitSig = this._visitSig(visit);
265
289
  this._emitScreenChange(visit.name, 'heuristic');
266
290
  }
@@ -517,16 +541,52 @@ export class AutoScreenDetector {
517
541
  this._listeners = [];
518
542
  this._manualScreen = null;
519
543
  this._autoScreen = null;
544
+ this._autoScreenTs = 0;
520
545
  this._navigationRef = null;
521
546
  _instance = null;
522
547
  }
523
548
 
524
549
  /** Get the current best-known screen name */
525
550
  getCurrentScreen(): string | null {
526
- if (this._manualScreen && this.isManualScreenActive()) {
527
- return this._manualScreen;
551
+ return this._currentScreen().name;
552
+ }
553
+
554
+ /**
555
+ * WHERE the current screen name came from, or 'none'.
556
+ *
557
+ * Recorded on every interaction (RN-8) so low screen coverage is DIAGNOSABLE rather
558
+ * than merely visible. Production shows 13.8% of Android interactions carrying a
559
+ * screen and 0.5% on iOS, and those numbers cannot today distinguish three different
560
+ * causes: the app never instrumented anything, the app instrumented manually and the
561
+ * value never reached interactions, or auto-detection ran and failed. Those have
562
+ * different owners and different fixes, and guessing between them is how a P0 stays
563
+ * open.
564
+ */
565
+ getCurrentScreenSource(): 'manual' | 'navigation' | 'none' {
566
+ return this._currentScreen().source;
567
+ }
568
+
569
+ /**
570
+ * LAST WRITER WINS between the manual beacon and auto-detection.
571
+ *
572
+ * A screen declared by `<ScaleBunScreen name>` stays current until something else
573
+ * declares a different one — that is what mounting a screen means. It does not
574
+ * expire, which is the correction here: the previous rule returned the manual name
575
+ * only while it was under 2000 ms old and then silently fell back to the auto value,
576
+ * which in a manually-instrumented app is `null`.
577
+ *
578
+ * Comparing timestamps rather than hard-coding a priority also handles the real
579
+ * interleaving: an app can use React Navigation for most screens AND drop a manual
580
+ * beacon on one modal, and whichever spoke last is the truth.
581
+ */
582
+ private _currentScreen(): { name: string | null; source: 'manual' | 'navigation' | 'none' } {
583
+ const manual = this._manualScreen;
584
+ const auto = this._autoScreen;
585
+ if (manual && (!auto || this._manualScreenTs >= this._autoScreenTs)) {
586
+ return { name: manual, source: 'manual' };
528
587
  }
529
- return this._autoScreen;
588
+ if (auto) return { name: auto, source: 'navigation' };
589
+ return { name: null, source: 'none' };
530
590
  }
531
591
 
532
592
  // ─── Internal ───────────────────────────────────────────────────────