@layers/react-native 0.2.0-alpha.9 → 1.0.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 CHANGED
@@ -1,48 +1,253 @@
1
1
  # @layers/react-native
2
2
 
3
- React Native SDK for Layers Analytics with ATT/SKAN support, deep link helpers, network connectors, and an Expo config plugin.
3
+ React Native SDK for Layers Analytics with ATT, SKAN, deep link support, and offline queueing.
4
4
 
5
5
  ## Install
6
6
 
7
- ```
8
- npm install @layers/react-native @react-native-community/netinfo @react-native-async-storage/async-storage
7
+ ```bash
8
+ npm install @layers/react-native
9
9
  # or
10
- pnpm add @layers/react-native @react-native-community/netinfo @react-native-async-storage/async-storage
10
+ pnpm add @layers/react-native
11
+ ```
12
+
13
+ ### Peer Dependencies
14
+
15
+ | Package | Required | What degrades without it |
16
+ | ------------------------------------------- | -------- | ----------------------------------------------------- |
17
+ | `react` | Yes | -- |
18
+ | `react-native` | Yes | -- |
19
+ | `@react-native-async-storage/async-storage` | Optional | Events are only persisted in memory; lost on app kill |
20
+ | `@react-native-community/netinfo` | Optional | SDK assumes always-online; no offline queueing |
21
+
22
+ ```bash
23
+ npm install @react-native-async-storage/async-storage @react-native-community/netinfo
11
24
  ```
12
25
 
13
- ## Quick start
26
+ ## Quick Start
14
27
 
15
28
  ```ts
16
- import Layers from '@layers/react-native';
29
+ import { LayersReactNative } from '@layers/react-native';
17
30
 
18
- await Layers.init({
31
+ const layers = new LayersReactNative({
19
32
  apiKey: 'your-api-key',
20
33
  appId: 'your-app-id',
21
34
  environment: 'production',
22
35
  enableDebug: __DEV__
23
36
  });
24
37
 
25
- await Layers.track('app_open');
38
+ await layers.init();
39
+
40
+ // Track events
41
+ await layers.track('app_open', { source: 'push_notification' });
42
+
43
+ // Track screens
44
+ await layers.screen('home');
45
+
46
+ // Identify a user
47
+ layers.setAppUserId('user-123');
48
+ ```
49
+
50
+ ## Configuration
51
+
52
+ All fields for `LayersRNConfig`:
53
+
54
+ | Field | Type | Default | Description |
55
+ | ----------------- | -------------------------------------------- | ----------------------- | ------------------------------------ |
56
+ | `apiKey` | `string` | _required_ | API key from the Layers dashboard |
57
+ | `appId` | `string` | _required_ | Application identifier |
58
+ | `environment` | `'development' \| 'staging' \| 'production'` | _required_ | Deployment environment |
59
+ | `appUserId` | `string` | `undefined` | Pre-set user ID at init time |
60
+ | `enableDebug` | `boolean` | `false` | Verbose console logging |
61
+ | `baseUrl` | `string` | `https://in.layers.com` | Override the ingest endpoint |
62
+ | `flushIntervalMs` | `number` | `30000` | Periodic flush interval (ms) |
63
+ | `flushThreshold` | `number` | `20` | Queue depth that triggers auto-flush |
64
+ | `maxQueueSize` | `number` | `10000` | Max events in queue before dropping |
65
+
66
+ ## User Identity
67
+
68
+ The SDK uses **set-user-once** semantics. Once `setAppUserId()` is called, subsequent calls are ignored until `clearAppUserId()` is called:
69
+
70
+ ```ts
71
+ layers.setAppUserId('user-123'); // sets the user ID
72
+ layers.setAppUserId('user-456'); // ignored (already set)
73
+ layers.clearAppUserId(); // clears it
74
+ layers.setAppUserId('user-456'); // now sets to user-456
75
+ ```
76
+
77
+ ## ATT (App Tracking Transparency)
78
+
79
+ iOS 14.5+ requires asking for tracking permission before accessing IDFA.
80
+
81
+ ```ts
82
+ import {
83
+ getATTStatus,
84
+ getAdvertisingId,
85
+ getVendorId,
86
+ isATTAvailable,
87
+ requestTrackingAuthorization
88
+ } from '@layers/react-native';
89
+
90
+ // Check if ATT is available on this device
91
+ const available = await isATTAvailable();
92
+
93
+ // Request permission (shows the system dialog)
94
+ const status = await requestTrackingAuthorization();
95
+ // Returns: 'authorized' | 'denied' | 'restricted' | 'not_determined'
96
+
97
+ // Check current status without prompting
98
+ const currentStatus = await getATTStatus();
99
+
100
+ // Get IDFA (only returns a value when status is 'authorized')
101
+ const idfa = await getAdvertisingId();
102
+
103
+ // Get IDFV (always available, does not require ATT)
104
+ const idfv = await getVendorId();
105
+
106
+ // Wire ATT status into consent
107
+ if (status === 'authorized') {
108
+ await layers.setConsent({ analytics: true, advertising: true });
109
+ } else {
110
+ await layers.setConsent({ analytics: true, advertising: false });
111
+ }
26
112
  ```
27
113
 
28
- ### Expo plugin
114
+ ATT functions require the native `LayersATT` module. On Android or when the native module is not linked, they return safe defaults (`'not_determined'`, `null`, `false`).
29
115
 
30
- Add to `app.json` / `app.config.js`:
116
+ ## SKAN (SKAdNetwork)
31
117
 
32
- ```js
33
- plugins: [
34
- [
35
- '@layers/react-native/plugin',
36
- { ios: { includeDefaultNetworks: true }, android: { intentFilters: [{ scheme: 'myapp' }] } }
37
- ]
38
- ];
118
+ Manage iOS SKAdNetwork conversion values with a rule-based engine:
119
+
120
+ ```ts
121
+ import { SKANManager } from '@layers/react-native';
122
+
123
+ const skan = new SKANManager((update) => {
124
+ console.log(`Conversion: ${update.previousValue} -> ${update.newValue} (${update.event})`);
125
+ });
126
+
127
+ await skan.initialize();
128
+
129
+ // Use a built-in preset
130
+ skan.setPreset('subscriptions'); // or 'engagement' or 'iap'
131
+
132
+ // Or define custom rules
133
+ skan.setCustomRules([
134
+ { eventName: 'app_open', conversionValue: 1, priority: 1 },
135
+ { eventName: 'trial_start', conversionValue: 20, priority: 5 },
136
+ { eventName: 'subscription_start', conversionValue: 50, priority: 10 }
137
+ ]);
138
+
139
+ // Call processEvent for each analytics event to evaluate rules
140
+ await skan.processEvent('trial_start', { plan: 'premium' });
141
+
142
+ // Check current state
143
+ console.log(skan.getCurrentValue()); // 20
144
+ console.log(skan.getMetrics());
39
145
  ```
40
146
 
41
- ## Links
147
+ SKAN requires the native `LayersSKAN` module. On Android or without the module, `isSupported()` returns `false` and all native operations are no-ops.
148
+
149
+ ## Deep Links
150
+
151
+ ### React Native Linking API
42
152
 
43
- - Repo: https://github.com/layers/sdks
44
- - Issues: https://github.com/layers/sdks/issues
153
+ ```ts
154
+ import { parseDeepLink, setupDeepLinkListener } from '@layers/react-native';
155
+
156
+ const unsubscribe = setupDeepLinkListener((data) => {
157
+ console.log(data.url); // 'myapp://product/123?ref=email'
158
+ console.log(data.scheme); // 'myapp'
159
+ console.log(data.host); // 'product'
160
+ console.log(data.path); // '/123'
161
+ console.log(data.queryParams); // { ref: 'email' }
162
+
163
+ // Track the deep link as an event
164
+ layers.track('deep_link', {
165
+ url: data.url,
166
+ source: data.queryParams.ref
167
+ });
168
+ });
169
+
170
+ // Clean up
171
+ unsubscribe();
172
+ ```
173
+
174
+ ### Expo Router
175
+
176
+ Automatic screen tracking with Expo Router:
177
+
178
+ ```ts
179
+ import { useLayersExpoRouterTracking } from '@layers/react-native';
180
+ import { usePathname, useGlobalSearchParams } from 'expo-router';
181
+
182
+ function RootLayout() {
183
+ useLayersExpoRouterTracking(layers, usePathname, useGlobalSearchParams);
184
+ return <Stack />;
185
+ }
186
+ ```
187
+
188
+ This fires a `screen()` call on every route change with the pathname and search params as properties.
189
+
190
+ ## Consent Management
191
+
192
+ ```ts
193
+ // Allow analytics, deny advertising
194
+ await layers.setConsent({ analytics: true, advertising: false });
195
+
196
+ // Check current state
197
+ const consent = layers.getConsentState();
198
+ ```
199
+
200
+ When `analytics` is `false`, `track()` and `screen()` calls are silently dropped.
201
+
202
+ ## Error Handling
203
+
204
+ Register error listeners to catch errors that would otherwise be silently dropped:
205
+
206
+ ```ts
207
+ layers.on('error', (err) => {
208
+ console.error('Layers SDK error:', err.message);
209
+ });
210
+
211
+ // Remove a listener
212
+ layers.off('error', myListener);
213
+ ```
214
+
215
+ When `enableDebug` is `true` and no error listeners are registered, errors are logged to `console.warn`.
216
+
217
+ ## Debug Mode
218
+
219
+ Enable `enableDebug: true` (or `__DEV__`) for detailed logging:
220
+
221
+ ```
222
+ [Layers] track("app_open", 1 properties)
223
+ [Layers] screen("home", 0 properties)
224
+ [Layers] setAppUserId("user-123")
225
+ ```
226
+
227
+ ## Testing
228
+
229
+ Mock the SDK in tests by replacing the instance with a simple spy object:
230
+
231
+ ```ts
232
+ const mockLayers = {
233
+ init: jest.fn().mockResolvedValue(undefined),
234
+ track: jest.fn().mockResolvedValue(undefined),
235
+ screen: jest.fn().mockResolvedValue(undefined),
236
+ setAppUserId: jest.fn(),
237
+ clearAppUserId: jest.fn(),
238
+ getAppUserId: jest.fn(),
239
+ setConsent: jest.fn().mockResolvedValue(undefined),
240
+ getConsentState: jest.fn().mockReturnValue({}),
241
+ setUserProperties: jest.fn().mockResolvedValue(undefined),
242
+ setDeviceInfo: jest.fn(),
243
+ flush: jest.fn().mockResolvedValue(undefined),
244
+ shutdown: jest.fn(),
245
+ getSessionId: jest.fn().mockReturnValue('mock-session-id'),
246
+ on: jest.fn().mockReturnThis(),
247
+ off: jest.fn().mockReturnThis()
248
+ };
249
+ ```
45
250
 
46
251
  ## License
47
252
 
48
- ISC
253
+ MIT
@@ -0,0 +1,42 @@
1
+ import { t as __require } from "./chunk-B1JASekH.js";
2
+
3
+ //#region src/att.ts
4
+ function getNativeModule() {
5
+ try {
6
+ const { NativeModules, Platform } = __require("react-native");
7
+ if (Platform.OS === "ios" && NativeModules.LayersATT) return NativeModules.LayersATT;
8
+ } catch {}
9
+ return null;
10
+ }
11
+ async function getATTStatus() {
12
+ const mod = getNativeModule();
13
+ if (!mod) return "not_determined";
14
+ return mod.getTrackingAuthorizationStatus();
15
+ }
16
+ async function requestTrackingAuthorization() {
17
+ const mod = getNativeModule();
18
+ if (!mod) return "not_determined";
19
+ const current = await mod.getTrackingAuthorizationStatus();
20
+ if (current !== "not_determined") return current;
21
+ return mod.requestTrackingAuthorization();
22
+ }
23
+ async function isATTAvailable() {
24
+ const mod = getNativeModule();
25
+ if (!mod) return false;
26
+ return mod.isATTAvailable();
27
+ }
28
+ async function getAdvertisingId() {
29
+ const mod = getNativeModule();
30
+ if (!mod) return null;
31
+ if (await mod.getTrackingAuthorizationStatus() !== "authorized") return null;
32
+ return mod.getAdvertisingId();
33
+ }
34
+ async function getVendorId() {
35
+ const mod = getNativeModule();
36
+ if (!mod) return null;
37
+ return mod.getVendorId();
38
+ }
39
+
40
+ //#endregion
41
+ export { requestTrackingAuthorization as a, isATTAvailable as i, getAdvertisingId as n, getVendorId as r, getATTStatus as t };
42
+ //# sourceMappingURL=att-C5tL1hKX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"att-C5tL1hKX.js","names":[],"sources":["../src/att.ts"],"sourcesContent":["// ATT Module — iOS-only App Tracking Transparency.\n// Bridges to native iOS ATTrackingManager via NativeModules.\n\nexport type ATTStatus = 'not_determined' | 'restricted' | 'denied' | 'authorized';\n\ninterface NativeATTModule {\n getTrackingAuthorizationStatus(): Promise<ATTStatus>;\n requestTrackingAuthorization(): Promise<ATTStatus>;\n isATTAvailable(): Promise<boolean>;\n getAdvertisingId(): Promise<string | null>;\n getVendorId(): Promise<string | null>;\n}\n\nfunction getNativeModule(): NativeATTModule | null {\n try {\n const { NativeModules, Platform } = require('react-native');\n if (Platform.OS === 'ios' && NativeModules.LayersATT) {\n return NativeModules.LayersATT as NativeATTModule;\n }\n } catch {\n // Not available\n }\n return null;\n}\n\nexport async function getATTStatus(): Promise<ATTStatus> {\n const mod = getNativeModule();\n if (!mod) return 'not_determined';\n return mod.getTrackingAuthorizationStatus();\n}\n\nexport async function requestTrackingAuthorization(): Promise<ATTStatus> {\n const mod = getNativeModule();\n if (!mod) return 'not_determined';\n\n const current = await mod.getTrackingAuthorizationStatus();\n if (current !== 'not_determined') return current;\n\n return mod.requestTrackingAuthorization();\n}\n\nexport async function isATTAvailable(): Promise<boolean> {\n const mod = getNativeModule();\n if (!mod) return false;\n return mod.isATTAvailable();\n}\n\nexport async function getAdvertisingId(): Promise<string | null> {\n const mod = getNativeModule();\n if (!mod) return null;\n const status = await mod.getTrackingAuthorizationStatus();\n if (status !== 'authorized') return null;\n return mod.getAdvertisingId();\n}\n\nexport async function getVendorId(): Promise<string | null> {\n const mod = getNativeModule();\n if (!mod) return null;\n return mod.getVendorId();\n}\n"],"mappings":";;;AAaA,SAAS,kBAA0C;AACjD,KAAI;EACF,MAAM,EAAE,eAAe,uBAAqB,eAAe;AAC3D,MAAI,SAAS,OAAO,SAAS,cAAc,UACzC,QAAO,cAAc;SAEjB;AAGR,QAAO;;AAGT,eAAsB,eAAmC;CACvD,MAAM,MAAM,iBAAiB;AAC7B,KAAI,CAAC,IAAK,QAAO;AACjB,QAAO,IAAI,gCAAgC;;AAG7C,eAAsB,+BAAmD;CACvE,MAAM,MAAM,iBAAiB;AAC7B,KAAI,CAAC,IAAK,QAAO;CAEjB,MAAM,UAAU,MAAM,IAAI,gCAAgC;AAC1D,KAAI,YAAY,iBAAkB,QAAO;AAEzC,QAAO,IAAI,8BAA8B;;AAG3C,eAAsB,iBAAmC;CACvD,MAAM,MAAM,iBAAiB;AAC7B,KAAI,CAAC,IAAK,QAAO;AACjB,QAAO,IAAI,gBAAgB;;AAG7B,eAAsB,mBAA2C;CAC/D,MAAM,MAAM,iBAAiB;AAC7B,KAAI,CAAC,IAAK,QAAO;AAEjB,KADe,MAAM,IAAI,gCAAgC,KAC1C,aAAc,QAAO;AACpC,QAAO,IAAI,kBAAkB;;AAG/B,eAAsB,cAAsC;CAC1D,MAAM,MAAM,iBAAiB;AAC7B,KAAI,CAAC,IAAK,QAAO;AACjB,QAAO,IAAI,aAAa"}
@@ -0,0 +1,10 @@
1
+ //#region src/att.d.ts
2
+ type ATTStatus = 'not_determined' | 'restricted' | 'denied' | 'authorized';
3
+ declare function getATTStatus(): Promise<ATTStatus>;
4
+ declare function requestTrackingAuthorization(): Promise<ATTStatus>;
5
+ declare function isATTAvailable(): Promise<boolean>;
6
+ declare function getAdvertisingId(): Promise<string | null>;
7
+ declare function getVendorId(): Promise<string | null>;
8
+ //#endregion
9
+ export { isATTAvailable as a, getVendorId as i, getATTStatus as n, requestTrackingAuthorization as o, getAdvertisingId as r, ATTStatus as t };
10
+ //# sourceMappingURL=att-Hyj9b7AG.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"att-Hyj9b7AG.d.ts","names":[],"sources":["../src/att.ts"],"sourcesContent":[],"mappings":";KAGY,SAAA;AAAA,iBAsBU,YAAA,CAAA,CAtBD,EAsBiB,OAtBjB,CAsByB,SAtBzB,CAAA;AAsBC,iBAMA,4BAAA,CAAA,CANuB,EAMS,OANT,CAMiB,SANjB,CAAA;AAMvB,iBAUA,cAAA,CAAA,CAV4B,EAUV,OAVsB,CAAA,OAAR,CAAA;AAUhC,iBAMA,gBAAA,CAAA,CANyB,EAML,OANK,CAAA,MAAA,GAAA,IAAA,CAAA;AAMzB,iBAQA,WAAA,CAAA,CARoB,EAQL,OARY,CAAA,MAAA,GAAA,IAAA,CAAA"}
package/dist/att.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import { a as isATTAvailable, i as getVendorId, n as getATTStatus, o as requestTrackingAuthorization, r as getAdvertisingId, t as ATTStatus } from "./att-Hyj9b7AG.js";
2
+ export { ATTStatus, getATTStatus, getAdvertisingId, getVendorId, isATTAvailable, requestTrackingAuthorization };
package/dist/att.js ADDED
@@ -0,0 +1,3 @@
1
+ import { a as requestTrackingAuthorization, i as isATTAvailable, n as getAdvertisingId, r as getVendorId, t as getATTStatus } from "./att-C5tL1hKX.js";
2
+
3
+ export { getATTStatus, getAdvertisingId, getVendorId, isATTAvailable, requestTrackingAuthorization };
@@ -0,0 +1,7 @@
1
+ import { createRequire } from "node:module";
2
+
3
+ //#region rolldown:runtime
4
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
5
+
6
+ //#endregion
7
+ export { __require as t };
@@ -0,0 +1,72 @@
1
+ import { ConsentState, ConsentState as ConsentState$1, DeviceContext, DeviceContext as DeviceContext$1, Environment, Environment as Environment$1, EventProperties, EventProperties as EventProperties$1, LayersError, UserProperties, UserProperties as UserProperties$1 } from "@layers/core-wasm";
2
+
3
+ //#region src/index.d.ts
4
+
5
+ interface LayersRNConfig {
6
+ apiKey: string;
7
+ appId: string;
8
+ environment: Environment;
9
+ appUserId?: string;
10
+ enableDebug?: boolean;
11
+ baseUrl?: string;
12
+ flushIntervalMs?: number;
13
+ flushThreshold?: number;
14
+ maxQueueSize?: number;
15
+ }
16
+ type ErrorListener = (error: Error) => void;
17
+ declare class LayersReactNative {
18
+ private core;
19
+ private appUserId;
20
+ private isOnline;
21
+ private readonly enableDebug;
22
+ private appStateSubscription;
23
+ private netInfoUnsubscribe;
24
+ private userIdLocked;
25
+ private readonly errorListeners;
26
+ constructor(config: LayersRNConfig);
27
+ init(): Promise<void>;
28
+ track(eventName: string, properties?: EventProperties): void;
29
+ screen(screenName: string, properties?: EventProperties): void;
30
+ setUserProperties(properties: UserProperties): Promise<void>;
31
+ setConsent(consent: ConsentState): Promise<void>;
32
+ /**
33
+ * Set the app user ID. Uses set-user-once semantics:
34
+ * once set, subsequent calls are ignored until clearAppUserId() is called.
35
+ */
36
+ setAppUserId(appUserId: string): void;
37
+ clearAppUserId(): void;
38
+ getAppUserId(): string | undefined;
39
+ getSessionId(): string;
40
+ getConsentState(): ConsentState;
41
+ setDeviceInfo(deviceInfo: DeviceContext): void;
42
+ flush(): Promise<void>;
43
+ /**
44
+ * Register an error listener. Errors from track/screen/flush
45
+ * that would otherwise be silently dropped are forwarded here.
46
+ */
47
+ on(event: 'error', listener: ErrorListener): this;
48
+ /**
49
+ * Remove a previously registered error listener.
50
+ */
51
+ off(event: 'error', listener: ErrorListener): this;
52
+ private emitError;
53
+ shutdown(): void;
54
+ private initializeDeviceInfo;
55
+ private setupAppStateListener;
56
+ private setupNetInfoListener;
57
+ }
58
+ declare function getOrSetInstallId(): Promise<string>;
59
+ interface DeepLinkData {
60
+ url: string;
61
+ scheme: string;
62
+ host: string;
63
+ path: string;
64
+ queryParams: Record<string, string>;
65
+ timestamp: number;
66
+ }
67
+ declare function setupDeepLinkListener(onDeepLink: (data: DeepLinkData) => void): () => void;
68
+ declare function parseDeepLink(url: string): DeepLinkData | null;
69
+ declare function useLayersExpoRouterTracking(layersInstance: LayersReactNative, usePathname: () => string, useGlobalSearchParams: () => Record<string, string | string[]>): void;
70
+ //#endregion
71
+ export { ErrorListener as a, LayersRNConfig as c, getOrSetInstallId as d, parseDeepLink as f, Environment$1 as i, LayersReactNative as l, useLayersExpoRouterTracking as m, DeepLinkData as n, EventProperties$1 as o, setupDeepLinkListener as p, DeviceContext$1 as r, LayersError as s, ConsentState$1 as t, UserProperties$1 as u };
72
+ //# sourceMappingURL=index-D4pdpobh.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-D4pdpobh.d.ts","names":[],"sources":["../src/index.ts"],"sourcesContent":[],"mappings":";;;;AAuGgB,UA9DC,cAAA,CA8DD;EASwB,MAAA,EAAA,MAAA;EAaE,KAAA,EAAA,MAAA;EAaJ,WAAA,EA9FvB,WA8FuB;EAAiB,SAAA,CAAA,EAAA,MAAA;EAI3B,WAAA,CAAA,EAAA,OAAA;EAAe,OAAA,CAAA,EAAA,MAAA;EAoCtB,eAAA,CAAA,EAAA,MAAA;EAIO,cAAA,CAAA,EAAA,MAAA;EAIX,YAAA,CAAA,EAAA,MAAA;;AAqBe,KAtJpB,aAAA,GAsJoB,CAAA,KAAA,EAtJI,KAsJJ,EAAA,GAAA,IAAA;AAAa,cApJhC,iBAAA,CAoJgC;EA8NvB,QAAA,IAAA;EAoCL,QAAA,SAAY;EASb,QAAA,QAAA;EA6BA,iBAAa,WAAe;EAsB5B,QAAA,oBAAA;;;;sBAncM;UA6BN;wCASwB;0CAaE;gCAaJ,iBAAiB;sBAI3B,eAAe;;;;;;;;;qBAoCtB;4BAIO;WAIX;;;;;+BAac;;;;gCAQC;;;;;;;iBA8NV,iBAAA,CAAA,GAAqB;UAoC1B,YAAA;;;;;eAKF;;;iBAIC,qBAAA,oBAAyC;iBA6BzC,aAAA,eAA4B;iBAsB5B,2BAAA,iBACE,2EAEa"}