@metarouter/react-native-sdk 1.5.1 → 1.8.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.
- package/README.md +190 -60
- package/android/build.gradle +41 -0
- package/android/src/main/AndroidManifest.xml +4 -0
- package/android/src/main/java/com/metarouter/reactnative/MetaRouterNetworkMonitorModule.kt +119 -0
- package/android/src/main/java/com/metarouter/reactnative/MetaRouterPackage.kt +23 -0
- package/android/src/main/java/com/metarouter/reactnative/MetaRouterQueueStorageModule.kt +124 -0
- package/ios/MetaRouterNetworkMonitor.m +76 -0
- package/ios/MetaRouterQueueStorage.m +127 -0
- package/lib/analytics/MetaRouterAnalyticsClient.d.ts +71 -4
- package/lib/analytics/MetaRouterAnalyticsClient.d.ts.map +1 -1
- package/lib/analytics/MetaRouterAnalyticsClient.js +396 -112
- package/lib/analytics/dispatcher.d.ts +57 -1
- package/lib/analytics/dispatcher.d.ts.map +1 -1
- package/lib/analytics/dispatcher.js +231 -32
- package/lib/analytics/init.d.ts +8 -1
- package/lib/analytics/init.d.ts.map +1 -1
- package/lib/analytics/init.js +198 -37
- package/lib/analytics/lifecycle/lifecycleEvents.d.ts +52 -0
- package/lib/analytics/lifecycle/lifecycleEvents.d.ts.map +1 -0
- package/lib/analytics/lifecycle/lifecycleEvents.js +66 -0
- package/lib/analytics/persistence/NativeQueueStorage.d.ts +5 -0
- package/lib/analytics/persistence/NativeQueueStorage.d.ts.map +1 -0
- package/lib/analytics/persistence/NativeQueueStorage.js +59 -0
- package/lib/analytics/persistence/PersistentEventQueue.d.ts +96 -0
- package/lib/analytics/persistence/PersistentEventQueue.d.ts.map +1 -0
- package/lib/analytics/persistence/PersistentEventQueue.js +401 -0
- package/lib/analytics/persistence/types.d.ts +20 -0
- package/lib/analytics/persistence/types.d.ts.map +1 -0
- package/lib/analytics/persistence/types.js +10 -0
- package/lib/analytics/proxy/proxyClient.d.ts +30 -1
- package/lib/analytics/proxy/proxyClient.d.ts.map +1 -1
- package/lib/analytics/proxy/proxyClient.js +145 -23
- package/lib/analytics/types.d.ts +61 -4
- package/lib/analytics/types.d.ts.map +1 -1
- package/lib/analytics/utils/appContext.d.ts +20 -0
- package/lib/analytics/utils/appContext.d.ts.map +1 -0
- package/lib/analytics/utils/appContext.js +22 -0
- package/lib/analytics/utils/circuitBreaker.d.ts +4 -1
- package/lib/analytics/utils/circuitBreaker.d.ts.map +1 -1
- package/lib/analytics/utils/circuitBreaker.js +23 -14
- package/lib/analytics/utils/contextInfo.d.ts +8 -4
- package/lib/analytics/utils/contextInfo.d.ts.map +1 -1
- package/lib/analytics/utils/contextInfo.js +34 -27
- package/lib/analytics/utils/debouncedNetworkMonitor.d.ts +25 -0
- package/lib/analytics/utils/debouncedNetworkMonitor.d.ts.map +1 -0
- package/lib/analytics/utils/debouncedNetworkMonitor.js +68 -0
- package/lib/analytics/utils/initOptions.d.ts +22 -0
- package/lib/analytics/utils/initOptions.d.ts.map +1 -0
- package/lib/analytics/utils/initOptions.js +100 -0
- package/lib/analytics/utils/lifecycleStorage.d.ts +13 -0
- package/lib/analytics/utils/lifecycleStorage.d.ts.map +1 -0
- package/lib/analytics/utils/lifecycleStorage.js +35 -0
- package/lib/analytics/utils/networkMonitor.d.ts +30 -0
- package/lib/analytics/utils/networkMonitor.d.ts.map +1 -0
- package/lib/analytics/utils/networkMonitor.js +90 -0
- package/lib/analytics/utils/responseCategory.d.ts +14 -0
- package/lib/analytics/utils/responseCategory.d.ts.map +1 -0
- package/lib/analytics/utils/responseCategory.js +26 -0
- package/lib/index.d.ts +4 -4
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +3 -3
- package/metarouter-react-native-sdk.podspec +19 -0
- package/package.json +6 -3
- package/react-native.config.js +15 -0
package/README.md
CHANGED
|
@@ -14,6 +14,8 @@ A lightweight React Native analytics SDK that transmits events to your MetaRoute
|
|
|
14
14
|
- [Direct Usage](#direct-usage)
|
|
15
15
|
- [API Reference](#api-reference)
|
|
16
16
|
- [Features](#features)
|
|
17
|
+
- [Disk-Backed Queue Persistence](#disk-backed-queue-persistence)
|
|
18
|
+
- [Application Lifecycle Events](#application-lifecycle-events)
|
|
17
19
|
- [Compatibility](#-compatibility)
|
|
18
20
|
- [Debugging](#debugging)
|
|
19
21
|
- [Identity Persistence](#identity-persistence)
|
|
@@ -27,6 +29,8 @@ A lightweight React Native analytics SDK that transmits events to your MetaRoute
|
|
|
27
29
|
npm install @metarouter/react-native-sdk @react-native-async-storage/async-storage react-native-device-info
|
|
28
30
|
```
|
|
29
31
|
|
|
32
|
+
After installing or upgrading, run `cd ios && pod install` and rebuild the native app. This release includes native iOS and Android modules for queue persistence, so a JavaScript-only reload is not sufficient.
|
|
33
|
+
|
|
30
34
|
## Usage
|
|
31
35
|
|
|
32
36
|
### Basic Setup
|
|
@@ -34,11 +38,11 @@ npm install @metarouter/react-native-sdk @react-native-async-storage/async-stora
|
|
|
34
38
|
```js
|
|
35
39
|
import { createAnalyticsClient } from "@metarouter/react-native-sdk";
|
|
36
40
|
|
|
37
|
-
//
|
|
38
|
-
const analytics =
|
|
41
|
+
// Returns the client right away; initialization finishes in the background
|
|
42
|
+
const analytics = createAnalyticsClient({
|
|
39
43
|
writeKey: "your-write-key",
|
|
40
44
|
ingestionHost: "https://your-ingestion-endpoint.com",
|
|
41
|
-
debug:
|
|
45
|
+
debug: __DEV__, // Optional: verbose logs, never in a store release
|
|
42
46
|
flushIntervalSeconds: 30, // Optional: flush events every 30 seconds
|
|
43
47
|
});
|
|
44
48
|
```
|
|
@@ -46,43 +50,25 @@ const analytics = await createAnalyticsClient({
|
|
|
46
50
|
### React Context Usage
|
|
47
51
|
|
|
48
52
|
```jsx
|
|
49
|
-
import React
|
|
53
|
+
import React from "react";
|
|
50
54
|
import {
|
|
51
55
|
createAnalyticsClient,
|
|
52
56
|
MetaRouterProvider,
|
|
53
57
|
useMetaRouter,
|
|
54
58
|
} from "@metarouter/react-native-sdk";
|
|
55
59
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
setAnalyticsClient(client);
|
|
69
|
-
} catch (error) {
|
|
70
|
-
console.error("Failed to initialize analytics:", error);
|
|
71
|
-
} finally {
|
|
72
|
-
setIsLoading(false);
|
|
73
|
-
}
|
|
74
|
-
};
|
|
75
|
-
initializeAnalytics();
|
|
76
|
-
}, []);
|
|
77
|
-
|
|
78
|
-
if (isLoading) return null; // or a loading spinner
|
|
79
|
-
|
|
80
|
-
return (
|
|
81
|
-
<MetaRouterProvider analyticsClient={analyticsClient}>
|
|
82
|
-
<YourApp />
|
|
83
|
-
</MetaRouterProvider>
|
|
84
|
-
);
|
|
85
|
-
};
|
|
60
|
+
// Create the client once, outside any component. It is usable immediately:
|
|
61
|
+
// there is no promise to await, and nothing to catch in a release build.
|
|
62
|
+
const analytics = createAnalyticsClient({
|
|
63
|
+
writeKey: "your-write-key",
|
|
64
|
+
ingestionHost: "https://your-ingestion-endpoint.com",
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
const App = () => (
|
|
68
|
+
<MetaRouterProvider analyticsClient={analytics}>
|
|
69
|
+
<YourApp />
|
|
70
|
+
</MetaRouterProvider>
|
|
71
|
+
);
|
|
86
72
|
|
|
87
73
|
// Use analytics in any component
|
|
88
74
|
const MyComponent = () => {
|
|
@@ -104,9 +90,9 @@ const MyComponent = () => {
|
|
|
104
90
|
```js
|
|
105
91
|
import { createAnalyticsClient } from "@metarouter/react-native-sdk";
|
|
106
92
|
|
|
107
|
-
//
|
|
108
|
-
//
|
|
109
|
-
const analytics =
|
|
93
|
+
// Usable immediately: calls made before initialization finishes are
|
|
94
|
+
// buffered and sent once the client is ready.
|
|
95
|
+
const analytics = createAnalyticsClient({
|
|
110
96
|
writeKey: "your-write-key",
|
|
111
97
|
ingestionHost: "https://your-ingestion-endpoint.com",
|
|
112
98
|
});
|
|
@@ -153,7 +139,7 @@ await analytics.reset();
|
|
|
153
139
|
|
|
154
140
|
```js
|
|
155
141
|
// Initial configuration
|
|
156
|
-
const analytics =
|
|
142
|
+
const analytics = createAnalyticsClient({
|
|
157
143
|
writeKey: "key-1",
|
|
158
144
|
ingestionHost: "https://endpoint-1.com",
|
|
159
145
|
});
|
|
@@ -161,8 +147,9 @@ const analytics = await createAnalyticsClient({
|
|
|
161
147
|
// Later, if you need to change configuration:
|
|
162
148
|
await analytics.reset(); // Must reset first!
|
|
163
149
|
|
|
164
|
-
// Now reconfigure with new options
|
|
165
|
-
|
|
150
|
+
// Now reconfigure with new options. The same client object is returned, so
|
|
151
|
+
// existing references (and MetaRouterProvider) keep working.
|
|
152
|
+
createAnalyticsClient({
|
|
166
153
|
writeKey: "key-2",
|
|
167
154
|
ingestionHost: "https://endpoint-2.com",
|
|
168
155
|
});
|
|
@@ -178,27 +165,61 @@ If you call `createAnalyticsClient()` with different options without resetting f
|
|
|
178
165
|
|
|
179
166
|
### createAnalyticsClient(options)
|
|
180
167
|
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
⚠️ `createAnalyticsClient()` is asynchronous, but you **do not** need to `await` it before using analytics methods.
|
|
168
|
+
Starts initialization and returns a **live proxy** to the client instance, synchronously. It does not return a Promise, so there is nothing to `await`, and in a release build nothing to `catch`: invalid options never throw there (development builds throw so the mistake surfaces at the call site). See [Invalid configuration](#invalid-configuration).
|
|
184
169
|
|
|
185
170
|
Calls to `track`, `identify`, etc. are **buffered in-memory** by the proxy and replayed **in order** once the client is fully initialized.
|
|
186
171
|
|
|
187
172
|
**Options:**
|
|
188
173
|
|
|
189
|
-
- `writeKey` (string, required): Your write key
|
|
190
|
-
- `ingestionHost` (string, required): Your MetaRouter
|
|
191
|
-
- `
|
|
192
|
-
- `
|
|
193
|
-
- `maxQueueEvents` (number, optional):
|
|
174
|
+
- `writeKey` (string, required): Your MetaRouter write key. Trimmed; empty or whitespace-only is a config error.
|
|
175
|
+
- `ingestionHost` (string, required): Your MetaRouter ingestion endpoint: an `http`/`https` URL with a host. Trimmed, and trailing slashes are removed. Cleartext `http` logs a warning unless the host is `localhost`, `127.0.0.1` or `::1`.
|
|
176
|
+
- `flushIntervalSeconds` (number, optional, default: `10`): How often the SDK attempts to send queued events. Values below 1 are clamped to 1.
|
|
177
|
+
- `debug` (boolean, optional, default: `false`): Enables verbose SDK logging. Can also be toggled at runtime via `analytics.enableDebugLogging()`.
|
|
178
|
+
- `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
|
+
- `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
|
+
- `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).
|
|
181
|
+
- `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
|
+
|
|
183
|
+
Out-of-range numbers are clamped and logged as a warning; they never fail initialization.
|
|
194
184
|
|
|
195
185
|
**Proxy behavior (quick notes):**
|
|
196
186
|
|
|
197
187
|
- Buffer is **in-memory only** (not persisted). Calls made before ready are lost if the process exits.
|
|
198
188
|
- Ordering is preserved relative to other buffered calls; normal FIFO + batching applies after ready.
|
|
199
|
-
- On fatal config errors (`401/403/404`), the client enters **disabled** state and drops subsequent calls.
|
|
189
|
+
- On fatal config errors from the ingestion host (`401/403/404`), the client enters **disabled** state and drops subsequent calls. This is separate from [invalid options](#invalid-configuration) and does not call `onConfigError`.
|
|
200
190
|
- `sentAt` is stamped when the batch is prepared for transmission (just before network send). If you need the original occurrence time, pass your own `timestamp` on each event.
|
|
201
191
|
|
|
192
|
+
### Invalid configuration
|
|
193
|
+
|
|
194
|
+
Invalid options (an empty `writeKey`, or an `ingestionHost` that is not an `http`/`https` URL with a host) never crash a release build. The same rules apply on iOS and Android.
|
|
195
|
+
|
|
196
|
+
| Build | What happens |
|
|
197
|
+
| ----- | ------------ |
|
|
198
|
+
| Development (`__DEV__`) | `createAnalyticsClient` throws `Invalid InitOptions: <reason>`, so the mistake shows up immediately at the call site. |
|
|
199
|
+
| Release | An always-on error is logged (`[MetaRouter] MetaRouter disabled for this session — <reason>`), `onConfigError` is called once, synchronously, and the SDK stays inert for the session: calls are accepted and nothing is sent. |
|
|
200
|
+
|
|
201
|
+
While the session is disabled:
|
|
202
|
+
|
|
203
|
+
- `getAnonymousId()` resolves `""` instead of waiting, and `flush()` resolves immediately.
|
|
204
|
+
- `getDebugInfo()` returns `lifecycle: "disabled"` and the reason as `configError`.
|
|
205
|
+
- Calls made while disabled are kept (up to the usual 20) and sent if the session recovers.
|
|
206
|
+
|
|
207
|
+
A later `createAnalyticsClient` with valid options recovers the session, and so does `reset()`. An invalid call made while a valid session is running disables that session too, rather than leaving the old configuration running unnoticed.
|
|
208
|
+
|
|
209
|
+
Disabling a running session resets its client, which clears the stored identity (anonymous ID, user ID, group ID, advertising ID), the same as the Android SDK. A single invalid call between two valid ones therefore starts the recovered session as a new anonymous user.
|
|
210
|
+
|
|
211
|
+
```js
|
|
212
|
+
const analytics = createAnalyticsClient({
|
|
213
|
+
writeKey: remoteConfig.writeKey,
|
|
214
|
+
ingestionHost: remoteConfig.ingestionHost,
|
|
215
|
+
onConfigError: (error) => {
|
|
216
|
+
// error.type is "emptyWriteKey" or "invalidIngestionHost" (with error.raw);
|
|
217
|
+
// error.description is the same text the iOS and Android SDKs report.
|
|
218
|
+
reportToYourDiagnostics("MetaRouter config", error.description);
|
|
219
|
+
},
|
|
220
|
+
});
|
|
221
|
+
```
|
|
222
|
+
|
|
202
223
|
### Analytics Interface
|
|
203
224
|
|
|
204
225
|
The analytics client provides the following methods:
|
|
@@ -209,8 +230,10 @@ The analytics client provides the following methods:
|
|
|
209
230
|
- `screen(name: string, properties?: Record<string, any>)`: Track screen views
|
|
210
231
|
- `page(name: string, properties?: Record<string, any>)`: Track page views
|
|
211
232
|
- `alias(newUserId: string)`: Connect anonymous users to known user IDs. See [Using the alias() Method](#using-the-alias-method) for details
|
|
233
|
+
- `recordOpenedURL(url: string, sourceApplication?: string)`: Forward a URL the host received (from `Linking.getInitialURL`, `Linking.addEventListener('url', ...)`, a UIScene URL handler, or an Android Intent) so it is attached to the next `Application Opened` event. The SDK does not read `Linking` itself, so only URLs passed here are recorded. One-shot — the buffer is cleared after the next Opened emit; last-write-wins if called multiple times. No-op (with a warning, always logged) when `trackLifecycleEvents` is disabled. See [Application Lifecycle Events](#application-lifecycle-events) for deep-link wiring details.
|
|
212
234
|
- `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
|
|
213
235
|
- `clearAdvertisingId()`: Clear the advertising identifier from storage and context. Useful for GDPR/CCPA compliance when users opt out of ad tracking
|
|
236
|
+
- `getAnonymousId(): Promise<string>`: Returns the current anonymous ID. Async, never returns null — guaranteed to resolve a string after `init()`
|
|
214
237
|
- `setTracing(enabled: boolean)`: Enable or disable tracing headers on API requests. When enabled, includes a `Trace: true` header for debugging request flows
|
|
215
238
|
- `flush()`: Flush events immediately
|
|
216
239
|
- `reset()`: Reset analytics state and clear all stored data (includes clearing advertising ID)
|
|
@@ -232,18 +255,118 @@ The analytics client provides the following methods:
|
|
|
232
255
|
- 🎣 **React Hooks**: Easy integration with React components
|
|
233
256
|
- 🔧 **TypeScript Support**: Full TypeScript support included
|
|
234
257
|
- 🚀 **Lightweight**: Minimal overhead and dependencies
|
|
258
|
+
- 💾 **Best-Effort Queue Persistence**: Can persist queued events to native disk storage and rehydrate them on next launch
|
|
259
|
+
- 📲 **Lifecycle Events (opt-in)**: Emit `Application Installed/Updated/Opened/Backgrounded` automatically when enabled — see [Application Lifecycle Events](#application-lifecycle-events)
|
|
235
260
|
- 🔄 **Reset Capability**: Easily reset analytics state for testing or logout scenarios
|
|
236
261
|
- 🐛 **Debug Support**: Built-in debugging tools for troubleshooting
|
|
237
262
|
|
|
263
|
+
## Disk-Backed Queue Persistence
|
|
264
|
+
|
|
265
|
+
This release adds native iOS and Android storage for best-effort queue durability.
|
|
266
|
+
|
|
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()`.
|
|
270
|
+
- 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
|
+
|
|
272
|
+
## Application Lifecycle Events
|
|
273
|
+
|
|
274
|
+
Opt-in. When enabled, the SDK emits four lifecycle events that mirror the iOS and Android native SDKs. They are sent through the same enrichment + batching pipeline as user-emitted events.
|
|
275
|
+
|
|
276
|
+
| Event | When it fires | Properties |
|
|
277
|
+
| --------------------------- | ---------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
|
|
278
|
+
| `Application Installed` | First launch with no prior version stored and no prior identity state. | `version`, `build` |
|
|
279
|
+
| `Application Updated` | First launch where the stored version/build differs from the current. | `version`, `build`, `previous_version`, `previous_build` |
|
|
280
|
+
| `Application Opened` | Cold launch (foreground) and every return to the foreground after a background entry. | `from_background` (false on cold launch, true on resume), `version`, `build`, optional `url`, optional `referring_application` |
|
|
281
|
+
| `Application Backgrounded` | App enters background from the foreground. | _(none)_ |
|
|
282
|
+
|
|
283
|
+
### Enabling lifecycle events
|
|
284
|
+
|
|
285
|
+
Lifecycle events are **opt-in** — existing customers upgrading the SDK do not begin emitting these events without explicitly setting the flag. To enable:
|
|
286
|
+
|
|
287
|
+
```js
|
|
288
|
+
const analytics = createAnalyticsClient({
|
|
289
|
+
writeKey: "your-write-key",
|
|
290
|
+
ingestionHost: "https://your-ingestion-endpoint.com",
|
|
291
|
+
trackLifecycleEvents: true, // default: false
|
|
292
|
+
});
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
### Notes
|
|
296
|
+
|
|
297
|
+
- `active → inactive → active` blips (Control Center, a FaceID prompt, system alerts) are **suppressed**. `Application Opened` with `from_background: true` needs a real background entry first; a return that passes through `inactive` (e.g. a passcode prompt on resume) still counts.
|
|
298
|
+
- On iOS, React Native reports `active → inactive → background` when the app is left; `Application Backgrounded` fires on the `background` step. A process that settles straight into the background from `unknown` (headless task, push wake) does not emit `Application Backgrounded`. On iOS the launch state is `inactive`, so locking the device before the app first becomes active does emit one, the same as the native iOS SDK.
|
|
299
|
+
- Cold launches in a background process state (silent push, headless task) suppress the cold-launch `Application Opened`; the next `background → active` transition emits with `from_background: false` as the cold-launch bridge.
|
|
300
|
+
- Existing users upgrading from a pre-lifecycle SDK build receive `Application Updated` with `previous_version="unknown"` and `previous_build="unknown"` (instead of a spurious `Application Installed`).
|
|
301
|
+
- Lifecycle storage (`metarouter:lifecycle:version`, `metarouter:lifecycle:build`) is **not** cleared by `reset()` — install/update history survives logout.
|
|
302
|
+
- `Application Backgrounded` is emitted **before** the SDK's flush-to-disk pass on background entry, so the event is captured by the same drain that ships pending events.
|
|
303
|
+
|
|
304
|
+
### Deep-link wiring
|
|
305
|
+
|
|
306
|
+
The SDK does **not** read `Linking` itself, the same as the iOS and Android SDKs: only URLs your app forwards through `recordOpenedURL` are attached to `Application Opened` (as `url`, plus `referring_application` when you pass one). Forward the cold-launch URL and runtime URL events:
|
|
307
|
+
|
|
308
|
+
```js
|
|
309
|
+
import { Linking } from "react-native";
|
|
310
|
+
|
|
311
|
+
const analytics = createAnalyticsClient({ /* ... */ trackLifecycleEvents: true });
|
|
312
|
+
|
|
313
|
+
// Cold launch: safe to call right after createAnalyticsClient(). A URL
|
|
314
|
+
// forwarded while initialization is still running reaches the cold-launch
|
|
315
|
+
// Application Opened.
|
|
316
|
+
Linking.getInitialURL().then((url) => {
|
|
317
|
+
if (url) analytics.recordOpenedURL(url);
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
// Resume: attached to the next Application Opened.
|
|
321
|
+
Linking.addEventListener("url", ({ url }) => {
|
|
322
|
+
analytics.recordOpenedURL(url);
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
// With a referring application (typically forwarded from native):
|
|
326
|
+
analytics.recordOpenedURL("myapp://product/123", "com.example.referrer");
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
URLs from outside `Linking` (a UIScene URL handler on iOS, an Android `Intent.ACTION_VIEW`, a deep-link library such as Branch) are forwarded the same way.
|
|
330
|
+
|
|
331
|
+
**Buffer semantics:**
|
|
332
|
+
|
|
333
|
+
- One-shot — the buffer is cleared after the next `Application Opened` emits.
|
|
334
|
+
- Last-write-wins — multiple `recordOpenedURL` calls before the next Opened keep only the most recent URL.
|
|
335
|
+
- No-op with an always-on warning when `trackLifecycleEvents` is disabled, so misconfigurations surface in logs instead of failing silently.
|
|
336
|
+
|
|
337
|
+
### Privacy & sanitization
|
|
338
|
+
|
|
339
|
+
URLs can contain sensitive material (auth tokens, OTPs, magic-link secrets, PII in query strings). The SDK records the URL verbatim, and because it only records what you forward, sanitizing before the call is enough:
|
|
340
|
+
|
|
341
|
+
```js
|
|
342
|
+
function sanitize(url) {
|
|
343
|
+
const u = new URL(url);
|
|
344
|
+
// Strip known sensitive query params before forwarding.
|
|
345
|
+
["token", "otp", "auth"].forEach((k) => u.searchParams.delete(k));
|
|
346
|
+
return u.toString();
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
Linking.addEventListener("url", ({ url }) => {
|
|
350
|
+
analytics.recordOpenedURL(sanitize(url));
|
|
351
|
+
});
|
|
352
|
+
```
|
|
353
|
+
|
|
354
|
+
### Why the SDK does not auto-instrument deep links
|
|
355
|
+
|
|
356
|
+
- **Privacy.** Hosts often receive URLs that contain credentials. Capturing them automatically would record secrets before the app has a chance to strip them.
|
|
357
|
+
- **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
|
+
- **Parity.** The iOS (`recordOpenedURL`) and Android (`recordOpenedUrl`) SDKs work the same way, so the same app behaves the same on every platform.
|
|
359
|
+
|
|
238
360
|
## ✅ Compatibility
|
|
239
361
|
|
|
240
362
|
| Component | Supported Versions |
|
|
241
363
|
| -------------------------- | ------------------ |
|
|
242
|
-
| React Native | >= 0.
|
|
364
|
+
| React Native | >= 0.73 |
|
|
243
365
|
| React | >= 16.8 |
|
|
244
366
|
| iOS Deployment Target | >= iOS 13 |
|
|
245
|
-
| Android Min SDK | >= API
|
|
246
|
-
|
|
|
367
|
+
| Android Min SDK | >= API 23 |
|
|
368
|
+
| Android Build JDK | >= 17 |
|
|
369
|
+
| Node.js | >= 18 |
|
|
247
370
|
|
|
248
371
|
## Debugging
|
|
249
372
|
|
|
@@ -253,7 +376,7 @@ If you're not seeing API calls being made, here are some steps to troubleshoot:
|
|
|
253
376
|
|
|
254
377
|
```js
|
|
255
378
|
// Initialize with debug enabled
|
|
256
|
-
const analytics =
|
|
379
|
+
const analytics = createAnalyticsClient({
|
|
257
380
|
writeKey: "your-write-key",
|
|
258
381
|
ingestionHost: "https://your-ingestion-endpoint.com",
|
|
259
382
|
debug: true, // This enables detailed logging
|
|
@@ -287,7 +410,7 @@ await analytics.flush();
|
|
|
287
410
|
|
|
288
411
|
### Delivery & Backoff (How events flow under failures)
|
|
289
412
|
|
|
290
|
-
Queue capacity: The SDK
|
|
413
|
+
Queue capacity: The SDK caps the in-memory queue at 5 MB (hardcoded). When either the 5 MB byte cap or the `maxQueueEvents` count cap is reached, the oldest events are dropped first (drop-oldest). Tune the event count via `maxQueueEvents` in `createAnalyticsClient(options)`.
|
|
291
414
|
|
|
292
415
|
This SDK uses a circuit breaker around network I/O. It keeps ordering stable, avoids tight retry loops, and backs off cleanly when your cluster is unhealthy or throttling.
|
|
293
416
|
|
|
@@ -299,7 +422,7 @@ Half-open probe: After cooldown, one probe is allowed.
|
|
|
299
422
|
Success → breaker CLOSED (keep flushing).
|
|
300
423
|
Failure → breaker OPEN again with longer cooldown.
|
|
301
424
|
|
|
302
|
-
sentAt semantics: sentAt is stamped when
|
|
425
|
+
sentAt semantics: sentAt is stamped when a batch is prepared for transmission. If the client is backing off, the actual transmit may be later; if you need the original occurrence time, include your own event `timestamp`.
|
|
303
426
|
|
|
304
427
|
| Status / Failure | Action | Breaker | Queue effect |
|
|
305
428
|
| ----------------------------------- | -------------------------------------------------------------------- | ------- | ------------------------------ |
|
|
@@ -379,6 +502,13 @@ The `anonymousId` is a unique identifier automatically generated for each device
|
|
|
379
502
|
- Remains stable across app sessions until `reset()` is called
|
|
380
503
|
- Cleared on `reset()` and a **new** UUID is generated on next `init()`
|
|
381
504
|
|
|
505
|
+
**Accessing the anonymous ID:**
|
|
506
|
+
|
|
507
|
+
```js
|
|
508
|
+
const anonymousId = await analytics.getAnonymousId();
|
|
509
|
+
console.log(anonymousId); // e.g. "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
|
510
|
+
```
|
|
511
|
+
|
|
382
512
|
**Use case:**
|
|
383
513
|
Track user behavior before they log in or create an account, then connect pre-login and post-login activity using the `alias()` method.
|
|
384
514
|
|
|
@@ -492,7 +622,7 @@ await analytics.reset();
|
|
|
492
622
|
|
|
493
623
|
```js
|
|
494
624
|
// App starts - SDK initializes
|
|
495
|
-
const analytics =
|
|
625
|
+
const analytics = createAnalyticsClient({...});
|
|
496
626
|
// anonymousId: "abc-123" (auto-generated and persisted)
|
|
497
627
|
|
|
498
628
|
// User browses before login
|
|
@@ -552,7 +682,7 @@ This does two things:
|
|
|
552
682
|
|
|
553
683
|
```js
|
|
554
684
|
// App starts - user is anonymous
|
|
555
|
-
const analytics =
|
|
685
|
+
const analytics = createAnalyticsClient({...});
|
|
556
686
|
// anonymousId: "abc-123" (auto-generated)
|
|
557
687
|
|
|
558
688
|
// User browses anonymously
|
|
@@ -624,7 +754,7 @@ The SDK supports including advertising identifiers (IDFA on iOS, GAID on Android
|
|
|
624
754
|
Use the `setAdvertisingId()` method to set the advertising identifier after initializing the analytics client:
|
|
625
755
|
|
|
626
756
|
```js
|
|
627
|
-
const analytics =
|
|
757
|
+
const analytics = createAnalyticsClient({
|
|
628
758
|
writeKey: "your-write-key",
|
|
629
759
|
ingestionHost: "https://your-ingestion-endpoint.com",
|
|
630
760
|
});
|
|
@@ -667,7 +797,7 @@ import { AppTrackingTransparency } from "react-native-tracking-transparency";
|
|
|
667
797
|
import { getAdvertisingId } from "@react-native-community/google-advertiser-id"; // or similar library
|
|
668
798
|
|
|
669
799
|
// Initialize analytics first
|
|
670
|
-
const analytics =
|
|
800
|
+
const analytics = createAnalyticsClient({
|
|
671
801
|
writeKey: "your-write-key",
|
|
672
802
|
ingestionHost: "https://your-ingestion-endpoint.com",
|
|
673
803
|
});
|
|
@@ -689,7 +819,7 @@ if (trackingStatus === "authorized") {
|
|
|
689
819
|
import { getAdvertisingId } from "@react-native-community/google-advertiser-id"; // or similar library
|
|
690
820
|
|
|
691
821
|
// Initialize analytics first
|
|
692
|
-
const analytics =
|
|
822
|
+
const analytics = createAnalyticsClient({
|
|
693
823
|
writeKey: "your-write-key",
|
|
694
824
|
ingestionHost: "https://your-ingestion-endpoint.com",
|
|
695
825
|
});
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
buildscript {
|
|
2
|
+
repositories {
|
|
3
|
+
google()
|
|
4
|
+
mavenCentral()
|
|
5
|
+
}
|
|
6
|
+
dependencies {
|
|
7
|
+
classpath 'com.android.tools.build:gradle:8.1.0'
|
|
8
|
+
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.9.10"
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
apply plugin: 'com.android.library'
|
|
13
|
+
apply plugin: 'kotlin-android'
|
|
14
|
+
|
|
15
|
+
android {
|
|
16
|
+
namespace "com.metarouter.reactnative"
|
|
17
|
+
compileSdkVersion 34
|
|
18
|
+
|
|
19
|
+
defaultConfig {
|
|
20
|
+
minSdkVersion 23
|
|
21
|
+
targetSdkVersion 34
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
compileOptions {
|
|
25
|
+
sourceCompatibility JavaVersion.VERSION_17
|
|
26
|
+
targetCompatibility JavaVersion.VERSION_17
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
kotlinOptions {
|
|
30
|
+
jvmTarget = "17"
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
repositories {
|
|
35
|
+
google()
|
|
36
|
+
mavenCentral()
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
dependencies {
|
|
40
|
+
implementation "com.facebook.react:react-android:+"
|
|
41
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
package com.metarouter.reactnative
|
|
2
|
+
|
|
3
|
+
import android.net.ConnectivityManager
|
|
4
|
+
import android.net.Network
|
|
5
|
+
import android.net.NetworkCapabilities
|
|
6
|
+
import android.net.NetworkRequest
|
|
7
|
+
import android.content.Context
|
|
8
|
+
import com.facebook.react.bridge.ReactApplicationContext
|
|
9
|
+
import com.facebook.react.bridge.ReactContextBaseJavaModule
|
|
10
|
+
import com.facebook.react.bridge.ReactMethod
|
|
11
|
+
import com.facebook.react.bridge.Promise
|
|
12
|
+
import com.facebook.react.bridge.Arguments
|
|
13
|
+
import com.facebook.react.modules.core.DeviceEventManagerModule
|
|
14
|
+
|
|
15
|
+
class MetaRouterNetworkMonitorModule(
|
|
16
|
+
private val reactContext: ReactApplicationContext
|
|
17
|
+
) : ReactContextBaseJavaModule(reactContext) {
|
|
18
|
+
|
|
19
|
+
override fun getName(): String = "MetaRouterNetworkMonitor"
|
|
20
|
+
|
|
21
|
+
@Volatile
|
|
22
|
+
private var isConnected: Boolean = true
|
|
23
|
+
|
|
24
|
+
private var connectivityManager: ConnectivityManager? = null
|
|
25
|
+
private var networkCallback: ConnectivityManager.NetworkCallback? = null
|
|
26
|
+
|
|
27
|
+
init {
|
|
28
|
+
connectivityManager = try {
|
|
29
|
+
reactContext.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
|
|
30
|
+
} catch (_: Exception) {
|
|
31
|
+
null
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Snapshot initial state
|
|
35
|
+
connectivityManager?.let { cm ->
|
|
36
|
+
isConnected = try {
|
|
37
|
+
val network = cm.activeNetwork
|
|
38
|
+
val caps = network?.let { cm.getNetworkCapabilities(it) }
|
|
39
|
+
caps?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) == true
|
|
40
|
+
} catch (_: Exception) {
|
|
41
|
+
true // fallback
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Register callback for changes
|
|
46
|
+
connectivityManager?.let { cm ->
|
|
47
|
+
val request = NetworkRequest.Builder()
|
|
48
|
+
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
|
49
|
+
.build()
|
|
50
|
+
|
|
51
|
+
val cb = object : ConnectivityManager.NetworkCallback() {
|
|
52
|
+
override fun onAvailable(network: Network) {
|
|
53
|
+
if (!isConnected) {
|
|
54
|
+
isConnected = true
|
|
55
|
+
sendEvent(true)
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
override fun onLost(network: Network) {
|
|
60
|
+
val activeNet = cm.activeNetwork
|
|
61
|
+
val caps = activeNet?.let { cm.getNetworkCapabilities(it) }
|
|
62
|
+
val hasInternet = caps?.hasCapability(
|
|
63
|
+
NetworkCapabilities.NET_CAPABILITY_INTERNET
|
|
64
|
+
) == true
|
|
65
|
+
if (!hasInternet && isConnected) {
|
|
66
|
+
isConnected = false
|
|
67
|
+
sendEvent(false)
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
try {
|
|
73
|
+
cm.registerNetworkCallback(request, cb)
|
|
74
|
+
networkCallback = cb
|
|
75
|
+
} catch (_: SecurityException) {
|
|
76
|
+
// Missing ACCESS_NETWORK_STATE — fallback to always connected
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
private fun sendEvent(connected: Boolean) {
|
|
82
|
+
val params = Arguments.createMap().apply {
|
|
83
|
+
putBoolean("isConnected", connected)
|
|
84
|
+
}
|
|
85
|
+
try {
|
|
86
|
+
reactContext
|
|
87
|
+
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
|
|
88
|
+
.emit("onConnectivityChange", params)
|
|
89
|
+
} catch (_: Exception) {
|
|
90
|
+
// JS runtime not ready yet — ignore
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
@ReactMethod
|
|
95
|
+
fun getCurrentStatus(promise: Promise) {
|
|
96
|
+
promise.resolve(isConnected)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
@ReactMethod
|
|
100
|
+
fun addListener(@Suppress("UNUSED_PARAMETER") eventName: String) {
|
|
101
|
+
// Required for RN event emitter
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
@ReactMethod
|
|
105
|
+
fun removeListeners(@Suppress("UNUSED_PARAMETER") count: Int) {
|
|
106
|
+
// Required for RN event emitter
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
override fun invalidate() {
|
|
110
|
+
networkCallback?.let { cb ->
|
|
111
|
+
try {
|
|
112
|
+
connectivityManager?.unregisterNetworkCallback(cb)
|
|
113
|
+
} catch (_: Exception) {
|
|
114
|
+
// ignore
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
networkCallback = null
|
|
118
|
+
}
|
|
119
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
package com.metarouter.reactnative
|
|
2
|
+
|
|
3
|
+
import com.facebook.react.ReactPackage
|
|
4
|
+
import com.facebook.react.bridge.NativeModule
|
|
5
|
+
import com.facebook.react.bridge.ReactApplicationContext
|
|
6
|
+
import com.facebook.react.uimanager.ViewManager
|
|
7
|
+
|
|
8
|
+
class MetaRouterPackage : ReactPackage {
|
|
9
|
+
override fun createNativeModules(
|
|
10
|
+
reactContext: ReactApplicationContext
|
|
11
|
+
): List<NativeModule> {
|
|
12
|
+
return listOf(
|
|
13
|
+
MetaRouterQueueStorageModule(reactContext),
|
|
14
|
+
MetaRouterNetworkMonitorModule(reactContext)
|
|
15
|
+
)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
override fun createViewManagers(
|
|
19
|
+
reactContext: ReactApplicationContext
|
|
20
|
+
): List<ViewManager<*, *>> {
|
|
21
|
+
return emptyList()
|
|
22
|
+
}
|
|
23
|
+
}
|