@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.
Files changed (64) hide show
  1. package/README.md +190 -60
  2. package/android/build.gradle +41 -0
  3. package/android/src/main/AndroidManifest.xml +4 -0
  4. package/android/src/main/java/com/metarouter/reactnative/MetaRouterNetworkMonitorModule.kt +119 -0
  5. package/android/src/main/java/com/metarouter/reactnative/MetaRouterPackage.kt +23 -0
  6. package/android/src/main/java/com/metarouter/reactnative/MetaRouterQueueStorageModule.kt +124 -0
  7. package/ios/MetaRouterNetworkMonitor.m +76 -0
  8. package/ios/MetaRouterQueueStorage.m +127 -0
  9. package/lib/analytics/MetaRouterAnalyticsClient.d.ts +71 -4
  10. package/lib/analytics/MetaRouterAnalyticsClient.d.ts.map +1 -1
  11. package/lib/analytics/MetaRouterAnalyticsClient.js +396 -112
  12. package/lib/analytics/dispatcher.d.ts +57 -1
  13. package/lib/analytics/dispatcher.d.ts.map +1 -1
  14. package/lib/analytics/dispatcher.js +231 -32
  15. package/lib/analytics/init.d.ts +8 -1
  16. package/lib/analytics/init.d.ts.map +1 -1
  17. package/lib/analytics/init.js +198 -37
  18. package/lib/analytics/lifecycle/lifecycleEvents.d.ts +52 -0
  19. package/lib/analytics/lifecycle/lifecycleEvents.d.ts.map +1 -0
  20. package/lib/analytics/lifecycle/lifecycleEvents.js +66 -0
  21. package/lib/analytics/persistence/NativeQueueStorage.d.ts +5 -0
  22. package/lib/analytics/persistence/NativeQueueStorage.d.ts.map +1 -0
  23. package/lib/analytics/persistence/NativeQueueStorage.js +59 -0
  24. package/lib/analytics/persistence/PersistentEventQueue.d.ts +96 -0
  25. package/lib/analytics/persistence/PersistentEventQueue.d.ts.map +1 -0
  26. package/lib/analytics/persistence/PersistentEventQueue.js +401 -0
  27. package/lib/analytics/persistence/types.d.ts +20 -0
  28. package/lib/analytics/persistence/types.d.ts.map +1 -0
  29. package/lib/analytics/persistence/types.js +10 -0
  30. package/lib/analytics/proxy/proxyClient.d.ts +30 -1
  31. package/lib/analytics/proxy/proxyClient.d.ts.map +1 -1
  32. package/lib/analytics/proxy/proxyClient.js +145 -23
  33. package/lib/analytics/types.d.ts +61 -4
  34. package/lib/analytics/types.d.ts.map +1 -1
  35. package/lib/analytics/utils/appContext.d.ts +20 -0
  36. package/lib/analytics/utils/appContext.d.ts.map +1 -0
  37. package/lib/analytics/utils/appContext.js +22 -0
  38. package/lib/analytics/utils/circuitBreaker.d.ts +4 -1
  39. package/lib/analytics/utils/circuitBreaker.d.ts.map +1 -1
  40. package/lib/analytics/utils/circuitBreaker.js +23 -14
  41. package/lib/analytics/utils/contextInfo.d.ts +8 -4
  42. package/lib/analytics/utils/contextInfo.d.ts.map +1 -1
  43. package/lib/analytics/utils/contextInfo.js +34 -27
  44. package/lib/analytics/utils/debouncedNetworkMonitor.d.ts +25 -0
  45. package/lib/analytics/utils/debouncedNetworkMonitor.d.ts.map +1 -0
  46. package/lib/analytics/utils/debouncedNetworkMonitor.js +68 -0
  47. package/lib/analytics/utils/initOptions.d.ts +22 -0
  48. package/lib/analytics/utils/initOptions.d.ts.map +1 -0
  49. package/lib/analytics/utils/initOptions.js +100 -0
  50. package/lib/analytics/utils/lifecycleStorage.d.ts +13 -0
  51. package/lib/analytics/utils/lifecycleStorage.d.ts.map +1 -0
  52. package/lib/analytics/utils/lifecycleStorage.js +35 -0
  53. package/lib/analytics/utils/networkMonitor.d.ts +30 -0
  54. package/lib/analytics/utils/networkMonitor.d.ts.map +1 -0
  55. package/lib/analytics/utils/networkMonitor.js +90 -0
  56. package/lib/analytics/utils/responseCategory.d.ts +14 -0
  57. package/lib/analytics/utils/responseCategory.d.ts.map +1 -0
  58. package/lib/analytics/utils/responseCategory.js +26 -0
  59. package/lib/index.d.ts +4 -4
  60. package/lib/index.d.ts.map +1 -1
  61. package/lib/index.js +3 -3
  62. package/metarouter-react-native-sdk.podspec +19 -0
  63. package/package.json +6 -3
  64. package/react-native.config.js +15 -0
@@ -1,11 +1,11 @@
1
- import { Dimensions, PixelRatio, Platform } from "react-native";
2
- import { getTimeZone } from "./timezone";
3
- import pkg from "../../../package.json";
1
+ import { Dimensions, PixelRatio, Platform } from 'react-native';
2
+ import { getTimeZone } from './timezone';
3
+ import pkg from '../../../package.json';
4
4
  let cachedContext = null;
5
- let cachedAdvertisingId = undefined;
5
+ let cachedAdvertisingId;
6
6
  let DeviceInfo = null;
7
7
  try {
8
- DeviceInfo = require("react-native-device-info");
8
+ DeviceInfo = require('react-native-device-info');
9
9
  }
10
10
  catch {
11
11
  DeviceInfo = null;
@@ -20,60 +20,67 @@ export function clearContextCache() {
20
20
  /**
21
21
  * Gathers and caches device, app, and environment context information for analytics events.
22
22
  *
23
- * - Collects details such as app name/version, device model/type, OS, screen size, locale, timezone, and network status.
24
- * - Uses `react-native-device-info` and the current environment to populate fields.
23
+ * - Collects details such as device model/type, OS, screen size, locale, timezone, and network status.
24
+ * - Uses `react-native-device-info` and the current environment to populate device/os fields.
25
+ * - Reuses the caller-provided AppContext for the `app:` block so version/build
26
+ * are sourced from the same snapshot used by lifecycle events.
25
27
  * - Caches the result for the lifetime of the app to avoid redundant async calls.
26
28
  * - Returns a context object suitable for event enrichment.
27
29
  *
30
+ * @param appContext - The host app identity snapshot (name, version, build, namespace).
28
31
  * @param advertisingId - Optional advertising identifier (IDFA on iOS, GAID on Android) for ad tracking and attribution.
29
32
  * @returns {Promise<EventContext>} A promise that resolves to the context information object.
30
33
  */
31
- export async function getContextInfo(advertisingId) {
32
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z;
34
+ export async function getContextInfo(appContext, advertisingId) {
35
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
33
36
  // Return cached context only if it exists AND the advertising ID hasn't changed
34
37
  if (cachedContext && cachedAdvertisingId === advertisingId)
35
38
  return cachedContext;
36
- let locale = "en-US";
37
- if (typeof Intl !== "undefined" &&
38
- typeof Intl.DateTimeFormat === "function") {
39
+ let locale = 'en-US';
40
+ if (typeof Intl !== 'undefined' &&
41
+ typeof Intl.DateTimeFormat === 'function') {
39
42
  const resolved = Intl.DateTimeFormat().resolvedOptions();
40
43
  locale = (_a = resolved.locale) !== null && _a !== void 0 ? _a : locale;
41
44
  }
42
- const { width, height } = Dimensions.get("screen");
45
+ const { width, height } = Dimensions.get('screen');
43
46
  const density = Number(PixelRatio.get().toFixed(2));
44
47
  cachedContext = {
45
48
  library: {
46
- name: "metarouter-react-native-sdk",
47
- version: (_b = pkg.version) !== null && _b !== void 0 ? _b : "0.0.0",
49
+ name: 'metarouter-react-native-sdk',
50
+ version: (_b = pkg.version) !== null && _b !== void 0 ? _b : '0.0.0',
48
51
  },
49
52
  locale,
50
53
  timezone: getTimeZone(),
51
54
  device: {
52
- manufacturer: (_d = (await ((_c = DeviceInfo === null || DeviceInfo === void 0 ? void 0 : DeviceInfo.getManufacturer) === null || _c === void 0 ? void 0 : _c.call(DeviceInfo)))) !== null && _d !== void 0 ? _d : "unknown",
53
- model: (_f = (_e = DeviceInfo === null || DeviceInfo === void 0 ? void 0 : DeviceInfo.getModel) === null || _e === void 0 ? void 0 : _e.call(DeviceInfo)) !== null && _f !== void 0 ? _f : "unknown",
54
- name: (_h = (await ((_g = DeviceInfo === null || DeviceInfo === void 0 ? void 0 : DeviceInfo.getDeviceName) === null || _g === void 0 ? void 0 : _g.call(DeviceInfo)))) !== null && _h !== void 0 ? _h : "unknown",
55
- type: ((_j = DeviceInfo === null || DeviceInfo === void 0 ? void 0 : DeviceInfo.getSystemName) === null || _j === void 0 ? void 0 : _j.call(DeviceInfo)) === "Android" ? "android" : "ios",
55
+ manufacturer: (_d = (await ((_c = DeviceInfo === null || DeviceInfo === void 0 ? void 0 : DeviceInfo.getManufacturer) === null || _c === void 0 ? void 0 : _c.call(DeviceInfo)))) !== null && _d !== void 0 ? _d : 'unknown',
56
+ model: Platform.OS === 'android'
57
+ ? ((_f = (_e = DeviceInfo === null || DeviceInfo === void 0 ? void 0 : DeviceInfo.getModel) === null || _e === void 0 ? void 0 : _e.call(DeviceInfo)) !== null && _f !== void 0 ? _f : 'unknown')
58
+ : ((_h = (_g = DeviceInfo === null || DeviceInfo === void 0 ? void 0 : DeviceInfo.getDeviceId) === null || _g === void 0 ? void 0 : _g.call(DeviceInfo)) !== null && _h !== void 0 ? _h : 'unknown'),
59
+ type: ((_j = DeviceInfo === null || DeviceInfo === void 0 ? void 0 : DeviceInfo.getSystemName) === null || _j === void 0 ? void 0 : _j.call(DeviceInfo)) === 'Android' ? 'android' : 'ios',
60
+ ...(Platform.OS === 'android'
61
+ ? { name: (_l = (await ((_k = DeviceInfo === null || DeviceInfo === void 0 ? void 0 : DeviceInfo.getDevice) === null || _k === void 0 ? void 0 : _k.call(DeviceInfo)))) !== null && _l !== void 0 ? _l : 'unknown' }
62
+ : {}),
56
63
  ...(advertisingId ? { advertisingId } : {}),
57
64
  },
58
65
  os: {
59
- name: (_l = (_k = DeviceInfo === null || DeviceInfo === void 0 ? void 0 : DeviceInfo.getSystemName) === null || _k === void 0 ? void 0 : _k.call(DeviceInfo)) !== null && _l !== void 0 ? _l : "unknown",
60
- version: (_o = (_m = DeviceInfo === null || DeviceInfo === void 0 ? void 0 : DeviceInfo.getSystemVersion) === null || _m === void 0 ? void 0 : _m.call(DeviceInfo)) !== null && _o !== void 0 ? _o : "unknown",
66
+ name: (_o = (_m = DeviceInfo === null || DeviceInfo === void 0 ? void 0 : DeviceInfo.getSystemName) === null || _m === void 0 ? void 0 : _m.call(DeviceInfo)) !== null && _o !== void 0 ? _o : 'unknown',
67
+ version: (_q = (_p = DeviceInfo === null || DeviceInfo === void 0 ? void 0 : DeviceInfo.getSystemVersion) === null || _p === void 0 ? void 0 : _p.call(DeviceInfo)) !== null && _q !== void 0 ? _q : 'unknown',
61
68
  },
62
69
  app: {
63
- name: (_q = (_p = DeviceInfo === null || DeviceInfo === void 0 ? void 0 : DeviceInfo.getApplicationName) === null || _p === void 0 ? void 0 : _p.call(DeviceInfo)) !== null && _q !== void 0 ? _q : "unknown",
64
- version: (_t = (_s = (_r = DeviceInfo === null || DeviceInfo === void 0 ? void 0 : DeviceInfo.getVersion) === null || _r === void 0 ? void 0 : _r.call(DeviceInfo)) !== null && _s !== void 0 ? _s : pkg.version) !== null && _t !== void 0 ? _t : "unknown",
65
- build: (_v = (_u = DeviceInfo === null || DeviceInfo === void 0 ? void 0 : DeviceInfo.getBuildNumber) === null || _u === void 0 ? void 0 : _u.call(DeviceInfo)) !== null && _v !== void 0 ? _v : "unknown",
66
- namespace: (_x = (_w = DeviceInfo === null || DeviceInfo === void 0 ? void 0 : DeviceInfo.getBundleId) === null || _w === void 0 ? void 0 : _w.call(DeviceInfo)) !== null && _x !== void 0 ? _x : "unknown",
70
+ name: appContext.name,
71
+ version: appContext.version,
72
+ build: appContext.build,
73
+ namespace: appContext.namespace,
67
74
  },
68
75
  screen: {
69
76
  width: Math.round(width),
70
77
  height: Math.round(height),
71
78
  density,
72
79
  },
73
- ...(Platform.OS === "android"
80
+ ...(Platform.OS === 'android'
74
81
  ? {
75
82
  network: {
76
- wifi: (_z = (await ((_y = DeviceInfo === null || DeviceInfo === void 0 ? void 0 : DeviceInfo.isWifiEnabled) === null || _y === void 0 ? void 0 : _y.call(DeviceInfo)))) !== null && _z !== void 0 ? _z : false,
83
+ wifi: (_s = (await ((_r = DeviceInfo === null || DeviceInfo === void 0 ? void 0 : DeviceInfo.isWifiEnabled) === null || _r === void 0 ? void 0 : _r.call(DeviceInfo)))) !== null && _s !== void 0 ? _s : false,
77
84
  },
78
85
  }
79
86
  : {}),
@@ -0,0 +1,25 @@
1
+ import type { NetworkReachability, NetworkStatus } from './networkMonitor';
2
+ /**
3
+ * Wraps a {@link NetworkReachability} with asymmetric debouncing:
4
+ * - **offline** transitions fire immediately (pause HTTP ASAP — no point
5
+ * burning retries on a down network).
6
+ * - **online** transitions wait for {@link ONLINE_DEBOUNCE_MS} of stable
7
+ * connectivity before firing, so flaky WiFi/cellular handoffs don't
8
+ * trigger spurious flush attempts that immediately fail.
9
+ *
10
+ * A pending online debounce is cancelled if offline arrives during the wait.
11
+ */
12
+ export declare class DebouncedNetworkMonitor implements NetworkReachability {
13
+ static readonly ONLINE_DEBOUNCE_MS = 2000;
14
+ private readonly inner;
15
+ private handler;
16
+ private unsubscribeInner;
17
+ private onlineTimer;
18
+ private _currentStatus;
19
+ constructor(inner: NetworkReachability);
20
+ get currentStatus(): NetworkStatus;
21
+ onStatusChange(handler: (status: NetworkStatus) => void): () => void;
22
+ stop(): void;
23
+ private clearOnlineTimer;
24
+ }
25
+ //# sourceMappingURL=debouncedNetworkMonitor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"debouncedNetworkMonitor.d.ts","sourceRoot":"","sources":["../../../src/analytics/utils/debouncedNetworkMonitor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAE3E;;;;;;;;;GASG;AACH,qBAAa,uBAAwB,YAAW,mBAAmB;IACjE,MAAM,CAAC,QAAQ,CAAC,kBAAkB,QAAQ;IAE1C,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAsB;IAC5C,OAAO,CAAC,OAAO,CAAkD;IACjE,OAAO,CAAC,gBAAgB,CAA6B;IACrD,OAAO,CAAC,WAAW,CAA8C;IACjE,OAAO,CAAC,cAAc,CAAgB;gBAE1B,KAAK,EAAE,mBAAmB;IA8BtC,IAAI,aAAa,IAAI,aAAa,CAEjC;IAED,cAAc,CAAC,OAAO,EAAE,CAAC,MAAM,EAAE,aAAa,KAAK,IAAI,GAAG,MAAM,IAAI;IAOpE,IAAI,IAAI,IAAI;IAOZ,OAAO,CAAC,gBAAgB;CAMzB"}
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Wraps a {@link NetworkReachability} with asymmetric debouncing:
3
+ * - **offline** transitions fire immediately (pause HTTP ASAP — no point
4
+ * burning retries on a down network).
5
+ * - **online** transitions wait for {@link ONLINE_DEBOUNCE_MS} of stable
6
+ * connectivity before firing, so flaky WiFi/cellular handoffs don't
7
+ * trigger spurious flush attempts that immediately fail.
8
+ *
9
+ * A pending online debounce is cancelled if offline arrives during the wait.
10
+ */
11
+ export class DebouncedNetworkMonitor {
12
+ constructor(inner) {
13
+ this.handler = null;
14
+ this.unsubscribeInner = null;
15
+ this.onlineTimer = null;
16
+ this.inner = inner;
17
+ this._currentStatus = inner.currentStatus;
18
+ this.unsubscribeInner = inner.onStatusChange((rawStatus) => {
19
+ var _a;
20
+ if (rawStatus === 'disconnected') {
21
+ this.clearOnlineTimer();
22
+ if (this._currentStatus !== 'disconnected') {
23
+ this._currentStatus = 'disconnected';
24
+ (_a = this.handler) === null || _a === void 0 ? void 0 : _a.call(this, 'disconnected');
25
+ }
26
+ return;
27
+ }
28
+ // rawStatus === 'connected': start/reset the debounce window
29
+ this.clearOnlineTimer();
30
+ if (this._currentStatus === 'connected')
31
+ return;
32
+ this.onlineTimer = setTimeout(() => {
33
+ var _a;
34
+ this.onlineTimer = null;
35
+ // Guard against racing with a late offline transition.
36
+ if (this.inner.currentStatus !== 'connected')
37
+ return;
38
+ if (this._currentStatus !== 'connected') {
39
+ this._currentStatus = 'connected';
40
+ (_a = this.handler) === null || _a === void 0 ? void 0 : _a.call(this, 'connected');
41
+ }
42
+ }, DebouncedNetworkMonitor.ONLINE_DEBOUNCE_MS);
43
+ });
44
+ }
45
+ get currentStatus() {
46
+ return this._currentStatus;
47
+ }
48
+ onStatusChange(handler) {
49
+ this.handler = handler;
50
+ return () => {
51
+ this.handler = null;
52
+ };
53
+ }
54
+ stop() {
55
+ var _a;
56
+ this.clearOnlineTimer();
57
+ (_a = this.unsubscribeInner) === null || _a === void 0 ? void 0 : _a.call(this);
58
+ this.unsubscribeInner = null;
59
+ this.handler = null;
60
+ }
61
+ clearOnlineTimer() {
62
+ if (this.onlineTimer) {
63
+ clearTimeout(this.onlineTimer);
64
+ this.onlineTimer = null;
65
+ }
66
+ }
67
+ }
68
+ DebouncedNetworkMonitor.ONLINE_DEBOUNCE_MS = 2000;
@@ -0,0 +1,22 @@
1
+ import type { ConfigError, InitOptions } from '../types';
2
+ export interface ValidatedInitOptions {
3
+ /** Normalized copy: trimmed key/host, trailing slashes removed, numbers clamped. */
4
+ options: InitOptions;
5
+ /** First error found (writeKey before host), or null when valid. */
6
+ configError: ConfigError | null;
7
+ }
8
+ /** True for localhost / 127.0.0.1 / ::1 (IPv6 brackets stripped), exact match. */
9
+ export declare function isLoopbackHost(host: string): boolean;
10
+ /**
11
+ * Single validation funnel, run once per `createAnalyticsClient` call — the
12
+ * equivalent of the native InitOptions constructor. Never throws: records the
13
+ * first error and clamps every numeric bound with a warning (one policy for
14
+ * all fields, matching iOS and Android). Warnings are logged here and nowhere
15
+ * else, so they appear once per call.
16
+ */
17
+ export declare function validateInitOptions(raw: InitOptions, opts?: {
18
+ logWarnings?: boolean;
19
+ }): ValidatedInitOptions;
20
+ export declare const DEFAULT_MAX_QUEUE_EVENTS = 2000;
21
+ export declare const DEFAULT_MAX_DISK_EVENTS = 10000;
22
+ //# sourceMappingURL=initOptions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"initOptions.d.ts","sourceRoot":"","sources":["../../../src/analytics/utils/initOptions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAsBzD,MAAM,WAAW,oBAAoB;IACnC,oFAAoF;IACpF,OAAO,EAAE,WAAW,CAAC;IACrB,oEAAoE;IACpE,WAAW,EAAE,WAAW,GAAG,IAAI,CAAC;CACjC;AAYD,kFAAkF;AAClF,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAIpD;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CACjC,GAAG,EAAE,WAAW,EAChB,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,OAAO,CAAA;CAAO,GACnC,oBAAoB,CA2EtB;AAED,eAAO,MAAM,wBAAwB,OAAO,CAAC;AAC7C,eAAO,MAAM,uBAAuB,QAAS,CAAC"}
@@ -0,0 +1,100 @@
1
+ import { warn as logWarn } from './logger';
2
+ /*
3
+ * Why the options were invalid. Recorded instead of thrown: a throw from the
4
+ * synchronous `createAnalyticsClient` call would take down a host that sources
5
+ * its config remotely and forgot a try/catch — the crash this contract exists
6
+ * to prevent. Each error carries its description, as `ConfigError.description`
7
+ * does on iOS and Android, and the text is byte-identical with both SDKs so one
8
+ * support answer covers all three.
9
+ */
10
+ const emptyWriteKeyError = () => ({
11
+ type: 'emptyWriteKey',
12
+ description: 'writeKey must not be empty or whitespace-only',
13
+ });
14
+ const invalidIngestionHostError = (raw) => ({
15
+ type: 'invalidIngestionHost',
16
+ raw,
17
+ description: `ingestionHost must be an http(s) URL, got "${raw}"`,
18
+ });
19
+ // `http(s)://[userinfo@]host[:port][/path]`. Parsed by hand rather than with
20
+ // `URL`: React Native's `URL` polyfill does not implement `hostname`, so it
21
+ // cannot tell "https:" (no host) from a real origin. Accepts what Foundation
22
+ // and java.net.URL accept, so the same string passes on all three platforms:
23
+ // userinfo, an empty port ("host:"), and bracketed IPv6 hosts.
24
+ const HTTP_URL = /^(https?):\/\/(?:[^\s/?#@]*@)?(\[[^\]\s]+\]|[^\s/?#:@]+)(:\d*)?([/?#]\S*)?$/i;
25
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1']);
26
+ /** True for localhost / 127.0.0.1 / ::1 (IPv6 brackets stripped), exact match. */
27
+ export function isLoopbackHost(host) {
28
+ const bare = host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host;
29
+ return LOOPBACK_HOSTS.has(bare);
30
+ }
31
+ /**
32
+ * Single validation funnel, run once per `createAnalyticsClient` call — the
33
+ * equivalent of the native InitOptions constructor. Never throws: records the
34
+ * first error and clamps every numeric bound with a warning (one policy for
35
+ * all fields, matching iOS and Android). Warnings are logged here and nowhere
36
+ * else, so they appear once per call.
37
+ */
38
+ export function validateInitOptions(raw, opts = {}) {
39
+ const warn = opts.logWarnings === false ? () => { } : logWarn;
40
+ let configError = null;
41
+ const writeKey = typeof raw.writeKey === 'string' ? raw.writeKey.trim() : '';
42
+ if (writeKey === '') {
43
+ configError = emptyWriteKeyError();
44
+ }
45
+ const rawHost = typeof raw.ingestionHost === 'string' ? raw.ingestionHost : '';
46
+ const ingestionHost = rawHost.trim().replace(/\/+$/, '');
47
+ const match = HTTP_URL.exec(ingestionHost);
48
+ if (!match) {
49
+ if (configError === null) {
50
+ configError = invalidIngestionHostError(rawHost);
51
+ }
52
+ }
53
+ else if (match[1].toLowerCase() === 'http' && !isLoopbackHost(match[2])) {
54
+ // A cleartext origin is spoofable in transit — legitimate for local
55
+ // development, worth a warning anywhere else.
56
+ warn(`ingestionHost ${ingestionHost} is cleartext http — use https outside local development.`);
57
+ }
58
+ // NaN / Infinity (e.g. Number('') from remote config) would slip past every
59
+ // `<` check and reach the dispatcher as a 0ms flush loop or a silently
60
+ // disabled disk queue. Treated as unset, with a warning. Native integer
61
+ // options cannot hold these values, so only JS needs the check.
62
+ const finiteOrUnset = (name, value) => {
63
+ if (value == null || Number.isFinite(value))
64
+ return value;
65
+ warn(`${name} (${value}) is not a finite number — using the default`);
66
+ return undefined;
67
+ };
68
+ const flushIntervalSeconds = finiteOrUnset('flushIntervalSeconds', raw.flushIntervalSeconds);
69
+ if (flushIntervalSeconds != null && flushIntervalSeconds < 1) {
70
+ warn(`flushIntervalSeconds (${flushIntervalSeconds}) clamped to 1`);
71
+ }
72
+ const maxQueueEvents = finiteOrUnset('maxQueueEvents', raw.maxQueueEvents);
73
+ if (maxQueueEvents != null && maxQueueEvents < 1) {
74
+ warn(`maxQueueEvents (${maxQueueEvents}) clamped to 1`);
75
+ }
76
+ const maxDiskEvents = finiteOrUnset('maxDiskEvents', raw.maxDiskEvents);
77
+ if (maxDiskEvents != null && maxDiskEvents < 0) {
78
+ warn(`maxDiskEvents (${maxDiskEvents}) clamped to 0 — use 0 to disable disk persistence`);
79
+ }
80
+ const clampedQueue = Math.max(1, maxQueueEvents !== null && maxQueueEvents !== void 0 ? maxQueueEvents : DEFAULT_MAX_QUEUE_EVENTS);
81
+ const clampedDisk = Math.max(0, maxDiskEvents !== null && maxDiskEvents !== void 0 ? maxDiskEvents : DEFAULT_MAX_DISK_EVENTS);
82
+ if (clampedDisk > 0 && clampedDisk < clampedQueue) {
83
+ warn(`maxDiskEvents (${clampedDisk}) is less than maxQueueEvents (${clampedQueue}) — memory can hold more events than disk can preserve; events may be dropped during background flush`);
84
+ }
85
+ return {
86
+ options: {
87
+ ...raw,
88
+ writeKey,
89
+ ingestionHost,
90
+ flushIntervalSeconds: flushIntervalSeconds != null
91
+ ? Math.max(1, flushIntervalSeconds)
92
+ : undefined,
93
+ maxQueueEvents: clampedQueue,
94
+ maxDiskEvents: clampedDisk,
95
+ },
96
+ configError,
97
+ };
98
+ }
99
+ export const DEFAULT_MAX_QUEUE_EVENTS = 2000;
100
+ export const DEFAULT_MAX_DISK_EVENTS = 10000;
@@ -0,0 +1,13 @@
1
+ export declare const LIFECYCLE_VERSION_KEY = "metarouter:lifecycle:version";
2
+ export declare const LIFECYCLE_BUILD_KEY = "metarouter:lifecycle:build";
3
+ /**
4
+ * Storage for app lifecycle state (last-seen version + build). Lives in a
5
+ * dedicated module so neither IdentityManager.reset() nor the client's reset()
6
+ * can wipe install/update history. Errors are swallowed so missing or
7
+ * unavailable storage is treated as "no prior lifecycle state" — the caller
8
+ * decides whether that means install or update.
9
+ */
10
+ export declare function getLifecycleVersion(): Promise<string | null>;
11
+ export declare function getLifecycleBuild(): Promise<string | null>;
12
+ export declare function setLifecycleVersionBuild(version: string, build: string): Promise<void>;
13
+ //# sourceMappingURL=lifecycleStorage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lifecycleStorage.d.ts","sourceRoot":"","sources":["../../../src/analytics/utils/lifecycleStorage.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,qBAAqB,iCAAiC,CAAC;AACpE,eAAO,MAAM,mBAAmB,+BAA+B,CAAC;AAEhE;;;;;;GAMG;AAEH,wBAAsB,mBAAmB,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAMlE;AAED,wBAAsB,iBAAiB,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAMhE;AAED,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,IAAI,CAAC,CAOf"}
@@ -0,0 +1,35 @@
1
+ import AsyncStorage from '@react-native-async-storage/async-storage';
2
+ export const LIFECYCLE_VERSION_KEY = 'metarouter:lifecycle:version';
3
+ export const LIFECYCLE_BUILD_KEY = 'metarouter:lifecycle:build';
4
+ /**
5
+ * Storage for app lifecycle state (last-seen version + build). Lives in a
6
+ * dedicated module so neither IdentityManager.reset() nor the client's reset()
7
+ * can wipe install/update history. Errors are swallowed so missing or
8
+ * unavailable storage is treated as "no prior lifecycle state" — the caller
9
+ * decides whether that means install or update.
10
+ */
11
+ export async function getLifecycleVersion() {
12
+ try {
13
+ return await AsyncStorage.getItem(LIFECYCLE_VERSION_KEY);
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ }
19
+ export async function getLifecycleBuild() {
20
+ try {
21
+ return await AsyncStorage.getItem(LIFECYCLE_BUILD_KEY);
22
+ }
23
+ catch {
24
+ return null;
25
+ }
26
+ }
27
+ export async function setLifecycleVersionBuild(version, build) {
28
+ try {
29
+ await AsyncStorage.setItem(LIFECYCLE_VERSION_KEY, version);
30
+ await AsyncStorage.setItem(LIFECYCLE_BUILD_KEY, build);
31
+ }
32
+ catch {
33
+ // best-effort; cold-launch state will be re-derived on next run
34
+ }
35
+ }
@@ -0,0 +1,30 @@
1
+ export type NetworkStatus = 'connected' | 'disconnected';
2
+ export interface NetworkReachability {
3
+ /** Current connectivity snapshot */
4
+ readonly currentStatus: NetworkStatus;
5
+ /** Register callback for status transitions. Returns unsubscribe function. */
6
+ onStatusChange(handler: (status: NetworkStatus) => void): () => void;
7
+ /** Tear down monitoring */
8
+ stop(): void;
9
+ }
10
+ export declare class NetworkMonitor implements NetworkReachability {
11
+ private _currentStatus;
12
+ private handler;
13
+ private unsubscribe;
14
+ private receivedNativeEvent;
15
+ get currentStatus(): NetworkStatus;
16
+ constructor();
17
+ onStatusChange(handler: (status: NetworkStatus) => void): () => void;
18
+ stop(): void;
19
+ }
20
+ export declare class StubNetworkMonitor implements NetworkReachability {
21
+ private _currentStatus;
22
+ private handler;
23
+ get currentStatus(): NetworkStatus;
24
+ constructor(initialStatus?: NetworkStatus);
25
+ onStatusChange(handler: (status: NetworkStatus) => void): () => void;
26
+ stop(): void;
27
+ /** Simulate a network transition from tests */
28
+ simulate(status: NetworkStatus): void;
29
+ }
30
+ //# sourceMappingURL=networkMonitor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"networkMonitor.d.ts","sourceRoot":"","sources":["../../../src/analytics/utils/networkMonitor.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,aAAa,GAAG,WAAW,GAAG,cAAc,CAAC;AAEzD,MAAM,WAAW,mBAAmB;IAClC,oCAAoC;IACpC,QAAQ,CAAC,aAAa,EAAE,aAAa,CAAC;IACtC,8EAA8E;IAC9E,cAAc,CAAC,OAAO,EAAE,CAAC,MAAM,EAAE,aAAa,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;IACrE,2BAA2B;IAC3B,IAAI,IAAI,IAAI,CAAC;CACd;AAED,qBAAa,cAAe,YAAW,mBAAmB;IACxD,OAAO,CAAC,cAAc,CAA8B;IACpD,OAAO,CAAC,OAAO,CAAkD;IACjE,OAAO,CAAC,WAAW,CAA6B;IAChD,OAAO,CAAC,mBAAmB,CAAS;IAEpC,IAAI,aAAa,IAAI,aAAa,CAEjC;;IAqDD,cAAc,CAAC,OAAO,EAAE,CAAC,MAAM,EAAE,aAAa,KAAK,IAAI,GAAG,MAAM,IAAI;IAOpE,IAAI,IAAI,IAAI;CAKb;AAED,qBAAa,kBAAmB,YAAW,mBAAmB;IAC5D,OAAO,CAAC,cAAc,CAAgB;IACtC,OAAO,CAAC,OAAO,CAAkD;IAEjE,IAAI,aAAa,IAAI,aAAa,CAEjC;gBAEW,aAAa,GAAE,aAA2B;IAItD,cAAc,CAAC,OAAO,EAAE,CAAC,MAAM,EAAE,aAAa,KAAK,IAAI,GAAG,MAAM,IAAI;IAOpE,IAAI,IAAI,IAAI;IAIZ,+CAA+C;IAC/C,QAAQ,CAAC,MAAM,EAAE,aAAa,GAAG,IAAI;CAMtC"}
@@ -0,0 +1,90 @@
1
+ import { warn } from './logger';
2
+ export class NetworkMonitor {
3
+ get currentStatus() {
4
+ return this._currentStatus;
5
+ }
6
+ constructor() {
7
+ this._currentStatus = 'connected';
8
+ this.handler = null;
9
+ this.unsubscribe = null;
10
+ this.receivedNativeEvent = false;
11
+ try {
12
+ const { NativeModules, NativeEventEmitter } = require('react-native');
13
+ const MetaRouterNetworkMonitor = NativeModules.MetaRouterNetworkMonitor;
14
+ if (!MetaRouterNetworkMonitor)
15
+ throw new Error('Native module not available');
16
+ // Get initial state from native — skip if a live event already arrived
17
+ MetaRouterNetworkMonitor.getCurrentStatus()
18
+ .then((connected) => {
19
+ var _a;
20
+ if (this.receivedNativeEvent)
21
+ return;
22
+ const newStatus = connected
23
+ ? 'connected'
24
+ : 'disconnected';
25
+ if (newStatus !== this._currentStatus) {
26
+ this._currentStatus = newStatus;
27
+ (_a = this.handler) === null || _a === void 0 ? void 0 : _a.call(this, newStatus);
28
+ }
29
+ })
30
+ .catch((err) => {
31
+ warn('Failed to get initial network status, defaulting to connected', err);
32
+ });
33
+ // Subscribe to native connectivity events
34
+ const emitter = new NativeEventEmitter(MetaRouterNetworkMonitor);
35
+ const subscription = emitter.addListener('onConnectivityChange', (event) => {
36
+ var _a;
37
+ this.receivedNativeEvent = true;
38
+ const newStatus = event.isConnected
39
+ ? 'connected'
40
+ : 'disconnected';
41
+ if (newStatus !== this._currentStatus) {
42
+ this._currentStatus = newStatus;
43
+ (_a = this.handler) === null || _a === void 0 ? void 0 : _a.call(this, newStatus);
44
+ }
45
+ });
46
+ this.unsubscribe = () => subscription.remove();
47
+ }
48
+ catch (err) {
49
+ warn('Native network monitor not available, defaulting to connected', err);
50
+ }
51
+ }
52
+ onStatusChange(handler) {
53
+ this.handler = handler;
54
+ return () => {
55
+ this.handler = null;
56
+ };
57
+ }
58
+ stop() {
59
+ var _a;
60
+ (_a = this.unsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
61
+ this.unsubscribe = null;
62
+ this.handler = null;
63
+ }
64
+ }
65
+ export class StubNetworkMonitor {
66
+ get currentStatus() {
67
+ return this._currentStatus;
68
+ }
69
+ constructor(initialStatus = 'connected') {
70
+ this.handler = null;
71
+ this._currentStatus = initialStatus;
72
+ }
73
+ onStatusChange(handler) {
74
+ this.handler = handler;
75
+ return () => {
76
+ this.handler = null;
77
+ };
78
+ }
79
+ stop() {
80
+ this.handler = null;
81
+ }
82
+ /** Simulate a network transition from tests */
83
+ simulate(status) {
84
+ var _a;
85
+ if (status !== this._currentStatus) {
86
+ this._currentStatus = status;
87
+ (_a = this.handler) === null || _a === void 0 ? void 0 : _a.call(this, status);
88
+ }
89
+ }
90
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Shared classification of HTTP status codes used by both
3
+ * the dispatcher and the disk drain.
4
+ */
5
+ export declare enum ResponseCategory {
6
+ SUCCESS = "SUCCESS",
7
+ SERVER_ERROR = "SERVER_ERROR",
8
+ RATE_LIMITED = "RATE_LIMITED",
9
+ PAYLOAD_TOO_LARGE = "PAYLOAD_TOO_LARGE",
10
+ FATAL_CONFIG = "FATAL_CONFIG",
11
+ CLIENT_ERROR = "CLIENT_ERROR"
12
+ }
13
+ export declare function categorizeResponse(statusCode: number): ResponseCategory;
14
+ //# sourceMappingURL=responseCategory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"responseCategory.d.ts","sourceRoot":"","sources":["../../../src/analytics/utils/responseCategory.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,oBAAY,gBAAgB;IAC1B,OAAO,YAAY;IACnB,YAAY,iBAAiB;IAC7B,YAAY,iBAAiB;IAC7B,iBAAiB,sBAAsB;IACvC,YAAY,iBAAiB;IAC7B,YAAY,iBAAiB;CAC9B;AAED,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,MAAM,GAAG,gBAAgB,CASvE"}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Shared classification of HTTP status codes used by both
3
+ * the dispatcher and the disk drain.
4
+ */
5
+ export var ResponseCategory;
6
+ (function (ResponseCategory) {
7
+ ResponseCategory["SUCCESS"] = "SUCCESS";
8
+ ResponseCategory["SERVER_ERROR"] = "SERVER_ERROR";
9
+ ResponseCategory["RATE_LIMITED"] = "RATE_LIMITED";
10
+ ResponseCategory["PAYLOAD_TOO_LARGE"] = "PAYLOAD_TOO_LARGE";
11
+ ResponseCategory["FATAL_CONFIG"] = "FATAL_CONFIG";
12
+ ResponseCategory["CLIENT_ERROR"] = "CLIENT_ERROR";
13
+ })(ResponseCategory || (ResponseCategory = {}));
14
+ export function categorizeResponse(statusCode) {
15
+ if (statusCode >= 200 && statusCode < 300)
16
+ return ResponseCategory.SUCCESS;
17
+ if (statusCode >= 500 || statusCode === 408)
18
+ return ResponseCategory.SERVER_ERROR;
19
+ if (statusCode === 429)
20
+ return ResponseCategory.RATE_LIMITED;
21
+ if (statusCode === 413)
22
+ return ResponseCategory.PAYLOAD_TOO_LARGE;
23
+ if (statusCode === 401 || statusCode === 403 || statusCode === 404)
24
+ return ResponseCategory.FATAL_CONFIG;
25
+ return ResponseCategory.CLIENT_ERROR;
26
+ }
package/lib/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- export { createAnalyticsClient } from "./analytics/init";
2
- export { MetaRouterProvider } from "./react/context";
3
- export { useMetaRouter } from "./react/useMetaRouter";
4
- export type { InitOptions, AnalyticsInterface } from "./analytics/types";
1
+ export { createAnalyticsClient } from './analytics/init';
2
+ export { MetaRouterProvider } from './react/context';
3
+ export { useMetaRouter } from './react/useMetaRouter';
4
+ export type { InitOptions, AnalyticsInterface, ConfigError, } from './analytics/types';
5
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAEzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,YAAY,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAEzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,YAAY,EACV,WAAW,EACX,kBAAkB,EAClB,WAAW,GACZ,MAAM,mBAAmB,CAAC"}
package/lib/index.js CHANGED
@@ -1,3 +1,3 @@
1
- export { createAnalyticsClient } from "./analytics/init";
2
- export { MetaRouterProvider } from "./react/context";
3
- export { useMetaRouter } from "./react/useMetaRouter";
1
+ export { createAnalyticsClient } from './analytics/init';
2
+ export { MetaRouterProvider } from './react/context';
3
+ export { useMetaRouter } from './react/useMetaRouter';
@@ -0,0 +1,19 @@
1
+ require 'json'
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
4
+
5
+ Pod::Spec.new do |s|
6
+ s.name = "metarouter-react-native-sdk"
7
+ s.version = package['version']
8
+ s.summary = "MetaRouter React Native SDK native modules"
9
+ s.homepage = package['repository']['url']
10
+ s.license = package['license']
11
+ s.author = package['author']
12
+ s.source = { :git => package['repository']['url'], :tag => s.version }
13
+
14
+ s.platform = :ios, '13.0'
15
+
16
+ s.source_files = "ios/**/*.{h,m,mm,swift}"
17
+
18
+ s.dependency "React-Core"
19
+ end
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metarouter/react-native-sdk",
3
- "version": "1.5.1",
3
+ "version": "1.8.0",
4
4
  "main": "./lib/index.js",
5
5
  "types": "./lib/index.d.ts",
6
6
  "exports": {
@@ -12,7 +12,10 @@
12
12
  },
13
13
  "files": [
14
14
  "lib",
15
- "react-native.config.js"
15
+ "ios",
16
+ "android",
17
+ "react-native.config.js",
18
+ "metarouter-react-native-sdk.podspec"
16
19
  ],
17
20
  "scripts": {
18
21
  "clean": "rm -rf lib",
@@ -41,7 +44,7 @@
41
44
  "peerDependencies": {
42
45
  "@react-native-async-storage/async-storage": ">=2.2.0",
43
46
  "react": ">=16.8.0",
44
- "react-native": ">=0.63.0",
47
+ "react-native": ">=0.73.0",
45
48
  "react-native-device-info": ">=14.0.4"
46
49
  },
47
50
  "devDependencies": {