@shotik/react-native 0.0.0-stage → 0.1.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.
@@ -0,0 +1,425 @@
1
+ // React Native glue for Shotik analytics: automatic capture with no native code. Taps come from one capture-phase
2
+ // touch listener on a root View (element identity from the React fiber of the touched view), screens from React
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.
5
+ // Every handler is O(depth) and allocation-light; uploads happen off the touch path.
6
+
7
+ import { Component, createElement, useEffect } from 'react'
8
+ import type { ReactNode } from 'react'
9
+ import { AppState, Dimensions, Linking, Platform, StyleSheet, View } from 'react-native'
10
+ 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'
14
+
15
+ type Fiber = {
16
+ type: unknown
17
+ tag: number
18
+ memoizedProps: Record<string, unknown> | string | null
19
+ return: Fiber | null
20
+ child: Fiber | null
21
+ sibling: Fiber | null
22
+ index: number
23
+ stateNode: unknown
24
+ }
25
+
26
+ let client: Analytics | null = null
27
+ const off: (() => void)[] = []
28
+
29
+ const opt = <T,>(load: () => T): T | null => {
30
+ try {
31
+ return load()
32
+ } catch {
33
+ return null
34
+ }
35
+ }
36
+
37
+ // Optional native modules: Metro only treats a require() as optional when it sits directly inside a try block.
38
+ function storage(): Storage | undefined {
39
+ let a = null
40
+ try {
41
+ const m = require('@react-native-async-storage/async-storage')
42
+ a = m?.default ?? m
43
+ } catch {}
44
+ if (a?.getItem) return { get: (k) => a.getItem(k), set: (k, v) => a.setItem(k, v), remove: (k) => a.removeItem(k) }
45
+ let mm = null
46
+ try {
47
+ const m = require('react-native-mmkv')
48
+ mm = m.createMMKV ? m.createMMKV({ id: 'shotik' }) : new m.MMKV({ id: 'shotik' })
49
+ } catch {}
50
+ if (mm?.getString) return { get: async (k) => mm.getString(k) ?? null, set: async (k, v) => mm.set(k, v), remove: async (k) => void (mm.remove ?? mm.delete).call(mm, k) }
51
+ // The keychain is a last resort: small values only, and it throws in unsigned simulator builds (reported as store: 'error').
52
+ let s = null
53
+ try {
54
+ s = require('expo-secure-store')
55
+ } catch {}
56
+ if (s?.getItemAsync) return { get: (k) => s.getItemAsync(k), set: (k, v) => s.setItemAsync(k, v), remove: (k) => s.deleteItemAsync(k) }
57
+ return undefined
58
+ }
59
+
60
+ function device(): DeviceContext {
61
+ let d = null
62
+ let a = null
63
+ try {
64
+ d = require('expo-device')
65
+ } catch {}
66
+ try {
67
+ a = require('expo-application')
68
+ } catch {}
69
+ const o = Intl.DateTimeFormat().resolvedOptions()
70
+ 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) }
72
+ }
73
+
74
+ // Fiber helpers
75
+
76
+ const nameOf = (t: unknown): string | null => {
77
+ if (!t || typeof t === 'string') return null
78
+ const o = t as { displayName?: string; name?: string; render?: { displayName?: string; name?: string }; type?: unknown }
79
+ return o.displayName || o.name || o.render?.displayName || o.render?.name || (o.type ? nameOf(o.type) : null)
80
+ }
81
+ 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/
83
+ const INPUT = /TextInput/
84
+ 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')
85
+
86
+ function textUnder(f: Fiber | null, max = 40): string {
87
+ const out: string[] = []
88
+ let n = 0
89
+ const walk = (x: Fiber | null) => {
90
+ 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)
94
+ x = x.sibling
95
+ }
96
+ }
97
+ walk(f?.child ?? null)
98
+ return out.join(' ').replace(/\s+/g, ' ').trim().slice(0, max)
99
+ }
100
+
101
+ const hash = (s: string) => {
102
+ let h = 0x811c9dc5
103
+ for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 0x01000193)
104
+ return (h >>> 0).toString(36)
105
+ }
106
+
107
+ const scrub = (s: string) => s.replace(/[^\s@]+@[^\s@]+/g, '[email]').replace(/\d/g, '#')
108
+
109
+ // 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 } {
112
+ let f = target
113
+ let handler: Fiber | null = null
114
+ let tid: string | undefined
115
+ let a11y: string | undefined
116
+ let nid: string | undefined
117
+ let path: (number | string)[] = []
118
+ let masked = false
119
+ let input = false
120
+ let scroll: Fiber | null = null
121
+ const names: string[] = []
122
+ for (let d = 0; f && d < 80; d++, f = f.return) {
123
+ const p = (typeof f.memoizedProps === 'object' && f.memoizedProps) || {}
124
+ const name = nameOf(f.type)
125
+ if (f.type === ShotikMask || p.shotikMask) masked = true
126
+ if ((name && INPUT.test(name)) || (typeof f.type === 'string' && /TextInput/.test(f.type))) input = true
127
+ if (!scroll && (f.stateNode as { _scrollMetrics?: unknown } | null)?._scrollMetrics) scroll = f
128
+ if (!handler && (handles(p) || (name && PRESS.test(name)))) (handler = f), (path = [])
129
+ path.push('cellKey' in p && 'item' in p ? '*' : f.index)
130
+ if (!handler || handler === f) {
131
+ if (!tid && typeof p.testID === 'string' && !p.testID.startsWith('shotik-mask')) tid = p.testID
132
+ if (!nid && typeof p.nativeID === 'string' && p.nativeID !== 'shotik-mask') nid = p.nativeID
133
+ if (!a11y && typeof (p.accessibilityLabel ?? p['aria-label']) === 'string') a11y = String(p.accessibilityLabel ?? p['aria-label'])
134
+ }
135
+ if (handler && name && names.length < 2 && !GENERIC.test(name)) names.push(name)
136
+ }
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 }
141
+ }
142
+
143
+ // Wireframes from the host tree (React Native DOM API, RN 0.82+ new architecture). Unavailable: no snapshot.
144
+ type HostEl = { tagName?: string; children?: ArrayLike<HostEl>; getBoundingClientRect?: () => { x: number; y: number; width: number; height: number }; __internalInstanceHandle?: Fiber }
145
+ function wireframe(root: HostEl): WireNode[] | null {
146
+ if (!root?.getBoundingClientRect || !root.children) return null
147
+ const out: WireNode[] = []
148
+ const { width: W, height: H } = Dimensions.get('window')
149
+ const visit = (el: HostEl) => {
150
+ if (out.length >= 450) return
151
+ const r = el.getBoundingClientRect?.()
152
+ if (!r || r.width < 2 || r.height < 2 || r.y > H || r.y + r.height < 0 || r.x > W || r.x + r.width < 0) return
153
+ const fib = el.__internalInstanceHandle
154
+ const p = (fib && typeof fib.memoizedProps === 'object' && fib.memoizedProps) || {}
155
+ const st = (StyleSheet.flatten(p.style as never) ?? {}) as Record<string, unknown>
156
+ const tag = el.tagName ?? ''
157
+ 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'))
159
+ if (/Text$/.test(tag) && !/Input/.test(tag)) return void out.push(box('t', st.color))
160
+ if (/Input/.test(tag)) return void out.push(box('n', st.backgroundColor, st.borderRadius))
161
+ if (/Image/.test(tag)) return void out.push(box('i', undefined, st.borderRadius))
162
+ const kind = handles(p) ? 'b' : /Scroll/.test(tag) ? 's' : 'v'
163
+ if (kind !== 'v' || st.backgroundColor || st.borderWidth) out.push(box(kind, st.backgroundColor ?? st.borderColor, st.borderRadius))
164
+ const kids = el.children
165
+ if (kids) for (let i = 0; i < kids.length; i++) visit(kids[i])
166
+ }
167
+ visit(root)
168
+ return out
169
+ }
170
+
171
+ // Root wrapper: one capture-phase touch listener for the whole app and the wireframe root.
172
+
173
+ interface RootProps {
174
+ children?: ReactNode
175
+ }
176
+
177
+ export class ShotikAnalyticsRoot extends Component<RootProps> {
178
+ private root: HostEl | null = null
179
+ private start: { x: number; y: number; t: number; dy: number } | null = null
180
+ private snapTimer: ReturnType<typeof setTimeout> | null = null
181
+ private lastScreen: string | undefined
182
+ private unsub: (() => void) | null = null
183
+
184
+ componentDidMount(): void {
185
+ this.unsub = onScreen((s) => this.queueSnapshot(s))
186
+ }
187
+
188
+ componentWillUnmount(): void {
189
+ this.unsub?.()
190
+ if (this.snapTimer) clearTimeout(this.snapTimer)
191
+ }
192
+
193
+ private queueSnapshot(screen: string): void {
194
+ if (!client?.wantsSnapshot(screen)) return
195
+ if (this.snapTimer) clearTimeout(this.snapTimer)
196
+ const idle = (globalThis as { requestIdleCallback?: (f: () => void) => void }).requestIdleCallback ?? ((f: () => void) => setTimeout(f, 0))
197
+ this.snapTimer = setTimeout(() => {
198
+ idle(() => {
199
+ if (!client || client.currentScreen !== screen || !this.root) return
200
+ const nodes = opt(() => wireframe(this.root!))
201
+ if (!nodes?.length) return
202
+ const { width, height } = Dimensions.get('window')
203
+ client.snapshot({ screen, w: Math.round(width), h: Math.round(height), nodes })
204
+ })
205
+ }, 900)
206
+ }
207
+
208
+ 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 }
212
+ }
213
+
214
+ private onEnd = (e: GestureResponderEvent) => {
215
+ const s = this.start
216
+ 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
226
+ }
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)
235
+ }
236
+
237
+ render() {
238
+ return createElement(
239
+ View,
240
+ {
241
+ style: { flex: 1 },
242
+ collapsable: false,
243
+ ref: (r: unknown) => void (this.root = r as HostEl),
244
+ onTouchStartCapture: this.onStart,
245
+ onTouchEndCapture: this.onEnd
246
+ } as never,
247
+ this.props.children
248
+ )
249
+ }
250
+ }
251
+
252
+ // Hides what's inside from tap labels and wireframes (one grey block).
253
+ export function ShotikMask({ children, style }: { children?: ReactNode; style?: unknown }) {
254
+ return createElement(View, { nativeID: 'shotik-mask', style: style as never }, children)
255
+ }
256
+
257
+ // Screen listeners (wireframe trigger).
258
+ const screenSubs = new Set<(s: string) => void>()
259
+ function onScreen(fn: (s: string) => void): () => void {
260
+ screenSubs.add(fn)
261
+ return () => screenSubs.delete(fn)
262
+ }
263
+
264
+ function screen(name: string): void {
265
+ if (!client || name === client.currentScreen) return
266
+ const t0 = Date.now()
267
+ client.screenView(name)
268
+ for (const fn of screenSubs) fn(name)
269
+ requestAnimationFrame(() => requestAnimationFrame(() => client?.screenReady(Date.now() - t0)))
270
+ }
271
+
272
+ // React Navigation state -> a route pattern like "(tabs)/index" or "day/[id]" (route names, never params).
273
+ type NavState = { index?: number; routes: { name: string; state?: NavState }[] }
274
+ const routePath = (s: NavState | undefined): string => {
275
+ const parts: string[] = []
276
+ while (s?.routes?.length) {
277
+ const r = s.routes[s.index ?? s.routes.length - 1]
278
+ parts.push(r.name)
279
+ s = r.state
280
+ }
281
+ return parts.filter((p) => p !== '__root').join('/')
282
+ }
283
+
284
+ export interface NavigationRefLike {
285
+ addListener(e: 'state', cb: (e: { data?: { state?: NavState } }) => void): () => void
286
+ getRootState?(): NavState | undefined
287
+ isReady?(): boolean
288
+ }
289
+
290
+ function trackNavigation(ref: NavigationRefLike): () => void {
291
+ const now = () => {
292
+ const p = routePath(ref.getRootState?.())
293
+ if (p) screen(p)
294
+ }
295
+ if (ref.isReady?.()) now()
296
+ const un = ref.addListener('state', (e) => {
297
+ const p = routePath(e.data?.state ?? ref.getRootState?.())
298
+ if (p) screen(p)
299
+ })
300
+ off.push(un)
301
+ return un
302
+ }
303
+
304
+ // Expo Router: call once in the root layout.
305
+ let expoRouter: { useNavigationContainerRef?: () => NavigationRefLike } | null = null
306
+ try {
307
+ expoRouter = require('expo-router')
308
+ } catch {}
309
+ export function useShotikExpoRouter(): void {
310
+ const ref = expoRouter?.useNavigationContainerRef?.()
311
+ useEffect(() => (ref ? trackNavigation(ref) : undefined), [ref])
312
+ }
313
+
314
+ export function useShotikScreen(name: string): void {
315
+ useEffect(() => screen(name), [name])
316
+ }
317
+
318
+ // RevenueCat (react-native-purchases): wraps the purchase calls once.
319
+ type Fn = (...a: unknown[]) => Promise<unknown>
320
+ function trackRevenueCat(P: Record<string, unknown>): void {
321
+ for (const m of ['purchasePackage', 'purchaseStoreProduct', 'purchaseProduct', 'purchaseSubscriptionOption']) {
322
+ const orig = P[m] as (Fn & { __shotik?: 1 }) | undefined
323
+ if (typeof orig !== 'function' || orig.__shotik) continue
324
+ 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
326
+ 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 }
328
+ client?.purchase({ ...info, status: 'start' })
329
+ try {
330
+ const r = await orig.apply(P, a)
331
+ client?.purchase({ ...info, status: 'done' })
332
+ return r
333
+ } catch (e) {
334
+ client?.purchase({ ...info, status: (e as { userCancelled?: boolean })?.userCancelled ? 'cancel' : 'fail' })
335
+ throw e
336
+ }
337
+ }
338
+ w.__shotik = 1
339
+ P[m] = w
340
+ }
341
+ }
342
+
343
+ function hookErrors(): void {
344
+ const EU = (globalThis as { ErrorUtils?: { getGlobalHandler(): (e: unknown, f?: boolean) => void; setGlobalHandler(h: (e: unknown, f?: boolean) => void): void } }).ErrorUtils
345
+ if (EU) {
346
+ const prev = EU.getGlobalHandler()
347
+ EU.setGlobalHandler((e, fatal) => {
348
+ client?.error(e, !!fatal)
349
+ prev(e, fatal)
350
+ })
351
+ }
352
+ const H = (globalThis as { HermesInternal?: { enablePromiseRejectionTracker?: (o: unknown) => void } }).HermesInternal
353
+ if (!(globalThis as { __DEV__?: boolean }).__DEV__) H?.enablePromiseRejectionTracker?.({ allRejections: true, onUnhandled: (_: number, r: unknown) => client?.error(r) })
354
+ }
355
+
356
+ function hookAppState(): void {
357
+ let state = AppState.currentState
358
+ 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') {
364
+ stalls(false)
365
+ client?.background()
366
+ }
367
+ state = next
368
+ })
369
+ off.push(() => sub.remove())
370
+ }
371
+
372
+ let stallTimer: ReturnType<typeof setInterval> | null = null
373
+ function stalls(on: boolean): void {
374
+ if (stallTimer) clearInterval(stallTimer)
375
+ stallTimer = null
376
+ if (!on) return
377
+ let last = Date.now()
378
+ stallTimer = setInterval(() => {
379
+ const now = Date.now()
380
+ const drift = now - last - 500
381
+ last = now
382
+ if (drift > 300 && drift < 60_000) client?.stall(drift)
383
+ }, 500)
384
+ }
385
+
386
+ export type ShotikAnalyticsConfig = Omit<AnalyticsConfig, 'storage' | 'device'> & { storage?: Storage }
387
+
388
+ export const ShotikAnalytics = {
389
+ init(cfg: ShotikAnalyticsConfig): Analytics {
390
+ if (client) return client
391
+ client = new Analytics({ ...cfg, storage: cfg.storage ?? storage(), device })
392
+ hookErrors()
393
+ hookAppState()
394
+ // Dev builds only: <scheme>://…?shotik-analytics=new-user starts a fresh install identity (test runs on one device).
395
+ if ((globalThis as { __DEV__?: boolean }).__DEV__) {
396
+ const sub = Linking.addEventListener('url', ({ url }: { url: string }) => {
397
+ if (url.includes('shotik-analytics=new-user')) void client?.reset()
398
+ })
399
+ off.push(() => sub.remove())
400
+ }
401
+ client.foreground()
402
+ stalls(true)
403
+ return client
404
+ },
405
+ get client(): Analytics | null {
406
+ return client
407
+ },
408
+ track: (name: string, props?: Record<string, unknown>) => client?.track(name, props),
409
+ screen,
410
+ identify: (userId: string | null, traits?: Record<string, unknown>) => client?.identify(userId, traits),
411
+ purchase: (p: Parameters<Analytics['purchase']>[0]) => client?.purchase(p),
412
+ setConsent: (c: Consent) => client?.setConsent(c),
413
+ optOut: () => client?.optOut(),
414
+ optIn: () => client?.optIn(),
415
+ reset: () => client?.reset(),
416
+ flush: () => client?.flush(),
417
+ trackNavigation,
418
+ trackRevenueCat,
419
+ stop(): void {
420
+ stalls(false)
421
+ off.splice(0).forEach((f) => f())
422
+ client?.stop()
423
+ client = null
424
+ }
425
+ }
@@ -0,0 +1,123 @@
1
+ // Shotik analytics wire format, shared by the SDK and the server (imported there as wire.ts). No imports, no platform
2
+ // code. A batch is dictionary-packed: every repeated string (screen, element, event name, session id) is sent once per
3
+ // batch and referenced by index, timestamps are deltas, and props keep short keys. React Native has no gzip without
4
+ // native code, so this is the compression: about 6x smaller than plain JSON on tap-heavy batches.
5
+
6
+ export const WIRE_VERSION = 1
7
+
8
+ // Event types. Codes are the array position, so append only.
9
+ export const TYPES = ['session', 'open', 'close', 'screen', 'leave', 'tap', 'rage', 'scroll', 'error', 'slow', 'purchase', 'custom', 'identify', 'snapshot'] as const
10
+ export type EventType = (typeof TYPES)[number]
11
+
12
+ export interface DeviceContext {
13
+ platform?: string
14
+ os?: string
15
+ model?: string
16
+ app?: string
17
+ build?: string
18
+ locale?: string
19
+ tz?: string
20
+ w?: number
21
+ h?: number
22
+ }
23
+
24
+ // Props by type (all optional, short keys keep batches small):
25
+ // session { first: 1 on the first session of this install, store: 'none' | 'error' when the id can't persist }
26
+ // screen { from, ms (ready time) } leave { dur, depth (0..1), drag (pt), stalls, maxStall }
27
+ // tap { el, id, label, x, y, nx, ny (0..1000), dead: 1, input: 1 } rage { el, id, label, n, x, y }
28
+ // id is the stable element key (testID, nativeID or a structural hash); el and label are for display
29
+ // error { msg, fatal: 1, stack (top frames, no values) } slow { ms, kind: 'ready' | 'stall' }
30
+ // purchase { product, price, currency, status: start | done | cancel | fail, store, trial: 1 }
31
+ // custom free-form (no PII by contract) identify { traits }
32
+ export interface WireEvent {
33
+ seq: number
34
+ ts: number
35
+ type: EventType
36
+ sessionId: string
37
+ name?: string
38
+ screen?: string
39
+ props?: Record<string, unknown>
40
+ }
41
+
42
+ export interface Batch {
43
+ anonymousId: string
44
+ userId?: string | null
45
+ firstSeen?: number
46
+ device?: DeviceContext
47
+ events: WireEvent[]
48
+ }
49
+
50
+ // [dt, type, seq, session, screen, name, props]; string slots are dictionary indexes, -1 = absent.
51
+ export type PackedEvent = [number, number, number, number, number, number, Record<string, unknown> | 0]
52
+ export interface PackedBatch {
53
+ v: 1
54
+ a: string
55
+ u?: string | null
56
+ f?: number
57
+ c?: DeviceContext
58
+ t0: number
59
+ d: string[]
60
+ e: PackedEvent[]
61
+ }
62
+
63
+ const PACKED_PROPS = ['el', 'label', 'from']
64
+
65
+ export function pack(b: Batch): PackedBatch {
66
+ const d: string[] = []
67
+ const ix = new Map<string, number>()
68
+ const s = (v: unknown): number => {
69
+ if (typeof v !== 'string') return -1
70
+ let i = ix.get(v)
71
+ if (i === undefined) {
72
+ i = d.length
73
+ d.push(v)
74
+ ix.set(v, i)
75
+ }
76
+ return i
77
+ }
78
+ const t0 = b.events.length ? b.events[0].ts : 0
79
+ let prev = t0
80
+ const e = b.events.map((ev): PackedEvent => {
81
+ const dt = ev.ts - prev
82
+ prev = ev.ts
83
+ let p: Record<string, unknown> | 0 = 0
84
+ if (ev.props) {
85
+ p = {}
86
+ for (const k in ev.props) {
87
+ const v = ev.props[k]
88
+ if (v === undefined) continue
89
+ p[k] = PACKED_PROPS.includes(k) && typeof v === 'string' ? s(v) : v
90
+ }
91
+ }
92
+ return [dt, TYPES.indexOf(ev.type), ev.seq, s(ev.sessionId), s(ev.screen), s(ev.name), p]
93
+ })
94
+ return { v: 1, a: b.anonymousId, u: b.userId ?? null, f: b.firstSeen, c: b.device, t0, d, e }
95
+ }
96
+
97
+ export function unpack(p: PackedBatch): Batch {
98
+ const str = (i: number) => (i >= 0 && i < p.d.length ? p.d[i] : undefined)
99
+ let ts = p.t0
100
+ const events = p.e.map(([dt, type, seq, sess, screen, name, props]): WireEvent => {
101
+ ts += dt
102
+ let pr: Record<string, unknown> | undefined
103
+ if (props) {
104
+ pr = {}
105
+ for (const k in props) pr[k] = PACKED_PROPS.includes(k) && typeof props[k] === 'number' ? str(props[k] as number) : props[k]
106
+ }
107
+ return { seq, ts, type: TYPES[type] ?? 'custom', sessionId: str(sess) ?? '', screen: str(screen), name: str(name), props: pr }
108
+ })
109
+ return { anonymousId: p.a, userId: p.u ?? null, firstSeen: p.f, device: p.c, events }
110
+ }
111
+
112
+ // Session wireframe: a privacy-safe picture of one screen. Text is a bar with no characters, images are boxes, inputs
113
+ // never carry their value. Node: [kind, x, y, w, h, fill?, radius?]. Kinds: v view, t text, i image, b button, n input, s scroll.
114
+ export type WireNode = [string, number, number, number, number, string?, number?]
115
+ export interface Wireframe {
116
+ sessionId: string
117
+ screen: string
118
+ ts: number
119
+ w: number
120
+ h: number
121
+ dark?: boolean
122
+ nodes: WireNode[]
123
+ }