@metarouter/react-native-sdk 1.8.0 → 1.9.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 (54) hide show
  1. package/README.md +139 -6
  2. package/android/build.gradle +2 -0
  3. package/android/src/main/java/com/metarouter/reactnative/MetaRouterClockModule.kt +24 -0
  4. package/android/src/main/java/com/metarouter/reactnative/MetaRouterPackage.kt +3 -1
  5. package/android/src/main/java/com/metarouter/reactnative/MetaRouterWebViewSupportModule.kt +27 -0
  6. package/ios/MetaRouterClock.m +31 -0
  7. package/lib/analytics/MetaRouterAnalyticsClient.d.ts +21 -0
  8. package/lib/analytics/MetaRouterAnalyticsClient.d.ts.map +1 -1
  9. package/lib/analytics/MetaRouterAnalyticsClient.js +77 -10
  10. package/lib/analytics/init.d.ts.map +1 -1
  11. package/lib/analytics/init.js +14 -1
  12. package/lib/analytics/proxy/proxyClient.d.ts +2 -0
  13. package/lib/analytics/proxy/proxyClient.d.ts.map +1 -1
  14. package/lib/analytics/proxy/proxyClient.js +28 -1
  15. package/lib/analytics/session/sessionManager.d.ts +108 -0
  16. package/lib/analytics/session/sessionManager.d.ts.map +1 -0
  17. package/lib/analytics/session/sessionManager.js +193 -0
  18. package/lib/analytics/types.d.ts +58 -0
  19. package/lib/analytics/types.d.ts.map +1 -1
  20. package/lib/analytics/utils/appContext.d.ts +5 -3
  21. package/lib/analytics/utils/appContext.d.ts.map +1 -1
  22. package/lib/analytics/utils/appContext.js +9 -8
  23. package/lib/analytics/utils/enrichEvent.d.ts +6 -2
  24. package/lib/analytics/utils/enrichEvent.d.ts.map +1 -1
  25. package/lib/analytics/utils/enrichEvent.js +20 -3
  26. package/lib/analytics/utils/initOptions.d.ts.map +1 -1
  27. package/lib/analytics/utils/initOptions.js +7 -0
  28. package/lib/analytics/utils/monotonicClock.d.ts +15 -0
  29. package/lib/analytics/utils/monotonicClock.d.ts.map +1 -0
  30. package/lib/analytics/utils/monotonicClock.js +52 -0
  31. package/lib/analytics/utils/sessionStorage.d.ts +27 -0
  32. package/lib/analytics/utils/sessionStorage.d.ts.map +1 -0
  33. package/lib/analytics/utils/sessionStorage.js +85 -0
  34. package/lib/analytics/webview/bridgeDedupStore.d.ts +37 -0
  35. package/lib/analytics/webview/bridgeDedupStore.d.ts.map +1 -0
  36. package/lib/analytics/webview/bridgeDedupStore.js +63 -0
  37. package/lib/analytics/webview/bridgeEnvelope.d.ts +68 -0
  38. package/lib/analytics/webview/bridgeEnvelope.d.ts.map +1 -0
  39. package/lib/analytics/webview/bridgeEnvelope.js +140 -0
  40. package/lib/analytics/webview/bridgeMessageProcessor.d.ts +38 -0
  41. package/lib/analytics/webview/bridgeMessageProcessor.d.ts.map +1 -0
  42. package/lib/analytics/webview/bridgeMessageProcessor.js +67 -0
  43. package/lib/analytics/webview/bridgeWrapperScript.d.ts +53 -0
  44. package/lib/analytics/webview/bridgeWrapperScript.d.ts.map +1 -0
  45. package/lib/analytics/webview/bridgeWrapperScript.js +161 -0
  46. package/lib/analytics/webview/webViewBridge.d.ts +39 -0
  47. package/lib/analytics/webview/webViewBridge.d.ts.map +1 -0
  48. package/lib/analytics/webview/webViewBridge.js +211 -0
  49. package/lib/analytics/webview/webViewSupport.d.ts +16 -0
  50. package/lib/analytics/webview/webViewSupport.d.ts.map +1 -0
  51. package/lib/analytics/webview/webViewSupport.js +52 -0
  52. package/lib/index.d.ts +1 -1
  53. package/lib/index.d.ts.map +1 -1
  54. package/package.json +11 -3
package/README.md CHANGED
@@ -16,6 +16,8 @@ A lightweight React Native analytics SDK that transmits events to your MetaRoute
16
16
  - [Features](#features)
17
17
  - [Disk-Backed Queue Persistence](#disk-backed-queue-persistence)
18
18
  - [Application Lifecycle Events](#application-lifecycle-events)
19
+ - [Session Tracking](#session-tracking)
20
+ - [WebView Bridge](#webview-bridge)
19
21
  - [Compatibility](#-compatibility)
20
22
  - [Debugging](#debugging)
21
23
  - [Identity Persistence](#identity-persistence)
@@ -178,6 +180,8 @@ Calls to `track`, `identify`, etc. are **buffered in-memory** by the proxy and r
178
180
  - `maxQueueEvents` (number, optional, default: `2000`): Maximum events held in the in-memory queue. Values below 1 are clamped to 1. The queue is also bounded by a 5 MB byte cap — whichever limit is reached first triggers drop-oldest eviction.
179
181
  - `maxDiskEvents` (number, optional, default: `10000`): Maximum unsent events retained on disk for crash safety and offline recovery. Negative values are clamped to `0` with a warning. Set to `0` to disable disk persistence (events are lost on app kill).
180
182
  - `trackLifecycleEvents` (boolean, optional, default: `false`): Opt-in. Set to `true` to emit `Application Installed`, `Application Updated`, `Application Opened`, and `Application Backgrounded` events automatically. See [Application Lifecycle Events](#application-lifecycle-events).
183
+ - `sessionTimeoutMinutes` (number, optional, default: `30`): Minutes of inactivity after which the next event starts a new session. Fractions are accepted (`1.5` is 90 seconds); values below 1 are clamped to 1. See [Session Tracking](#session-tracking).
184
+ - `fireSessionStarted` (boolean, optional, default: `false`): Emit a `Session Started` track event each time a new session starts. See [Session Tracking](#session-tracking).
181
185
  - `onConfigError` (function, optional): Called with a `ConfigError` (`type`, `description`, and `raw` for a bad host) when the options are invalid in a release build. See [Invalid configuration](#invalid-configuration).
182
186
 
183
187
  Out-of-range numbers are clamped and logged as a warning; they never fail initialization.
@@ -234,9 +238,11 @@ The analytics client provides the following methods:
234
238
  - `setAdvertisingId(advertisingId: string)`: Set the advertising identifier (IDFA on iOS, GAID on Android) for ad tracking. See [Advertising ID](#advertising-id-idfagaid) section for usage and compliance requirements
235
239
  - `clearAdvertisingId()`: Clear the advertising identifier from storage and context. Useful for GDPR/CCPA compliance when users opt out of ad tracking
236
240
  - `getAnonymousId(): Promise<string>`: Returns the current anonymous ID. Async, never returns null — guaranteed to resolve a string after `init()`
241
+ - `attachWebView(webViewRef, allowedOrigins: string[])`: Bridge a `react-native-webview` WebView so its pages' events are sent through the SDK. Returns props to spread onto the `<WebView>`. See [WebView Bridge](#webview-bridge)
242
+ - `getSessionId(): Promise<string | null>`: Returns the current session ID, or `null` before the first event has been sent this launch. Never waits for initialization and never extends the session. See [Session Tracking](#session-tracking)
237
243
  - `setTracing(enabled: boolean)`: Enable or disable tracing headers on API requests. When enabled, includes a `Trace: true` header for debugging request flows
238
244
  - `flush()`: Flush events immediately
239
- - `reset()`: Reset analytics state and clear all stored data (includes clearing advertising ID)
245
+ - `reset()`: Reset analytics state and clear stored identity (includes clearing advertising ID). The analytics session survives, so a logout does not split it
240
246
  - `enableDebugLogging()`: Enable debug logging
241
247
  - `getDebugInfo()`: Get current debug information
242
248
 
@@ -255,18 +261,23 @@ The analytics client provides the following methods:
255
261
  - 🎣 **React Hooks**: Easy integration with React components
256
262
  - 🔧 **TypeScript Support**: Full TypeScript support included
257
263
  - 🚀 **Lightweight**: Minimal overhead and dependencies
258
- - 💾 **Best-Effort Queue Persistence**: Can persist queued events to native disk storage and rehydrate them on next launch
264
+ - 💾 **Best-Effort Queue Persistence**: Persists unsent events to native disk storage and delivers them on reconnect or next launch
265
+ - 🌐 **WebView Bridge**: Events from pages in a `react-native-webview` WebView arrive with the app's identity — see [WebView Bridge](#webview-bridge)
266
+ - ⏱️ **Session Tracking**: Every event carries a session ID and count — see [Session Tracking](#session-tracking)
259
267
  - 📲 **Lifecycle Events (opt-in)**: Emit `Application Installed/Updated/Opened/Backgrounded` automatically when enabled — see [Application Lifecycle Events](#application-lifecycle-events)
260
268
  - 🔄 **Reset Capability**: Easily reset analytics state for testing or logout scenarios
261
269
  - 🐛 **Debug Support**: Built-in debugging tools for troubleshooting
262
270
 
263
271
  ## Disk-Backed Queue Persistence
264
272
 
265
- This release adds native iOS and Android storage for best-effort queue durability.
273
+ Native iOS and Android storage gives the queue best-effort durability.
266
274
 
267
- - If queued events remain buffered when the app backgrounds, the SDK may persist the remaining queue to disk.
268
- - If the in-memory queue grows past internal persistence thresholds, the SDK may snapshot the queue to disk as a fallback.
269
- - Persisted events are rehydrated during the next `init()`.
275
+ - Events still in memory when the app backgrounds are written to disk.
276
+ - Once 500 events or 2 MB are queued in memory, the queue is also written to disk as a crash-safety snapshot.
277
+ - When the in-memory queue reaches `maxQueueEvents`, or the device is offline, overflowing events go to disk instead of being dropped.
278
+ - Events on disk are sent straight to the network when connectivity returns or on the next launch, without being loaded back into the memory queue. Events older than 7 days are discarded.
279
+ - When disk storage reaches `maxDiskEvents`, the oldest events are dropped. `reset()` deletes everything on disk.
280
+ - Without the native modules (for example in Expo Go), persistence is disabled with a warning.
270
281
  - This is a durability baseline, not a full offline mode. The SDK still primarily uses in-memory batching and normal network delivery, and it does not guarantee zero-loss across every crash or termination window.
271
282
 
272
283
  ## Application Lifecycle Events
@@ -357,6 +368,128 @@ Linking.addEventListener("url", ({ url }) => {
357
368
  - **Host control.** Apps with custom URL routers or deep-link libraries (react-navigation linking, react-native-firebase dynamic links, Branch) need to decide *if* and *which* URLs reach analytics — `recordOpenedURL` is the explicit hand-off point.
358
369
  - **Parity.** The iOS (`recordOpenedURL`) and Android (`recordOpenedUrl`) SDKs work the same way, so the same app behaves the same on every platform.
359
370
 
371
+ ## Session Tracking
372
+
373
+ Every event carries the analytics session it belongs to, stamped as:
374
+
375
+ ```json
376
+ "context": {
377
+ "providers": {
378
+ "metarouter": {
379
+ "sessionID": "1757400000000",
380
+ "sessionCount": 3
381
+ }
382
+ }
383
+ }
384
+ ```
385
+
386
+ This is the same path and shape the web SDK's MetaRouter session sync and the iOS and Android SDKs produce, so pipeline mappings (e.g. GA4 `session_id` / `session_number`) read one field from every platform. `sessionID` is the epoch-millisecond timestamp of the session's first activity, as a string; `sessionCount` is the lifetime session ordinal for the install.
387
+
388
+ Session stamping is **always on** — there is nothing to enable and no network cost. A session starts with the first event and ends after `sessionTimeoutMinutes` (default 30) of inactivity; the window slides, so steady activity keeps one session alive indefinitely. Any tracked or lifecycle event counts as activity. Sessions survive app restarts that happen inside the window, and survive `reset()` — a logout mid-session does not split the session. Session state (id, count and last activity) is kept in AsyncStorage as one JSON value under `metarouter:session`, separate from identity, which is why `reset()` leaves it alone.
389
+
390
+ While the app is running, inactivity is measured on a native clock that keeps counting while the device sleeps and ignores changes to the device time. Across an app restart only the device time is available, so changing it can start a new session. Without the SDK's native modules (for example in Expo Go), the SDK uses the device time throughout and logs a warning.
391
+
392
+ ### Session Started event
393
+
394
+ Optionally, the SDK emits a `Session Started` track event (no properties, matching web) each time a new session starts:
395
+
396
+ ```ts
397
+ const analytics = createAnalyticsClient({
398
+ writeKey: 'YOUR_WRITE_KEY',
399
+ ingestionHost: 'https://your-ingestion-host.com',
400
+ sessionTimeoutMinutes: 30, // default
401
+ fireSessionStarted: true, // default false
402
+ });
403
+ ```
404
+
405
+ `fireSessionStarted` is off by default so upgrading the SDK never changes an app's event volume. Turn it on when a downstream destination needs an explicit session-start signal (GA4's `session_start`, for example).
406
+
407
+ ## WebView Bridge
408
+
409
+ Hybrid apps render some screens as web content inside a WebView. Without extra work that activity is invisible to MetaRouter, or double-tracked by an in-page analytics setup on a separate identity. The WebView bridge captures events fired by page JavaScript and sends them through the SDK, so WebView and app activity arrive at your cluster as **one user, one pipeline**: the app's identity, device context and session, plus the page's own facts, on every event.
410
+
411
+ ### Attaching
412
+
413
+ The bridge works with [`react-native-webview`](https://github.com/react-native-webview/react-native-webview) 13.13.1 or newer, an optional peer dependency (earlier versions report the main page's URL for messages from iframes, which the origin check relies on). `attachWebView` returns the props that wire the bridge into a `<WebView>`:
414
+
415
+ ```tsx
416
+ import { useRef } from 'react';
417
+ import { WebView } from 'react-native-webview';
418
+
419
+ function CheckoutScreen() {
420
+ const webViewRef = useRef<WebView>(null);
421
+ const bridge = analytics.attachWebView(webViewRef, ['https://www.example.com']);
422
+
423
+ return (
424
+ <WebView
425
+ ref={webViewRef}
426
+ source={{ uri: 'https://www.example.com/checkout' }}
427
+ injectedJavaScriptBeforeContentLoaded={bridge.injectedJavaScriptBeforeContentLoaded}
428
+ onMessage={(event) => {
429
+ if (!bridge.onMessage(event)) {
430
+ // Not a bridge message — the app's own page messages arrive here.
431
+ }
432
+ }}
433
+ />
434
+ );
435
+ }
436
+ ```
437
+
438
+ - `bridge.onMessage` returns `true` when it handled a bridge message and `false` for anything else, so an app that already uses `onMessage` chains its own handler. Without one, pass `onMessage={bridge.onMessage}`.
439
+ - Pass the ref so the page receives an ack or error for each message. Without a ref, events are still captured.
440
+ - Calling `attachWebView` on every render is fine, and so is calling it before `createAnalyticsClient` has finished initializing: messages that arrive before then are answered `not_ready`. The bridge keeps working across `reset()` and re-initialization.
441
+ - If the app already sets `injectedJavaScriptBeforeContentLoaded`, join the two scripts (`bridge.injectedJavaScriptBeforeContentLoaded + yourScript`). When the attach is refused the bridge script is empty, so the join stays safe.
442
+
443
+ Origins must be explicit `scheme://host[:port]` rules — no wildcards, paths or trailing slashes. Scheme and host are case-insensitive and default ports are ignored. Invalid rules are refused with a warning, and the returned props then do nothing. Origin scoping is the bridge's security boundary: it keeps other pages loaded in the same WebView (ads, redirects) from injecting events. `react-native-webview` does not scope its message channel to origins, so the SDK enforces the allowlist in two places: the injected wrapper defines nothing on other pages, and every message's sending-frame URL is checked — a message from any other origin is ignored without a reply. Messages must also carry a random token that the injected wrapper holds, as a second layer against frames that never received the wrapper. The token is not a secret from scripts on an allowed page (they are trusted already, and can call the bridge directly). Cleartext `http` origins log a warning unless the host is loopback.
444
+
445
+ ### What the page sees
446
+
447
+ Pages loaded from an allowed origin get a `window.metarouterBridge` object with two methods. Properties may be a plain object or a JSON string of one:
448
+
449
+ ```js
450
+ window.metarouterBridge.page('page_view', { section: 'checkout' });
451
+ window.metarouterBridge.track('product_viewed', JSON.stringify({ sku: 'SKU-123' }));
452
+ ```
453
+
454
+ A typical integration is a small shim in the page's tag manager:
455
+
456
+ ```js
457
+ function logEvent(name, params) {
458
+ var value = JSON.stringify(params);
459
+ if (!window.metarouterBridge) return; // origin not allowed
460
+ if (name === 'page_view') {
461
+ window.metarouterBridge.page(name, value);
462
+ } else {
463
+ window.metarouterBridge.track(name, value);
464
+ }
465
+ }
466
+ ```
467
+
468
+ The page-visible surface is identical in the iOS, Android and React Native SDKs, so one tag-manager integration serves every app.
469
+
470
+ ### What arrives at the cluster
471
+
472
+ Bridged events go through the same enrichment as the app's own events. The page contributes only what the app cannot know:
473
+
474
+ | From the page (stamped at call time) | From the SDK (merged at receipt) |
475
+ |---|---|
476
+ | event type (`track`/`page`), name, properties | `anonymousId` / `userId`, device + app context, session |
477
+ | `context.page` — url, path, search, title, referrer | `messageId`, `timestamp` |
478
+
479
+ Each bridge message carries an ID minted by the page, used to drop duplicate deliveries within 5 minutes. Malformed input is rejected with a coded error, never silently dropped, and events arriving while the SDK cannot accept them are answered `not_ready` rather than acknowledged.
480
+
481
+ ### Limits
482
+
483
+ - **Main frame only.** `react-native-webview` injects scripts before content loads into the main frame only, so iframes do not get the bridge (the iOS and Android SDKs also bridge allowlisted iframes).
484
+ - **Injection timing.** On iOS the wrapper is injected at document start. On Android, `react-native-webview` injects it when the page starts loading, which is not guaranteed to happen before the page's own scripts: an inline script at the top of the page can run first, find no bridge, and lose its call. Calls made once the page has loaded (and user-triggered ones) see the bridge. Guard calls with `if (window.metarouterBridge)` as in the shim above. A page already loaded when the props were first set has no bridge until it reloads.
485
+ - **Android WebView 82 or newer.** On Android the bridge needs the device's WebView provider to support `WEB_MESSAGE_LISTENER`, which Android System WebView has had since version 82 (2020) and which updates through Google Play. Without it `react-native-webview` reports the main page's URL for messages from every frame, so the origin check could not keep an iframe out; the bridge then refuses to attach, with a warning, and `attachWebView` returns props that do nothing (the Android SDK does the same). The check is a native module, so the app must be rebuilt after upgrading; without the module (e.g. Expo Go) the bridge also stays off.
486
+ - **Replies go to the current page.** Replies are delivered to whatever page is in the main frame when they are sent, and only if its origin is allowed.
487
+
488
+ ### Debugging
489
+
490
+ - SDK logs (`debug: true` or `enableDebugLogging()`) show attach confirmations, rejected messages with their error codes, and duplicate drops.
491
+ - In Safari's Develop menu (iOS) or `chrome://inspect` (Android), check `typeof window.metarouterBridge` to verify injection, and read replies with `window.__metaRouterNativeChannel.onmessage = e => console.log(e.data)`.
492
+
360
493
  ## ✅ Compatibility
361
494
 
362
495
  | Component | Supported Versions |
@@ -38,4 +38,6 @@ repositories {
38
38
 
39
39
  dependencies {
40
40
  implementation "com.facebook.react:react-android:+"
41
+ // Same version as the Android SDK; WebViewFeature for the bridge check.
42
+ implementation "androidx.webkit:webkit:1.12.1"
41
43
  }
@@ -0,0 +1,24 @@
1
+ package com.metarouter.reactnative
2
+
3
+ import android.os.SystemClock
4
+ import com.facebook.react.bridge.ReactApplicationContext
5
+ import com.facebook.react.bridge.ReactContextBaseJavaModule
6
+ import com.facebook.react.bridge.ReactMethod
7
+
8
+ /**
9
+ * Synchronous monotonic clock for session inactivity. elapsedRealtime keeps
10
+ * counting through deep sleep; uptimeMillis (and the CLOCK_MONOTONIC behind
11
+ * React Native's performance.now) does not, so a phone left asleep for hours
12
+ * would resume into the same session. Same clock as the Android SDK's
13
+ * SessionManager.
14
+ */
15
+ class MetaRouterClockModule(
16
+ reactContext: ReactApplicationContext
17
+ ) : ReactContextBaseJavaModule(reactContext) {
18
+
19
+ override fun getName(): String = "MetaRouterClock"
20
+
21
+ // Double: the bridge has no Long, and ms since boot fits a double exactly.
22
+ @ReactMethod(isBlockingSynchronousMethod = true)
23
+ fun continuousMillis(): Double = SystemClock.elapsedRealtime().toDouble()
24
+ }
@@ -11,7 +11,9 @@ class MetaRouterPackage : ReactPackage {
11
11
  ): List<NativeModule> {
12
12
  return listOf(
13
13
  MetaRouterQueueStorageModule(reactContext),
14
- MetaRouterNetworkMonitorModule(reactContext)
14
+ MetaRouterNetworkMonitorModule(reactContext),
15
+ MetaRouterClockModule(reactContext),
16
+ MetaRouterWebViewSupportModule(reactContext)
15
17
  )
16
18
  }
17
19
 
@@ -0,0 +1,27 @@
1
+ package com.metarouter.reactnative
2
+
3
+ import androidx.webkit.WebViewFeature
4
+ import com.facebook.react.bridge.ReactApplicationContext
5
+ import com.facebook.react.bridge.ReactContextBaseJavaModule
6
+ import com.facebook.react.bridge.ReactMethod
7
+
8
+ /**
9
+ * Whether this device's WebView provider supports WEB_MESSAGE_LISTENER. Without
10
+ * it react-native-webview falls back to addJavascriptInterface, which every
11
+ * frame can call and which reports the main page's URL for every message, so
12
+ * the bridge's origin check cannot tell an iframe from the page. The Android
13
+ * SDK refuses to attach there; the RN bridge does the same.
14
+ *
15
+ * DOCUMENT_START_SCRIPT, the Android SDK's other requirement, is not checked:
16
+ * react-native-webview never uses it, so it would refuse nothing extra.
17
+ */
18
+ class MetaRouterWebViewSupportModule(
19
+ reactContext: ReactApplicationContext
20
+ ) : ReactContextBaseJavaModule(reactContext) {
21
+
22
+ override fun getName(): String = "MetaRouterWebViewSupport"
23
+
24
+ @ReactMethod(isBlockingSynchronousMethod = true)
25
+ fun isWebMessageListenerSupported(): Boolean =
26
+ WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)
27
+ }
@@ -0,0 +1,31 @@
1
+ #import <React/RCTBridgeModule.h>
2
+ #include <mach/mach_time.h>
3
+
4
+ // Synchronous monotonic clock for session inactivity. mach_continuous_time
5
+ // keeps counting while the device sleeps; mach_absolute_time (and the
6
+ // CACurrentMediaTime behind React Native's performance.now) does not, so a
7
+ // phone locked for hours would resume into the same session. Same clock as
8
+ // the iOS SDK's MonotonicClock.
9
+ @interface MetaRouterClock : NSObject <RCTBridgeModule>
10
+ @end
11
+
12
+ @implementation MetaRouterClock
13
+
14
+ RCT_EXPORT_MODULE()
15
+
16
+ + (BOOL)requiresMainQueueSetup {
17
+ return NO;
18
+ }
19
+
20
+ RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(continuousMillis)
21
+ {
22
+ static mach_timebase_info_data_t timebase;
23
+ static dispatch_once_t once;
24
+ dispatch_once(&once, ^{
25
+ mach_timebase_info(&timebase);
26
+ });
27
+ uint64_t nanos = mach_continuous_time() * timebase.numer / timebase.denom;
28
+ return @((double)(nanos / NSEC_PER_MSEC));
29
+ }
30
+
31
+ @end
@@ -1,5 +1,7 @@
1
1
  import { InitOptions, Lifecycle } from './types';
2
2
  import { type NetworkReachability, type NetworkStatus } from './utils/networkMonitor';
3
+ import { SessionManager } from './session/sessionManager';
4
+ import type { BridgeEnvelope } from './webview/bridgeEnvelope';
3
5
  /**
4
6
  * Analytics client for MetaRouter.
5
7
  * - Handles event queueing, batching, and delivery with retries.
@@ -33,12 +35,14 @@ export declare class MetaRouterAnalyticsClient {
33
35
  private pendingDeepLink;
34
36
  private coldLaunchOpenDeferred;
35
37
  private wasBackgrounded;
38
+ private sessionManager;
36
39
  /**
37
40
  * Initializes the analytics client with the provided options.
38
41
  * @param options - The initialization options.
39
42
  */
40
43
  constructor(options: InitOptions, deps?: {
41
44
  networkMonitor?: NetworkReachability;
45
+ sessionManager?: SessionManager;
42
46
  });
43
47
  /**
44
48
  * Initializes the analytics client.
@@ -75,6 +79,15 @@ export declare class MetaRouterAnalyticsClient {
75
79
  * @param event - The event to enqueue.
76
80
  */
77
81
  private enqueue;
82
+ /**
83
+ * Bridge sink: a validated, deduplicated WebView envelope enters the normal
84
+ * event path. Identity, device context, session, messageId and timestamp
85
+ * all come from the existing enrichment — the envelope contributes only the
86
+ * event and the page it happened on. Returns false when the client cannot
87
+ * accept it, so the page gets `not_ready` rather than a false ack.
88
+ */
89
+ enqueueBridgeEvent(envelope: BridgeEnvelope): boolean;
90
+ private enqueueEnriched;
78
91
  private scheduleFlushIn;
79
92
  private stopFlushLoop;
80
93
  private clearNextTimer;
@@ -203,10 +216,18 @@ export declare class MetaRouterAnalyticsClient {
203
216
  * never initialized or a reset() races with this call.
204
217
  */
205
218
  getAnonymousId(): Promise<string>;
219
+ /**
220
+ * The current session id, or null before the first event of the process
221
+ * has been enriched. A peek, not a touch: a diagnostic read is not activity
222
+ * and must not extend the inactivity window.
223
+ */
224
+ getSessionId(): Promise<string | null>;
206
225
  /**
207
226
  * Get current state for debugging
208
227
  */
209
228
  getDebugInfo(): Promise<{
229
+ sessionId?: string | undefined;
230
+ sessionCount?: number | undefined;
210
231
  lifecycle: Lifecycle;
211
232
  queueLength: number;
212
233
  ingestionHost: string;
@@ -1 +1 @@
1
- {"version":3,"file":"MetaRouterAnalyticsClient.d.ts","sourceRoot":"","sources":["../../src/analytics/MetaRouterAnalyticsClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,WAAW,EACX,SAAS,EACV,MAAM,SAAS,CAAC;AA6BjB,OAAO,EAEL,KAAK,mBAAmB,EACxB,KAAK,aAAa,EACnB,MAAM,wBAAwB,CAAC;AAOhC;;;;;;GAMG;AACH,qBAAa,yBAAyB;IACpC,OAAO,CAAC,SAAS,CAAqB;IACtC,OAAO,CAAC,WAAW,CAA8B;IACjD,OAAO,CAAC,KAAK,CAAsB;IACnC,OAAO,CAAC,oBAAoB,CAAM;IAClC,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,OAAO,CAAgB;IAC/B,OAAO,CAAC,UAAU,CAAc;IAChC,OAAO,CAAC,QAAQ,CAAyC;IACzD,OAAO,CAAC,oBAAoB,CAAwC;IACpE,OAAO,CAAC,eAAe,CAAkB;IACzC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,oBAAoB,CAAM;IAGlD,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,eAAe,CAAmB;IAC1D,OAAO,CAAC,aAAa,CAAmC;IACxD,OAAO,CAAC,UAAU,CAAc;IAChC,OAAO,CAAC,eAAe,CAAwB;IAC/C,OAAO,CAAC,cAAc,CAAkB;IACxC,OAAO,CAAC,cAAc,CAAsB;IAC5C,OAAO,CAAC,aAAa,CAA8B;IACnD,OAAO,CAAC,kBAAkB,CAA6B;IAGvD,OAAO,CAAC,gBAAgB,CAAiC;IAGzD,OAAO,CAAC,oBAAoB,CAAkB;IAG9C,OAAO,CAAC,eAAe,CAA6B;IAGpD,OAAO,CAAC,sBAAsB,CAAkB;IAMhD,OAAO,CAAC,eAAe,CAAkB;IAEzC;;;OAGG;gBAED,OAAO,EAAE,WAAW,EACpB,IAAI,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AAM,EAAE,GAAG,CAAC;IASrD;;;;OAIG;IACH,KAAK,CAAC,SAAS,EAAE,MAAM;IAKvB;;;;;;;;;OASG;IACG,gBAAgB,CAAC,aAAa,EAAE,MAAM;IAwB5C;;;;;;OAMG;IACG,kBAAkB;IAexB;;;;;;OAMG;IACH,UAAU,CAAC,OAAO,EAAE,OAAO;IAK3B;;;OAGG;IACH,gBAAgB,IAAI,OAAO;IAI3B;;OAEG;IACH,kBAAkB;IAKlB;;;;OAIG;IACG,cAAc,IAAI,OAAO,CAAC,MAAM,CAAC;IAavC;;OAEG;IACG,YAAY;;;;;;;;;;;;;;;;;;;IAuBlB;;;OAGG;IACG,KAAK;IAIX;;OAEG;IACU,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAsCpC"}
1
+ {"version":3,"file":"MetaRouterAnalyticsClient.d.ts","sourceRoot":"","sources":["../../src/analytics/MetaRouterAnalyticsClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,WAAW,EACX,SAAS,EACV,MAAM,SAAS,CAAC;AA6BjB,OAAO,EAEL,KAAK,mBAAmB,EACxB,KAAK,aAAa,EACnB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAGL,cAAc,EACf,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,cAAc,EAAe,MAAM,0BAA0B,CAAC;AAM5E;;;;;;GAMG;AACH,qBAAa,yBAAyB;IACpC,OAAO,CAAC,SAAS,CAAqB;IACtC,OAAO,CAAC,WAAW,CAA8B;IACjD,OAAO,CAAC,KAAK,CAAsB;IACnC,OAAO,CAAC,oBAAoB,CAAM;IAClC,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,OAAO,CAAgB;IAC/B,OAAO,CAAC,UAAU,CAAc;IAChC,OAAO,CAAC,QAAQ,CAAyC;IACzD,OAAO,CAAC,oBAAoB,CAAwC;IACpE,OAAO,CAAC,eAAe,CAAkB;IACzC,OAAO,C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OAAO,CAAC,IAAI,CAAC;CAyCpC"}
@@ -12,6 +12,7 @@ import Dispatcher from './dispatcher';
12
12
  import { PersistentEventQueue } from './persistence/PersistentEventQueue';
13
13
  import { NetworkMonitor, } from './utils/networkMonitor';
14
14
  import { DebouncedNetworkMonitor } from './utils/debouncedNetworkMonitor';
15
+ import { DEFAULT_SESSION_TIMEOUT_MINUTES, SESSION_STARTED_EVENT, SessionManager, } from './session/sessionManager';
15
16
  import { DEFAULT_MAX_DISK_EVENTS, validateInitOptions, } from './utils/initOptions';
16
17
  /**
17
18
  * Analytics client for MetaRouter.
@@ -26,7 +27,7 @@ export class MetaRouterAnalyticsClient {
26
27
  * @param options - The initialization options.
27
28
  */
28
29
  constructor(options, deps) {
29
- var _a, _b, _c, _d;
30
+ var _a, _b, _c, _d, _e, _f;
30
31
  this.lifecycle = 'idle';
31
32
  this.initPromise = null;
32
33
  this.queue = [];
@@ -144,12 +145,20 @@ export class MetaRouterAnalyticsClient {
144
145
  setDebugLogging((_b = options.debug) !== null && _b !== void 0 ? _b : false);
145
146
  this.trackLifecycleEvents = (_c = options.trackLifecycleEvents) !== null && _c !== void 0 ? _c : false;
146
147
  this.identityManager = new IdentityManager();
148
+ this.sessionManager =
149
+ (_d = deps === null || deps === void 0 ? void 0 : deps.sessionManager) !== null && _d !== void 0 ? _d : new SessionManager((_e = normalized.sessionTimeoutMinutes) !== null && _e !== void 0 ? _e : DEFAULT_SESSION_TIMEOUT_MINUTES);
150
+ // Installed here, before init() can let any event through: a handler
151
+ // installed after the install's first mint would drop its Session
152
+ // Started, which never recurs for that session.
153
+ if (options.fireSessionStarted) {
154
+ this.sessionManager.setOnSessionStart(() => this.track(SESSION_STARTED_EVENT));
155
+ }
147
156
  // Default: wrap the raw native monitor with the asymmetric debounce
148
157
  // (immediate offline, 2s stable-online). If a caller injects their own
149
158
  // monitor (e.g. in tests), use it as-is so they control the debounce
150
159
  // behavior explicitly.
151
160
  this.networkMonitor =
152
- (_d = deps === null || deps === void 0 ? void 0 : deps.networkMonitor) !== null && _d !== void 0 ? _d : new DebouncedNetworkMonitor(new NetworkMonitor());
161
+ (_f = deps === null || deps === void 0 ? void 0 : deps.networkMonitor) !== null && _f !== void 0 ? _f : new DebouncedNetworkMonitor(new NetworkMonitor());
153
162
  this.dispatcher = new Dispatcher({
154
163
  maxEventCount: maxQueueEvents,
155
164
  maxQueueBytes: MetaRouterAnalyticsClient.MAX_QUEUE_BYTES,
@@ -227,7 +236,13 @@ export class MetaRouterAnalyticsClient {
227
236
  const hadIdentityBeforeInit = this.trackLifecycleEvents
228
237
  ? await this.hasIdentityState()
229
238
  : false;
230
- await this.identityManager.init();
239
+ // The session load must settle before `ready`: the first enriched
240
+ // event decides between resuming the persisted session and minting a
241
+ // new one. Independent of identity, so the reads overlap.
242
+ await Promise.all([
243
+ this.identityManager.init(),
244
+ this.sessionManager.loadPersisted(),
245
+ ]);
231
246
  // Cheap existence check — memory queue starts empty. Any on-disk
232
247
  // events are drained directly to the network below (if online) via
233
248
  // drainDiskToNetwork, avoiding a memory spike from rehydrating a
@@ -329,9 +344,12 @@ export class MetaRouterAnalyticsClient {
329
344
  * enqueue() and the lifecycle emitter so both paths produce identical
330
345
  * payloads.
331
346
  */
332
- buildEnrichedEvent(event) {
347
+ buildEnrichedEvent(event, page) {
333
348
  const eventWithIdentity = this.identityManager.addIdentityInfo(event);
334
- return enrichEvent(eventWithIdentity, this.writeKey, this.context);
349
+ // Every enriched event is session activity, and this is the funnel all
350
+ // event sources share (public calls, lifecycle events, the WebView
351
+ // bridge), so touching here is what makes the session stamp universal.
352
+ return enrichEvent(eventWithIdentity, this.writeKey, this.context, this.sessionManager.touch(), page);
335
353
  }
336
354
  /**
337
355
  * Enqueues an event for processing.
@@ -342,12 +360,41 @@ export class MetaRouterAnalyticsClient {
342
360
  warn('Analytics client is not ready to operate');
343
361
  return;
344
362
  }
345
- this.dispatcher.enqueue(this.buildEnrichedEvent(event));
363
+ this.enqueueEnriched(this.buildEnrichedEvent(event));
364
+ }
365
+ /**
366
+ * Bridge sink: a validated, deduplicated WebView envelope enters the normal
367
+ * event path. Identity, device context, session, messageId and timestamp
368
+ * all come from the existing enrichment — the envelope contributes only the
369
+ * event and the page it happened on. Returns false when the client cannot
370
+ * accept it, so the page gets `not_ready` rather than a false ack.
371
+ */
372
+ enqueueBridgeEvent(envelope) {
373
+ if (!this.isReady())
374
+ return false;
375
+ this.enqueueEnriched(this.buildEnrichedEvent({
376
+ type: envelope.type,
377
+ event: envelope.name,
378
+ properties: envelope.properties,
379
+ timestamp: this.now(),
380
+ }, envelope.page));
381
+ return true;
382
+ }
383
+ enqueueEnriched(enriched) {
384
+ this.dispatcher.enqueue(enriched);
346
385
  // Check if we should flush to disk based on thresholds
347
- if (this.persistentQueue.shouldFlushToDisk()) {
348
- void this.persistentQueue.flushToDisk().catch((err) => {
349
- warn('Failed to flush queue to disk after threshold:', err);
350
- });
386
+ // Nothing here may throw out of this method: the event is already queued,
387
+ // and a bridge caller that saw a throw would NAK it and let the page
388
+ // re-send it as a duplicate.
389
+ try {
390
+ if (this.persistentQueue.shouldFlushToDisk()) {
391
+ void this.persistentQueue.flushToDisk().catch((err) => {
392
+ warn('Failed to flush queue to disk after threshold:', err);
393
+ });
394
+ }
395
+ }
396
+ catch (err) {
397
+ warn('Failed to flush queue to disk after threshold:', err);
351
398
  }
352
399
  }
353
400
  scheduleFlushIn(ms, opts) {
@@ -626,11 +673,21 @@ export class MetaRouterAnalyticsClient {
626
673
  }
627
674
  return id;
628
675
  }
676
+ /**
677
+ * The current session id, or null before the first event of the process
678
+ * has been enriched. A peek, not a touch: a diagnostic read is not activity
679
+ * and must not extend the inactivity window.
680
+ */
681
+ async getSessionId() {
682
+ var _a, _b;
683
+ return (_b = (_a = this.sessionManager.peek()) === null || _a === void 0 ? void 0 : _a.sessionId) !== null && _b !== void 0 ? _b : null;
684
+ }
629
685
  /**
630
686
  * Get current state for debugging
631
687
  */
632
688
  async getDebugInfo() {
633
689
  const d = this.dispatcher.getDebugInfo();
690
+ const session = this.sessionManager.peek();
634
691
  return {
635
692
  lifecycle: this.lifecycle,
636
693
  queueLength: d.queueLength,
@@ -649,6 +706,13 @@ export class MetaRouterAnalyticsClient {
649
706
  tracingEnabled: this.tracingEnabled,
650
707
  hasDiskData: this.persistentQueue.hasDiskData,
651
708
  networkStatus: this.networkStatus,
709
+ // Unmasked on purpose: a session id is an epoch-ms timestamp, not an
710
+ // identifier tied to a person, and the point of surfacing it here is
711
+ // matching it against event payloads.
712
+ ...(session && {
713
+ sessionId: session.sessionId,
714
+ sessionCount: session.sessionCount,
715
+ }),
652
716
  };
653
717
  }
654
718
  /**
@@ -678,6 +742,9 @@ export class MetaRouterAnalyticsClient {
678
742
  this.coldLaunchOpenDeferred = false;
679
743
  this.wasBackgrounded = false;
680
744
  this.lifecycleEmitter = null;
745
+ // The session survives reset() through storage: the next
746
+ // createAnalyticsClient builds a new client that resumes from it.
747
+ this.sessionManager.persistActivity();
681
748
  this.dispatcher.reset();
682
749
  await this.persistentQueue.deleteSnapshot();
683
750
  // Clear identity (must remove persisted IDs)
@@ -1 +1 @@
1
- {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../src/analytics/init.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,WAAW,EAAE,kBAAkB,EAAe,MAAM,SAAS,CAAC;AA0B5E;;;GAGG;AACH,eAAO,MAAM,WAAW;8BACE,OAAO;CAEhC,CAAC;AAoCF,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,WAAW,GACnB,kBAAkB,CAsCpB"}
1
+ {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../src/analytics/init.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,WAAW,EAAE,kBAAkB,EAAe,MAAM,SAAS,CAAC;AA4B5E;;;GAGG;AACH,eAAO,MAAM,WAAW;8BACE,OAAO;CAEhC,CAAC;AAoCF,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,WAAW,GACnB,kBAAkB,CAsCpB"}
@@ -1,6 +1,8 @@
1
1
  import { MetaRouterAnalyticsClient } from './MetaRouterAnalyticsClient';
2
- import { clearConfigDisabled, markConfigDisabled, proxyClient, setInitializingClient, setRealClient, setResetHandler, takePendingOpenedURLs, } from './proxy/proxyClient';
2
+ import { clearConfigDisabled, markConfigDisabled, proxyClient, setInitializingClient, setRealClient, setAttachWebViewHandler, setResetHandler, takePendingOpenedURLs, } from './proxy/proxyClient';
3
3
  import { validateInitOptions } from './utils/initOptions';
4
+ import { BridgeMessageProcessor } from './webview/bridgeMessageProcessor';
5
+ import { attachWebViewBridge } from './webview/webViewBridge';
4
6
  /*
5
7
  * Session choreography. Init, disable and reset work runs strictly FIFO on
6
8
  * `workChain`, and the flags below follow one rule (the one the Android SDK
@@ -182,6 +184,15 @@ function resetSession() {
182
184
  return enqueue(() => runReset(decision));
183
185
  }
184
186
  setResetHandler(resetSession);
187
+ // One processor for every WebView the host attaches, across sessions — like
188
+ // the native proxy's. The sink resolves the client per message: the props are
189
+ // handed out at the first render, long before a client binds, and must keep
190
+ // working across reset() and re-init. Before a bind, or during a teardown,
191
+ // messages are refused with not_ready.
192
+ const bridgeProcessor = new BridgeMessageProcessor((envelope) => { var _a; return (_a = activeClient === null || activeClient === void 0 ? void 0 : activeClient.enqueueBridgeEvent(envelope)) !== null && _a !== void 0 ? _a : false; });
193
+ const attachWebView = (webViewRef, allowedOrigins) => attachWebViewBridge(webViewRef, allowedOrigins, bridgeProcessor);
194
+ // The proxy routes every attachWebView here, bound or not.
195
+ setAttachWebViewHandler(attachWebView);
185
196
  function bindClient(instance) {
186
197
  return {
187
198
  track: (event, props) => instance.track(event, props),
@@ -197,6 +208,8 @@ function bindClient(instance) {
197
208
  enableDebugLogging: () => instance.enableDebugLogging(),
198
209
  getDebugInfo: () => instance.getDebugInfo(),
199
210
  getAnonymousId: () => instance.getAnonymousId(),
211
+ getSessionId: () => instance.getSessionId(),
212
+ attachWebView,
200
213
  flush: () => instance.flush(),
201
214
  reset: () => resetSession(),
202
215
  };
@@ -36,6 +36,8 @@ export declare function setInitializingClient(client: Pick<AnalyticsInterface, '
36
36
  export declare function setRealClient(client: AnalyticsInterface | null, opts?: {
37
37
  dropPending?: boolean;
38
38
  }): void;
39
+ /** Registers init.ts's WebView bridge, used by `attachWebView()` in every state. */
40
+ export declare function setAttachWebViewHandler(handler: AnalyticsInterface['attachWebView'] | null): void;
39
41
  /** Registers init.ts's session reset, used by `reset()` in every state. */
40
42
  export declare function setResetHandler(handler: (() => Promise<void>) | null): void;
41
43
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"proxyClient.d.ts","sourceRoot":"","sources":["../../../src/analytics/proxy/proxyClient.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAgOnD,eAAO,MAAM,WAAW,EAAE,kBAoBzB,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,IAAI,CAAC,kBAAkB,EAAE,iBAAiB,CAAC,GAAG,IAAI,QAG3D;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,aAAa,CAC3B,MAAM,EAAE,kBAAkB,GAAG,IAAI,EACjC,IAAI,CAAC,EAAE;IAAE,WAAW,CAAC,EAAE,OAAO,CAAA;CAAE,QAuBjC;AAED,2EAA2E;AAC3E,wBAAgB,eAAe,CAAC,OAAO,EAAE,CAAC,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG,IAAI,QAEpE;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,WAAW,EAAE,MAAM,QAMrD;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,SAElC;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,IAAI,UAAU,CACjD,kBAAkB,CAAC,iBAAiB,CAAC,CACtC,EAAE,CAYF"}
1
+ {"version":3,"file":"proxyClient.d.ts","sourceRoot":"","sources":["../../../src/analytics/proxy/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