@oodle-ai/mobile-sdk-reactnative 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.
Files changed (166) hide show
  1. package/LICENSE +201 -0
  2. package/OodleMobileSdkReactNative.podspec +24 -0
  3. package/README.md +191 -2
  4. package/android/build.gradle +55 -0
  5. package/android/proguard-rules.pro +5 -0
  6. package/android/src/main/AndroidManifest.xml +4 -0
  7. package/android/src/main/java/ai/oodle/rum/Connectivity.kt +19 -0
  8. package/android/src/main/java/ai/oodle/rum/CrashReporter.kt +88 -0
  9. package/android/src/main/java/ai/oodle/rum/DeviceInfo.kt +50 -0
  10. package/android/src/main/java/ai/oodle/rum/ExitReasons.kt +104 -0
  11. package/android/src/main/java/ai/oodle/rum/NativeEvents.kt +24 -0
  12. package/android/src/main/java/ai/oodle/rum/OodleRumModule.kt +96 -0
  13. package/android/src/main/java/ai/oodle/rum/OodleRumPackage.kt +26 -0
  14. package/android/src/main/java/ai/oodle/rum/Storage.kt +84 -0
  15. package/android/src/main/java/ai/oodle/rum/Vitals.kt +188 -0
  16. package/android/src/main/java/ai/oodle/rum/Watchdog.kt +81 -0
  17. package/android/src/main/java/ai/oodle/rum/WireframeCapture.kt +398 -0
  18. package/bin/oodle-rum-upload.mjs +104 -0
  19. package/ios/OodleCrashReporter.h +16 -0
  20. package/ios/OodleCrashReporter.m +202 -0
  21. package/ios/OodleRum.h +18 -0
  22. package/ios/OodleRum.mm +129 -0
  23. package/ios/OodleRumImpl.swift +450 -0
  24. package/ios/WireframeWalker.swift +279 -0
  25. package/lib/core/clock.d.ts +19 -0
  26. package/lib/core/clock.js +47 -0
  27. package/lib/core/clock.js.map +1 -0
  28. package/lib/core/config.d.ts +142 -0
  29. package/lib/core/config.js +178 -0
  30. package/lib/core/config.js.map +1 -0
  31. package/lib/core/consent.d.ts +5 -0
  32. package/lib/core/consent.js +33 -0
  33. package/lib/core/consent.js.map +1 -0
  34. package/lib/core/context.d.ts +36 -0
  35. package/lib/core/context.js +172 -0
  36. package/lib/core/context.js.map +1 -0
  37. package/lib/core/flags.d.ts +3 -0
  38. package/lib/core/flags.js +20 -0
  39. package/lib/core/flags.js.map +1 -0
  40. package/lib/core/ids.d.ts +7 -0
  41. package/lib/core/ids.js +40 -0
  42. package/lib/core/ids.js.map +1 -0
  43. package/lib/core/internal.d.ts +6 -0
  44. package/lib/core/internal.js +10 -0
  45. package/lib/core/internal.js.map +1 -0
  46. package/lib/core/logger.d.ts +8 -0
  47. package/lib/core/logger.js +38 -0
  48. package/lib/core/logger.js.map +1 -0
  49. package/lib/core/native.d.ts +71 -0
  50. package/lib/core/native.js +156 -0
  51. package/lib/core/native.js.map +1 -0
  52. package/lib/core/rate-limiter.d.ts +7 -0
  53. package/lib/core/rate-limiter.js +31 -0
  54. package/lib/core/rate-limiter.js.map +1 -0
  55. package/lib/core/session.d.ts +51 -0
  56. package/lib/core/session.js +196 -0
  57. package/lib/core/session.js.map +1 -0
  58. package/lib/core/size.d.ts +15 -0
  59. package/lib/core/size.js +68 -0
  60. package/lib/core/size.js.map +1 -0
  61. package/lib/core/tags.d.ts +10 -0
  62. package/lib/core/tags.js +33 -0
  63. package/lib/core/tags.js.map +1 -0
  64. package/lib/core/telemetry.d.ts +6 -0
  65. package/lib/core/telemetry.js +37 -0
  66. package/lib/core/telemetry.js.map +1 -0
  67. package/lib/core/tracing.d.ts +9 -0
  68. package/lib/core/tracing.js +57 -0
  69. package/lib/core/tracing.js.map +1 -0
  70. package/lib/core/transport.d.ts +76 -0
  71. package/lib/core/transport.js +560 -0
  72. package/lib/core/transport.js.map +1 -0
  73. package/lib/core/user.d.ts +12 -0
  74. package/lib/core/user.js +41 -0
  75. package/lib/core/user.js.map +1 -0
  76. package/lib/events/actions.d.ts +13 -0
  77. package/lib/events/actions.js +147 -0
  78. package/lib/events/actions.js.map +1 -0
  79. package/lib/events/emit.d.ts +21 -0
  80. package/lib/events/emit.js +144 -0
  81. package/lib/events/emit.js.map +1 -0
  82. package/lib/events/errors.d.ts +19 -0
  83. package/lib/events/errors.js +257 -0
  84. package/lib/events/errors.js.map +1 -0
  85. package/lib/events/lifecycle.d.ts +7 -0
  86. package/lib/events/lifecycle.js +101 -0
  87. package/lib/events/lifecycle.js.map +1 -0
  88. package/lib/events/longtasks.d.ts +2 -0
  89. package/lib/events/longtasks.js +42 -0
  90. package/lib/events/longtasks.js.map +1 -0
  91. package/lib/events/resources.d.ts +15 -0
  92. package/lib/events/resources.js +156 -0
  93. package/lib/events/resources.js.map +1 -0
  94. package/lib/events/tap-target.d.ts +42 -0
  95. package/lib/events/tap-target.js +191 -0
  96. package/lib/events/tap-target.js.map +1 -0
  97. package/lib/events/view-state.d.ts +13 -0
  98. package/lib/events/view-state.js +25 -0
  99. package/lib/events/view-state.js.map +1 -0
  100. package/lib/events/views.d.ts +21 -0
  101. package/lib/events/views.js +347 -0
  102. package/lib/events/views.js.map +1 -0
  103. package/lib/index.d.ts +16 -0
  104. package/lib/index.js +24 -0
  105. package/lib/index.js.map +1 -0
  106. package/lib/navigation/react-navigation.d.ts +33 -0
  107. package/lib/navigation/react-navigation.js +61 -0
  108. package/lib/navigation/react-navigation.js.map +1 -0
  109. package/lib/react/OodlePrivacy.d.ts +15 -0
  110. package/lib/react/OodlePrivacy.js +13 -0
  111. package/lib/react/OodlePrivacy.js.map +1 -0
  112. package/lib/react/OodleProvider.d.ts +18 -0
  113. package/lib/react/OodleProvider.js +72 -0
  114. package/lib/react/OodleProvider.js.map +1 -0
  115. package/lib/replay/recorder.d.ts +22 -0
  116. package/lib/replay/recorder.js +317 -0
  117. package/lib/replay/recorder.js.map +1 -0
  118. package/lib/replay/rrweb.d.ts +105 -0
  119. package/lib/replay/rrweb.js +335 -0
  120. package/lib/replay/rrweb.js.map +1 -0
  121. package/lib/rum.d.ts +52 -0
  122. package/lib/rum.js +281 -0
  123. package/lib/rum.js.map +1 -0
  124. package/lib/specs/NativeOodleRum.d.ts +43 -0
  125. package/lib/specs/NativeOodleRum.js +5 -0
  126. package/lib/specs/NativeOodleRum.js.map +1 -0
  127. package/lib/version.d.ts +1 -0
  128. package/lib/version.js +6 -0
  129. package/lib/version.js.map +1 -0
  130. package/package.json +91 -4
  131. package/react-native.config.js +10 -0
  132. package/src/core/clock.ts +43 -0
  133. package/src/core/config.ts +344 -0
  134. package/src/core/consent.ts +32 -0
  135. package/src/core/context.ts +189 -0
  136. package/src/core/flags.ts +15 -0
  137. package/src/core/ids.ts +35 -0
  138. package/src/core/internal.ts +6 -0
  139. package/src/core/logger.ts +37 -0
  140. package/src/core/native.ts +201 -0
  141. package/src/core/rate-limiter.ts +34 -0
  142. package/src/core/session.ts +209 -0
  143. package/src/core/size.ts +79 -0
  144. package/src/core/tags.ts +30 -0
  145. package/src/core/telemetry.ts +35 -0
  146. package/src/core/tracing.ts +60 -0
  147. package/src/core/transport.ts +590 -0
  148. package/src/core/user.ts +45 -0
  149. package/src/events/actions.ts +157 -0
  150. package/src/events/emit.ts +131 -0
  151. package/src/events/errors.ts +283 -0
  152. package/src/events/lifecycle.ts +102 -0
  153. package/src/events/longtasks.ts +40 -0
  154. package/src/events/resources.ts +167 -0
  155. package/src/events/tap-target.ts +210 -0
  156. package/src/events/view-state.ts +30 -0
  157. package/src/events/views.ts +356 -0
  158. package/src/index.ts +34 -0
  159. package/src/navigation/react-navigation.ts +72 -0
  160. package/src/react/OodlePrivacy.tsx +25 -0
  161. package/src/react/OodleProvider.tsx +88 -0
  162. package/src/replay/recorder.ts +310 -0
  163. package/src/replay/rrweb.ts +460 -0
  164. package/src/rum.ts +295 -0
  165. package/src/specs/NativeOodleRum.ts +51 -0
  166. package/src/version.ts +2 -0
@@ -0,0 +1,344 @@
1
+ import type { Verbosity } from './logger';
2
+
3
+ const DEFAULT_REPLAY_SAMPLE_RATE = 10;
4
+
5
+ export type TrackingConsent = 'granted' | 'not-granted' | 'pending';
6
+
7
+ export type Propagator = 'tracecontext' | 'b3' | 'b3multi' | 'datadog';
8
+
9
+ export type UrlMatcher = string | RegExp | ((url: string) => boolean);
10
+
11
+ export interface TracingUrl {
12
+ /**
13
+ * A string matches the request host and its subdomains
14
+ * (`api.example.com` matches `eu.api.example.com`). A RegExp or a
15
+ * function gets the full URL.
16
+ */
17
+ match: UrlMatcher;
18
+ /** Headers to add. Default: `['tracecontext']`. */
19
+ propagators?: Propagator[];
20
+ }
21
+
22
+ export type TextAndInputPrivacy =
23
+ | 'mask-sensitive-inputs'
24
+ | 'mask-all-inputs'
25
+ | 'mask-all';
26
+
27
+ export type ImagePrivacy = 'mask-all';
28
+
29
+ export type TouchPrivacy = 'show' | 'hide';
30
+
31
+ export interface SessionReplayConfig {
32
+ /**
33
+ * Percentage of sampled sessions that record a replay. Default 10.
34
+ * Replay costs the most JS thread time, device storage and network of
35
+ * all features, so the default records only a sample of sessions.
36
+ */
37
+ sampleRate?: number;
38
+ /** Default `'mask-all-inputs'`. */
39
+ textAndInputPrivacy?: TextAndInputPrivacy;
40
+ /** Images are recorded as placeholders. Default `'mask-all'`. */
41
+ imagePrivacy?: ImagePrivacy;
42
+ /** Default `'show'`. */
43
+ touchPrivacy?: TouchPrivacy;
44
+ /** When false, recording waits for `OodleSessionReplay.start()`. Default true. */
45
+ startRecordingImmediately?: boolean;
46
+ }
47
+
48
+ export type TagValue = string | number | boolean;
49
+
50
+ export interface OodleRumConfig {
51
+ /** Oodle instance ID. */
52
+ instanceId: string;
53
+ /** RUM API key. It can only write RUM data, so it is safe in an app. */
54
+ apiKey: string;
55
+ /** Collector URL, for example `https://<instance>-rum.collector.oodle.ai`. */
56
+ endpoint: string;
57
+ /** Application name. */
58
+ service: string;
59
+ env?: string;
60
+ /** App version. Default: the native app version. */
61
+ version?: string;
62
+ /** App build number. Default: the native build number. */
63
+ build?: string;
64
+
65
+ /** Default `'granted'`. */
66
+ trackingConsent?: TrackingConsent;
67
+ /** Percentage of sessions to track. Default 100. */
68
+ sessionSampleRate?: number;
69
+
70
+ /** Record taps through `OodleProvider`. Default true. */
71
+ trackInteractions?: boolean;
72
+ /** Use `accessibilityLabel` to name taps. Default true. */
73
+ useAccessibilityLabel?: boolean;
74
+ /** Prop that gives a tap its name. Default `'oodle-action-name'`. */
75
+ actionNameAttribute?: string;
76
+ /** Record XHR and fetch requests. Default true. */
77
+ trackResources?: boolean;
78
+ /** Record JS errors and unhandled promise rejections. Default true. */
79
+ trackErrors?: boolean;
80
+ /** Record console.error and console.warn. Default true. */
81
+ trackConsole?: boolean;
82
+
83
+ /** Requests that get trace headers. */
84
+ allowedTracingUrls?: Array<UrlMatcher | TracingUrl>;
85
+ /** Percentage of traced requests marked as sampled. Default 100. */
86
+ traceSampleRate?: number;
87
+
88
+ /** Native crash capture. Default true. */
89
+ nativeCrashReporting?: boolean;
90
+ /** ANR (Android) and app hang (iOS) detection. Default true. */
91
+ trackAnrs?: boolean;
92
+ /** Main thread stall that counts. Default 5000 on Android, 2000 on iOS. */
93
+ anrThresholdMs?: number;
94
+ /** JS thread stall that counts as a long task, or false. Default 200. */
95
+ longTaskThresholdMs?: number | false;
96
+ /** Frame rate, frozen frames, memory and CPU per view. Default true. */
97
+ vitals?: boolean;
98
+
99
+ /** Tags added to every event. */
100
+ tags?: Record<string, TagValue>;
101
+
102
+ /** Session replay settings, or false to turn replay off. Default on. */
103
+ sessionReplay?: boolean | SessionReplayConfig;
104
+
105
+ /** Batch flush interval. Default 5000. */
106
+ flushIntervalMs?: number;
107
+ /** SDK console output. Default `'warn'`. */
108
+ verbosity?: Verbosity;
109
+ /**
110
+ * Called for each event before it is queued. Return the event (changed
111
+ * or not) to keep it, or null to drop it.
112
+ */
113
+ beforeSend?: (
114
+ event: Record<string, unknown>,
115
+ ) => Record<string, unknown> | null | undefined | void;
116
+ }
117
+
118
+ export interface ResolvedTracingUrl {
119
+ test: (url: string) => boolean;
120
+ propagators: Propagator[];
121
+ }
122
+
123
+ export interface ResolvedConfig {
124
+ instanceId: string;
125
+ apiKey: string;
126
+ endpoint: string;
127
+ service: string;
128
+ env: string;
129
+ version?: string;
130
+ build?: string;
131
+ trackingConsent: TrackingConsent;
132
+ sessionSampleRate: number;
133
+ trackInteractions: boolean;
134
+ useAccessibilityLabel: boolean;
135
+ actionNameAttribute: string;
136
+ trackResources: boolean;
137
+ trackErrors: boolean;
138
+ trackConsole: boolean;
139
+ tracingUrls: ResolvedTracingUrl[];
140
+ traceSampleRate: number;
141
+ nativeCrashReporting: boolean;
142
+ trackAnrs: boolean;
143
+ anrThresholdMs: number;
144
+ longTaskThresholdMs: number;
145
+ vitals: boolean;
146
+ tags: Record<string, string>;
147
+ replay: Required<SessionReplayConfig> & { enabled: boolean };
148
+ flushIntervalMs: number;
149
+ verbosity: Verbosity;
150
+ beforeSend?: OodleRumConfig['beforeSend'];
151
+ }
152
+
153
+ function rate(value: unknown, fallback: number): number {
154
+ const n = typeof value === 'number' ? value : fallback;
155
+ if (!Number.isFinite(n)) return fallback;
156
+ return Math.max(0, Math.min(100, n));
157
+ }
158
+
159
+ function hostMatches(host: string, pattern: string): boolean {
160
+ const h = host.toLowerCase();
161
+ const p = pattern.toLowerCase().replace(/^\*\./, '');
162
+ return h === p || h.endsWith('.' + p);
163
+ }
164
+
165
+ export function urlHost(url: string): string {
166
+ const m = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/?#]*@)?(\[[^\]]*\]|[^:/?#]*)/i.exec(
167
+ url,
168
+ );
169
+ return m ? m[1].toLowerCase() : '';
170
+ }
171
+
172
+ export function toUrlTest(match: UrlMatcher): (url: string) => boolean {
173
+ if (typeof match === 'function') {
174
+ return (url) => {
175
+ try {
176
+ return Boolean(match(url));
177
+ } catch {
178
+ return false;
179
+ }
180
+ };
181
+ }
182
+ if (match instanceof RegExp) {
183
+ return (url) => {
184
+ match.lastIndex = 0;
185
+ return match.test(url);
186
+ };
187
+ }
188
+ // A full URL prefix ("https://api.example.com/v1") matches by prefix;
189
+ // a bare host matches the host and its subdomains.
190
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(match)) {
191
+ return (url) => url.startsWith(match);
192
+ }
193
+ return (url) => {
194
+ const host = urlHost(url);
195
+ return host !== '' && hostMatches(host, match);
196
+ };
197
+ }
198
+
199
+ function resolveTracing(
200
+ urls: OodleRumConfig['allowedTracingUrls'],
201
+ ): ResolvedTracingUrl[] {
202
+ if (!Array.isArray(urls)) return [];
203
+ const out: ResolvedTracingUrl[] = [];
204
+ for (const entry of urls) {
205
+ if (
206
+ typeof entry === 'string' ||
207
+ entry instanceof RegExp ||
208
+ typeof entry === 'function'
209
+ ) {
210
+ out.push({ test: toUrlTest(entry), propagators: ['tracecontext'] });
211
+ } else if (entry && typeof entry === 'object' && 'match' in entry) {
212
+ const propagators =
213
+ Array.isArray(entry.propagators) && entry.propagators.length > 0
214
+ ? entry.propagators
215
+ : (['tracecontext'] as Propagator[]);
216
+ out.push({ test: toUrlTest(entry.match), propagators });
217
+ }
218
+ }
219
+ return out;
220
+ }
221
+
222
+ const PRIVATE_HOST =
223
+ /^(localhost|127\.\d+\.\d+\.\d+|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(1[6-9]|2\d|3[01])\.\d+\.\d+|\[::1\]|[^.]+\.local|[^.]+\.test)$/i;
224
+
225
+ /**
226
+ * Returns an error message, or null when the endpoint is usable. Plain
227
+ * HTTP is accepted only for loopback and private hosts, because the API
228
+ * key travels in a header.
229
+ */
230
+ export function checkEndpoint(endpoint: string): string | null {
231
+ if (!/^https?:\/\//i.test(endpoint)) {
232
+ return `endpoint must be an http(s) URL, got "${endpoint}"`;
233
+ }
234
+ const host = urlHost(endpoint);
235
+ if (!host) return `endpoint has no host: "${endpoint}"`;
236
+ if (/^http:/i.test(endpoint) && !PRIVATE_HOST.test(host)) {
237
+ return `endpoint must use https for a public host, got "${endpoint}"`;
238
+ }
239
+ return null;
240
+ }
241
+
242
+ export function stringifyTags(
243
+ tags: Record<string, TagValue> | undefined,
244
+ ): Record<string, string> {
245
+ const out: Record<string, string> = {};
246
+ if (!tags || typeof tags !== 'object') return out;
247
+ for (const [k, v] of Object.entries(tags)) {
248
+ if (v === undefined || v === null) continue;
249
+ out[k] = String(v);
250
+ }
251
+ return out;
252
+ }
253
+
254
+ export function resolveConfig(
255
+ input: OodleRumConfig,
256
+ platformOS: string,
257
+ ): { config?: ResolvedConfig; error?: string } {
258
+ if (!input || typeof input !== 'object') {
259
+ return { error: 'init() needs a configuration object' };
260
+ }
261
+ for (const key of ['instanceId', 'apiKey', 'endpoint', 'service'] as const) {
262
+ if (typeof input[key] !== 'string' || input[key].trim() === '') {
263
+ return { error: `"${key}" is required` };
264
+ }
265
+ }
266
+ const endpoint = input.endpoint.trim().replace(/\/+$/, '');
267
+ const endpointError = checkEndpoint(endpoint);
268
+ if (endpointError) return { error: endpointError };
269
+
270
+ const replayInput = input.sessionReplay;
271
+ const replayObj: SessionReplayConfig =
272
+ replayInput && typeof replayInput === 'object' ? replayInput : {};
273
+ const longTask = input.longTaskThresholdMs;
274
+
275
+ const config: ResolvedConfig = {
276
+ instanceId: input.instanceId.trim(),
277
+ apiKey: input.apiKey.trim(),
278
+ endpoint,
279
+ service: input.service.trim(),
280
+ env: input.env ?? '',
281
+ version: input.version || undefined,
282
+ build: input.build || undefined,
283
+ trackingConsent:
284
+ input.trackingConsent === 'not-granted' ||
285
+ input.trackingConsent === 'pending'
286
+ ? input.trackingConsent
287
+ : 'granted',
288
+ sessionSampleRate: rate(input.sessionSampleRate, 100),
289
+ trackInteractions: input.trackInteractions !== false,
290
+ useAccessibilityLabel: input.useAccessibilityLabel !== false,
291
+ actionNameAttribute: input.actionNameAttribute || 'oodle-action-name',
292
+ trackResources: input.trackResources !== false,
293
+ trackErrors: input.trackErrors !== false,
294
+ trackConsole: input.trackConsole !== false,
295
+ tracingUrls: resolveTracing(input.allowedTracingUrls),
296
+ traceSampleRate: rate(input.traceSampleRate, 100),
297
+ nativeCrashReporting: input.nativeCrashReporting !== false,
298
+ trackAnrs: input.trackAnrs !== false,
299
+ anrThresholdMs:
300
+ typeof input.anrThresholdMs === 'number' && input.anrThresholdMs > 0
301
+ ? input.anrThresholdMs
302
+ : platformOS === 'ios'
303
+ ? 2000
304
+ : 5000,
305
+ longTaskThresholdMs:
306
+ longTask === false
307
+ ? 0
308
+ : typeof longTask === 'number' && longTask > 0
309
+ ? Math.max(50, longTask)
310
+ : 200,
311
+ vitals: input.vitals !== false,
312
+ tags: stringifyTags(input.tags),
313
+ replay: {
314
+ enabled: replayInput !== false,
315
+ sampleRate: rate(replayObj.sampleRate, DEFAULT_REPLAY_SAMPLE_RATE),
316
+ textAndInputPrivacy:
317
+ replayObj.textAndInputPrivacy === 'mask-sensitive-inputs' ||
318
+ replayObj.textAndInputPrivacy === 'mask-all'
319
+ ? replayObj.textAndInputPrivacy
320
+ : 'mask-all-inputs',
321
+ imagePrivacy: 'mask-all',
322
+ touchPrivacy: replayObj.touchPrivacy === 'hide' ? 'hide' : 'show',
323
+ startRecordingImmediately: replayObj.startRecordingImmediately !== false,
324
+ },
325
+ flushIntervalMs:
326
+ typeof input.flushIntervalMs === 'number' && input.flushIntervalMs >= 1000
327
+ ? input.flushIntervalMs
328
+ : 5000,
329
+ verbosity: input.verbosity ?? 'warn',
330
+ beforeSend:
331
+ typeof input.beforeSend === 'function' ? input.beforeSend : undefined,
332
+ };
333
+ return { config };
334
+ }
335
+
336
+ let current: ResolvedConfig | null = null;
337
+
338
+ export function setConfig(c: ResolvedConfig | null) {
339
+ current = c;
340
+ }
341
+
342
+ export function getConfig(): ResolvedConfig | null {
343
+ return current;
344
+ }
@@ -0,0 +1,32 @@
1
+ import type { TrackingConsent } from './config';
2
+
3
+ let consent: TrackingConsent = 'granted';
4
+ const listeners: Array<(c: TrackingConsent, previous: TrackingConsent) => void> = [];
5
+
6
+ export function getConsent(): TrackingConsent {
7
+ return consent;
8
+ }
9
+
10
+ export function setConsentState(next: TrackingConsent) {
11
+ const previous = consent;
12
+ consent = next;
13
+ if (previous === next) return;
14
+ for (const fn of listeners) {
15
+ try {
16
+ fn(next, previous);
17
+ } catch {
18
+ // keep notifying the other listeners
19
+ }
20
+ }
21
+ }
22
+
23
+ export function onConsentChange(
24
+ fn: (c: TrackingConsent, previous: TrackingConsent) => void,
25
+ ) {
26
+ listeners.push(fn);
27
+ }
28
+
29
+ export function resetConsent() {
30
+ consent = 'granted';
31
+ listeners.length = 0;
32
+ }
@@ -0,0 +1,189 @@
1
+ import { Platform } from 'react-native';
2
+ import { SDK_VERSION } from '../version';
3
+ import { getCurrentViewInfo, getPreviousScreenName } from '../events/view-state';
4
+ import { getConfig } from './config';
5
+ import { getFeatureFlags } from './flags';
6
+ import { getDeviceInfo, native, storage } from './native';
7
+ import { getSession } from './session';
8
+ import { getTags } from './tags';
9
+ import { getUser, userFields } from './user';
10
+ import { isoTime } from './clock';
11
+ import { uuid } from './ids';
12
+
13
+ const CONNECTIVITY_TTL_MS = 30_000;
14
+
15
+ let connection = 'unknown';
16
+ let connectionCheckedAt = 0;
17
+ let replayIdProvider: () => string = () => '';
18
+ let cachedStatic: Record<string, string> | null = null;
19
+
20
+ export const PLATFORM = 'react-native';
21
+ export const RUNTIME_NAME = 'React Native';
22
+
23
+ /** The replay module reports whether this session has a stored replay. */
24
+ export function setReplayIdProvider(fn: () => string) {
25
+ replayIdProvider = fn;
26
+ }
27
+
28
+ export function refreshConnectivity() {
29
+ connection = native.getConnectivity() || 'unknown';
30
+ connectionCheckedAt = Date.now();
31
+ }
32
+
33
+ /** Native connection names as `network.connection.type` values. */
34
+ const OTEL_CONNECTION_TYPE: Record<string, string> = {
35
+ wifi: 'wifi',
36
+ cellular: 'cell',
37
+ ethernet: 'wired',
38
+ none: 'unavailable',
39
+ };
40
+
41
+ function connectivity(): string {
42
+ if (Date.now() - connectionCheckedAt > CONNECTIVITY_TTL_MS) refreshConnectivity();
43
+ return OTEL_CONNECTION_TYPE[connection] ?? 'unknown';
44
+ }
45
+
46
+ const INSTALLATION_ID_KEY = 'installation_id';
47
+
48
+ /**
49
+ * A random ID for this install of the app (`app.installation.id`). It
50
+ * counts devices for people who are not signed in. It is kept in the
51
+ * app's own files, so it ends when the app is removed.
52
+ */
53
+ function installationId(): string {
54
+ let id = storage.get(INSTALLATION_ID_KEY);
55
+ if (!id) {
56
+ id = uuid();
57
+ storage.set(INSTALLATION_ID_KEY, id);
58
+ }
59
+ return id;
60
+ }
61
+
62
+ function rnVersion(): string {
63
+ const v = (Platform as unknown as {
64
+ constants?: { reactNativeVersion?: { major: number; minor: number; patch: number } };
65
+ }).constants?.reactNativeVersion;
66
+ return v ? `${v.major}.${v.minor}.${v.patch}` : '';
67
+ }
68
+
69
+ export function appVersion(): string {
70
+ return getConfig()?.version || getDeviceInfo().appVersion || '';
71
+ }
72
+
73
+ export function appBuild(): string {
74
+ return getConfig()?.build || getDeviceInfo().appBuild || '';
75
+ }
76
+
77
+ function staticContext(): Record<string, string> {
78
+ if (cachedStatic) return cachedStatic;
79
+ const d = getDeviceInfo();
80
+ const c = getConfig();
81
+ const service = c?.service ?? '';
82
+ const version = appVersion();
83
+ // Names follow the OpenTelemetry semantic conventions where one exists
84
+ // (`service.name` is `service_name`). The collector maps them to its
85
+ // RUM columns.
86
+ cachedStatic = {
87
+ service_name: service,
88
+ deployment_environment_name: c?.env ?? '',
89
+ service_version: version,
90
+ app_build: appBuild(),
91
+ device_type: d.deviceType,
92
+ device_manufacturer: d.brand,
93
+ device_model_identifier: d.model,
94
+ app_installation_id: installationId(),
95
+ os_name: d.osName,
96
+ os_version: d.osVersion,
97
+ process_runtime_name: RUNTIME_NAME,
98
+ process_runtime_version: rnVersion(),
99
+ platform: PLATFORM,
100
+ language: d.locale,
101
+ user_agent_original:
102
+ `${service}/${version} (${d.osName} ${d.osVersion}; ${d.brand} ${d.model}) ` +
103
+ `ReactNative/${rnVersion()} oodle-rn/${SDK_VERSION}`,
104
+ };
105
+ return cachedStatic;
106
+ }
107
+
108
+ /** The app as a URL host. `view_url` is `app://<service>/<Screen>`. */
109
+ export function viewUrlFor(name: string): { url: string; path: string } {
110
+ const service = getConfig()?.service ?? 'app';
111
+ const path = '/' + encodeURIComponent(name || 'unknown');
112
+ return { url: `app://${service}${path}`, path };
113
+ }
114
+
115
+ /**
116
+ * Fields on every event. `activity` is false for background work (view
117
+ * refreshes, telemetry) so it cannot keep an idle session alive.
118
+ */
119
+ export function baseContext(activity: boolean): Record<string, unknown> {
120
+ const session = getSession(activity);
121
+ const view = getCurrentViewInfo();
122
+ const ctx: Record<string, unknown> = {
123
+ ...staticContext(),
124
+ session_id: session.id,
125
+ ...userFields(),
126
+ timestamp: isoTime(),
127
+ app_screen_name: view?.name ?? '',
128
+ app_screen_previous_name: getPreviousScreenName(),
129
+ view_id: view?.id ?? '',
130
+ network_connection_type: connectivity(),
131
+ session_view_count: session.viewCount,
132
+ session_error_count: session.errorCount,
133
+ session_action_count: session.actionCount,
134
+ replay_id: replayIdProvider(),
135
+ tags: getTags(),
136
+ };
137
+ const flags = getFeatureFlags();
138
+ if (flags) ctx.feature_flags = flags;
139
+ return ctx;
140
+ }
141
+
142
+ const LAST_CONTEXT_KEY = 'last_context';
143
+
144
+ /**
145
+ * Saves who and where the app is, so a native crash reported on the next
146
+ * start can be attached to the session and screen it happened on.
147
+ */
148
+ export function saveLastContext() {
149
+ const session = getSession(false);
150
+ const view = getCurrentViewInfo();
151
+ const user = getUser();
152
+ storage.setJSON(LAST_CONTEXT_KEY, {
153
+ session_id: session.id,
154
+ sampled: session.sampled,
155
+ app_screen_name: view?.name ?? '',
156
+ view_id: view?.id ?? '',
157
+ user: user ? { ...user } : null,
158
+ tags: getTags(),
159
+ version: appVersion(),
160
+ app_build: appBuild(),
161
+ });
162
+ }
163
+
164
+ export interface LastContext {
165
+ session_id: string;
166
+ sampled: boolean;
167
+ app_screen_name: string;
168
+ view_id: string;
169
+ user: Record<string, unknown> | null;
170
+ tags: Record<string, string>;
171
+ version: string;
172
+ app_build: string;
173
+ }
174
+
175
+ export function loadLastContext(): LastContext | null {
176
+ return storage.getJSON<LastContext | null>(LAST_CONTEXT_KEY, null);
177
+ }
178
+
179
+ export function staticFields(): Record<string, string> {
180
+ return staticContext();
181
+ }
182
+
183
+ /** Test hook. */
184
+ export function resetContext() {
185
+ cachedStatic = null;
186
+ connection = 'unknown';
187
+ connectionCheckedAt = 0;
188
+ replayIdProvider = () => '';
189
+ }
@@ -0,0 +1,15 @@
1
+ const flags = new Map<string, string>();
2
+
3
+ export function addFeatureFlag(name: string, value: unknown) {
4
+ if (!name) return;
5
+ flags.set(name, typeof value === 'string' ? value : JSON.stringify(value));
6
+ }
7
+
8
+ export function getFeatureFlags(): Record<string, string> | undefined {
9
+ if (flags.size === 0) return undefined;
10
+ return Object.fromEntries(flags);
11
+ }
12
+
13
+ export function clearFeatureFlags() {
14
+ flags.clear();
15
+ }
@@ -0,0 +1,35 @@
1
+ function randomHex(chars: number): string {
2
+ let out = '';
3
+ for (let i = 0; i < chars; i++) {
4
+ out += ((Math.random() * 16) | 0).toString(16);
5
+ }
6
+ return out;
7
+ }
8
+
9
+ /** RFC 4122 version 4 id. Hermes has no crypto.randomUUID. */
10
+ export function uuid(): string {
11
+ const c = globalThis.crypto as { randomUUID?: () => string } | undefined;
12
+ if (c && typeof c.randomUUID === 'function') {
13
+ try {
14
+ return c.randomUUID();
15
+ } catch {
16
+ // fall through to the Math.random form
17
+ }
18
+ }
19
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (ch) => {
20
+ const r = (Math.random() * 16) | 0;
21
+ const v = ch === 'x' ? r : (r & 0x3) | 0x8;
22
+ return v.toString(16);
23
+ });
24
+ }
25
+
26
+ /**
27
+ * Hex id of `bytes` random bytes that is never all zeros, because W3C
28
+ * trace context treats an all-zero trace or span id as invalid.
29
+ */
30
+ export function hexId(bytes: number): string {
31
+ for (;;) {
32
+ const id = randomHex(bytes * 2);
33
+ if (!/^0+$/.test(id)) return id;
34
+ }
35
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Marks the SDK's own upload requests. The XHR tracker skips any request
3
+ * that carries it, so an upload never records itself as a resource and
4
+ * never feeds the next upload.
5
+ */
6
+ export const INTERNAL_REQUEST = '__oodleInternalRequest';
@@ -0,0 +1,37 @@
1
+ export type Verbosity = 'debug' | 'warn' | 'error' | 'none';
2
+
3
+ export const LOG_PREFIX = '[@oodle-ai/mobile-sdk-reactnative]';
4
+
5
+ const LEVELS: Record<Verbosity, number> = {
6
+ debug: 0,
7
+ warn: 1,
8
+ error: 2,
9
+ none: 3,
10
+ };
11
+
12
+ let level: Verbosity = 'warn';
13
+
14
+ // The console tracker wraps console.warn and console.error. The SDK
15
+ // keeps the original functions so its own messages never come back
16
+ // to it as console events.
17
+ const original = {
18
+ log: console.log.bind(console),
19
+ warn: console.warn.bind(console),
20
+ error: console.error.bind(console),
21
+ };
22
+
23
+ export function setVerbosity(v: Verbosity | undefined) {
24
+ level = v && v in LEVELS ? v : 'warn';
25
+ }
26
+
27
+ export const logger = {
28
+ debug(...args: unknown[]) {
29
+ if (LEVELS[level] <= LEVELS.debug) original.log(LOG_PREFIX, ...args);
30
+ },
31
+ warn(...args: unknown[]) {
32
+ if (LEVELS[level] <= LEVELS.warn) original.warn(LOG_PREFIX, ...args);
33
+ },
34
+ error(...args: unknown[]) {
35
+ if (LEVELS[level] <= LEVELS.error) original.error(LOG_PREFIX, ...args);
36
+ },
37
+ };