@shotik/react-native 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/LICENSE +26 -0
  3. package/README.md +39 -3
  4. package/README.ru.md +40 -3
  5. package/dist/analytics/core.d.ts +96 -11
  6. package/dist/analytics/core.js +295 -22
  7. package/dist/analytics/privacy.d.ts +4 -0
  8. package/dist/analytics/privacy.js +46 -0
  9. package/dist/analytics/replay.d.ts +41 -0
  10. package/dist/analytics/replay.js +192 -0
  11. package/dist/analytics/rn.d.ts +52 -2
  12. package/dist/analytics/rn.js +669 -62
  13. package/dist/analytics/wire.d.ts +54 -2
  14. package/dist/analytics/wire.js +44 -4
  15. package/dist/client.d.ts +94 -1
  16. package/dist/client.js +254 -17
  17. package/dist/flow.d.ts +48 -0
  18. package/dist/flow.js +56 -0
  19. package/dist/index.d.ts +4 -4
  20. package/dist/index.js +2 -2
  21. package/dist/parts.d.ts +42 -1
  22. package/dist/parts.js +72 -14
  23. package/dist/react.d.ts +24 -3
  24. package/dist/react.js +42 -15
  25. package/dist/sheet.d.ts +2 -1
  26. package/dist/sheet.js +207 -16
  27. package/dist/support.js +2 -2
  28. package/dist/theme.d.ts +43 -0
  29. package/dist/theme.js +90 -4
  30. package/package.json +15 -2
  31. package/recipe.json +1 -1
  32. package/src/analytics/README.md +10 -6
  33. package/src/analytics/core.ts +314 -25
  34. package/src/analytics/privacy.ts +50 -0
  35. package/src/analytics/recipe.json +1 -1
  36. package/src/analytics/replay.ts +190 -0
  37. package/src/analytics/rn.tsx +620 -63
  38. package/src/analytics/wire.ts +99 -8
  39. package/src/client.ts +344 -19
  40. package/src/flow.ts +100 -0
  41. package/src/index.ts +4 -4
  42. package/src/parts.tsx +102 -14
  43. package/src/react.tsx +57 -16
  44. package/src/sheet.tsx +423 -20
  45. package/src/support.ts +2 -2
  46. package/src/theme.ts +90 -4
@@ -1,16 +1,19 @@
1
1
  // React Native glue for Shotik analytics: automatic capture with no native code. Taps come from one capture-phase
2
2
  // touch listener on a root View (element identity from the React fiber of the touched view), screens from React
3
3
  // Navigation / Expo Router state, app open and close from AppState, crashes from the global error handler, stalls
4
- // from a 500 ms timer's drift, purchases from RevenueCat, and wireframes from the host tree's DOM API.
4
+ // from a 500 ms timer's drift, purchases from RevenueCat, and wireframes from the host tree's DOM API. Non-tap touches
5
+ // become gestures or settled scroll offsets, and wireframe replay diffs the host tree after interactions (PROTOCOL.md 4.7).
5
6
  // Every handler is O(depth) and allocation-light; uploads happen off the touch path.
6
7
 
7
8
  import { Component, createElement, useEffect } from 'react'
8
9
  import type { ReactNode } from 'react'
9
10
  import { AppState, Dimensions, Linking, Platform, StyleSheet, View } from 'react-native'
10
11
  import type { AppStateStatus, GestureResponderEvent } from 'react-native'
11
- import { Analytics } from './core'
12
- import type { AnalyticsConfig, Consent, Storage } from './core'
13
- import type { DeviceContext, WireNode } from './wire'
12
+ import { Analytics, SDK_VERSION } from './core'
13
+ import type { AnalyticsConfig, Consent, Entitled, Storage } from './core'
14
+ import { idWords, redact } from './privacy'
15
+ import type { DeviceContext, KeyedNode, ReplayScroll, WireNode } from './wire'
16
+ import { registerAnalytics } from '../client'
14
17
 
15
18
  type Fiber = {
16
19
  type: unknown
@@ -21,9 +24,13 @@ type Fiber = {
21
24
  sibling: Fiber | null
22
25
  index: number
23
26
  stateNode: unknown
27
+ alternate?: Fiber | null
28
+ memoizedState?: unknown
24
29
  }
25
30
 
31
+ type Labels = NonNullable<AnalyticsConfig['labels']>
26
32
  let client: Analytics | null = null
33
+ let labelMode: Labels = 'a11y'
27
34
  const off: (() => void)[] = []
28
35
 
29
36
  const opt = <T,>(load: () => T): T | null => {
@@ -60,15 +67,36 @@ function storage(): Storage | undefined {
60
67
  function device(): DeviceContext {
61
68
  let d = null
62
69
  let a = null
70
+ let u = null
63
71
  try {
64
72
  d = require('expo-device')
65
73
  } catch {}
66
74
  try {
67
75
  a = require('expo-application')
68
76
  } catch {}
77
+ try {
78
+ u = require('expo-updates')
79
+ } catch {}
69
80
  const o = Intl.DateTimeFormat().resolvedOptions()
70
81
  const { width, height } = Dimensions.get('window')
71
- return { platform: Platform.OS, os: d?.osVersion ?? String(Platform.Version), model: d?.modelName ?? undefined, app: a?.nativeApplicationVersion ?? undefined, build: a?.nativeBuildVersion ?? undefined, locale: o.locale, tz: o.timeZone, w: Math.round(width), h: Math.round(height) }
82
+ const ota = u && !u.isEmbeddedLaunch && typeof u.updateId === 'string' ? u.updateId : undefined
83
+ return { platform: Platform.OS, os: d?.osVersion ?? String(Platform.Version), model: d?.modelName ?? undefined, app: a?.nativeApplicationVersion ?? undefined, build: a?.nativeBuildVersion ?? undefined, locale: o.locale, tz: o.timeZone, w: Math.round(width), h: Math.round(height), ota, ch: u?.channel || undefined, rt: u?.runtimeVersion || undefined, sdk: 'rn/' + SDK_VERSION, tzo: -new Date().getTimezoneOffset(), dev: (globalThis as { __DEV__?: boolean }).__DEV__ ? 1 : undefined }
84
+ }
85
+
86
+ // Wi-Fi only replay uploads (PROTOCOL.md 4.7): @react-native-community/netinfo, else expo-network; neither installed: never.
87
+ function wifi(): Promise<boolean> {
88
+ let n = null
89
+ try {
90
+ const m = require('@react-native-community/netinfo')
91
+ n = m?.default ?? m
92
+ } catch {}
93
+ if (n?.fetch) return n.fetch().then((s: { type?: string }) => s?.type === 'wifi' || s?.type === 'ethernet')
94
+ let x = null
95
+ try {
96
+ x = require('expo-network')
97
+ } catch {}
98
+ if (x?.getNetworkStateAsync) return x.getNetworkStateAsync().then((s: { type?: string }) => s?.type === 'WIFI' || s?.type === 'ETHERNET')
99
+ return Promise.resolve(false)
72
100
  }
73
101
 
74
102
  // Fiber helpers
@@ -79,18 +107,24 @@ const nameOf = (t: unknown): string | null => {
79
107
  return o.displayName || o.name || o.render?.displayName || o.render?.name || (o.type ? nameOf(o.type) : null)
80
108
  }
81
109
  const GENERIC = /^(View|Text|Image|Animated.*|AnimatedComponent.*|Pressable|Touchable.*|TouchableOpacity|Fragment|Memo|ForwardRef|Unknown|ScrollView|SafeAreaView|.{0,2}|.*Provider|.*Context|Screen.*|Navigation.*|Stack.*|Route.*|ShotikMask|ShotikAnalyticsRoot)$/
82
- const PRESS = /Button|Touchable|Pressable|Link|Gesture|Swipeable/
110
+ const PRESS_HOST = /^(RNGestureHandlerButton|RCTSwitch|Switch|AndroidSwitch)$/
83
111
  const INPUT = /TextInput/
84
112
  const handles = (p: Record<string, unknown>) => !!(p.onPress || p.onPressIn || p.onLongPress || p.onClick || p.onResponderRelease || p.onValueChange || p.accessibilityRole === 'button' || p.role === 'button' || p.accessibilityRole === 'link')
113
+ // A press handler is a fiber with real press props or a host component known to be pressable, never a component name:
114
+ // providers such as GestureHandlerRootView or React 19's LinkingContext sit above every tap. Scroll hosts carry responder
115
+ // props for scrolling, not pressing. A GestureDetector (`gesture` prop) counts.
116
+ const isHandler = (f: Fiber, p: Record<string, unknown>) => (typeof f.type === 'string' ? PRESS_HOST.test(f.type) || (!/Scroll/.test(f.type) && handles(p)) : handles(p) || !!p.gesture)
117
+ const isText = (f: Fiber) => typeof f.type === 'string' && /Text$/.test(f.type) && !INPUT.test(f.type)
85
118
 
86
119
  function textUnder(f: Fiber | null, max = 40): string {
87
120
  const out: string[] = []
88
121
  let n = 0
89
122
  const walk = (x: Fiber | null) => {
90
123
  while (x && n++ < 60 && out.join(' ').length < max) {
91
- if (x.tag === 6 && typeof x.memoizedProps === 'string') out.push(x.memoizedProps)
92
- else if (typeof x.memoizedProps === 'object' && x.memoizedProps && typeof (x.memoizedProps as { children?: unknown }).children === 'string' && x.type === 'RCTText') out.push((x.memoizedProps as { children: string }).children)
93
- walk(x.child)
124
+ const p = x.memoizedProps
125
+ if (x.tag === 6 && typeof p === 'string') out.push(p)
126
+ else if (x.type === 'RCTText' && typeof p === 'object' && p && typeof p.children === 'string') out.push(p.children)
127
+ else walk(x.child)
94
128
  x = x.sibling
95
129
  }
96
130
  }
@@ -98,17 +132,19 @@ function textUnder(f: Fiber | null, max = 40): string {
98
132
  return out.join(' ').replace(/\s+/g, ' ').trim().slice(0, max)
99
133
  }
100
134
 
101
- const hash = (s: string) => {
135
+ const fnv = (s: string) => {
102
136
  let h = 0x811c9dc5
103
137
  for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 0x01000193)
104
- return (h >>> 0).toString(36)
138
+ return h >>> 0
105
139
  }
106
-
107
- const scrub = (s: string) => s.replace(/[^\s@]+@[^\s@]+/g, '[email]').replace(/\d/g, '#')
140
+ const hash = (s: string) => fnv(s).toString(36)
108
141
 
109
142
  // id: testID, else nativeID, else a hash of the fiber index path from the pressable up (list rows collapse to one id).
110
- // It ignores labels and component names, so it survives locale switches and minified release builds.
111
- export function describeTarget(target: Fiber | null): { el: string; id: string; label?: string; dead: boolean; input: boolean; scroll: Fiber | null } {
143
+ // It ignores labels and component names, so it survives locale switches and minified release builds. A tap nothing
144
+ // handles takes its ids only from the touched element (up to the next host view) and a label only when it hit text.
145
+ // labels (PROTOCOL.md §7): 'a11y' the accessibility label or a testID-derived name, 'visible' also the visible text, 'none'.
146
+ // masked: inside <ShotikMask> or a secure text input (no label, no tap position); secure: a secureTextEntry input.
147
+ export function describeTarget(target: Fiber | null, labels: Labels = labelMode): { el: string; id: string; label?: string; dead: boolean; input: boolean; masked: boolean; secure: boolean; scroll: Fiber | null } {
112
148
  let f = target
113
149
  let handler: Fiber | null = null
114
150
  let tid: string | undefined
@@ -116,16 +152,20 @@ export function describeTarget(target: Fiber | null): { el: string; id: string;
116
152
  let nid: string | undefined
117
153
  let path: (number | string)[] = []
118
154
  let masked = false
155
+ let secure = false
119
156
  let input = false
120
157
  let scroll: Fiber | null = null
158
+ let own: { tid?: string; nid?: string; a11y?: string } | null = null
121
159
  const names: string[] = []
122
160
  for (let d = 0; f && d < 80; d++, f = f.return) {
123
161
  const p = (typeof f.memoizedProps === 'object' && f.memoizedProps) || {}
124
162
  const name = nameOf(f.type)
163
+ if (!handler && !own && d > 0 && typeof f.type === 'string') own = { tid, nid, a11y }
125
164
  if (f.type === ShotikMask || p.shotikMask) masked = true
126
165
  if ((name && INPUT.test(name)) || (typeof f.type === 'string' && /TextInput/.test(f.type))) input = true
166
+ if (p.secureTextEntry === true) secure = true
127
167
  if (!scroll && (f.stateNode as { _scrollMetrics?: unknown } | null)?._scrollMetrics) scroll = f
128
- if (!handler && (handles(p) || (name && PRESS.test(name)))) (handler = f), (path = [])
168
+ if (!handler && isHandler(f, p)) (handler = f), (path = [])
129
169
  path.push('cellKey' in p && 'item' in p ? '*' : f.index)
130
170
  if (!handler || handler === f) {
131
171
  if (!tid && typeof p.testID === 'string' && !p.testID.startsWith('shotik-mask')) tid = p.testID
@@ -134,10 +174,78 @@ export function describeTarget(target: Fiber | null): { el: string; id: string;
134
174
  }
135
175
  if (handler && name && names.length < 2 && !GENERIC.test(name)) names.push(name)
136
176
  }
137
- const raw = masked || input ? '' : a11y || textUnder(handler ?? target)
138
- const label = raw ? scrub(raw) : undefined
139
- const el = (names.reverse().join('>') || (handler ? nameOf(handler.type) || 'Pressable' : 'View')) + (tid ? '#' + tid : '')
140
- return { el: input ? 'TextInput' : el, id: tid ?? nid ?? 'h' + hash(path.join('.')), label, dead: !handler && !input, input, scroll }
177
+ if (!handler && own) ({ tid, nid, a11y } = own)
178
+ const hide = masked || secure || input || labels === 'none'
179
+ const raw = hide ? '' : a11y || (labels === 'visible' ? (handler ? textUnder(handler) : target && isText(target) ? textUnder(target) : '') : tid ? idWords(tid) : '')
180
+ const label = raw ? redact(raw).replace(/\d/g, '#').slice(0, 40) : undefined
181
+ const el = input ? 'TextInput' : names.reverse().join('>') || (handler ? nameOf(handler.type) || 'Pressable' : 'View')
182
+ return { el: el + (tid ? '#' + tid : ''), id: tid ?? nid ?? 'h' + hash(path.join('.')), label, dead: !handler && !input, input, masked: masked || secure, secure, scroll }
183
+ }
184
+
185
+ // UI-state fingerprint (PROTOCOL.md §4.1 state): FNV-1a 32 of the sorted set of interactive elements visible in the window
186
+ // (testID, nativeID, else "h" + hash of the index path from the nearest navigator screen) plus "c" + key per visible
187
+ // list cell. Hidden subtrees are skipped: inactive react-native-screens, a11y-hidden stack cards, display: none, hidden
188
+ // Offscreen/Activity. Layout comes from the DOM API or nativeFabricUIManager; without it (old architecture) every mounted
189
+ // element counts. Pure pointer walking, no allocation per fiber; null past MAX_FIBERS.
190
+ const MAX_FIBERS = 30_000
191
+ type Rect = { x: number; y: number; width: number; height: number }
192
+ const none = (s: unknown): boolean => !!s && typeof s === 'object' && (Array.isArray(s) ? s.length < 6 && s.some(none) : (s as { display?: string }).display === 'none')
193
+ const hidden = (f: Fiber, p: Record<string, unknown>) => (f.tag === 22 && f.memoizedState != null) || p.activityState === 0 || p.accessibilityElementsHidden === true || p['aria-hidden'] === true || p.importantForAccessibility === 'no-hide-descendants' || (typeof f.type === 'string' && none(p.style))
194
+ function rectOf(f: Fiber): Rect | null {
195
+ const s = f.stateNode as (HostEl & { node?: unknown; canonical?: { publicInstance?: HostEl | null } }) | null
196
+ const el = s?.canonical?.publicInstance ?? s
197
+ if (el?.getBoundingClientRect) return el.getBoundingClientRect()
198
+ const ui = (globalThis as { nativeFabricUIManager?: { getBoundingClientRect?: (n: unknown, t: boolean) => number[] | undefined } }).nativeFabricUIManager
199
+ const r = s?.node ? ui?.getBoundingClientRect?.(s.node, true) : undefined
200
+ return r ? { x: r[0], y: r[1], width: r[2], height: r[3] } : null
201
+ }
202
+ const shown = (f: Fiber | null, W: number, H: number) => {
203
+ let h = f
204
+ for (let i = 0; h && typeof h.type !== 'string' && i < 8; i++) h = h.child
205
+ const r = h && typeof h.type === 'string' ? rectOf(h) : null
206
+ return !r || (r.width > 0 && r.height > 0 && r.x < W && r.x + r.width > 0 && r.y < H && r.y + r.height > 0)
207
+ }
208
+
209
+ export function uiFingerprint(root: Fiber | null, W: number, H: number): { h: string; n: number } | null {
210
+ if (!root) return null
211
+ const ids: string[] = []
212
+ const idx: number[] = []
213
+ const bnd: number[] = [-1]
214
+ let f = root.child
215
+ let d = 0
216
+ let seen = 0
217
+ while (f) {
218
+ if (++seen > MAX_FIBERS) return null
219
+ idx[d] = f.index
220
+ const p = (typeof f.memoizedProps === 'object' && f.memoizedProps) || {}
221
+ let into = !hidden(f, p)
222
+ if (into) {
223
+ if (p.route && p.navigation) bnd.push(d)
224
+ if ('cellKey' in p && 'item' in p) {
225
+ if (shown(f, W, H)) ids.push('c' + String(p.cellKey))
226
+ else into = false
227
+ } else if (typeof f.type === 'string' && isHandler(f, p) && shown(f, W, H)) ids.push(typeof p.testID === 'string' ? p.testID : typeof p.nativeID === 'string' ? p.nativeID : 'h' + hash(idx.slice(bnd[bnd.length - 1] + 1, d + 1).join('.')))
228
+ }
229
+ if (into && f.child) {
230
+ f = f.child
231
+ d++
232
+ continue
233
+ }
234
+ while (f) {
235
+ if (bnd[bnd.length - 1] === d) bnd.pop()
236
+ if (f.sibling) {
237
+ f = f.sibling
238
+ break
239
+ }
240
+ f = f.return
241
+ if (--d < 0) f = null
242
+ }
243
+ }
244
+ ids.sort()
245
+ let s = ''
246
+ let n = 0
247
+ for (let i = 0; i < ids.length; i++) if (ids[i] !== ids[i - 1]) (s += ids[i] + '\n'), n++
248
+ return { h: fnv(s).toString(16).padStart(8, '0'), n }
141
249
  }
142
250
 
143
251
  // Wireframes from the host tree (React Native DOM API, RN 0.82+ new architecture). Unavailable: no snapshot.
@@ -155,11 +263,11 @@ function wireframe(root: HostEl): WireNode[] | null {
155
263
  const st = (StyleSheet.flatten(p.style as never) ?? {}) as Record<string, unknown>
156
264
  const tag = el.tagName ?? ''
157
265
  const box = (k: string, fill?: unknown, rad?: unknown): WireNode => [k, Math.round(r.x), Math.round(r.y), Math.round(r.width), Math.round(r.height), typeof fill === 'string' ? fill : undefined, typeof rad === 'number' ? rad : undefined]
158
- if (p.nativeID === 'shotik-mask') return void out.push(box('m'))
266
+ if (p.nativeID === 'shotik-mask' || p.shotikMask) return void out.push(box('m'))
159
267
  if (/Text$/.test(tag) && !/Input/.test(tag)) return void out.push(box('t', st.color))
160
268
  if (/Input/.test(tag)) return void out.push(box('n', st.backgroundColor, st.borderRadius))
161
269
  if (/Image/.test(tag)) return void out.push(box('i', undefined, st.borderRadius))
162
- const kind = handles(p) ? 'b' : /Scroll/.test(tag) ? 's' : 'v'
270
+ const kind = fib && isHandler(fib, p) ? 'b' : /Scroll/.test(tag) ? 's' : 'v'
163
271
  if (kind !== 'v' || st.backgroundColor || st.borderWidth) out.push(box(kind, st.backgroundColor ?? st.borderColor, st.borderRadius))
164
272
  const kids = el.children
165
273
  if (kids) for (let i = 0; i < kids.length; i++) visit(kids[i])
@@ -168,26 +276,274 @@ function wireframe(root: HostEl): WireNode[] | null {
168
276
  return out
169
277
  }
170
278
 
171
- // Root wrapper: one capture-phase touch listener for the whole app and the wireframe root.
279
+ // Replay walk (PROTOCOL.md 4.7): the host tree from the root, nodes intersecting the window grown by half a window on each
280
+ // side, keyed by base36 FNV-1a of kind + host index path (a list cell's view by its item index). Nodes inside a scroll
281
+ // view are in its content space (`in` = its key), so scrolling moves one offset instead of every node. Masked subtrees,
282
+ // secure inputs, inputs and web views are one box with nothing inside walked. Kinds come from the host fiber's type.
283
+ const MAX_REPLAY = 600
284
+ const EMPTY: Record<string, unknown> = {}
285
+ const props = (f: Fiber | null | undefined): Record<string, unknown> => (f && typeof f.memoizedProps === 'object' && f.memoizedProps) || EMPTY
286
+ const styleOf = (s: unknown): Record<string, unknown> => (!s ? EMPTY : typeof s === 'object' && !Array.isArray(s) ? (s as Record<string, unknown>) : ((StyleSheet.flatten(s as never) ?? EMPTY) as Record<string, unknown>))
287
+ const cellIndex = (f: Fiber | undefined): number => {
288
+ for (let x = f?.return, i = 0; x && typeof x.type !== 'string' && i < 4; x = x.return, i++) {
289
+ const p = props(x)
290
+ if ('cellKey' in p && typeof p.index === 'number') return p.index
291
+ }
292
+ return -1
293
+ }
294
+
295
+ export function replayWalk(root: HostEl | null, W: number, H: number): { nodes: KeyedNode[]; scroll: ReplayScroll[] } | null {
296
+ if (!root?.getBoundingClientRect || !root.children) return null
297
+ const nodes: KeyedNode[] = []
298
+ const scroll: ReplayScroll[] = []
299
+ const x0 = -W / 2
300
+ const x1 = W * 1.5
301
+ const y0 = -H / 2
302
+ const y1 = H * 1.5
303
+ const visit = (el: HostEl, path: string, ox: number, oy: number, inKey: string | null): void => {
304
+ if (nodes.length >= MAX_REPLAY) return
305
+ const r = el.getBoundingClientRect?.()
306
+ if (!r || r.width < 2 || r.height < 2 || r.y > y1 || r.y + r.height < y0 || r.x > x1 || r.x + r.width < x0) return
307
+ const fib = el.__internalInstanceHandle
308
+ const p = props(fib)
309
+ if (fib && hidden(fib, p)) return
310
+ const tag = (typeof fib?.type === 'string' ? fib.type : '') || el.tagName || ''
311
+ const st = styleOf(p.style)
312
+ const push = (k: string, fill?: unknown, rad?: unknown): string => {
313
+ const key = fnv(k + path).toString(36)
314
+ const n: KeyedNode = [key, k, Math.round(r.x - ox), Math.round(r.y - oy), Math.round(r.width), Math.round(r.height)]
315
+ const f = typeof fill === 'string' ? fill : null
316
+ const rd = typeof rad === 'number' ? rad : null
317
+ if (inKey) n.push(f, rd, inKey)
318
+ else if (rd !== null) n.push(f, rd)
319
+ else if (f !== null) n.push(f)
320
+ nodes.push(n)
321
+ return key
322
+ }
323
+ if (p.nativeID === 'shotik-mask' || p.shotikMask || p.secureTextEntry === true) return void push('m')
324
+ if (/WebView/.test(tag)) return void push('w')
325
+ if (/Input/.test(tag)) return void push('n', st.backgroundColor, st.borderRadius)
326
+ if (/Text$|Paragraph/.test(tag)) return void push('t', st.color)
327
+ if (/Image/.test(tag)) return void push('i', undefined, st.borderRadius)
328
+ const sv = /ScrollView$/.test(tag)
329
+ const kind = fib && isHandler(fib, p) ? 'b' : sv ? 's' : 'v'
330
+ const key = kind !== 'v' || st.backgroundColor || st.borderWidth ? push(kind, st.backgroundColor ?? st.borderColor, st.borderRadius) : null
331
+ const kids = el.children
332
+ if (!kids) return
333
+ let cx = ox
334
+ let cy = oy
335
+ let inner = inKey
336
+ const cr = sv && key && kids.length ? kids[0].getBoundingClientRect?.() : null
337
+ if (cr && key) {
338
+ cx = cr.x
339
+ cy = cr.y
340
+ inner = key
341
+ const s: ReplayScroll = { node: key, y: Math.round(r.y - cr.y) }
342
+ const sx = Math.round(r.x - cr.x)
343
+ if (sx) s.x = sx
344
+ scroll.push(s)
345
+ }
346
+ for (let i = 0; i < kids.length; i++) {
347
+ const ci = cellIndex(kids[i].__internalInstanceHandle)
348
+ visit(kids[i], path + '.' + (ci >= 0 ? 'r' + ci : i), cx, cy, inner)
349
+ }
350
+ }
351
+ visit(root, '0', 0, 0, null)
352
+ return { nodes, scroll }
353
+ }
354
+
355
+ // Scroll containers (PROTOCOL.md 4.1 touch classes): the nearest host scroll view on the touch's axis, its offset from the
356
+ // layout (scroll view rect minus its content container's rect) or a VirtualizedList's metrics, and its element identity.
357
+ type ScrollRead = { off: number; len: number; vis: number }
358
+ const isHz = (f: Fiber, p: Record<string, unknown>) => p.horizontal === true || /Horizontal/.test(String(f.type))
359
+ function scrollHost(target: Fiber | null, hz: boolean): Fiber | null {
360
+ for (let f = target, d = 0; f && d < 80; d++, f = f.return) if (typeof f.type === 'string' && /ScrollView$/.test(f.type) && isHz(f, props(f)) === hz) return f
361
+ return null
362
+ }
363
+ function readScroll(f: Fiber, hz: boolean): ScrollRead | null {
364
+ let c = f.child
365
+ while (c && typeof c.type !== 'string') c = c.child
366
+ const sr = rectOf(f)
367
+ const cr = c ? rectOf(c) : null
368
+ if (sr && cr) return hz ? { off: Math.round(sr.x - cr.x), len: Math.round(cr.width), vis: Math.round(sr.width) } : { off: Math.round(sr.y - cr.y), len: Math.round(cr.height), vis: Math.round(sr.height) }
369
+ for (let a = f.return, i = 0; a && i < 6; a = a.return, i++) {
370
+ const m = (a.stateNode as { _scrollMetrics?: { offset: number; visibleLength: number; contentLength: number } } | null)?._scrollMetrics
371
+ if (m) return { off: Math.round(m.offset), len: Math.round(m.contentLength), vis: Math.round(m.visibleLength) }
372
+ }
373
+ return null
374
+ }
375
+ function containerOf(f: Fiber): { el: string; id: string } {
376
+ let tid: string | undefined
377
+ let nid: string | undefined
378
+ const path: (number | string)[] = []
379
+ const names: string[] = []
380
+ for (let x: Fiber | null = f, d = 0; x && d < 80; d++, x = x.return) {
381
+ const p = props(x)
382
+ if (d < 6 && !tid && typeof p.testID === 'string') tid = p.testID
383
+ if (d < 6 && !nid && typeof p.nativeID === 'string') nid = p.nativeID
384
+ path.push('cellKey' in p && 'item' in p ? '*' : x.index)
385
+ const name = nameOf(x.type)
386
+ if (name && names.length < 2 && !GENERIC.test(name) && !/^VirtualizedList/.test(name)) names.push(name)
387
+ }
388
+ return { el: (names.reverse().join('>') || 'ScrollView') + (tid ? '#' + tid : ''), id: tid ?? nid ?? 'h' + hash(path.join('.')) }
389
+ }
390
+
391
+ // Root wrapper: one capture-phase touch listener for the whole app, capture-phase focus / blur / change for fields,
392
+ // the wireframe root and the UI-state fingerprint root.
172
393
 
173
394
  interface RootProps {
174
395
  children?: ReactNode
175
396
  }
176
397
 
398
+ type Ev = { target?: unknown; nativeEvent?: { text?: unknown }; _targetInst?: Fiber }
399
+ const fiberOf = (e: Ev): Fiber | null => (e._targetInst ?? (e.target as HostEl | undefined)?.__internalInstanceHandle ?? null) as Fiber | null
400
+ const pnow = () => (globalThis as { performance?: { now(): number } }).performance?.now() ?? Date.now()
401
+
402
+ type Pt = { pageX: number; pageY: number; identifier?: number }
403
+ type TouchNE = Pt & { touches?: Pt[]; changedTouches?: Pt[] }
404
+ type Touch = { x: number; y: number; t: number; max: number; n: number; ids: Set<unknown>; span0?: number; span?: number; cx0?: number; cy0?: number; cx?: number; cy?: number }
405
+ // Two pointers: the first reading is the pinch's start span and centroid, later ones its current span and centroid.
406
+ function pinchAt(s: Touch, ts: Pt[] | undefined): void {
407
+ if (!ts || ts.length < 2) return
408
+ const span = Math.hypot(ts[1].pageX - ts[0].pageX, ts[1].pageY - ts[0].pageY)
409
+ const cx = (ts[0].pageX + ts[1].pageX) / 2
410
+ const cy = (ts[0].pageY + ts[1].pageY) / 2
411
+ if (s.span0 === undefined) (s.span0 = span), (s.cx0 = cx), (s.cy0 = cy)
412
+ s.span = span
413
+ s.cx = cx
414
+ s.cy = cy
415
+ }
416
+
417
+ // The class instance's fiber may be the stale alternate; the current one is the side whose root is the FiberRoot's current.
418
+ function currentFiber(f: Fiber | null | undefined): Fiber | null {
419
+ if (!f) return null
420
+ let top = f
421
+ while (top.return) top = top.return
422
+ return (top.stateNode as { current?: Fiber } | null)?.current === top || !f.alternate ? f : f.alternate
423
+ }
424
+
177
425
  export class ShotikAnalyticsRoot extends Component<RootProps> {
178
426
  private root: HostEl | null = null
179
- private start: { x: number; y: number; t: number; dy: number } | null = null
427
+ private start: Touch | null = null
428
+ private capTimer: ReturnType<typeof setTimeout> | null = null
429
+ private capAt = 0
430
+ private capAgain = false
431
+ private lastCap = 0
432
+ private capGap = 1000
433
+ private settling = new Map<unknown, ReturnType<typeof setTimeout>>()
434
+ private lastOff = new Map<string, number>()
180
435
  private snapTimer: ReturnType<typeof setTimeout> | null = null
181
- private lastScreen: string | undefined
182
- private unsub: (() => void) | null = null
436
+ private walkTimer: ReturnType<typeof setTimeout> | null = null
437
+ private firstKick = 0
438
+ private lastWalk = 0
439
+ private gap = 1000
440
+ private loud = false
441
+ private focus: { target: unknown; id: string; el: string; secure: boolean; ts: number; screen?: string; edits: number; filled: boolean } | null = null
442
+ private unsub: (() => void)[] = []
183
443
 
184
444
  componentDidMount(): void {
185
- this.unsub = onScreen((s) => this.queueSnapshot(s))
445
+ this.unsub.push(onScreen((s) => (this.endField(), this.queueSnapshot(s), this.kick(700), this.capture(600, true))), onAway(() => this.endField()))
446
+ this.kick(700)
186
447
  }
187
448
 
188
449
  componentWillUnmount(): void {
189
- this.unsub?.()
450
+ this.unsub.splice(0).forEach((f) => f())
451
+ this.endField()
190
452
  if (this.snapTimer) clearTimeout(this.snapTimer)
453
+ if (this.walkTimer) clearTimeout(this.walkTimer)
454
+ if (this.capTimer) clearTimeout(this.capTimer)
455
+ this.settling.forEach((t) => clearTimeout(t))
456
+ this.settling.clear()
457
+ }
458
+
459
+ // Fingerprint walks: ms after the interaction, debounced up to 1 s after the first kick, at most one per gap (1 s, or
460
+ // 1000 x the last walk's ms), postponed while a finger is down. quiet: only vertical scrolls since the last walk.
461
+ private kick(ms: number, quiet = false): void {
462
+ if (!client) return
463
+ const now = Date.now()
464
+ if (!quiet) this.loud = true
465
+ if (this.walkTimer) clearTimeout(this.walkTimer)
466
+ else this.firstKick = now
467
+ const at = Math.max(Math.min(now + ms, this.firstKick + 1000), this.lastWalk + this.gap)
468
+ this.walkTimer = setTimeout(this.walk, at - now)
469
+ }
470
+
471
+ private walk = () => {
472
+ this.walkTimer = null
473
+ if (!client) return
474
+ if (this.start) return this.kick(300, !this.loud)
475
+ const loud = this.loud
476
+ this.loud = false
477
+ const { width, height } = Dimensions.get('window')
478
+ const t0 = pnow()
479
+ const fp = opt(() => uiFingerprint(currentFiber((this as unknown as { _reactInternals?: Fiber })._reactInternals), width, height))
480
+ const ms = pnow() - t0
481
+ this.lastWalk = Date.now()
482
+ this.gap = Math.min(30_000, Math.max(1000, ms * 1000))
483
+ if (fp) client.measure('fp', ms)
484
+ if (client.uiState(fp?.h ?? null, fp?.n ?? 0, !loud)) this.capture(0)
485
+ }
486
+
487
+ // Replay captures (PROTOCOL.md 4.7): ms after the trigger, at most one per capGap (1 s, or 500 x the last capture's ms),
488
+ // postponed while a finger is down. A screen change (key) reschedules to its own time; again: after a capture that
489
+ // found changes, look once more 1 s after the interaction.
490
+ private capture(ms: number, key = false, again = false): void {
491
+ if (!client?.replayOn) return
492
+ const now = Date.now()
493
+ const at = Math.max(now + ms, this.lastCap + this.capGap)
494
+ if (this.capTimer) {
495
+ if (!key && this.capAt <= at) return void (this.capAgain ||= again)
496
+ clearTimeout(this.capTimer)
497
+ }
498
+ this.capAt = at
499
+ this.capAgain = again
500
+ this.capTimer = setTimeout(this.snap, at - now)
501
+ }
502
+
503
+ private snap = () => {
504
+ this.capTimer = null
505
+ if (!client || !this.root) return
506
+ if (this.start) return this.capture(300, false, this.capAgain)
507
+ const again = this.capAgain
508
+ this.capAgain = false
509
+ const { width, height } = Dimensions.get('window')
510
+ const t0 = pnow()
511
+ const w = opt(() => replayWalk(this.root, width, height))
512
+ const made = !!w && client.replayFrame({ screen: client.currentScreen ?? '', w: Math.round(width), h: Math.round(height), ...w })
513
+ const ms = pnow() - t0
514
+ this.lastCap = Date.now()
515
+ if (!w) return
516
+ client.measure('walk', ms)
517
+ this.capGap = Math.max(1000, ms * 500)
518
+ if (made && again) this.capture(700)
519
+ }
520
+
521
+ private onFocus = (e: Ev) => {
522
+ const f = client && fiberOf(e)
523
+ const d = f && opt(() => describeTarget(f))
524
+ if (!client || !f || !d?.input) return
525
+ this.endField()
526
+ const p = (typeof f.memoizedProps === 'object' && f.memoizedProps) || {}
527
+ const v = [p.value, p.text, p.defaultValue].find((x) => typeof x === 'string')
528
+ this.focus = { target: e.target, id: d.id, el: d.el, secure: d.secure, ts: Date.now(), screen: client.currentScreen, edits: 0, filled: !!v }
529
+ }
530
+
531
+ private onChange = (e: Ev) => {
532
+ const f = this.focus
533
+ if (!f || e.target !== f.target) return
534
+ f.edits++
535
+ const t = e.nativeEvent?.text
536
+ if (typeof t === 'string') f.filled = t.length > 0
537
+ }
538
+
539
+ private onBlur = (e: Ev) => {
540
+ if (this.focus && e.target === this.focus.target) this.endField()
541
+ }
542
+
543
+ private endField(): void {
544
+ const f = this.focus
545
+ this.focus = null
546
+ if (f && client) client.field({ id: f.id, el: f.el, ts: f.ts, ms: Date.now() - f.ts, edits: f.secure ? undefined : f.edits, filled: f.filled, screen: f.screen })
191
547
  }
192
548
 
193
549
  private queueSnapshot(screen: string): void {
@@ -205,33 +561,100 @@ export class ShotikAnalyticsRoot extends Component<RootProps> {
205
561
  }, 900)
206
562
  }
207
563
 
564
+ // Touches (PROTOCOL.md 4.1 touch classes): first pointer down to last pointer up. Moves only track the farthest distance
565
+ // and, with two pointers, their span and centroid; everything else happens at the end.
208
566
  private onStart = (e: GestureResponderEvent) => {
209
- const t = e.nativeEvent.touches?.length ?? 1
210
- if (t > 1) return void (this.start = null)
211
- this.start = { x: e.nativeEvent.pageX, y: e.nativeEvent.pageY, t: Date.now(), dy: 0 }
567
+ const ne = e.nativeEvent as unknown as TouchNE
568
+ const s = (this.start ??= { x: ne.pageX, y: ne.pageY, t: Date.now(), max: 0, n: 0, ids: new Set() })
569
+ for (const c of ne.changedTouches ?? [ne]) s.ids.add(c.identifier)
570
+ s.n = Math.max(s.n, s.ids.size, ne.touches?.length ?? 1)
571
+ if (s.n > 1) pinchAt(s, ne.touches)
212
572
  }
213
573
 
214
- private onEnd = (e: GestureResponderEvent) => {
574
+ private onMove = (e: GestureResponderEvent) => {
575
+ const s = this.start
576
+ if (!s) return
577
+ const ne = e.nativeEvent as unknown as TouchNE
578
+ if (s.n > 1 || (ne.touches?.length ?? 1) > 1) return void ((s.n = Math.max(s.n, ne.touches?.length ?? 1)), pinchAt(s, ne.touches))
579
+ const d = Math.hypot(ne.pageX - s.x, ne.pageY - s.y)
580
+ if (d > s.max) s.max = d
581
+ }
582
+
583
+ private onCancel = (e: GestureResponderEvent) => this.onEnd(e, true)
584
+
585
+ // A native scroll view or gesture that takes the touch over cancels it after a few points (touch slop), so a cancel that
586
+ // moved > 3 pt can only be a scroll, read once it settles; a still one counts only as a long press.
587
+ private onEnd = (e: GestureResponderEvent, cancel = false) => {
215
588
  const s = this.start
589
+ if (!s) return
590
+ const ne = e.nativeEvent as unknown as TouchNE
591
+ for (const c of ne.changedTouches ?? [ne]) s.ids.delete(c.identifier)
592
+ if (s.ids.size && ne.touches?.length !== 0) return
216
593
  this.start = null
217
- if (!client || !s) return
218
- const { pageX: x, pageY: y } = e.nativeEvent
219
- const moved = Math.hypot(x - s.x, y - s.y)
220
- const target = ((e as unknown as { _targetInst?: Fiber })._targetInst ?? (e.target as unknown as HostEl)?.__internalInstanceHandle ?? null) as Fiber | null
221
- if (moved > 12) {
222
- const sc = target && describeTarget(target).scroll
223
- const m = (sc?.stateNode as { _scrollMetrics?: { offset: number; visibleLength: number; contentLength: number } } | undefined)?._scrollMetrics
224
- client.scroll(m && m.contentLength > 0 ? (m.offset + m.visibleLength) / m.contentLength : null, y - s.y)
225
- return
594
+ if (!client) return
595
+ const t0 = pnow()
596
+ const now = Date.now()
597
+ const { pageX: x, pageY: y } = ne
598
+ const dx = x - s.x
599
+ const dy = y - s.y
600
+ const moved = Math.max(s.max, Math.hypot(dx, dy))
601
+ const ms = now - s.t
602
+ const target = fiberOf(e as unknown as Ev)
603
+ const still = moved <= (cancel ? 3 : 12)
604
+ if (s.n > 1 || (still && ms > 500)) {
605
+ if (cancel && s.n > 1) return
606
+ const d = describeTarget(target)
607
+ const sc = s.span0 && s.span ? s.span / s.span0 : 1
608
+ client.gesture(s.n > 1 ? { k: 'pinch', dir: sc > 1 ? 'out' : 'in', dx: (s.cx ?? 0) - (s.cx0 ?? 0), dy: (s.cy ?? 0) - (s.cy0 ?? 0), ms, el: d.el, id: d.id, sc, ts: s.t } : { k: 'long', dx, dy, ms, el: d.el, id: d.id, ts: s.t })
609
+ this.kick(400)
610
+ this.capture(300, false, true)
611
+ } else if (!still) {
612
+ const hz = Math.abs(dx) > Math.abs(dy)
613
+ if (!cancel) client.scroll(null, dy)
614
+ this.kick(hz ? 600 : 800, !hz)
615
+ const host = scrollHost(target, hz)
616
+ if (host) this.settle(host, hz, now, client.currentScreen)
617
+ else if (!cancel) {
618
+ const d = describeTarget(target)
619
+ client.gesture({ k: ms <= 300 && moved / Math.max(1, ms) >= 0.3 ? 'swipe' : 'pan', dir: hz ? (dx > 0 ? 'right' : 'left') : dy > 0 ? 'down' : 'up', dx, dy, ms, el: d.el, id: d.id, ts: s.t })
620
+ this.capture(300, false, true)
621
+ }
622
+ } else if (!cancel) {
623
+ const d = describeTarget(target)
624
+ const { width, height } = Dimensions.get('window')
625
+ client.tap({ el: d.el, id: d.id, label: d.label, x, y, nx: Math.round((x / width) * 1000), ny: Math.round((y / height) * 1000), dead: d.dead, input: d.input, masked: d.masked, ts: now })
626
+ this.kick(400)
627
+ this.capture(300, false, true)
226
628
  }
227
- if (Date.now() - s.t > 1500) return
228
- const d = describeTarget(target)
229
- const { width, height } = Dimensions.get('window')
230
- const tap = { el: d.el, id: d.id, label: d.label, x, y, nx: Math.round((x / width) * 1000), ny: Math.round((y / height) * 1000), input: d.input, ts: Date.now() }
231
- if (!d.dead) return client.tap(tap)
232
- // Dead-tap candidate: nothing handles presses here. Confirm that the screen didn't change within a second.
233
- const screen = client.currentScreen
234
- setTimeout(() => client?.tap({ ...tap, dead: client.currentScreen === screen }), 1000)
629
+ client.measure('tap', pnow() - t0)
630
+ }
631
+
632
+ // A scrolled container: read 600 ms after the touch, then every 300 ms until two reads agree (at most 3 s). A new touch on
633
+ // the same container restarts it.
634
+ private settle(f: Fiber, hz: boolean, ts: number, screen: string | undefined, prev: ScrollRead | null = null, n = 0): void {
635
+ const k = f.stateNode ?? f
636
+ const old = this.settling.get(k)
637
+ if (old) clearTimeout(old)
638
+ this.settling.set(
639
+ k,
640
+ setTimeout(() => {
641
+ this.settling.delete(k)
642
+ if (!client || client.currentScreen !== screen) return
643
+ const r = opt(() => readScroll(f, hz))
644
+ if (!r) return
645
+ if (!prev || (Math.abs(r.off - prev.off) >= 1 && n < 8)) return this.settle(f, hz, ts, screen, r, n + 1)
646
+ if (!hz && r.len > 0) client.scroll(Math.min(1, (r.off + r.vis) / r.len), 0)
647
+ const c = containerOf(f)
648
+ const key = (screen ?? '') + '|' + c.id
649
+ if (Math.abs(r.off - (this.lastOff.get(key) ?? 0)) < 1) return
650
+ if (this.lastOff.size > 200) this.lastOff.clear()
651
+ this.lastOff.set(key, r.off)
652
+ const p = { ...props(f.return), ...props(f) }
653
+ const snap = typeof p.snapToInterval === 'number' && p.snapToInterval > 0 ? p.snapToInterval : p.pagingEnabled === true ? r.vis : 0
654
+ client.scrolled({ ...c, ...r, hz, pg: snap ? Math.round(r.off / snap) : undefined, ts, screen })
655
+ this.capture(0)
656
+ }, prev ? 300 : 600)
657
+ )
235
658
  }
236
659
 
237
660
  render() {
@@ -242,7 +665,12 @@ export class ShotikAnalyticsRoot extends Component<RootProps> {
242
665
  collapsable: false,
243
666
  ref: (r: unknown) => void (this.root = r as HostEl),
244
667
  onTouchStartCapture: this.onStart,
245
- onTouchEndCapture: this.onEnd
668
+ onTouchMoveCapture: this.onMove,
669
+ onTouchEndCapture: this.onEnd,
670
+ onTouchCancelCapture: this.onCancel,
671
+ onFocusCapture: this.onFocus,
672
+ onBlurCapture: this.onBlur,
673
+ onChangeCapture: this.onChange
246
674
  } as never,
247
675
  this.props.children
248
676
  )
@@ -258,7 +686,14 @@ export function ShotikMask({ children, style }: { children?: ReactNode; style?:
258
686
  const screenSubs = new Set<(s: string) => void>()
259
687
  function onScreen(fn: (s: string) => void): () => void {
260
688
  screenSubs.add(fn)
261
- return () => screenSubs.delete(fn)
689
+ return () => void screenSubs.delete(fn)
690
+ }
691
+
692
+ // Background listeners, run before the client closes the visit (an open field span ends first).
693
+ const awaySubs = new Set<() => void>()
694
+ function onAway(fn: () => void): () => void {
695
+ awaySubs.add(fn)
696
+ return () => void awaySubs.delete(fn)
262
697
  }
263
698
 
264
699
  function screen(name: string): void {
@@ -315,29 +750,78 @@ export function useShotikScreen(name: string): void {
315
750
  useEffect(() => screen(name), [name])
316
751
  }
317
752
 
318
- // RevenueCat (react-native-purchases): wraps the purchase calls once.
753
+ // RevenueCat (react-native-purchases): wraps the purchase calls once for start / cancel / fail and the done of a purchase
754
+ // made through them; trial comes from the purchase result: an active entitlement for the bought product in its TRIAL
755
+ // period (an intro offer on the product isn't a started trial). addCustomerInfoUpdateListener adds store truth for
756
+ // everything else (renewals, trial conversions, RevenueCatUI paywalls) through core.entitled's per-product watermark.
757
+ // A product being bought through a wrapped call is left to that call; restorePurchases only moves the watermark.
319
758
  type Fn = (...a: unknown[]) => Promise<unknown>
759
+ type Entitlement = { productIdentifier?: string; periodType?: string; isActive?: boolean; latestPurchaseDateMillis?: number; latestPurchaseDate?: string; originalPurchaseDateMillis?: number; originalPurchaseDate?: string }
760
+ type Info = { entitlements?: { active?: Record<string, Entitlement> } } | null | undefined
761
+ const base = (s: string) => s.split(':')[0]
762
+ const ms = (n?: number, s?: string) => (typeof n === 'number' && n > 0 ? n : s ? Date.parse(s) || 0 : 0)
763
+ const entitlementsOf = (info: Info): Entitled[] =>
764
+ Object.values(info?.entitlements?.active ?? {})
765
+ .filter((e) => e && e.isActive !== false && e.productIdentifier)
766
+ .map((e) => ({ product: base(e.productIdentifier!), at: ms(e.latestPurchaseDateMillis, e.latestPurchaseDate), first: ms(e.originalPurchaseDateMillis, e.originalPurchaseDate) || undefined, trial: e.periodType === 'TRIAL' }))
767
+ const startedTrial = (r: unknown, product: string): boolean => {
768
+ const res = r as { productIdentifier?: string; customerInfo?: Info } | null
769
+ const pid = base(res?.productIdentifier ?? product)
770
+ return entitlementsOf(res?.customerInfo).some((e) => e.trial && e.product === pid)
771
+ }
772
+ const buying = new Set<string>()
773
+ let restoring = 0
320
774
  function trackRevenueCat(P: Record<string, unknown>): void {
321
775
  for (const m of ['purchasePackage', 'purchaseStoreProduct', 'purchaseProduct', 'purchaseSubscriptionOption']) {
322
776
  const orig = P[m] as (Fn & { __shotik?: 1 }) | undefined
323
777
  if (typeof orig !== 'function' || orig.__shotik) continue
324
778
  const w: Fn & { __shotik?: 1 } = async (...a) => {
325
- const it = a[0] as { product?: Record<string, unknown>; identifier?: string; price?: number; currencyCode?: string; introPrice?: unknown } | string
779
+ const it = a[0] as { product?: Record<string, unknown>; identifier?: string; price?: number; currencyCode?: string } | string
326
780
  const prod = (typeof it === 'object' && (it.product ?? it)) || {}
327
- const info = { product: String((prod as { identifier?: string }).identifier ?? it ?? 'unknown'), price: (prod as { price?: number }).price, currency: (prod as { currencyCode?: string }).currencyCode, store: 'revenuecat', trial: !!(prod as { introPrice?: unknown }).introPrice }
781
+ const info = { product: String((prod as { identifier?: string }).identifier ?? it ?? 'unknown'), price: (prod as { price?: number }).price, currency: (prod as { currencyCode?: string }).currencyCode, store: 'revenuecat' }
782
+ const pid = base(info.product)
328
783
  client?.purchase({ ...info, status: 'start' })
784
+ buying.add(pid)
329
785
  try {
330
786
  const r = await orig.apply(P, a)
331
- client?.purchase({ ...info, status: 'done' })
787
+ const mine = opt(() => entitlementsOf((r as { customerInfo?: Info } | null)?.customerInfo).filter((e) => e.product === pid)) ?? []
788
+ client?.purchase({ ...info, status: 'done', trial: opt(() => startedTrial(r, info.product)) ?? false, at: mine[0]?.at || undefined })
789
+ client?.entitled(mine, true)
332
790
  return r
333
791
  } catch (e) {
334
792
  client?.purchase({ ...info, status: (e as { userCancelled?: boolean })?.userCancelled ? 'cancel' : 'fail' })
335
793
  throw e
794
+ } finally {
795
+ buying.delete(pid)
336
796
  }
337
797
  }
338
798
  w.__shotik = 1
339
799
  P[m] = w
340
800
  }
801
+ const restore = P.restorePurchases as (Fn & { __shotik?: 1 }) | undefined
802
+ if (typeof restore === 'function' && !restore.__shotik) {
803
+ const w: Fn & { __shotik?: 1 } = async (...a) => {
804
+ restoring++
805
+ try {
806
+ const r = await restore.apply(P, a)
807
+ client?.entitled(opt(() => entitlementsOf(r as Info)) ?? [], true)
808
+ return r
809
+ } finally {
810
+ restoring--
811
+ }
812
+ }
813
+ w.__shotik = 1
814
+ P.restorePurchases = w
815
+ }
816
+ const add = P.addCustomerInfoUpdateListener as ((l: (i: Info) => void) => unknown) | undefined
817
+ if (typeof add !== 'function' || P.__shotikListener) return
818
+ const listener = (i: Info) => client?.entitled((opt(() => entitlementsOf(i)) ?? []).filter((e) => !buying.has(e.product)), restoring > 0)
819
+ P.__shotikListener = listener
820
+ add.call(P, listener)
821
+ off.push(() => {
822
+ ;(P.removeCustomerInfoUpdateListener as ((l: unknown) => unknown) | undefined)?.call(P, listener)
823
+ delete P.__shotikListener
824
+ })
341
825
  }
342
826
 
343
827
  function hookErrors(): void {
@@ -353,22 +837,88 @@ function hookErrors(): void {
353
837
  if (!(globalThis as { __DEV__?: boolean }).__DEV__) H?.enablePromiseRejectionTracker?.({ allRejections: true, onUnhandled: (_: number, r: unknown) => client?.error(r) })
354
838
  }
355
839
 
840
+ // Only 'background' closes the visit. iOS 'inactive' (the App Store purchase sheet, Control Center, the app switcher
841
+ // peek) keeps the screen open, so a paywall visit isn't split by its own purchase sheet.
356
842
  function hookAppState(): void {
357
- let state = AppState.currentState
843
+ let away = false
358
844
  const sub = AppState.addEventListener('change', (next: AppStateStatus) => {
359
- if (next === state) return
360
- if (next === 'active') {
361
- client?.foreground()
362
- stalls(true)
363
- } else if (state === 'active') {
845
+ if (next === 'background' && !away) {
846
+ away = true
364
847
  stalls(false)
848
+ for (const fn of awaySubs) fn()
365
849
  client?.background()
850
+ } else if (next === 'active' && away) {
851
+ away = false
852
+ client?.foreground()
853
+ stalls(true)
366
854
  }
367
- state = next
368
855
  })
369
856
  off.push(() => sub.remove())
370
857
  }
371
858
 
859
+ // Network: fetch and XMLHttpRequest are wrapped once. Every request start counts as a response to the newest tap;
860
+ // only failures and slow calls become events (core.net). Requests to the Shotik server are skipped. React Native's fetch
861
+ // runs on XMLHttpRequest, so an XHR opened inside a wrapped fetch call is left to the fetch wrapper.
862
+ let inFetch = false
863
+ type Xhr = XMLHttpRequest & { __shotik?: { m: string; url: string } | null }
864
+ function hookNet(base: string): void {
865
+ const g = globalThis as { fetch?: typeof fetch & { __shotik?: 1 }; XMLHttpRequest?: { prototype: Xhr } }
866
+ const F = g.fetch
867
+ if (F && !F.__shotik) {
868
+ const w = ((input: Parameters<typeof fetch>[0], init?: RequestInit) => {
869
+ const url = typeof input === 'string' ? input : ((input as { url?: string }).url ?? String(input))
870
+ if (!client || url.startsWith(base)) return F.call(globalThis, input, init)
871
+ const m = init?.method ?? (input as { method?: string }).method ?? 'GET'
872
+ const t0 = Date.now()
873
+ client.netStart()
874
+ inFetch = true
875
+ let p: Promise<Response>
876
+ try {
877
+ p = F.call(globalThis, input, init)
878
+ } finally {
879
+ inFetch = false
880
+ }
881
+ return p.then(
882
+ (r) => (client?.net(m, url, r.status, Date.now() - t0), r),
883
+ (e) => {
884
+ if ((e as { name?: string })?.name !== 'AbortError') client?.net(m, url, 0, Date.now() - t0)
885
+ throw e
886
+ }
887
+ )
888
+ }) as typeof fetch & { __shotik?: 1 }
889
+ w.__shotik = 1
890
+ g.fetch = w
891
+ off.push(() => void (g.fetch === w && (g.fetch = F)))
892
+ }
893
+ const X = g.XMLHttpRequest?.prototype
894
+ if (X && !(X.open as { __shotik?: 1 }).__shotik) {
895
+ const { open, send } = X
896
+ const o = function (this: Xhr, m: string, url: string | URL, ...rest: unknown[]) {
897
+ const u = String(url)
898
+ this.__shotik = inFetch || !client || u.startsWith(base) ? null : { m, url: u }
899
+ return (open as (...a: unknown[]) => void).call(this, m, url, ...rest)
900
+ }
901
+ const s = function (this: Xhr, body?: Document | XMLHttpRequestBodyInit | null) {
902
+ const r = this.__shotik
903
+ if (r && client) {
904
+ const t0 = Date.now()
905
+ let aborted = false
906
+ client.netStart()
907
+ this.addEventListener('abort', () => (aborted = true))
908
+ this.addEventListener('loadend', () => aborted || client?.net(r.m, r.url, this.status, Date.now() - t0))
909
+ }
910
+ return send.call(this, body)
911
+ }
912
+ Object.assign(o, { __shotik: 1 })
913
+ X.open = o as Xhr['open']
914
+ X.send = s
915
+ off.push(() => {
916
+ if (X.open === o) X.open = open
917
+ if (X.send === s) X.send = send
918
+ })
919
+ }
920
+ }
921
+
372
922
  let stallTimer: ReturnType<typeof setInterval> | null = null
373
923
  function stalls(on: boolean): void {
374
924
  if (stallTimer) clearInterval(stallTimer)
@@ -388,9 +938,12 @@ export type ShotikAnalyticsConfig = Omit<AnalyticsConfig, 'storage' | 'device'>
388
938
  export const ShotikAnalytics = {
389
939
  init(cfg: ShotikAnalyticsConfig): Analytics {
390
940
  if (client) return client
391
- client = new Analytics({ ...cfg, storage: cfg.storage ?? storage(), device })
941
+ labelMode = cfg.labels ?? 'a11y'
942
+ client = new Analytics({ ...cfg, storage: cfg.storage ?? storage(), device, wifi: cfg.wifi ?? wifi })
943
+ registerAnalytics(client)
392
944
  hookErrors()
393
945
  hookAppState()
946
+ hookNet(cfg.serverUrl)
394
947
  // Dev builds only: <scheme>://…?shotik-analytics=new-user starts a fresh install identity (test runs on one device).
395
948
  if ((globalThis as { __DEV__?: boolean }).__DEV__) {
396
949
  const sub = Linking.addEventListener('url', ({ url }: { url: string }) => {
@@ -413,7 +966,9 @@ export const ShotikAnalytics = {
413
966
  optOut: () => client?.optOut(),
414
967
  optIn: () => client?.optIn(),
415
968
  reset: () => client?.reset(),
969
+ forget: () => client?.forget() ?? Promise.resolve(false),
416
970
  flush: () => client?.flush(),
971
+ sendTestEvent: () => client?.sendTestEvent() ?? Promise.resolve(),
417
972
  trackNavigation,
418
973
  trackRevenueCat,
419
974
  stop(): void {
@@ -421,5 +976,7 @@ export const ShotikAnalytics = {
421
976
  off.splice(0).forEach((f) => f())
422
977
  client?.stop()
423
978
  client = null
979
+ registerAnalytics(null)
980
+ labelMode = 'a11y'
424
981
  }
425
982
  }