@shotik/react-native 0.0.0-stage → 0.1.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.
@@ -0,0 +1,345 @@
1
+ // Shotik analytics core: sessions, screens and time on screen, taps with rage detection, scroll depth, stalls, the
2
+ // offline queue and batched upload. Platform-free (no React Native imports), so it runs and is tested under plain Node.
3
+ import { pack } from './wire';
4
+ const K = { anon: 'shotik.support.anon', state: 'shotik.analytics.state', queue: 'shotik.analytics.queue', consent: 'shotik.analytics.consent' };
5
+ const MAX_QUEUE = 2000;
6
+ const BATCH = 300;
7
+ const RAGE_N = 3;
8
+ const RAGE_MS = 800;
9
+ const RAGE_PT = 40;
10
+ const rnd = () => Math.random().toString(36).slice(2, 10);
11
+ const uid = () => Date.now().toString(36) + rnd() + rnd();
12
+ export class Analytics {
13
+ constructor(cfg) {
14
+ this.queue = [];
15
+ this.snaps = [];
16
+ this.anon = '';
17
+ this.userId = null;
18
+ this.firstSeen = 0;
19
+ this.sessionId = '';
20
+ this.lastActive = 0;
21
+ this.seq = 0;
22
+ this.sampled = false;
23
+ this.screenAt = 0;
24
+ this.screenStats = { depth: 0, drag: 0, stalls: 0, maxStall: 0 };
25
+ this.taps = [];
26
+ this.snapped = new Set();
27
+ this.timer = null;
28
+ this.saveTimer = null;
29
+ this.sending = false;
30
+ this.inflight = null;
31
+ this.backoff = 0;
32
+ this.active = true;
33
+ this.loaded = false;
34
+ this.fresh = true;
35
+ this.cfg = cfg;
36
+ this.st = cfg.storage ?? null;
37
+ this.now = cfg.now ?? Date.now;
38
+ this.consent = cfg.consent ?? 'granted';
39
+ this.ready = this.load();
40
+ }
41
+ async load() {
42
+ const st = this.st;
43
+ if (st) {
44
+ try {
45
+ const [anon, raw, q, c] = await Promise.all([st.get(K.anon), st.get(K.state), st.get(K.queue), st.get(K.consent)]);
46
+ this.anon = anon ?? '';
47
+ const s = raw ? JSON.parse(raw) : null;
48
+ if (s) {
49
+ this.fresh = false;
50
+ this.firstSeen = s.f ?? 0;
51
+ this.sessionId = s.s ?? '';
52
+ this.lastActive = s.l ?? 0;
53
+ this.seq = s.q ?? 0;
54
+ this.sampled = !!s.p;
55
+ this.userId = this.userId ?? s.u ?? null;
56
+ }
57
+ if (q)
58
+ this.queue = JSON.parse(q).concat(this.queue).slice(-MAX_QUEUE);
59
+ if (c === 'granted' || c === 'denied')
60
+ this.consent = c;
61
+ }
62
+ catch {
63
+ this.storeIssue = 'error';
64
+ }
65
+ }
66
+ else
67
+ this.storeIssue = 'none';
68
+ if (!this.anon) {
69
+ this.anon = 'anon_' + uid();
70
+ st?.set(K.anon, this.anon).catch(() => { });
71
+ }
72
+ if (!this.firstSeen)
73
+ this.firstSeen = this.now();
74
+ this.loaded = true;
75
+ const pre = this.queue.filter((e) => !e.sessionId);
76
+ const n = this.queue.length;
77
+ this.touch(pre[0]?.ts);
78
+ const at = pre.length && this.queue.length > n ? this.queue.indexOf(pre[0]) : -1;
79
+ if (at >= 0) {
80
+ const [s] = this.queue.splice(this.queue.length - 1, 1);
81
+ this.queue.splice(at, 0, { ...s, screen: pre[0].screen });
82
+ }
83
+ for (const ev of pre)
84
+ Object.assign(ev, { sessionId: this.sessionId, seq: ++this.seq });
85
+ if (pre.length)
86
+ this.lastActive = Math.max(this.lastActive, pre[pre.length - 1].ts);
87
+ this.schedule();
88
+ }
89
+ // Starts a new session after sessionTimeoutMs (30 min) of inactivity. at: when the activity happened (events queued before storage loaded).
90
+ touch(at) {
91
+ const t = at ?? this.now();
92
+ if (!this.loaded)
93
+ return;
94
+ if (!this.sessionId || t - this.lastActive > (this.cfg.sessionTimeoutMs ?? 30 * 60000)) {
95
+ const first = this.fresh;
96
+ this.fresh = false;
97
+ this.sessionId = 's_' + uid();
98
+ this.seq = 0;
99
+ this.sampled = Math.random() < (this.cfg.snapshots ?? 0.2);
100
+ this.snapped.clear();
101
+ this.lastActive = t;
102
+ const props = { ...(first && { first: 1 }), ...(this.storeIssue && { store: this.storeIssue }) };
103
+ this.push('session', undefined, Object.keys(props).length ? props : undefined, t);
104
+ }
105
+ this.lastActive = t;
106
+ }
107
+ push(type, name, props, ts) {
108
+ if (this.consent === 'denied')
109
+ return;
110
+ this.queue.push({ seq: ++this.seq, ts: ts ?? this.now(), type, sessionId: this.sessionId, screen: this.screen, name, props });
111
+ if (this.queue.length > MAX_QUEUE)
112
+ this.queue.splice(0, this.queue.length - MAX_QUEUE);
113
+ if (this.cfg.debug)
114
+ console.log('[shotik]', type, name ?? '', this.screen ?? '', props ?? '');
115
+ this.save();
116
+ if (this.queue.length >= BATCH)
117
+ this.flush();
118
+ }
119
+ save() {
120
+ if (!this.st || this.saveTimer)
121
+ return;
122
+ this.saveTimer = setTimeout(() => {
123
+ this.saveTimer = null;
124
+ this.persist();
125
+ }, 1000);
126
+ }
127
+ persist() {
128
+ const st = this.st;
129
+ if (!st)
130
+ return;
131
+ st.set(K.state, JSON.stringify({ f: this.firstSeen, s: this.sessionId, l: this.lastActive, q: this.seq, p: this.sampled ? 1 : 0, u: this.userId })).catch(() => { });
132
+ st.set(K.queue, JSON.stringify(this.queue)).catch(() => { });
133
+ }
134
+ schedule() {
135
+ if (this.timer)
136
+ clearTimeout(this.timer);
137
+ this.timer = setTimeout(() => {
138
+ this.timer = null;
139
+ this.flush().finally(() => this.active && this.schedule());
140
+ }, (this.cfg.flushMs ?? 10000) * Math.pow(2, this.backoff));
141
+ }
142
+ // Public API
143
+ track(name, props) {
144
+ this.touch();
145
+ this.push('custom', name, props);
146
+ }
147
+ identify(userId, traits) {
148
+ this.userId = userId;
149
+ this.push('identify', undefined, traits ? { traits } : undefined);
150
+ }
151
+ // Screen change: closes the previous screen with its time and scroll depth.
152
+ screenView(name) {
153
+ if (name === this.screen)
154
+ return;
155
+ this.touch();
156
+ const from = this.screen;
157
+ this.leave();
158
+ this.screen = name;
159
+ this.screenAt = this.now();
160
+ this.push('screen', name, from ? { from } : undefined);
161
+ }
162
+ leave() {
163
+ if (!this.screen)
164
+ return;
165
+ const s = this.screenStats;
166
+ const p = { dur: this.now() - this.screenAt };
167
+ if (s.depth)
168
+ p.depth = Math.round(s.depth * 100) / 100;
169
+ if (s.drag)
170
+ p.drag = Math.round(s.drag);
171
+ if (s.stalls) {
172
+ p.stalls = s.stalls;
173
+ p.maxStall = s.maxStall;
174
+ }
175
+ this.push('leave', this.screen, p);
176
+ this.screenStats = { depth: 0, drag: 0, stalls: 0, maxStall: 0 };
177
+ }
178
+ get currentScreen() {
179
+ return this.screen;
180
+ }
181
+ screenReady(ms) {
182
+ if (ms > 700)
183
+ this.push('slow', this.screen, { ms: Math.round(ms), kind: 'ready' });
184
+ }
185
+ stall(ms) {
186
+ const s = this.screenStats;
187
+ s.stalls++;
188
+ s.maxStall = Math.max(s.maxStall, Math.round(ms));
189
+ if (ms > 1000)
190
+ this.push('slow', this.screen, { ms: Math.round(ms), kind: 'stall' });
191
+ }
192
+ // A tap with its element identity. dead = nothing on the touched element handles presses.
193
+ tap(t) {
194
+ this.touch();
195
+ const now = t.ts ?? this.now();
196
+ const p = { el: t.el, x: Math.round(t.x), y: Math.round(t.y), nx: t.nx, ny: t.ny };
197
+ if (t.id)
198
+ p.id = t.id;
199
+ if (t.label)
200
+ p.label = t.label;
201
+ if (t.dead)
202
+ p.dead = 1;
203
+ if (t.input)
204
+ p.input = 1;
205
+ this.push('tap', undefined, p, now);
206
+ this.taps = this.taps.filter((q) => now - q.t < RAGE_MS && Math.hypot(q.x - t.x, q.y - t.y) < RAGE_PT);
207
+ this.taps.push({ el: t.el, id: t.id, label: t.label, x: t.x, y: t.y, t: now });
208
+ if (this.taps.length === RAGE_N)
209
+ this.push('rage', undefined, { el: t.el, id: t.id, label: t.label, n: RAGE_N, x: Math.round(t.x), y: Math.round(t.y) }, now);
210
+ }
211
+ scroll(depth, drag) {
212
+ const s = this.screenStats;
213
+ if (depth != null)
214
+ s.depth = Math.max(s.depth, Math.min(1, depth));
215
+ s.drag += Math.abs(drag);
216
+ }
217
+ error(e, fatal = false) {
218
+ const err = e instanceof Error ? e : new Error(String(e));
219
+ const stack = (err.stack ?? '')
220
+ .split('\n')
221
+ .slice(1, 6)
222
+ .map((l) => l.trim().replace(/https?:\/\/[^\s)]+\//g, '').slice(0, 120));
223
+ this.push('error', err.name, { msg: err.message.slice(0, 200), fatal: fatal ? 1 : undefined, stack });
224
+ if (fatal)
225
+ this.persist();
226
+ }
227
+ purchase(p) {
228
+ this.touch();
229
+ this.push('purchase', p.product, { product: p.product, status: p.status, price: p.price, currency: p.currency, store: p.store, trial: p.trial ? 1 : undefined });
230
+ }
231
+ // Wireframes are recorded once per screen per sampled session.
232
+ wantsSnapshot(screen) {
233
+ return this.sampled && this.consent === 'granted' && !this.snapped.has(screen);
234
+ }
235
+ snapshot(w) {
236
+ if (!this.wantsSnapshot(w.screen))
237
+ return;
238
+ this.snapped.add(w.screen);
239
+ this.snaps.push({ ...w, sessionId: this.sessionId, ts: this.now() });
240
+ this.push('snapshot', w.screen, { n: w.nodes.length });
241
+ }
242
+ foreground() {
243
+ this.touch();
244
+ this.push('open');
245
+ if (this.screen) {
246
+ this.screenAt = this.now();
247
+ this.push('screen', this.screen, { resume: 1 });
248
+ }
249
+ this.active = true;
250
+ this.schedule();
251
+ }
252
+ background() {
253
+ this.leave();
254
+ this.push('close');
255
+ this.active = false;
256
+ this.persist();
257
+ this.flush();
258
+ }
259
+ setConsent(c) {
260
+ this.consent = c;
261
+ this.st?.set(K.consent, c).catch(() => { });
262
+ if (c === 'denied') {
263
+ this.queue = [];
264
+ this.snaps = [];
265
+ this.persist();
266
+ }
267
+ else if (c === 'granted')
268
+ this.flush();
269
+ }
270
+ optOut() {
271
+ this.setConsent('denied');
272
+ }
273
+ optIn() {
274
+ this.setConsent('granted');
275
+ }
276
+ // Sign-out: a new anonymous id and session, nothing of the old user kept.
277
+ async reset() {
278
+ await this.flush();
279
+ this.userId = null;
280
+ this.anon = 'anon_' + uid();
281
+ this.sessionId = '';
282
+ this.firstSeen = this.now();
283
+ await this.st?.set(K.anon, this.anon).catch(() => { });
284
+ this.touch();
285
+ }
286
+ flush() {
287
+ if (this.inflight)
288
+ return this.inflight.then(() => (this.queue.length && !this.backoff ? this.flush() : undefined));
289
+ this.inflight = this.send().finally(() => (this.inflight = null));
290
+ return this.inflight;
291
+ }
292
+ async send() {
293
+ await this.ready;
294
+ if (this.sending || this.consent !== 'granted' || (!this.queue.length && !this.snaps.length))
295
+ return;
296
+ this.sending = true;
297
+ const events = this.queue.slice(0, BATCH);
298
+ const snaps = this.snaps.splice(0, 4);
299
+ const f = this.cfg.fetch ?? fetch;
300
+ const headers = { 'content-type': 'application/json', 'x-shotik-key': this.cfg.appKey };
301
+ try {
302
+ if (events.length) {
303
+ const body = JSON.stringify(pack({ anonymousId: this.anon, userId: this.userId, firstSeen: this.firstSeen, device: this.cfg.device?.(), events }));
304
+ const r = await f(this.cfg.serverUrl + '/analytics/v1/events', { method: 'POST', headers, body });
305
+ if (!r.ok && r.status < 500 && r.status !== 429) {
306
+ if (this.cfg.debug)
307
+ console.warn('[shotik] dropped batch', r.status);
308
+ }
309
+ else if (!r.ok)
310
+ throw new Error(String(r.status));
311
+ this.queue.splice(0, events.length);
312
+ }
313
+ for (const s of snaps)
314
+ await f(this.cfg.serverUrl + '/analytics/v1/snapshots', { method: 'POST', headers, body: JSON.stringify({ anonymousId: this.anon, ...s }) });
315
+ this.backoff = 0;
316
+ this.persist();
317
+ }
318
+ catch {
319
+ this.snaps.unshift(...snaps);
320
+ this.backoff = Math.min(this.backoff + 1, 5);
321
+ }
322
+ finally {
323
+ this.sending = false;
324
+ }
325
+ if (this.queue.length >= BATCH && !this.backoff)
326
+ return this.send();
327
+ }
328
+ stop() {
329
+ this.active = false;
330
+ if (this.timer)
331
+ clearTimeout(this.timer);
332
+ if (this.saveTimer)
333
+ clearTimeout(this.saveTimer);
334
+ this.persist();
335
+ }
336
+ get ids() {
337
+ return { anonymousId: this.anon, sessionId: this.sessionId, userId: this.userId };
338
+ }
339
+ get pending() {
340
+ return this.queue.length;
341
+ }
342
+ whenReady() {
343
+ return this.ready;
344
+ }
345
+ }
@@ -0,0 +1,5 @@
1
+ export { ShotikAnalytics, ShotikAnalyticsRoot, ShotikMask, useShotikExpoRouter, useShotikScreen, describeTarget } from './rn';
2
+ export type { ShotikAnalyticsConfig, NavigationRefLike } from './rn';
3
+ export { Analytics } from './core';
4
+ export type { AnalyticsConfig, Consent, Storage } from './core';
5
+ export type { Batch, DeviceContext, EventType, WireEvent, Wireframe, WireNode } from './wire';
@@ -0,0 +1,3 @@
1
+ // @shotik/react-native/analytics: behavioral analytics for React Native and Expo, answered by Shotik insights.
2
+ export { ShotikAnalytics, ShotikAnalyticsRoot, ShotikMask, useShotikExpoRouter, useShotikScreen, describeTarget } from './rn';
3
+ export { Analytics } from './core';
@@ -0,0 +1,84 @@
1
+ import { Component } from 'react';
2
+ import type { ReactNode } from 'react';
3
+ import { View } from 'react-native';
4
+ import { Analytics } from './core';
5
+ import type { AnalyticsConfig, Consent, Storage } from './core';
6
+ type Fiber = {
7
+ type: unknown;
8
+ tag: number;
9
+ memoizedProps: Record<string, unknown> | string | null;
10
+ return: Fiber | null;
11
+ child: Fiber | null;
12
+ sibling: Fiber | null;
13
+ index: number;
14
+ stateNode: unknown;
15
+ };
16
+ export declare function describeTarget(target: Fiber | null): {
17
+ el: string;
18
+ id: string;
19
+ label?: string;
20
+ dead: boolean;
21
+ input: boolean;
22
+ scroll: Fiber | null;
23
+ };
24
+ interface RootProps {
25
+ children?: ReactNode;
26
+ }
27
+ export declare class ShotikAnalyticsRoot extends Component<RootProps> {
28
+ private root;
29
+ private start;
30
+ private snapTimer;
31
+ private lastScreen;
32
+ private unsub;
33
+ componentDidMount(): void;
34
+ componentWillUnmount(): void;
35
+ private queueSnapshot;
36
+ private onStart;
37
+ private onEnd;
38
+ render(): import("react").CElement<import("react-native").ViewProps, View>;
39
+ }
40
+ export declare function ShotikMask({ children, style }: {
41
+ children?: ReactNode;
42
+ style?: unknown;
43
+ }): import("react").CElement<import("react-native").ViewProps, View>;
44
+ declare function screen(name: string): void;
45
+ type NavState = {
46
+ index?: number;
47
+ routes: {
48
+ name: string;
49
+ state?: NavState;
50
+ }[];
51
+ };
52
+ export interface NavigationRefLike {
53
+ addListener(e: 'state', cb: (e: {
54
+ data?: {
55
+ state?: NavState;
56
+ };
57
+ }) => void): () => void;
58
+ getRootState?(): NavState | undefined;
59
+ isReady?(): boolean;
60
+ }
61
+ declare function trackNavigation(ref: NavigationRefLike): () => void;
62
+ export declare function useShotikExpoRouter(): void;
63
+ export declare function useShotikScreen(name: string): void;
64
+ declare function trackRevenueCat(P: Record<string, unknown>): void;
65
+ export type ShotikAnalyticsConfig = Omit<AnalyticsConfig, 'storage' | 'device'> & {
66
+ storage?: Storage;
67
+ };
68
+ export declare const ShotikAnalytics: {
69
+ init(cfg: ShotikAnalyticsConfig): Analytics;
70
+ readonly client: Analytics | null;
71
+ track: (name: string, props?: Record<string, unknown>) => void | undefined;
72
+ screen: typeof screen;
73
+ identify: (userId: string | null, traits?: Record<string, unknown>) => void | undefined;
74
+ purchase: (p: Parameters<Analytics["purchase"]>[0]) => void | undefined;
75
+ setConsent: (c: Consent) => void | undefined;
76
+ optOut: () => void | undefined;
77
+ optIn: () => void | undefined;
78
+ reset: () => Promise<void> | undefined;
79
+ flush: () => Promise<void> | undefined;
80
+ trackNavigation: typeof trackNavigation;
81
+ trackRevenueCat: typeof trackRevenueCat;
82
+ stop(): void;
83
+ };
84
+ export {};