@layers/react-native 1.2.0 → 1.4.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/dist/att-BlUZv4_u.d.ts.map +1 -1
- package/dist/{index-DBiAzZYP.d.ts → index-nttdlILS.d.ts} +69 -2
- package/dist/index-nttdlILS.d.ts.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/react.d.ts +1 -1
- package/dist/react.js +1 -1
- package/dist/{src-BesYeXC6.js → src-CYaAvWR2.js} +204 -5
- package/dist/src-CYaAvWR2.js.map +1 -0
- package/package.json +2 -2
- package/dist/index-DBiAzZYP.d.ts.map +0 -1
- package/dist/src-BesYeXC6.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"att-BlUZv4_u.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,
|
|
1
|
+
{"version":3,"file":"att-BlUZv4_u.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,OAAA,CAAR;AAUhC,iBAMA,gBAAA,CAAA,CANyB,EAML,OANK,CAAA,MAAA,GAAA,IAAA,CAAA;AAMzB,iBAQA,WAAA,CAAA,CARoB,EAQL,OARY,CAAA,MAAA,GAAA,IAAA,CAAA"}
|
|
@@ -44,12 +44,18 @@ declare class LayersReactNative {
|
|
|
44
44
|
private userIdLocked;
|
|
45
45
|
private readonly errorListeners;
|
|
46
46
|
private _skanManager;
|
|
47
|
+
private _lastSkanConfigStr;
|
|
47
48
|
private deepLinkUnsubscribe;
|
|
49
|
+
private _configPollTimer;
|
|
50
|
+
private static readonly CONFIG_POLL_INTERVAL_MS;
|
|
51
|
+
private _adServicesToken;
|
|
52
|
+
private _installReferrer;
|
|
48
53
|
constructor(config: LayersRNConfig);
|
|
49
54
|
init(): Promise<void>;
|
|
50
55
|
track(eventName: string, properties?: EventProperties): void;
|
|
51
56
|
screen(screenName: string, properties?: EventProperties): void;
|
|
52
57
|
setUserProperties(properties: UserProperties): Promise<void>;
|
|
58
|
+
setUserPropertiesOnce(properties: UserProperties): Promise<void>;
|
|
53
59
|
setConsent(consent: ConsentState): Promise<void>;
|
|
54
60
|
/**
|
|
55
61
|
* Request App Tracking Transparency authorization (iOS only).
|
|
@@ -67,11 +73,31 @@ declare class LayersReactNative {
|
|
|
67
73
|
*/
|
|
68
74
|
setAppUserId(appUserId: string): void;
|
|
69
75
|
clearAppUserId(): void;
|
|
76
|
+
/**
|
|
77
|
+
* Reset the SDK state: clears the user ID, unlocks set-user-once,
|
|
78
|
+
* clears user properties, and starts a new session.
|
|
79
|
+
*
|
|
80
|
+
* After reset(), the SDK behaves as if no user has been identified.
|
|
81
|
+
* A new anonymous session is started. Events tracked after reset()
|
|
82
|
+
* will not carry the previous user's identity.
|
|
83
|
+
*/
|
|
84
|
+
reset(): void;
|
|
70
85
|
getAppUserId(): string | undefined;
|
|
71
86
|
getSessionId(): string;
|
|
72
87
|
getConsentState(): ConsentState;
|
|
73
88
|
setDeviceInfo(deviceInfo: DeviceContext): void;
|
|
74
89
|
flush(): Promise<void>;
|
|
90
|
+
/**
|
|
91
|
+
* Flush all queued events synchronously (blocking).
|
|
92
|
+
*
|
|
93
|
+
* Drains all batches from the queue and sends them via HTTP, awaiting
|
|
94
|
+
* each batch before proceeding. Does not return until all batches have
|
|
95
|
+
* been sent or failed.
|
|
96
|
+
*
|
|
97
|
+
* This is useful for AppState background transitions where the app may
|
|
98
|
+
* be suspended shortly after the call returns.
|
|
99
|
+
*/
|
|
100
|
+
flushBlocking(): Promise<void>;
|
|
75
101
|
/**
|
|
76
102
|
* Register an error listener. Errors from track/screen/flush
|
|
77
103
|
* that would otherwise be silently dropped are forwarded here.
|
|
@@ -81,6 +107,17 @@ declare class LayersReactNative {
|
|
|
81
107
|
* Remove a previously registered error listener.
|
|
82
108
|
*/
|
|
83
109
|
off(event: 'error', listener: ErrorListener): this;
|
|
110
|
+
/**
|
|
111
|
+
* Returns the AdServices attribution token (iOS only), or null if not
|
|
112
|
+
* available. Collected automatically during init() on iOS 14.3+.
|
|
113
|
+
* Does NOT require ATT consent.
|
|
114
|
+
*/
|
|
115
|
+
getAdServicesToken(): string | null;
|
|
116
|
+
/**
|
|
117
|
+
* Returns the Google Play install referrer data (Android only), or null
|
|
118
|
+
* if not available. Collected automatically during init() on Android.
|
|
119
|
+
*/
|
|
120
|
+
getInstallReferrer(): InstallReferrerData | null;
|
|
84
121
|
/**
|
|
85
122
|
* Returns the auto-configured SKANManager instance, or null if SKAN was not
|
|
86
123
|
* configured by the server's remote config.
|
|
@@ -96,6 +133,9 @@ declare class LayersReactNative {
|
|
|
96
133
|
private initializeDeviceInfo;
|
|
97
134
|
private setupAppStateListener;
|
|
98
135
|
private configureSkanFromRemoteConfig;
|
|
136
|
+
private startConfigPolling;
|
|
137
|
+
private stopConfigPolling;
|
|
138
|
+
private pollRemoteConfig;
|
|
99
139
|
private setupNetInfoListener;
|
|
100
140
|
}
|
|
101
141
|
declare function getOrSetInstallId(): Promise<string>;
|
|
@@ -104,6 +144,33 @@ interface ClipboardAttribution {
|
|
|
104
144
|
clickId: string;
|
|
105
145
|
}
|
|
106
146
|
declare function readClipboardAttribution(): Promise<ClipboardAttribution | null>;
|
|
147
|
+
interface GoogleAdvertisingInfo {
|
|
148
|
+
id: string;
|
|
149
|
+
isLimitAdTrackingEnabled: boolean;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Fetch the Google Advertising ID (GAID) on Android via NativeModules.
|
|
153
|
+
* Returns null on iOS or when the native module is not available.
|
|
154
|
+
*/
|
|
155
|
+
declare function getGoogleAdvertisingId(): Promise<GoogleAdvertisingInfo | null>;
|
|
156
|
+
/**
|
|
157
|
+
* Request the AdServices attribution token on iOS 14.3+.
|
|
158
|
+
* Uses the LayersAdServices native module which calls AAAttribution.attributionToken().
|
|
159
|
+
* Does NOT require ATT consent.
|
|
160
|
+
* Returns null on Android or when the native module is not available.
|
|
161
|
+
*/
|
|
162
|
+
declare function getAdServicesToken(): Promise<string | null>;
|
|
163
|
+
interface InstallReferrerData {
|
|
164
|
+
referrerUrl: string;
|
|
165
|
+
referrerClickTimestamp?: number;
|
|
166
|
+
installBeginTimestamp?: number;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Fetch the Google Play install referrer on Android via NativeModules.
|
|
170
|
+
* Requires the `com.android.installreferrer` library on the native side.
|
|
171
|
+
* Returns null on iOS or when the native module is not available.
|
|
172
|
+
*/
|
|
173
|
+
declare function getInstallReferrer(): Promise<InstallReferrerData | null>;
|
|
107
174
|
interface DeepLinkData {
|
|
108
175
|
url: string;
|
|
109
176
|
scheme: string;
|
|
@@ -116,5 +183,5 @@ declare function setupDeepLinkListener(onDeepLink: (data: DeepLinkData) => void)
|
|
|
116
183
|
declare function parseDeepLink(url: string): DeepLinkData | null;
|
|
117
184
|
declare function useLayersExpoRouterTracking(layersInstance: LayersReactNative, usePathname: () => string, useGlobalSearchParams: () => Record<string, string | string[]>): void;
|
|
118
185
|
//#endregion
|
|
119
|
-
export { Environment$1 as a,
|
|
120
|
-
//# sourceMappingURL=index-
|
|
186
|
+
export { getOrSetInstallId as _, Environment$1 as a, setupDeepLinkListener as b, GoogleAdvertisingInfo as c, LayersRNConfig as d, LayersReactNative as f, getInstallReferrer as g, getGoogleAdvertisingId as h, DeviceContext$1 as i, InstallReferrerData as l, getAdServicesToken as m, ConsentState$1 as n, ErrorListener as o, UserProperties$1 as p, DeepLinkData as r, EventProperties$1 as s, ClipboardAttribution as t, LayersError as u, parseDeepLink as v, useLayersExpoRouterTracking as x, readClipboardAttribution as y };
|
|
187
|
+
//# sourceMappingURL=index-nttdlILS.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index-nttdlILS.d.ts","names":[],"sources":["../src/index.ts"],"sourcesContent":[],"mappings":";;;;;;AAmJgB,UAlGC,cAAA,CAkGD;EA4GwB,KAAA,EAAA,MAAA;EAoBE,WAAA,EAhO3B,WAgO2B;EAaJ,SAAA,CAAA,EAAA,MAAA;EAAiB,WAAA,CAAA,EAAA,OAAA;EAIb,OAAA,CAAA,EAAA,MAAA;EAAiB,eAAA,CAAA,EAAA,MAAA;EAI/B,cAAA,CAAA,EAAA,MAAA;EAAe,YAAA,CAAA,EAAA,MAAA;EAaE;;;;;EA0IpB,gBAAA,CAAA,EAAA,OAAA;EAoBM;;;;;AA2gB/B;AA6BA;AAOA;AA2FA;AASA;AAwBA;EAgBiB,kBAAA,CAAA,EAAA,OAAmB;AAWpC;AAkBiB,KAzlCL,aAAA,GAylCiB,CAAA,KAKd,EA9lCqB,KA8lCf,EAAA,GAAA,IAAA;AAIL,cAhmCH,iBAAA,CAgmCwB;EA6BrB,QAAA,IAAA;EAsBA,QAAA,SAAA;;;;;;;;;;;;;;;sBAlnCM;UA8BN;wCA4GwB;0CAoBE;gCAaJ,iBAAiB;oCAIb,iBAAiB;sBAI/B,eAAe;;;;;;;;;;+BAaN,QAAQ;;;;;;;;;;;;;;;;;;qBA+GxB;4BAIO;WAIX;;;;;;;;;;;mBAmBQ;;;;;+BAoBM;;;;gCAQC;;;;;;;;;;;wBAkBR;;;;;;;;oBAWJ;;;;;;;;;;;;;iBAseE,iBAAA,CAAA,GAAqB;UA6B1B,oBAAA;;;;iBAOK,wBAAA,CAAA,GAA4B,QAAQ;UA2FzC,qBAAA;;;;;;;;iBASK,sBAAA,CAAA,GAA0B,QAAQ;;;;;;;iBAwBlC,kBAAA,CAAA,GAAsB;UAgB3B,mBAAA;;;;;;;;;;iBAWK,kBAAA,CAAA,GAAsB,QAAQ;UAkBnC,YAAA;;;;;eAKF;;;iBAIC,qBAAA,oBAAyC;iBA6BzC,aAAA,eAA4B;iBAsB5B,2BAAA,iBACE,2EAEa"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { a as isATTAvailable, i as getVendorId, n as getATTStatus, o as requestTrackingAuthorization, r as getAdvertisingId, t as ATTStatus } from "./att-BlUZv4_u.js";
|
|
2
2
|
import { i as SKANPresetConfig, n as SKANManager, r as SKANMetrics, t as SKANConversionRule } from "./skan-DvnRgJo1.js";
|
|
3
|
-
import { a as Environment, c as
|
|
4
|
-
export { ATTStatus, ClipboardAttribution, ConsentState, DeepLinkData, DeviceContext, Environment, ErrorListener, EventProperties, LayersError, LayersRNConfig, LayersReactNative, SKANConversionRule, SKANManager, SKANMetrics, SKANPresetConfig, UserProperties, getATTStatus, getAdvertisingId, getOrSetInstallId, getVendorId, isATTAvailable, parseDeepLink, readClipboardAttribution, requestTrackingAuthorization, setupDeepLinkListener, useLayersExpoRouterTracking };
|
|
3
|
+
import { _ as getOrSetInstallId, a as Environment, b as setupDeepLinkListener, c as GoogleAdvertisingInfo, d as LayersRNConfig, f as LayersReactNative, g as getInstallReferrer, h as getGoogleAdvertisingId, i as DeviceContext, l as InstallReferrerData, m as getAdServicesToken, n as ConsentState, o as ErrorListener, p as UserProperties, r as DeepLinkData, s as EventProperties, t as ClipboardAttribution, u as LayersError, v as parseDeepLink, x as useLayersExpoRouterTracking, y as readClipboardAttribution } from "./index-nttdlILS.js";
|
|
4
|
+
export { ATTStatus, ClipboardAttribution, ConsentState, DeepLinkData, DeviceContext, Environment, ErrorListener, EventProperties, GoogleAdvertisingInfo, InstallReferrerData, LayersError, LayersRNConfig, LayersReactNative, SKANConversionRule, SKANManager, SKANMetrics, SKANPresetConfig, UserProperties, getATTStatus, getAdServicesToken, getAdvertisingId, getGoogleAdvertisingId, getInstallReferrer, getOrSetInstallId, getVendorId, isATTAvailable, parseDeepLink, readClipboardAttribution, requestTrackingAuthorization, setupDeepLinkListener, useLayersExpoRouterTracking };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { a as requestTrackingAuthorization, i as isATTAvailable, n as getAdvertisingId, r as getVendorId, t as getATTStatus } from "./att-DaUoQWpj.js";
|
|
2
2
|
import { t as SKANManager } from "./skan-DFFAN4wu.js";
|
|
3
|
-
import { a as readClipboardAttribution, i as
|
|
3
|
+
import { a as getInstallReferrer, c as readClipboardAttribution, i as getGoogleAdvertisingId, l as setupDeepLinkListener, n as LayersReactNative, o as getOrSetInstallId, r as getAdServicesToken, s as parseDeepLink, t as LayersError, u as useLayersExpoRouterTracking } from "./src-CYaAvWR2.js";
|
|
4
4
|
|
|
5
|
-
export { LayersError, LayersReactNative, SKANManager, getATTStatus, getAdvertisingId, getOrSetInstallId, getVendorId, isATTAvailable, parseDeepLink, readClipboardAttribution, requestTrackingAuthorization, setupDeepLinkListener, useLayersExpoRouterTracking };
|
|
5
|
+
export { LayersError, LayersReactNative, SKANManager, getATTStatus, getAdServicesToken, getAdvertisingId, getGoogleAdvertisingId, getInstallReferrer, getOrSetInstallId, getVendorId, isATTAvailable, parseDeepLink, readClipboardAttribution, requestTrackingAuthorization, setupDeepLinkListener, useLayersExpoRouterTracking };
|
package/dist/react.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import "./att-BlUZv4_u.js";
|
|
2
2
|
import "./skan-DvnRgJo1.js";
|
|
3
|
-
import {
|
|
3
|
+
import { d as LayersRNConfig, f as LayersReactNative, n as ConsentState, s as EventProperties } from "./index-nttdlILS.js";
|
|
4
4
|
import { ReactNode } from "react";
|
|
5
5
|
import * as react_jsx_runtime0 from "react/jsx-runtime";
|
|
6
6
|
|
package/dist/react.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import "./att-DaUoQWpj.js";
|
|
2
2
|
import "./skan-DFFAN4wu.js";
|
|
3
|
-
import { n as LayersReactNative } from "./src-
|
|
3
|
+
import { n as LayersReactNative } from "./src-CYaAvWR2.js";
|
|
4
4
|
import { createContext, useCallback, useContext, useEffect, useRef } from "react";
|
|
5
5
|
import { jsx } from "react/jsx-runtime";
|
|
6
6
|
|
|
@@ -5,7 +5,7 @@ import { FetchHttpClient, LayersCore, LayersError as LayersError$1, MemoryPersis
|
|
|
5
5
|
|
|
6
6
|
//#region src/index.ts
|
|
7
7
|
const SDK_VERSION = typeof __LAYERS_RN_VERSION__ !== "undefined" ? __LAYERS_RN_VERSION__ : "0.1.0";
|
|
8
|
-
var LayersReactNative = class {
|
|
8
|
+
var LayersReactNative = class LayersReactNative {
|
|
9
9
|
core;
|
|
10
10
|
appUserId;
|
|
11
11
|
isOnline = true;
|
|
@@ -16,7 +16,12 @@ var LayersReactNative = class {
|
|
|
16
16
|
userIdLocked = false;
|
|
17
17
|
errorListeners = /* @__PURE__ */ new Set();
|
|
18
18
|
_skanManager = null;
|
|
19
|
+
_lastSkanConfigStr = null;
|
|
19
20
|
deepLinkUnsubscribe = null;
|
|
21
|
+
_configPollTimer = null;
|
|
22
|
+
static CONFIG_POLL_INTERVAL_MS = 3e5;
|
|
23
|
+
_adServicesToken = null;
|
|
24
|
+
_installReferrer = null;
|
|
20
25
|
constructor(config) {
|
|
21
26
|
this.enableDebug = config.enableDebug ?? false;
|
|
22
27
|
this.appUserId = config.appUserId;
|
|
@@ -67,6 +72,7 @@ var LayersReactNative = class {
|
|
|
67
72
|
this.setupNetInfoListener();
|
|
68
73
|
await this.core.fetchRemoteConfig().catch(() => {});
|
|
69
74
|
await this.configureSkanFromRemoteConfig();
|
|
75
|
+
this.startConfigPolling();
|
|
70
76
|
let clipboardData = null;
|
|
71
77
|
try {
|
|
72
78
|
const { Platform } = __require("react-native");
|
|
@@ -85,6 +91,12 @@ var LayersReactNative = class {
|
|
|
85
91
|
appOpenProps.clipboard_attribution_url = clipboardData.clickUrl;
|
|
86
92
|
appOpenProps.clipboard_click_id = clipboardData.clickId;
|
|
87
93
|
}
|
|
94
|
+
if (this._adServicesToken) appOpenProps.adservices_token = this._adServicesToken;
|
|
95
|
+
if (this._installReferrer) {
|
|
96
|
+
appOpenProps.install_referrer_url = this._installReferrer.referrerUrl;
|
|
97
|
+
if (this._installReferrer.referrerClickTimestamp) appOpenProps.install_referrer_click_timestamp = this._installReferrer.referrerClickTimestamp;
|
|
98
|
+
if (this._installReferrer.installBeginTimestamp) appOpenProps.install_referrer_install_timestamp = this._installReferrer.installBeginTimestamp;
|
|
99
|
+
}
|
|
88
100
|
this.track("app_open", appOpenProps);
|
|
89
101
|
}
|
|
90
102
|
if (this.config.autoTrackDeepLinks !== false) this.setupDeepLinkAutoTracking();
|
|
@@ -109,6 +121,9 @@ var LayersReactNative = class {
|
|
|
109
121
|
async setUserProperties(properties) {
|
|
110
122
|
this.core.setUserProperties(properties);
|
|
111
123
|
}
|
|
124
|
+
async setUserPropertiesOnce(properties) {
|
|
125
|
+
this.core.setUserPropertiesOnce(properties);
|
|
126
|
+
}
|
|
112
127
|
async setConsent(consent) {
|
|
113
128
|
this.core.setConsent(consent);
|
|
114
129
|
}
|
|
@@ -169,6 +184,29 @@ var LayersReactNative = class {
|
|
|
169
184
|
this.appUserId = void 0;
|
|
170
185
|
this.userIdLocked = false;
|
|
171
186
|
}
|
|
187
|
+
/**
|
|
188
|
+
* Reset the SDK state: clears the user ID, unlocks set-user-once,
|
|
189
|
+
* clears user properties, and starts a new session.
|
|
190
|
+
*
|
|
191
|
+
* After reset(), the SDK behaves as if no user has been identified.
|
|
192
|
+
* A new anonymous session is started. Events tracked after reset()
|
|
193
|
+
* will not carry the previous user's identity.
|
|
194
|
+
*/
|
|
195
|
+
reset() {
|
|
196
|
+
if (this.enableDebug) console.log("[Layers] reset()");
|
|
197
|
+
this.appUserId = void 0;
|
|
198
|
+
this.userIdLocked = false;
|
|
199
|
+
try {
|
|
200
|
+
this.core.setUserProperties({});
|
|
201
|
+
} catch (e) {
|
|
202
|
+
this.emitError(e);
|
|
203
|
+
}
|
|
204
|
+
try {
|
|
205
|
+
this.core.startNewSession();
|
|
206
|
+
} catch (e) {
|
|
207
|
+
this.emitError(e);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
172
210
|
getAppUserId() {
|
|
173
211
|
return this.appUserId;
|
|
174
212
|
}
|
|
@@ -190,6 +228,29 @@ var LayersReactNative = class {
|
|
|
190
228
|
}
|
|
191
229
|
}
|
|
192
230
|
/**
|
|
231
|
+
* Flush all queued events synchronously (blocking).
|
|
232
|
+
*
|
|
233
|
+
* Drains all batches from the queue and sends them via HTTP, awaiting
|
|
234
|
+
* each batch before proceeding. Does not return until all batches have
|
|
235
|
+
* been sent or failed.
|
|
236
|
+
*
|
|
237
|
+
* This is useful for AppState background transitions where the app may
|
|
238
|
+
* be suspended shortly after the call returns.
|
|
239
|
+
*/
|
|
240
|
+
async flushBlocking() {
|
|
241
|
+
try {
|
|
242
|
+
let depth = this.core.queueDepth();
|
|
243
|
+
while (depth > 0) {
|
|
244
|
+
await this.core.flushAsync();
|
|
245
|
+
const newDepth = this.core.queueDepth();
|
|
246
|
+
if (newDepth >= depth) break;
|
|
247
|
+
depth = newDepth;
|
|
248
|
+
}
|
|
249
|
+
} catch (e) {
|
|
250
|
+
this.emitError(e);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
193
254
|
* Register an error listener. Errors from track/screen/flush
|
|
194
255
|
* that would otherwise be silently dropped are forwarded here.
|
|
195
256
|
*/
|
|
@@ -205,6 +266,21 @@ var LayersReactNative = class {
|
|
|
205
266
|
return this;
|
|
206
267
|
}
|
|
207
268
|
/**
|
|
269
|
+
* Returns the AdServices attribution token (iOS only), or null if not
|
|
270
|
+
* available. Collected automatically during init() on iOS 14.3+.
|
|
271
|
+
* Does NOT require ATT consent.
|
|
272
|
+
*/
|
|
273
|
+
getAdServicesToken() {
|
|
274
|
+
return this._adServicesToken;
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Returns the Google Play install referrer data (Android only), or null
|
|
278
|
+
* if not available. Collected automatically during init() on Android.
|
|
279
|
+
*/
|
|
280
|
+
getInstallReferrer() {
|
|
281
|
+
return this._installReferrer;
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
208
284
|
* Returns the auto-configured SKANManager instance, or null if SKAN was not
|
|
209
285
|
* configured by the server's remote config.
|
|
210
286
|
* On iOS, when remote config contains a `skan` section with `preset` or
|
|
@@ -222,6 +298,7 @@ var LayersReactNative = class {
|
|
|
222
298
|
if (this.enableDebug && this.errorListeners.size === 0) console.warn("[Layers]", err.message);
|
|
223
299
|
}
|
|
224
300
|
shutdown() {
|
|
301
|
+
this.stopConfigPolling();
|
|
225
302
|
if (this.appStateSubscription) {
|
|
226
303
|
this.appStateSubscription.remove();
|
|
227
304
|
this.appStateSubscription = null;
|
|
@@ -274,18 +351,28 @@ var LayersReactNative = class {
|
|
|
274
351
|
deviceModel = "iPhone";
|
|
275
352
|
}
|
|
276
353
|
else deviceModel = "unknown";
|
|
354
|
+
let appVersion;
|
|
355
|
+
try {
|
|
356
|
+
appVersion = await getAppVersion(Platform, NativeModules);
|
|
357
|
+
} catch {}
|
|
277
358
|
const context = {
|
|
278
359
|
platform,
|
|
279
360
|
osVersion,
|
|
280
361
|
deviceModel,
|
|
281
362
|
locale: getLocale(),
|
|
282
363
|
screenSize: `${Math.round(window.width)}x${Math.round(window.height)}`,
|
|
283
|
-
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
|
|
364
|
+
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
365
|
+
...appVersion != null && { appVersion }
|
|
284
366
|
};
|
|
285
367
|
if (Platform.OS === "ios") try {
|
|
286
368
|
const idfv = await getVendorId();
|
|
287
369
|
if (idfv) context.idfv = idfv;
|
|
288
370
|
} catch {}
|
|
371
|
+
if (Platform.OS === "android") try {
|
|
372
|
+
const gaid = await getGoogleAdvertisingId();
|
|
373
|
+
if (gaid) context.idfa = gaid.id;
|
|
374
|
+
if (gaid && gaid.isLimitAdTrackingEnabled != null) context.attStatus = gaid.isLimitAdTrackingEnabled ? "denied" : "authorized";
|
|
375
|
+
} catch {}
|
|
289
376
|
try {
|
|
290
377
|
const installId = await getOrSetInstallId();
|
|
291
378
|
if (installId) context.installId = installId;
|
|
@@ -304,6 +391,17 @@ var LayersReactNative = class {
|
|
|
304
391
|
} catch {}
|
|
305
392
|
this.core.setDeviceContext(context);
|
|
306
393
|
}
|
|
394
|
+
try {
|
|
395
|
+
const { Platform } = __require("react-native");
|
|
396
|
+
if (Platform.OS === "ios") try {
|
|
397
|
+
const token = await getAdServicesToken();
|
|
398
|
+
if (token) this._adServicesToken = token;
|
|
399
|
+
} catch {}
|
|
400
|
+
if (Platform.OS === "android") try {
|
|
401
|
+
const referrer = await getInstallReferrer();
|
|
402
|
+
if (referrer) this._installReferrer = referrer;
|
|
403
|
+
} catch {}
|
|
404
|
+
} catch {}
|
|
307
405
|
}
|
|
308
406
|
setupAppStateListener() {
|
|
309
407
|
try {
|
|
@@ -323,19 +421,45 @@ var LayersReactNative = class {
|
|
|
323
421
|
const configJson = this.core.getRemoteConfigJson?.();
|
|
324
422
|
if (!configJson) return;
|
|
325
423
|
const skanConfig = JSON.parse(configJson)?.skan;
|
|
326
|
-
if (!skanConfig || skanConfig.enabled === false)
|
|
424
|
+
if (!skanConfig || skanConfig.enabled === false) {
|
|
425
|
+
this._skanManager = null;
|
|
426
|
+
this._lastSkanConfigStr = null;
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
const skanConfigStr = JSON.stringify(skanConfig);
|
|
430
|
+
if (this._skanManager && this._lastSkanConfigStr === skanConfigStr) return;
|
|
327
431
|
const manager = new SKANManager();
|
|
328
432
|
if (skanConfig.preset) manager.setPreset(skanConfig.preset);
|
|
329
433
|
else if (skanConfig.customRules && Array.isArray(skanConfig.customRules)) manager.setCustomRules(skanConfig.customRules);
|
|
330
434
|
else return;
|
|
331
435
|
await manager.initialize();
|
|
332
436
|
this._skanManager = manager;
|
|
437
|
+
this._lastSkanConfigStr = skanConfigStr;
|
|
333
438
|
if (this.enableDebug) {
|
|
334
439
|
const metrics = manager.getMetrics();
|
|
335
440
|
console.log(`[Layers] SKAN auto-configured from remote config: preset=${metrics.currentPreset}, rules=${String(metrics.ruleCount)}`);
|
|
336
441
|
}
|
|
337
442
|
} catch {}
|
|
338
443
|
}
|
|
444
|
+
startConfigPolling() {
|
|
445
|
+
this.stopConfigPolling();
|
|
446
|
+
this._configPollTimer = setInterval(() => {
|
|
447
|
+
this.pollRemoteConfig();
|
|
448
|
+
}, LayersReactNative.CONFIG_POLL_INTERVAL_MS);
|
|
449
|
+
}
|
|
450
|
+
stopConfigPolling() {
|
|
451
|
+
if (this._configPollTimer) {
|
|
452
|
+
clearInterval(this._configPollTimer);
|
|
453
|
+
this._configPollTimer = null;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
async pollRemoteConfig() {
|
|
457
|
+
try {
|
|
458
|
+
await this.core.fetchRemoteConfig();
|
|
459
|
+
await this.configureSkanFromRemoteConfig();
|
|
460
|
+
if (this.enableDebug) console.log("[Layers] Remote config updated (poll)");
|
|
461
|
+
} catch {}
|
|
462
|
+
}
|
|
339
463
|
setupNetInfoListener() {
|
|
340
464
|
try {
|
|
341
465
|
this.netInfoUnsubscribe = __require("@react-native-community/netinfo").addEventListener((state) => {
|
|
@@ -513,6 +637,81 @@ async function readClipboardAttribution() {
|
|
|
513
637
|
clickId: match[2]
|
|
514
638
|
};
|
|
515
639
|
}
|
|
640
|
+
/**
|
|
641
|
+
* Attempt to read the host app version from platform-specific APIs.
|
|
642
|
+
* On Android, reads from PackageInfo via Platform.constants or a native module.
|
|
643
|
+
* On iOS, reads from the LayersDeviceInfo native module which can access the Info.plist.
|
|
644
|
+
*/
|
|
645
|
+
async function getAppVersion(Platform, NativeModules) {
|
|
646
|
+
try {
|
|
647
|
+
if (Platform.OS === "android") {
|
|
648
|
+
const mod = NativeModules.LayersDeviceInfo;
|
|
649
|
+
if (mod?.getAppVersion) {
|
|
650
|
+
const version = await mod.getAppVersion();
|
|
651
|
+
if (version) return version;
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
if (Platform.OS === "ios") {
|
|
655
|
+
const mod = NativeModules.LayersDeviceInfo;
|
|
656
|
+
if (mod?.getAppVersion) {
|
|
657
|
+
const version = await mod.getAppVersion();
|
|
658
|
+
if (version) return version;
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
} catch {}
|
|
662
|
+
}
|
|
663
|
+
/**
|
|
664
|
+
* Fetch the Google Advertising ID (GAID) on Android via NativeModules.
|
|
665
|
+
* Returns null on iOS or when the native module is not available.
|
|
666
|
+
*/
|
|
667
|
+
async function getGoogleAdvertisingId() {
|
|
668
|
+
try {
|
|
669
|
+
const { NativeModules, Platform } = __require("react-native");
|
|
670
|
+
if (Platform.OS !== "android") return null;
|
|
671
|
+
const mod = NativeModules.LayersAdvertisingId;
|
|
672
|
+
if (!mod?.getAdvertisingInfo) return null;
|
|
673
|
+
const info = await mod.getAdvertisingInfo();
|
|
674
|
+
if (!info || !info.id || info.id === "00000000-0000-0000-0000-000000000000") return null;
|
|
675
|
+
return info;
|
|
676
|
+
} catch {
|
|
677
|
+
return null;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
/**
|
|
681
|
+
* Request the AdServices attribution token on iOS 14.3+.
|
|
682
|
+
* Uses the LayersAdServices native module which calls AAAttribution.attributionToken().
|
|
683
|
+
* Does NOT require ATT consent.
|
|
684
|
+
* Returns null on Android or when the native module is not available.
|
|
685
|
+
*/
|
|
686
|
+
async function getAdServicesToken() {
|
|
687
|
+
try {
|
|
688
|
+
const { NativeModules, Platform } = __require("react-native");
|
|
689
|
+
if (Platform.OS !== "ios") return null;
|
|
690
|
+
const mod = NativeModules.LayersAdServices;
|
|
691
|
+
if (!mod?.getAttributionToken) return null;
|
|
692
|
+
return await mod.getAttributionToken();
|
|
693
|
+
} catch {
|
|
694
|
+
return null;
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
/**
|
|
698
|
+
* Fetch the Google Play install referrer on Android via NativeModules.
|
|
699
|
+
* Requires the `com.android.installreferrer` library on the native side.
|
|
700
|
+
* Returns null on iOS or when the native module is not available.
|
|
701
|
+
*/
|
|
702
|
+
async function getInstallReferrer() {
|
|
703
|
+
try {
|
|
704
|
+
const { NativeModules, Platform } = __require("react-native");
|
|
705
|
+
if (Platform.OS !== "android") return null;
|
|
706
|
+
const mod = NativeModules.LayersInstallReferrer;
|
|
707
|
+
if (!mod?.getInstallReferrer) return null;
|
|
708
|
+
const data = await mod.getInstallReferrer();
|
|
709
|
+
if (!data || !data.referrerUrl) return null;
|
|
710
|
+
return data;
|
|
711
|
+
} catch {
|
|
712
|
+
return null;
|
|
713
|
+
}
|
|
714
|
+
}
|
|
516
715
|
function setupDeepLinkListener(onDeepLink) {
|
|
517
716
|
try {
|
|
518
717
|
const { Linking } = __require("react-native");
|
|
@@ -569,5 +768,5 @@ function useLayersExpoRouterTracking(layersInstance, usePathname, useGlobalSearc
|
|
|
569
768
|
}
|
|
570
769
|
|
|
571
770
|
//#endregion
|
|
572
|
-
export {
|
|
573
|
-
//# sourceMappingURL=src-
|
|
771
|
+
export { getInstallReferrer as a, readClipboardAttribution as c, getGoogleAdvertisingId as i, setupDeepLinkListener as l, LayersReactNative as n, getOrSetInstallId as o, getAdServicesToken as r, parseDeepLink as s, LayersError$1 as t, useLayersExpoRouterTracking as u };
|
|
772
|
+
//# sourceMappingURL=src-CYaAvWR2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-CYaAvWR2.js","names":["SDK_VERSION: string","clipboardData: ClipboardAttribution | null","appOpenProps: Record<string, unknown>","status: ATTStatus","requestATT","updates: DeviceContext","properties: Record<string, unknown>","deviceModel: string","appVersion: string | undefined","context: DeviceContext","SKANManagerImpl","keys: string[]","_asyncStorage: AsyncStorageStatic | undefined","_asyncStoragePromise: Promise<AsyncStorageStatic | null> | null","text: string | null","params: Record<string, string>"],"sources":["../src/index.ts"],"sourcesContent":["// @layers/react-native — React Native SDK.\n// Thin wrapper over @layers/core-wasm. Owns only:\n// - AsyncStorage persistence backend\n// - React Native device info (Platform, Dimensions)\n// - SKAN module (iOS-only conversion value management)\n// - ATT module (iOS-only App Tracking Transparency)\n// - Deep links via React Native Linking API\n// - AppState listener for background/foreground flush\n// - NetInfo for online/offline detection\nimport { FetchHttpClient, LayersCore, LayersError, MemoryPersistence } from '@layers/core-wasm';\nimport type {\n ConsentState,\n DeviceContext,\n Environment,\n EventProperties,\n PersistenceBackend,\n Platform as PlatformType,\n UserProperties\n} from '@layers/core-wasm';\n\nimport {\n getAdvertisingId,\n getVendorId,\n requestTrackingAuthorization as requestATT\n} from './att.js';\nimport type { ATTStatus } from './att.js';\nimport { SKANManager as SKANManagerImpl } from './skan.js';\n\nexport type {\n ConsentState,\n DeviceContext,\n Environment,\n EventProperties,\n UserProperties\n} from '@layers/core-wasm';\n\nexport { LayersError } from '@layers/core-wasm';\n\nexport type { SKANConversionRule, SKANPresetConfig, SKANMetrics } from './skan.js';\nexport { SKANManager } from './skan.js';\nexport type { ATTStatus } from './att.js';\nexport {\n getATTStatus,\n requestTrackingAuthorization,\n isATTAvailable,\n getAdvertisingId,\n getVendorId\n} from './att.js';\n\nexport interface LayersRNConfig {\n appId: string;\n environment: Environment;\n appUserId?: string;\n enableDebug?: boolean;\n baseUrl?: string;\n flushIntervalMs?: number;\n flushThreshold?: number;\n maxQueueSize?: number;\n /**\n * Whether to automatically fire an `app_open` event during init().\n * Set to `false` if you want to fire the event manually.\n * @default true\n */\n autoTrackAppOpen?: boolean;\n /**\n * Whether to automatically track `deep_link_opened` events when a deep link\n * is received. The tracked event includes the parsed URL components and all\n * query parameters (UTM params, click IDs like fbclid/gclid/ttclid, etc.)\n * as flat top-level properties.\n *\n * This listener runs in addition to any consumer-registered listener via\n * `setupDeepLinkListener()` -- it does not replace it.\n *\n * @default true\n */\n autoTrackDeepLinks?: boolean;\n}\n\ndeclare const __LAYERS_RN_VERSION__: string;\nconst SDK_VERSION: string =\n typeof __LAYERS_RN_VERSION__ !== 'undefined' ? __LAYERS_RN_VERSION__ : '0.1.0';\n\nexport type ErrorListener = (error: Error) => void;\n\nexport class LayersReactNative {\n private core!: LayersCore;\n private appUserId: string | undefined;\n private isOnline = true;\n private readonly enableDebug: boolean;\n private appStateSubscription: { remove(): void } | null = null;\n private netInfoUnsubscribe: (() => void) | null = null;\n private readonly config: LayersRNConfig;\n\n // set-user-once semantics: once appUserId is set, it cannot be changed\n // (must clearAppUserId first)\n private userIdLocked = false;\n\n // Error listeners\n private readonly errorListeners: Set<ErrorListener> = new Set();\n\n // SKAN manager auto-configured from remote config (iOS only)\n private _skanManager: SKANManagerImpl | null = null;\n private _lastSkanConfigStr: string | null = null;\n\n // Internal deep link listener unsubscribe (auto-tracking)\n private deepLinkUnsubscribe: (() => void) | null = null;\n\n // Remote config polling timer (300s interval, matches Swift/Kotlin/Flutter/Unity SDKs)\n private _configPollTimer: ReturnType<typeof setInterval> | null = null;\n private static readonly CONFIG_POLL_INTERVAL_MS = 300_000; // 5 minutes\n\n // Cached AdServices attribution token (iOS only)\n private _adServicesToken: string | null = null;\n\n // Cached install referrer data (Android only)\n private _installReferrer: InstallReferrerData | null = null;\n\n constructor(config: LayersRNConfig) {\n this.enableDebug = config.enableDebug ?? false;\n this.appUserId = config.appUserId;\n this.config = config;\n\n // Create the core eagerly with an empty MemoryPersistence so that\n // track()/screen()/etc. work immediately (before init() is called).\n // init() will replace this with a fully-hydrated AsyncStorage backend.\n const httpClient = new FetchHttpClient();\n this.core = LayersCore.init({\n config: {\n appId: config.appId,\n environment: config.environment,\n ...(config.baseUrl != null && { baseUrl: config.baseUrl }),\n ...(config.enableDebug != null && { enableDebug: config.enableDebug }),\n ...(config.flushIntervalMs != null && { flushIntervalMs: config.flushIntervalMs }),\n ...(config.flushThreshold != null && { flushThreshold: config.flushThreshold }),\n ...(config.maxQueueSize != null && { maxQueueSize: config.maxQueueSize }),\n sdkVersion: `react-native/${SDK_VERSION}`\n },\n httpClient,\n persistence: new MemoryPersistence()\n });\n\n if (this.appUserId) {\n this.core.identify(this.appUserId);\n this.userIdLocked = true;\n }\n }\n\n async init(): Promise<void> {\n // Re-create the core with a pre-loaded AsyncStorage persistence backend\n // so that events persisted in a prior session are properly rehydrated.\n try {\n const persistence = await createAsyncStoragePersistence(this.config.appId);\n const httpClient = new FetchHttpClient();\n // Shut down the eager core before replacing it\n this.core.shutdown();\n this.core = LayersCore.init({\n config: {\n appId: this.config.appId,\n environment: this.config.environment,\n ...(this.config.baseUrl != null && { baseUrl: this.config.baseUrl }),\n ...(this.config.enableDebug != null && { enableDebug: this.config.enableDebug }),\n ...(this.config.flushIntervalMs != null && {\n flushIntervalMs: this.config.flushIntervalMs\n }),\n ...(this.config.flushThreshold != null && {\n flushThreshold: this.config.flushThreshold\n }),\n ...(this.config.maxQueueSize != null && { maxQueueSize: this.config.maxQueueSize }),\n sdkVersion: `react-native/${SDK_VERSION}`\n },\n httpClient,\n persistence\n });\n\n if (this.appUserId) {\n this.core.identify(this.appUserId);\n }\n } catch {\n // AsyncStorage pre-load failed; keep using the eager core with MemoryPersistence\n }\n\n await this.initializeDeviceInfo();\n this.setupAppStateListener();\n this.setupNetInfoListener();\n\n // Remote config fetch is best-effort. The JS layer fetches the config\n // endpoint; when the WASM/Rust core is loaded, it applies sampling,\n // rate limits, and filtering internally. The JS fallback path does not\n // currently parse/apply the config response — a future enhancement\n // will add JS-side config application for non-WASM environments.\n await this.core.fetchRemoteConfig().catch(() => {});\n\n // Auto-configure SKAN from remote config (iOS only).\n // The server's remote config `skan` section drives preset/rules so consumers\n // don't need to call SKANManager.setPreset() manually.\n await this.configureSkanFromRemoteConfig();\n\n // Start periodic remote config polling (every 300s).\n // Matches Swift, Kotlin, Flutter, and Unity SDKs.\n this.startConfigPolling();\n\n // Clipboard attribution: on first iOS launch, check clipboard for Layers click URL\n let clipboardData: ClipboardAttribution | null = null;\n try {\n const { Platform } = require('react-native');\n if (Platform.OS === 'ios') {\n // Check remote config for clipboard_attribution_enabled flag.\n // Default to false: only read clipboard if the server explicitly enables it.\n let clipboardEnabled = false;\n try {\n const configJson = this.core.getRemoteConfigJson?.();\n if (configJson) {\n const config = JSON.parse(configJson);\n clipboardEnabled = config?.clipboard_attribution_enabled === true;\n }\n } catch {}\n if (clipboardEnabled) {\n clipboardData = await readClipboardAttribution();\n }\n }\n } catch {}\n\n // Auto-track app_open event with attribution signals\n if (this.config.autoTrackAppOpen !== false) {\n const appOpenProps: Record<string, unknown> = {};\n if (clipboardData) {\n appOpenProps.clipboard_attribution_url = clipboardData.clickUrl;\n appOpenProps.clipboard_click_id = clipboardData.clickId;\n }\n if (this._adServicesToken) {\n appOpenProps.adservices_token = this._adServicesToken;\n }\n if (this._installReferrer) {\n appOpenProps.install_referrer_url = this._installReferrer.referrerUrl;\n if (this._installReferrer.referrerClickTimestamp) {\n appOpenProps.install_referrer_click_timestamp =\n this._installReferrer.referrerClickTimestamp;\n }\n if (this._installReferrer.installBeginTimestamp) {\n appOpenProps.install_referrer_install_timestamp =\n this._installReferrer.installBeginTimestamp;\n }\n }\n this.track('app_open', appOpenProps);\n }\n\n // Auto-track deep link events (default: enabled).\n // Sets up an internal deep link listener that fires a `deep_link_opened`\n // event with the full parsed URL and all query params spread as top-level\n // properties. This runs in addition to any consumer-registered listener.\n if (this.config.autoTrackDeepLinks !== false) {\n this.setupDeepLinkAutoTracking();\n }\n }\n\n track(eventName: string, properties?: EventProperties): void {\n if (this.enableDebug) {\n console.log(\n `[Layers] track(\"${eventName}\", ${Object.keys(properties ?? {}).length} properties)`\n );\n }\n try {\n this.core.track(eventName, properties, this.appUserId);\n\n // Forward event to SKAN rule engine if auto-configured from remote config\n if (this._skanManager) {\n void this._skanManager\n .processEvent(eventName, (properties as Record<string, unknown>) ?? {})\n .catch(() => {});\n }\n } catch (e) {\n this.emitError(e);\n }\n }\n\n screen(screenName: string, properties?: EventProperties): void {\n if (this.enableDebug) {\n console.log(\n `[Layers] screen(\"${screenName}\", ${Object.keys(properties ?? {}).length} properties)`\n );\n }\n try {\n this.core.screen(screenName, properties, this.appUserId);\n } catch (e) {\n this.emitError(e);\n }\n }\n\n async setUserProperties(properties: UserProperties): Promise<void> {\n this.core.setUserProperties(properties as Record<string, unknown>);\n }\n\n async setUserPropertiesOnce(properties: UserProperties): Promise<void> {\n this.core.setUserPropertiesOnce(properties as Record<string, unknown>);\n }\n\n async setConsent(consent: ConsentState): Promise<void> {\n this.core.setConsent(consent);\n }\n\n /**\n * Request App Tracking Transparency authorization (iOS only).\n * After the user responds, this method automatically:\n * - Collects IDFA if authorized\n * - Updates device info with IDFA and ATT status\n * - Sets advertising consent based on ATT result\n *\n * Returns the ATT status string.\n */\n async requestTrackingPermission(): Promise<ATTStatus> {\n // Auto-detect expo-tracking-transparency and prefer it when available\n let status: ATTStatus;\n try {\n const ExpoTT = await import('expo-tracking-transparency').catch(() => null);\n if (ExpoTT) {\n const { status: expoStatus } = await ExpoTT.requestTrackingPermissionsAsync();\n const statusMap: Record<string, ATTStatus> = {\n granted: 'authorized',\n denied: 'denied',\n restricted: 'restricted',\n undetermined: 'not_determined'\n };\n status = statusMap[expoStatus] ?? 'not_determined';\n } else {\n status = await requestATT();\n }\n } catch {\n status = await requestATT();\n }\n\n // Update device context with ATT status and IDFA (if authorized)\n const currentContext = this.core.getDeviceContext();\n const updates: DeviceContext = { ...currentContext, attStatus: status };\n if (status === 'authorized') {\n try {\n const idfa = await getAdvertisingId();\n if (idfa) updates.idfa = idfa;\n } catch {\n // IDFA collection is best-effort\n }\n }\n this.core.setDeviceContext(updates);\n\n // Auto-set advertising consent based on ATT result\n const advertisingAllowed = status === 'authorized';\n this.core.setConsent({ advertising: advertisingAllowed });\n\n if (this.enableDebug) {\n console.log(\n `[Layers] ATT status: ${status}, advertising consent: ${String(advertisingAllowed)}`\n );\n }\n\n return status;\n }\n\n /**\n * Set the app user ID. Uses set-user-once semantics:\n * once set, subsequent calls are ignored until clearAppUserId() is called.\n */\n setAppUserId(appUserId: string): void {\n if (this.enableDebug) {\n console.log(`[Layers] setAppUserId(\"${appUserId}\")`);\n }\n if (this.userIdLocked && this.appUserId) {\n if (this.enableDebug) {\n console.warn('[Layers] appUserId already set. Call clearAppUserId() first to change it.');\n }\n return;\n }\n this.appUserId = appUserId;\n this.userIdLocked = true;\n this.core.identify(appUserId);\n }\n\n clearAppUserId(): void {\n this.appUserId = undefined;\n this.userIdLocked = false;\n }\n\n /**\n * Reset the SDK state: clears the user ID, unlocks set-user-once,\n * clears user properties, and starts a new session.\n *\n * After reset(), the SDK behaves as if no user has been identified.\n * A new anonymous session is started. Events tracked after reset()\n * will not carry the previous user's identity.\n */\n reset(): void {\n if (this.enableDebug) {\n console.log('[Layers] reset()');\n }\n // Clear JS-side user state\n this.appUserId = undefined;\n this.userIdLocked = false;\n\n // Clear user properties on the core\n try {\n this.core.setUserProperties({});\n } catch (e) {\n this.emitError(e);\n }\n\n // Start a new session so subsequent events don't correlate\n // with the previous user's session\n try {\n this.core.startNewSession();\n } catch (e) {\n this.emitError(e);\n }\n }\n\n getAppUserId(): string | undefined {\n return this.appUserId;\n }\n\n getSessionId(): string {\n return this.core.getSessionId();\n }\n\n getConsentState(): ConsentState {\n return this.core.getConsentState();\n }\n\n setDeviceInfo(deviceInfo: DeviceContext): void {\n this.core.setDeviceContext(deviceInfo);\n }\n\n async flush(): Promise<void> {\n try {\n await this.core.flushAsync();\n } catch (e) {\n this.emitError(e);\n this.core.flush();\n }\n }\n\n /**\n * Flush all queued events synchronously (blocking).\n *\n * Drains all batches from the queue and sends them via HTTP, awaiting\n * each batch before proceeding. Does not return until all batches have\n * been sent or failed.\n *\n * This is useful for AppState background transitions where the app may\n * be suspended shortly after the call returns.\n */\n async flushBlocking(): Promise<void> {\n try {\n // Keep flushing until the queue is empty\n let depth = this.core.queueDepth();\n while (depth > 0) {\n await this.core.flushAsync();\n const newDepth = this.core.queueDepth();\n // Break if no progress was made (avoids infinite loop on persistent failures)\n if (newDepth >= depth) break;\n depth = newDepth;\n }\n } catch (e) {\n this.emitError(e);\n }\n }\n\n /**\n * Register an error listener. Errors from track/screen/flush\n * that would otherwise be silently dropped are forwarded here.\n */\n on(event: 'error', listener: ErrorListener): this {\n if (event === 'error') this.errorListeners.add(listener);\n return this;\n }\n\n /**\n * Remove a previously registered error listener.\n */\n off(event: 'error', listener: ErrorListener): this {\n if (event === 'error') this.errorListeners.delete(listener);\n return this;\n }\n\n /**\n * Returns the AdServices attribution token (iOS only), or null if not\n * available. Collected automatically during init() on iOS 14.3+.\n * Does NOT require ATT consent.\n */\n getAdServicesToken(): string | null {\n return this._adServicesToken;\n }\n\n /**\n * Returns the Google Play install referrer data (Android only), or null\n * if not available. Collected automatically during init() on Android.\n */\n getInstallReferrer(): InstallReferrerData | null {\n return this._installReferrer;\n }\n\n /**\n * Returns the auto-configured SKANManager instance, or null if SKAN was not\n * configured by the server's remote config.\n * On iOS, when remote config contains a `skan` section with `preset` or\n * `customRules`, the SDK automatically creates and configures a SKANManager.\n * Every `track()` call is automatically forwarded to SKAN rule evaluation.\n */\n getSkanManager(): SKANManagerImpl | null {\n return this._skanManager;\n }\n\n private emitError(error: unknown): void {\n const err = error instanceof Error ? error : new Error(String(error));\n for (const listener of this.errorListeners) {\n try {\n listener(err);\n } catch {}\n }\n if (this.enableDebug && this.errorListeners.size === 0) {\n console.warn('[Layers]', err.message);\n }\n }\n\n shutdown(): void {\n this.stopConfigPolling();\n if (this.appStateSubscription) {\n this.appStateSubscription.remove();\n this.appStateSubscription = null;\n }\n if (this.netInfoUnsubscribe) {\n this.netInfoUnsubscribe();\n this.netInfoUnsubscribe = null;\n }\n if (this.deepLinkUnsubscribe) {\n this.deepLinkUnsubscribe();\n this.deepLinkUnsubscribe = null;\n }\n this.core.shutdown();\n }\n\n // --- Platform-specific: Deep link auto-tracking ---\n\n private _trackedDeepLinkUrls = new Set<string>();\n\n private setupDeepLinkAutoTracking(): void {\n this.deepLinkUnsubscribe = setupDeepLinkListener((data: DeepLinkData) => {\n // Deduplicate: getInitialURL and addEventListener can both fire for the\n // same URL on some RN versions. Skip if we already tracked this exact URL.\n if (this._trackedDeepLinkUrls.has(data.url)) return;\n this._trackedDeepLinkUrls.add(data.url);\n // Clear after a short delay so the same URL can be tracked if the user\n // taps the same link again later\n setTimeout(() => this._trackedDeepLinkUrls.delete(data.url), 2000);\n try {\n const properties: Record<string, unknown> = {\n ...data.queryParams,\n url: data.url,\n scheme: data.scheme,\n host: data.host,\n path: data.path\n };\n this.track('deep_link_opened', properties);\n if (this.enableDebug) {\n console.log(`[Layers] auto-tracked deep_link_opened: ${data.url}`);\n }\n } catch (e) {\n this.emitError(e);\n }\n });\n }\n\n // --- Platform-specific: React Native device info ---\n\n private async initializeDeviceInfo(): Promise<void> {\n try {\n const { Platform, Dimensions, NativeModules } = require('react-native');\n const window = Dimensions.get('window');\n\n const platform =\n Platform.OS === 'ios' ? 'ios' : Platform.OS === 'android' ? 'android' : 'react-native';\n const osVersion =\n typeof Platform.Version === 'string' ? Platform.Version : String(Platform.Version);\n\n // Device model: use platform constants where available\n let deviceModel: string;\n if (Platform.OS === 'android') {\n const brand = Platform.constants?.Brand ?? '';\n const model = Platform.constants?.Model ?? '';\n deviceModel = brand && model ? `${brand} ${model}` : model || brand || 'Android';\n } else if (Platform.OS === 'ios') {\n // Try to get the real iOS model identifier from native module\n try {\n const model = await NativeModules.LayersDeviceInfo?.getModelIdentifier();\n deviceModel = model || 'iPhone';\n } catch {\n deviceModel = 'iPhone';\n }\n } else {\n deviceModel = 'unknown';\n }\n\n // Auto-detect app version from native platform APIs\n let appVersion: string | undefined;\n try {\n appVersion = await getAppVersion(Platform, NativeModules);\n } catch {\n // App version collection is best-effort\n }\n\n const context: DeviceContext = {\n platform: platform as PlatformType,\n osVersion,\n deviceModel,\n locale: getLocale(),\n screenSize: `${Math.round(window.width)}x${Math.round(window.height)}`,\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n ...(appVersion != null && { appVersion })\n };\n\n // Auto-collect IDFV on iOS (first-party identifier, no ATT consent required)\n if (Platform.OS === 'ios') {\n try {\n const idfv = await getVendorId();\n if (idfv) context.idfv = idfv;\n } catch {\n // IDFV collection is best-effort\n }\n }\n\n // Auto-collect GAID on Android (Google Advertising ID)\n if (Platform.OS === 'android') {\n try {\n const gaid = await getGoogleAdvertisingId();\n if (gaid) context.idfa = gaid.id;\n if (gaid && gaid.isLimitAdTrackingEnabled != null) {\n context.attStatus = gaid.isLimitAdTrackingEnabled ? 'denied' : 'authorized';\n }\n } catch {\n // GAID collection is best-effort\n }\n }\n\n // Auto-populate installId from persistent storage\n try {\n const installId = await getOrSetInstallId();\n if (installId) context.installId = installId;\n } catch {\n // installId collection is best-effort\n }\n\n this.core.setDeviceContext(context);\n } catch {\n // React Native APIs not available (e.g. in tests)\n const context: DeviceContext = {\n platform: 'react-native',\n osVersion: 'unknown',\n deviceModel: 'unknown',\n locale: 'en-US'\n };\n // Still try to populate installId in fallback path\n try {\n const installId = await getOrSetInstallId();\n if (installId) context.installId = installId;\n } catch {\n // best-effort\n }\n this.core.setDeviceContext(context);\n }\n\n // Collect attribution signals independently of device context\n // so a failure above doesn't prevent attribution collection\n try {\n const { Platform } = require('react-native');\n if (Platform.OS === 'ios') {\n try {\n const token = await getAdServicesToken();\n if (token) this._adServicesToken = token;\n } catch {\n // best-effort\n }\n }\n if (Platform.OS === 'android') {\n try {\n const referrer = await getInstallReferrer();\n if (referrer) this._installReferrer = referrer;\n } catch {\n // best-effort\n }\n }\n } catch {\n // Platform not available\n }\n }\n\n // --- Platform-specific: AppState listener ---\n\n private setupAppStateListener(): void {\n try {\n const { AppState } = require('react-native');\n\n this.appStateSubscription = AppState.addEventListener('change', (nextAppState: string) => {\n if (nextAppState === 'background' || nextAppState === 'inactive') {\n // Use synchronous flush to persist events to disk before OS suspends\n // (async HTTP may not complete before suspension)\n this.core.flush();\n }\n if (nextAppState === 'active' && this.isOnline) {\n void this.core.flushAsync().catch(() => {});\n }\n });\n } catch {\n // AppState not available\n }\n }\n\n // --- Platform-specific: SKAN auto-configuration from remote config ---\n\n private async configureSkanFromRemoteConfig(): Promise<void> {\n // SKAN is iOS-only; skip on other platforms.\n try {\n const { Platform } = require('react-native');\n if (Platform.OS !== 'ios') return;\n } catch {\n // react-native not available (e.g. test env) — proceed with SKAN config\n }\n\n try {\n const configJson = this.core.getRemoteConfigJson?.();\n if (!configJson) return;\n\n const config = JSON.parse(configJson);\n const skanConfig = config?.skan;\n if (!skanConfig || skanConfig.enabled === false) {\n // SKAN disabled or removed from config — clear any existing manager\n this._skanManager = null;\n this._lastSkanConfigStr = null;\n return;\n }\n\n // Skip re-creation if SKAN config hasn't changed (avoids resetting state every poll)\n const skanConfigStr = JSON.stringify(skanConfig);\n if (this._skanManager && this._lastSkanConfigStr === skanConfigStr) return;\n\n const manager = new SKANManagerImpl();\n\n if (skanConfig.preset) {\n manager.setPreset(skanConfig.preset);\n } else if (skanConfig.customRules && Array.isArray(skanConfig.customRules)) {\n manager.setCustomRules(skanConfig.customRules);\n } else {\n // SKAN section present but no preset or rules — nothing to configure\n return;\n }\n\n await manager.initialize();\n this._skanManager = manager;\n this._lastSkanConfigStr = skanConfigStr;\n\n if (this.enableDebug) {\n const metrics = manager.getMetrics();\n console.log(\n `[Layers] SKAN auto-configured from remote config: preset=${metrics.currentPreset}, rules=${String(metrics.ruleCount)}`\n );\n }\n } catch {\n // SKAN auto-configuration is best-effort\n }\n }\n\n // --- Remote config polling ---\n\n private startConfigPolling(): void {\n this.stopConfigPolling();\n this._configPollTimer = setInterval(() => {\n void this.pollRemoteConfig();\n }, LayersReactNative.CONFIG_POLL_INTERVAL_MS);\n }\n\n private stopConfigPolling(): void {\n if (this._configPollTimer) {\n clearInterval(this._configPollTimer);\n this._configPollTimer = null;\n }\n }\n\n private async pollRemoteConfig(): Promise<void> {\n try {\n await this.core.fetchRemoteConfig();\n // Re-run SKAN configuration to pick up any changes\n await this.configureSkanFromRemoteConfig();\n if (this.enableDebug) {\n console.log('[Layers] Remote config updated (poll)');\n }\n } catch {\n // Config polling is best-effort — errors are silently ignored\n }\n }\n\n // --- Platform-specific: NetInfo listener ---\n\n private setupNetInfoListener(): void {\n try {\n const NetInfo = require('@react-native-community/netinfo');\n this.netInfoUnsubscribe = NetInfo.addEventListener(\n (state: { isConnected: boolean | null }) => {\n const wasOffline = !this.isOnline;\n this.isOnline = state.isConnected !== false;\n\n if (wasOffline && this.isOnline) {\n void this.core.flushAsync().catch(() => {});\n }\n }\n );\n } catch {\n // NetInfo not available — assume always online\n }\n }\n}\n\n// --- AsyncStorage persistence backend ---\n\nasync function createAsyncStoragePersistence(appId: string): Promise<PersistenceBackend> {\n const prefix = `layers_sdk_${appId}_`;\n const memoryStore = new Map<string, Uint8Array>();\n\n // Pre-load from AsyncStorage so that events persisted in a prior session\n // are available synchronously when the core hydrates on init.\n try {\n const AsyncStorage = await loadAsyncStorage();\n if (AsyncStorage) {\n const allKeys = await AsyncStorage.getAllKeys();\n const layersKeys = allKeys.filter((k) => k.startsWith(prefix));\n if (layersKeys.length > 0) {\n const pairs = await AsyncStorage.multiGet(layersKeys);\n for (const [key, value] of pairs) {\n if (value) {\n const shortKey = key.slice(prefix.length);\n memoryStore.set(shortKey, base64Decode(value));\n }\n }\n }\n }\n } catch {\n // Pre-load is best-effort; memoryStore stays empty\n }\n\n return {\n write(key: string, data: Uint8Array): void {\n memoryStore.set(key, new Uint8Array(data));\n // Fire-and-forget async write to AsyncStorage\n void writeToAsyncStorage(prefix + key, data);\n },\n read(key: string): Uint8Array | null {\n return memoryStore.get(key) ?? null;\n },\n delete(key: string): void {\n memoryStore.delete(key);\n void deleteFromAsyncStorage(prefix + key);\n },\n listKeys(keyPrefix: string): string[] {\n const keys: string[] = [];\n for (const k of memoryStore.keys()) {\n if (k.startsWith(keyPrefix)) {\n keys.push(k);\n }\n }\n keys.sort();\n return keys;\n }\n };\n}\n\n// Binary-safe base64 encoding that handles large arrays without stack overflow.\n// btoa(String.fromCharCode(...data)) spreads the entire array onto the call stack,\n// which crashes for event batches larger than ~125 KB.\nconst B64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nconst B64_LOOKUP = new Uint8Array(128);\nfor (let _i = 0; _i < B64_CHARS.length; _i += 1) {\n B64_LOOKUP[B64_CHARS.charCodeAt(_i)] = _i;\n}\n\nfunction base64Decode(str: string): Uint8Array {\n const lookup = B64_LOOKUP;\n // Strip padding to determine decoded length\n let len = str.length;\n if (str[len - 1] === '=') len -= 1;\n if (str[len - 1] === '=') len -= 1;\n const bytes = new Uint8Array(Math.floor((len * 3) / 4));\n let p = 0;\n for (let i = 0; i < len; i += 4) {\n const b0 = lookup[str.charCodeAt(i)]!;\n const b1 = lookup[str.charCodeAt(i + 1)]!;\n const b2 = i + 2 < len ? lookup[str.charCodeAt(i + 2)]! : 0;\n const b3 = i + 3 < len ? lookup[str.charCodeAt(i + 3)]! : 0;\n bytes[p] = (b0 << 2) | (b1 >> 4);\n p += 1;\n if (i + 2 < len) {\n bytes[p] = ((b1 & 0x0f) << 4) | (b2 >> 2);\n p += 1;\n }\n if (i + 3 < len) {\n bytes[p] = ((b2 & 0x03) << 6) | b3;\n p += 1;\n }\n }\n return bytes;\n}\n\nfunction base64Encode(bytes: Uint8Array): string {\n let result = '';\n const len = bytes.length;\n for (let i = 0; i < len; i += 3) {\n const b0 = bytes[i]!;\n const b1 = i + 1 < len ? bytes[i + 1]! : 0;\n const b2 = i + 2 < len ? bytes[i + 2]! : 0;\n result += B64_CHARS[(b0 >> 2)!]!;\n result += B64_CHARS[((b0 & 0x03) << 4) | (b1 >> 4)]!;\n result += i + 1 < len ? B64_CHARS[((b1 & 0x0f) << 2) | (b2 >> 6)]! : '=';\n result += i + 2 < len ? B64_CHARS[b2 & 0x3f]! : '=';\n }\n return result;\n}\n\nasync function writeToAsyncStorage(key: string, data: Uint8Array): Promise<void> {\n try {\n const AsyncStorage = await loadAsyncStorage();\n if (!AsyncStorage) return;\n const encoded = base64Encode(data);\n await AsyncStorage.setItem(key, encoded);\n } catch {\n // Best effort\n }\n}\n\nasync function deleteFromAsyncStorage(key: string): Promise<void> {\n try {\n const AsyncStorage = await loadAsyncStorage();\n if (!AsyncStorage) return;\n await AsyncStorage.removeItem(key);\n } catch {\n // Best effort\n }\n}\n\ninterface AsyncStorageStatic {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n getAllKeys(): Promise<readonly string[]>;\n multiGet(keys: readonly string[]): Promise<readonly [string, string | null][]>;\n}\n\nlet _asyncStorage: AsyncStorageStatic | undefined = undefined;\nlet _asyncStoragePromise: Promise<AsyncStorageStatic | null> | null = null;\n\nasync function loadAsyncStorage(): Promise<AsyncStorageStatic | null> {\n if (_asyncStorage) return _asyncStorage;\n if (!_asyncStoragePromise) {\n _asyncStoragePromise = import('@react-native-async-storage/async-storage')\n .then((mod) => {\n _asyncStorage = mod.default ?? mod;\n return _asyncStorage;\n })\n .catch(() => null);\n }\n return _asyncStoragePromise;\n}\n\n// --- Locale helper ---\n\nfunction getLocale(): string {\n try {\n const { Platform, NativeModules } = require('react-native');\n if (Platform.OS === 'ios') {\n return (\n NativeModules.SettingsManager?.settings?.AppleLocale ??\n NativeModules.SettingsManager?.settings?.AppleLanguages?.[0] ??\n 'en-US'\n );\n }\n if (Platform.OS === 'android') {\n return NativeModules.I18nManager?.localeIdentifier ?? 'en-US';\n }\n } catch {\n // Fallback\n }\n return 'en-US';\n}\n\n// --- Install ID via AsyncStorage ---\n\nconst INSTALL_ID_KEY = 'layers_install_id';\n\nexport async function getOrSetInstallId(): Promise<string> {\n try {\n const AsyncStorage = await loadAsyncStorage();\n if (!AsyncStorage) return generateUUID();\n\n const existing = await AsyncStorage.getItem(INSTALL_ID_KEY);\n if (existing) return existing;\n\n const newId = generateUUID();\n await AsyncStorage.setItem(INSTALL_ID_KEY, newId);\n return newId;\n } catch {\n return generateUUID();\n }\n}\n\nfunction generateUUID(): string {\n if (typeof crypto !== 'undefined' && crypto.randomUUID) {\n return crypto.randomUUID();\n }\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n// --- Clipboard Attribution (iOS-only deferred deep links) ---\n\nexport interface ClipboardAttribution {\n clickUrl: string;\n clickId: string;\n}\n\nconst CLIPBOARD_CHECKED_KEY = '@layers/clipboard_checked';\n\nexport async function readClipboardAttribution(): Promise<ClipboardAttribution | null> {\n try {\n const { Platform } = require('react-native');\n if (Platform.OS !== 'ios') return null;\n } catch {\n return null;\n }\n\n // Check if we've already read clipboard (once per install)\n try {\n const AS = await loadAsyncStorage();\n if (AS) {\n const flag = await AS.getItem(CLIPBOARD_CHECKED_KEY);\n if (flag === 'true') return null;\n }\n } catch {}\n\n let text: string | null = null;\n try {\n // Try @react-native-clipboard/clipboard first (recommended)\n const Clipboard = await import('@react-native-clipboard/clipboard')\n .then((m) => m.default)\n .catch(() => null);\n if (Clipboard) {\n text = await Clipboard.getString();\n } else {\n // Fallback to deprecated RN Clipboard\n const { Clipboard: RNClipboard } = require('react-native');\n if (RNClipboard) {\n text = await RNClipboard.getString();\n }\n }\n } catch {}\n\n // Mark as checked regardless of result\n try {\n const AS = await loadAsyncStorage();\n if (AS) await AS.setItem(CLIPBOARD_CHECKED_KEY, 'true');\n } catch {}\n\n if (!text) return null;\n\n // Check for Layers click URL pattern\n const match = text.match(/https?:\\/\\/(in\\.layers\\.com|link\\.layers\\.com)\\/c\\/([^?\\s]+)/);\n if (!match) return null;\n\n return { clickUrl: text, clickId: match[2]! };\n}\n\n// --- App Version Helper ---\n\n/**\n * Attempt to read the host app version from platform-specific APIs.\n * On Android, reads from PackageInfo via Platform.constants or a native module.\n * On iOS, reads from the LayersDeviceInfo native module which can access the Info.plist.\n */\nasync function getAppVersion(\n Platform: { OS: string; constants?: Record<string, unknown> },\n NativeModules: Record<string, unknown>\n): Promise<string | undefined> {\n try {\n // Android: Platform.constants may include the app version via ReactNativeVersion\n // or we can use a native module\n if (Platform.OS === 'android') {\n const mod = NativeModules.LayersDeviceInfo as\n | { getAppVersion?(): Promise<string | null> }\n | undefined;\n if (mod?.getAppVersion) {\n const version = await mod.getAppVersion();\n if (version) return version;\n }\n }\n\n // iOS: use LayersDeviceInfo native module\n if (Platform.OS === 'ios') {\n const mod = NativeModules.LayersDeviceInfo as\n | { getAppVersion?(): Promise<string | null> }\n | undefined;\n if (mod?.getAppVersion) {\n const version = await mod.getAppVersion();\n if (version) return version;\n }\n }\n } catch {\n // Best-effort\n }\n return undefined;\n}\n\n// --- Google Advertising ID (Android only) ---\n\nexport interface GoogleAdvertisingInfo {\n id: string;\n isLimitAdTrackingEnabled: boolean;\n}\n\n/**\n * Fetch the Google Advertising ID (GAID) on Android via NativeModules.\n * Returns null on iOS or when the native module is not available.\n */\nexport async function getGoogleAdvertisingId(): Promise<GoogleAdvertisingInfo | null> {\n try {\n const { NativeModules, Platform } = require('react-native');\n if (Platform.OS !== 'android') return null;\n const mod = NativeModules.LayersAdvertisingId as\n | { getAdvertisingInfo?(): Promise<GoogleAdvertisingInfo | null> }\n | undefined;\n if (!mod?.getAdvertisingInfo) return null;\n const info = await mod.getAdvertisingInfo();\n if (!info || !info.id || info.id === '00000000-0000-0000-0000-000000000000') return null;\n return info;\n } catch {\n return null;\n }\n}\n\n// --- AdServices Attribution Token (iOS only) ---\n\n/**\n * Request the AdServices attribution token on iOS 14.3+.\n * Uses the LayersAdServices native module which calls AAAttribution.attributionToken().\n * Does NOT require ATT consent.\n * Returns null on Android or when the native module is not available.\n */\nexport async function getAdServicesToken(): Promise<string | null> {\n try {\n const { NativeModules, Platform } = require('react-native');\n if (Platform.OS !== 'ios') return null;\n const mod = NativeModules.LayersAdServices as\n | { getAttributionToken?(): Promise<string | null> }\n | undefined;\n if (!mod?.getAttributionToken) return null;\n return await mod.getAttributionToken();\n } catch {\n return null;\n }\n}\n\n// --- Install Referrer (Android only) ---\n\nexport interface InstallReferrerData {\n referrerUrl: string;\n referrerClickTimestamp?: number;\n installBeginTimestamp?: number;\n}\n\n/**\n * Fetch the Google Play install referrer on Android via NativeModules.\n * Requires the `com.android.installreferrer` library on the native side.\n * Returns null on iOS or when the native module is not available.\n */\nexport async function getInstallReferrer(): Promise<InstallReferrerData | null> {\n try {\n const { NativeModules, Platform } = require('react-native');\n if (Platform.OS !== 'android') return null;\n const mod = NativeModules.LayersInstallReferrer as\n | { getInstallReferrer?(): Promise<InstallReferrerData | null> }\n | undefined;\n if (!mod?.getInstallReferrer) return null;\n const data = await mod.getInstallReferrer();\n if (!data || !data.referrerUrl) return null;\n return data;\n } catch {\n return null;\n }\n}\n\n// --- Deep Links ---\n\nexport interface DeepLinkData {\n url: string;\n scheme: string;\n host: string;\n path: string;\n queryParams: Record<string, string>;\n timestamp: number;\n}\n\nexport function setupDeepLinkListener(onDeepLink: (data: DeepLinkData) => void): () => void {\n try {\n const { Linking } = require('react-native');\n\n const handler = (event: { url: string }) => {\n const parsed = parseDeepLink(event.url);\n if (parsed) onDeepLink(parsed);\n };\n\n const subscription = Linking.addEventListener('url', handler);\n\n // Check initial URL\n void Linking.getInitialURL().then((url: string | null) => {\n if (url) {\n const parsed = parseDeepLink(url);\n if (parsed) onDeepLink(parsed);\n }\n });\n\n return () => {\n if (subscription?.remove) {\n subscription.remove();\n }\n };\n } catch {\n return () => {};\n }\n}\n\nexport function parseDeepLink(url: string): DeepLinkData | null {\n try {\n const parsed = new URL(url);\n const params: Record<string, string> = {};\n parsed.searchParams.forEach((value, key) => {\n params[key] = value;\n });\n return {\n url,\n scheme: parsed.protocol.replace(':', ''),\n host: parsed.hostname,\n path: parsed.pathname,\n queryParams: params,\n timestamp: Date.now()\n };\n } catch {\n return null;\n }\n}\n\n// --- Expo Router Integration ---\n\nexport function useLayersExpoRouterTracking(\n layersInstance: LayersReactNative,\n usePathname: () => string,\n useGlobalSearchParams: () => Record<string, string | string[]>\n): void {\n const { useEffect } = require('react');\n const pathname = usePathname();\n const params = useGlobalSearchParams();\n const paramsString = JSON.stringify(params);\n\n useEffect(() => {\n if (pathname) {\n const properties: Record<string, unknown> = {};\n Object.entries(params).forEach(([key, value]) => {\n properties[key] = Array.isArray(value) ? value.join(',') : value;\n });\n void layersInstance.screen(pathname, properties);\n }\n }, [pathname, paramsString]);\n}\n"],"mappings":";;;;;;AA+EA,MAAMA,cACJ,OAAO,0BAA0B,cAAc,wBAAwB;AAIzE,IAAa,oBAAb,MAAa,kBAAkB;CAC7B,AAAQ;CACR,AAAQ;CACR,AAAQ,WAAW;CACnB,AAAiB;CACjB,AAAQ,uBAAkD;CAC1D,AAAQ,qBAA0C;CAClD,AAAiB;CAIjB,AAAQ,eAAe;CAGvB,AAAiB,iCAAqC,IAAI,KAAK;CAG/D,AAAQ,eAAuC;CAC/C,AAAQ,qBAAoC;CAG5C,AAAQ,sBAA2C;CAGnD,AAAQ,mBAA0D;CAClE,OAAwB,0BAA0B;CAGlD,AAAQ,mBAAkC;CAG1C,AAAQ,mBAA+C;CAEvD,YAAY,QAAwB;AAClC,OAAK,cAAc,OAAO,eAAe;AACzC,OAAK,YAAY,OAAO;AACxB,OAAK,SAAS;EAKd,MAAM,aAAa,IAAI,iBAAiB;AACxC,OAAK,OAAO,WAAW,KAAK;GAC1B,QAAQ;IACN,OAAO,OAAO;IACd,aAAa,OAAO;IACpB,GAAI,OAAO,WAAW,QAAQ,EAAE,SAAS,OAAO,SAAS;IACzD,GAAI,OAAO,eAAe,QAAQ,EAAE,a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": "public"
|
|
6
6
|
},
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
"mobile"
|
|
51
51
|
],
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@layers/core-wasm": "1.
|
|
53
|
+
"@layers/core-wasm": "1.3.1"
|
|
54
54
|
},
|
|
55
55
|
"peerDependencies": {
|
|
56
56
|
"@react-native-async-storage/async-storage": ">=1.21.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index-DBiAzZYP.d.ts","names":[],"sources":["../src/index.ts"],"sourcesContent":[],"mappings":";;;;;;AAwIgB,UAvFC,cAAA,CAuFD;EA0FwB,KAAA,EAAA,MAAA;EAoBE,WAAA,EAnM3B,WAmM2B;EAaJ,SAAA,CAAA,EAAA,MAAA;EAAiB,WAAA,CAAA,EAAA,OAAA;EAI3B,OAAA,CAAA,EAAA,MAAA;EAAe,eAAA,CAAA,EAAA,MAAA;EAaE,cAAA,CAAA,EAAA,MAAA;EAAR,YAAA,CAAA,EAAA,MAAA;EA+EhB;;;;;EAyCD,gBAAA,CAAA,EAAA,OAAA;EAAe;AAmZnC;AA6BA;AAOA;AAmDA;AASA;AA6BA;AAsBA;;;;;;KAh2BY,aAAA,WAAwB;cAEvB,iBAAA;;;;;;;;;;;;sBAsBS;UA8BN;wCA0FwB;0CAoBE;gCAaJ,iBAAiB;sBAI3B,eAAe;;;;;;;;;;+BAaN,QAAQ;;;;;;;;;qBA+ExB;4BAIO;WAIX;;;;;+BAac;;;;gCAQC;;;;;;;;oBAYZ;;;;;;;;;;iBAmZE,iBAAA,CAAA,GAAqB;UA6B1B,oBAAA;;;;iBAOK,wBAAA,CAAA,GAA4B,QAAQ;UAmDzC,YAAA;;;;;eAKF;;;iBAIC,qBAAA,oBAAyC;iBA6BzC,aAAA,eAA4B;iBAsB5B,2BAAA,iBACE,2EAEa"}
|
package/dist/src-BesYeXC6.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"src-BesYeXC6.js","names":["SDK_VERSION: string","clipboardData: ClipboardAttribution | null","appOpenProps: Record<string, unknown>","status: ATTStatus","requestATT","updates: DeviceContext","properties: Record<string, unknown>","deviceModel: string","context: DeviceContext","SKANManagerImpl","keys: string[]","_asyncStorage: AsyncStorageStatic | undefined","_asyncStoragePromise: Promise<AsyncStorageStatic | null> | null","text: string | null","params: Record<string, string>"],"sources":["../src/index.ts"],"sourcesContent":["// @layers/react-native — React Native SDK.\n// Thin wrapper over @layers/core-wasm. Owns only:\n// - AsyncStorage persistence backend\n// - React Native device info (Platform, Dimensions)\n// - SKAN module (iOS-only conversion value management)\n// - ATT module (iOS-only App Tracking Transparency)\n// - Deep links via React Native Linking API\n// - AppState listener for background/foreground flush\n// - NetInfo for online/offline detection\nimport { FetchHttpClient, LayersCore, LayersError, MemoryPersistence } from '@layers/core-wasm';\nimport type {\n ConsentState,\n DeviceContext,\n Environment,\n EventProperties,\n PersistenceBackend,\n Platform as PlatformType,\n UserProperties\n} from '@layers/core-wasm';\n\nimport {\n getAdvertisingId,\n getVendorId,\n requestTrackingAuthorization as requestATT\n} from './att.js';\nimport type { ATTStatus } from './att.js';\nimport { SKANManager as SKANManagerImpl } from './skan.js';\n\nexport type {\n ConsentState,\n DeviceContext,\n Environment,\n EventProperties,\n UserProperties\n} from '@layers/core-wasm';\n\nexport { LayersError } from '@layers/core-wasm';\n\nexport type { SKANConversionRule, SKANPresetConfig, SKANMetrics } from './skan.js';\nexport { SKANManager } from './skan.js';\nexport type { ATTStatus } from './att.js';\nexport {\n getATTStatus,\n requestTrackingAuthorization,\n isATTAvailable,\n getAdvertisingId,\n getVendorId\n} from './att.js';\n\nexport interface LayersRNConfig {\n appId: string;\n environment: Environment;\n appUserId?: string;\n enableDebug?: boolean;\n baseUrl?: string;\n flushIntervalMs?: number;\n flushThreshold?: number;\n maxQueueSize?: number;\n /**\n * Whether to automatically fire an `app_open` event during init().\n * Set to `false` if you want to fire the event manually.\n * @default true\n */\n autoTrackAppOpen?: boolean;\n /**\n * Whether to automatically track `deep_link_opened` events when a deep link\n * is received. The tracked event includes the parsed URL components and all\n * query parameters (UTM params, click IDs like fbclid/gclid/ttclid, etc.)\n * as flat top-level properties.\n *\n * This listener runs in addition to any consumer-registered listener via\n * `setupDeepLinkListener()` -- it does not replace it.\n *\n * @default true\n */\n autoTrackDeepLinks?: boolean;\n}\n\ndeclare const __LAYERS_RN_VERSION__: string;\nconst SDK_VERSION: string =\n typeof __LAYERS_RN_VERSION__ !== 'undefined' ? __LAYERS_RN_VERSION__ : '0.1.0';\n\nexport type ErrorListener = (error: Error) => void;\n\nexport class LayersReactNative {\n private core!: LayersCore;\n private appUserId: string | undefined;\n private isOnline = true;\n private readonly enableDebug: boolean;\n private appStateSubscription: { remove(): void } | null = null;\n private netInfoUnsubscribe: (() => void) | null = null;\n private readonly config: LayersRNConfig;\n\n // set-user-once semantics: once appUserId is set, it cannot be changed\n // (must clearAppUserId first)\n private userIdLocked = false;\n\n // Error listeners\n private readonly errorListeners: Set<ErrorListener> = new Set();\n\n // SKAN manager auto-configured from remote config (iOS only)\n private _skanManager: SKANManagerImpl | null = null;\n\n // Internal deep link listener unsubscribe (auto-tracking)\n private deepLinkUnsubscribe: (() => void) | null = null;\n\n constructor(config: LayersRNConfig) {\n this.enableDebug = config.enableDebug ?? false;\n this.appUserId = config.appUserId;\n this.config = config;\n\n // Create the core eagerly with an empty MemoryPersistence so that\n // track()/screen()/etc. work immediately (before init() is called).\n // init() will replace this with a fully-hydrated AsyncStorage backend.\n const httpClient = new FetchHttpClient();\n this.core = LayersCore.init({\n config: {\n appId: config.appId,\n environment: config.environment,\n ...(config.baseUrl != null && { baseUrl: config.baseUrl }),\n ...(config.enableDebug != null && { enableDebug: config.enableDebug }),\n ...(config.flushIntervalMs != null && { flushIntervalMs: config.flushIntervalMs }),\n ...(config.flushThreshold != null && { flushThreshold: config.flushThreshold }),\n ...(config.maxQueueSize != null && { maxQueueSize: config.maxQueueSize }),\n sdkVersion: `react-native/${SDK_VERSION}`\n },\n httpClient,\n persistence: new MemoryPersistence()\n });\n\n if (this.appUserId) {\n this.core.identify(this.appUserId);\n this.userIdLocked = true;\n }\n }\n\n async init(): Promise<void> {\n // Re-create the core with a pre-loaded AsyncStorage persistence backend\n // so that events persisted in a prior session are properly rehydrated.\n try {\n const persistence = await createAsyncStoragePersistence(this.config.appId);\n const httpClient = new FetchHttpClient();\n // Shut down the eager core before replacing it\n this.core.shutdown();\n this.core = LayersCore.init({\n config: {\n appId: this.config.appId,\n environment: this.config.environment,\n ...(this.config.baseUrl != null && { baseUrl: this.config.baseUrl }),\n ...(this.config.enableDebug != null && { enableDebug: this.config.enableDebug }),\n ...(this.config.flushIntervalMs != null && {\n flushIntervalMs: this.config.flushIntervalMs\n }),\n ...(this.config.flushThreshold != null && {\n flushThreshold: this.config.flushThreshold\n }),\n ...(this.config.maxQueueSize != null && { maxQueueSize: this.config.maxQueueSize }),\n sdkVersion: `react-native/${SDK_VERSION}`\n },\n httpClient,\n persistence\n });\n\n if (this.appUserId) {\n this.core.identify(this.appUserId);\n }\n } catch {\n // AsyncStorage pre-load failed; keep using the eager core with MemoryPersistence\n }\n\n await this.initializeDeviceInfo();\n this.setupAppStateListener();\n this.setupNetInfoListener();\n\n // Remote config fetch is best-effort. The JS layer fetches the config\n // endpoint; when the WASM/Rust core is loaded, it applies sampling,\n // rate limits, and filtering internally. The JS fallback path does not\n // currently parse/apply the config response — a future enhancement\n // will add JS-side config application for non-WASM environments.\n await this.core.fetchRemoteConfig().catch(() => {});\n\n // Auto-configure SKAN from remote config (iOS only).\n // The server's remote config `skan` section drives preset/rules so consumers\n // don't need to call SKANManager.setPreset() manually.\n await this.configureSkanFromRemoteConfig();\n\n // Clipboard attribution: on first iOS launch, check clipboard for Layers click URL\n let clipboardData: ClipboardAttribution | null = null;\n try {\n const { Platform } = require('react-native');\n if (Platform.OS === 'ios') {\n // Check remote config for clipboard_attribution_enabled flag.\n // Default to false: only read clipboard if the server explicitly enables it.\n let clipboardEnabled = false;\n try {\n const configJson = this.core.getRemoteConfigJson?.();\n if (configJson) {\n const config = JSON.parse(configJson);\n clipboardEnabled = config?.clipboard_attribution_enabled === true;\n }\n } catch {}\n if (clipboardEnabled) {\n clipboardData = await readClipboardAttribution();\n }\n }\n } catch {}\n\n // Auto-track app_open event with clipboard attribution if found\n if (this.config.autoTrackAppOpen !== false) {\n const appOpenProps: Record<string, unknown> = {};\n if (clipboardData) {\n appOpenProps.clipboard_attribution_url = clipboardData.clickUrl;\n appOpenProps.clipboard_click_id = clipboardData.clickId;\n }\n this.track('app_open', appOpenProps);\n }\n\n // Auto-track deep link events (default: enabled).\n // Sets up an internal deep link listener that fires a `deep_link_opened`\n // event with the full parsed URL and all query params spread as top-level\n // properties. This runs in addition to any consumer-registered listener.\n if (this.config.autoTrackDeepLinks !== false) {\n this.setupDeepLinkAutoTracking();\n }\n }\n\n track(eventName: string, properties?: EventProperties): void {\n if (this.enableDebug) {\n console.log(\n `[Layers] track(\"${eventName}\", ${Object.keys(properties ?? {}).length} properties)`\n );\n }\n try {\n this.core.track(eventName, properties, this.appUserId);\n\n // Forward event to SKAN rule engine if auto-configured from remote config\n if (this._skanManager) {\n void this._skanManager\n .processEvent(eventName, (properties as Record<string, unknown>) ?? {})\n .catch(() => {});\n }\n } catch (e) {\n this.emitError(e);\n }\n }\n\n screen(screenName: string, properties?: EventProperties): void {\n if (this.enableDebug) {\n console.log(\n `[Layers] screen(\"${screenName}\", ${Object.keys(properties ?? {}).length} properties)`\n );\n }\n try {\n this.core.screen(screenName, properties, this.appUserId);\n } catch (e) {\n this.emitError(e);\n }\n }\n\n async setUserProperties(properties: UserProperties): Promise<void> {\n this.core.setUserProperties(properties as Record<string, unknown>);\n }\n\n async setConsent(consent: ConsentState): Promise<void> {\n this.core.setConsent(consent);\n }\n\n /**\n * Request App Tracking Transparency authorization (iOS only).\n * After the user responds, this method automatically:\n * - Collects IDFA if authorized\n * - Updates device info with IDFA and ATT status\n * - Sets advertising consent based on ATT result\n *\n * Returns the ATT status string.\n */\n async requestTrackingPermission(): Promise<ATTStatus> {\n // Auto-detect expo-tracking-transparency and prefer it when available\n let status: ATTStatus;\n try {\n const ExpoTT = await import('expo-tracking-transparency').catch(() => null);\n if (ExpoTT) {\n const { status: expoStatus } = await ExpoTT.requestTrackingPermissionsAsync();\n const statusMap: Record<string, ATTStatus> = {\n granted: 'authorized',\n denied: 'denied',\n restricted: 'restricted',\n undetermined: 'not_determined'\n };\n status = statusMap[expoStatus] ?? 'not_determined';\n } else {\n status = await requestATT();\n }\n } catch {\n status = await requestATT();\n }\n\n // Update device context with ATT status and IDFA (if authorized)\n const currentContext = this.core.getDeviceContext();\n const updates: DeviceContext = { ...currentContext, attStatus: status };\n if (status === 'authorized') {\n try {\n const idfa = await getAdvertisingId();\n if (idfa) updates.idfa = idfa;\n } catch {\n // IDFA collection is best-effort\n }\n }\n this.core.setDeviceContext(updates);\n\n // Auto-set advertising consent based on ATT result\n const advertisingAllowed = status === 'authorized';\n this.core.setConsent({ advertising: advertisingAllowed });\n\n if (this.enableDebug) {\n console.log(\n `[Layers] ATT status: ${status}, advertising consent: ${String(advertisingAllowed)}`\n );\n }\n\n return status;\n }\n\n /**\n * Set the app user ID. Uses set-user-once semantics:\n * once set, subsequent calls are ignored until clearAppUserId() is called.\n */\n setAppUserId(appUserId: string): void {\n if (this.enableDebug) {\n console.log(`[Layers] setAppUserId(\"${appUserId}\")`);\n }\n if (this.userIdLocked && this.appUserId) {\n if (this.enableDebug) {\n console.warn('[Layers] appUserId already set. Call clearAppUserId() first to change it.');\n }\n return;\n }\n this.appUserId = appUserId;\n this.userIdLocked = true;\n this.core.identify(appUserId);\n }\n\n clearAppUserId(): void {\n this.appUserId = undefined;\n this.userIdLocked = false;\n }\n\n getAppUserId(): string | undefined {\n return this.appUserId;\n }\n\n getSessionId(): string {\n return this.core.getSessionId();\n }\n\n getConsentState(): ConsentState {\n return this.core.getConsentState();\n }\n\n setDeviceInfo(deviceInfo: DeviceContext): void {\n this.core.setDeviceContext(deviceInfo);\n }\n\n async flush(): Promise<void> {\n try {\n await this.core.flushAsync();\n } catch (e) {\n this.emitError(e);\n this.core.flush();\n }\n }\n\n /**\n * Register an error listener. Errors from track/screen/flush\n * that would otherwise be silently dropped are forwarded here.\n */\n on(event: 'error', listener: ErrorListener): this {\n if (event === 'error') this.errorListeners.add(listener);\n return this;\n }\n\n /**\n * Remove a previously registered error listener.\n */\n off(event: 'error', listener: ErrorListener): this {\n if (event === 'error') this.errorListeners.delete(listener);\n return this;\n }\n\n /**\n * Returns the auto-configured SKANManager instance, or null if SKAN was not\n * configured by the server's remote config.\n * On iOS, when remote config contains a `skan` section with `preset` or\n * `customRules`, the SDK automatically creates and configures a SKANManager.\n * Every `track()` call is automatically forwarded to SKAN rule evaluation.\n */\n getSkanManager(): SKANManagerImpl | null {\n return this._skanManager;\n }\n\n private emitError(error: unknown): void {\n const err = error instanceof Error ? error : new Error(String(error));\n for (const listener of this.errorListeners) {\n try {\n listener(err);\n } catch {}\n }\n if (this.enableDebug && this.errorListeners.size === 0) {\n console.warn('[Layers]', err.message);\n }\n }\n\n shutdown(): void {\n if (this.appStateSubscription) {\n this.appStateSubscription.remove();\n this.appStateSubscription = null;\n }\n if (this.netInfoUnsubscribe) {\n this.netInfoUnsubscribe();\n this.netInfoUnsubscribe = null;\n }\n if (this.deepLinkUnsubscribe) {\n this.deepLinkUnsubscribe();\n this.deepLinkUnsubscribe = null;\n }\n this.core.shutdown();\n }\n\n // --- Platform-specific: Deep link auto-tracking ---\n\n private _trackedDeepLinkUrls = new Set<string>();\n\n private setupDeepLinkAutoTracking(): void {\n this.deepLinkUnsubscribe = setupDeepLinkListener((data: DeepLinkData) => {\n // Deduplicate: getInitialURL and addEventListener can both fire for the\n // same URL on some RN versions. Skip if we already tracked this exact URL.\n if (this._trackedDeepLinkUrls.has(data.url)) return;\n this._trackedDeepLinkUrls.add(data.url);\n // Clear after a short delay so the same URL can be tracked if the user\n // taps the same link again later\n setTimeout(() => this._trackedDeepLinkUrls.delete(data.url), 2000);\n try {\n const properties: Record<string, unknown> = {\n ...data.queryParams,\n url: data.url,\n scheme: data.scheme,\n host: data.host,\n path: data.path\n };\n this.track('deep_link_opened', properties);\n if (this.enableDebug) {\n console.log(`[Layers] auto-tracked deep_link_opened: ${data.url}`);\n }\n } catch (e) {\n this.emitError(e);\n }\n });\n }\n\n // --- Platform-specific: React Native device info ---\n\n private async initializeDeviceInfo(): Promise<void> {\n try {\n const { Platform, Dimensions, NativeModules } = require('react-native');\n const window = Dimensions.get('window');\n\n const platform =\n Platform.OS === 'ios' ? 'ios' : Platform.OS === 'android' ? 'android' : 'react-native';\n const osVersion =\n typeof Platform.Version === 'string' ? Platform.Version : String(Platform.Version);\n\n // Device model: use platform constants where available\n let deviceModel: string;\n if (Platform.OS === 'android') {\n const brand = Platform.constants?.Brand ?? '';\n const model = Platform.constants?.Model ?? '';\n deviceModel = brand && model ? `${brand} ${model}` : model || brand || 'Android';\n } else if (Platform.OS === 'ios') {\n // Try to get the real iOS model identifier from native module\n try {\n const model = await NativeModules.LayersDeviceInfo?.getModelIdentifier();\n deviceModel = model || 'iPhone';\n } catch {\n deviceModel = 'iPhone';\n }\n } else {\n deviceModel = 'unknown';\n }\n\n // appVersion is intentionally left undefined here — the SDK version is\n // already transmitted via the sdkVersion config field. Consumers can\n // provide their host app version via setDeviceInfo({ appVersion: '...' }).\n const context: DeviceContext = {\n platform: platform as PlatformType,\n osVersion,\n deviceModel,\n locale: getLocale(),\n screenSize: `${Math.round(window.width)}x${Math.round(window.height)}`,\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone\n };\n\n // Auto-collect IDFV on iOS (first-party identifier, no ATT consent required)\n if (Platform.OS === 'ios') {\n try {\n const idfv = await getVendorId();\n if (idfv) context.idfv = idfv;\n } catch {\n // IDFV collection is best-effort\n }\n }\n\n // Auto-populate installId from persistent storage (Gap 11)\n try {\n const installId = await getOrSetInstallId();\n if (installId) context.installId = installId;\n } catch {\n // installId collection is best-effort\n }\n\n this.core.setDeviceContext(context);\n } catch {\n // React Native APIs not available (e.g. in tests)\n const context: DeviceContext = {\n platform: 'react-native',\n osVersion: 'unknown',\n deviceModel: 'unknown',\n locale: 'en-US'\n };\n\n // Still try to populate installId in fallback path\n try {\n const installId = await getOrSetInstallId();\n if (installId) context.installId = installId;\n } catch {\n // installId collection is best-effort\n }\n\n this.core.setDeviceContext(context);\n }\n }\n\n // --- Platform-specific: AppState listener ---\n\n private setupAppStateListener(): void {\n try {\n const { AppState } = require('react-native');\n\n this.appStateSubscription = AppState.addEventListener('change', (nextAppState: string) => {\n if (nextAppState === 'background' || nextAppState === 'inactive') {\n this.core.flush();\n }\n if (nextAppState === 'active' && this.isOnline) {\n void this.core.flushAsync().catch(() => {});\n }\n });\n } catch {\n // AppState not available\n }\n }\n\n // --- Platform-specific: SKAN auto-configuration from remote config ---\n\n private async configureSkanFromRemoteConfig(): Promise<void> {\n // SKAN is iOS-only; skip on other platforms.\n try {\n const { Platform } = require('react-native');\n if (Platform.OS !== 'ios') return;\n } catch {\n // react-native not available (e.g. test env) — proceed with SKAN config\n }\n\n try {\n const configJson = this.core.getRemoteConfigJson?.();\n if (!configJson) return;\n\n const config = JSON.parse(configJson);\n const skanConfig = config?.skan;\n if (!skanConfig || skanConfig.enabled === false) return;\n\n const manager = new SKANManagerImpl();\n\n if (skanConfig.preset) {\n manager.setPreset(skanConfig.preset);\n } else if (skanConfig.customRules && Array.isArray(skanConfig.customRules)) {\n manager.setCustomRules(skanConfig.customRules);\n } else {\n // SKAN section present but no preset or rules — nothing to configure\n return;\n }\n\n await manager.initialize();\n this._skanManager = manager;\n\n if (this.enableDebug) {\n const metrics = manager.getMetrics();\n console.log(\n `[Layers] SKAN auto-configured from remote config: preset=${metrics.currentPreset}, rules=${String(metrics.ruleCount)}`\n );\n }\n } catch {\n // SKAN auto-configuration is best-effort\n }\n }\n\n // --- Platform-specific: NetInfo listener ---\n\n private setupNetInfoListener(): void {\n try {\n const NetInfo = require('@react-native-community/netinfo');\n this.netInfoUnsubscribe = NetInfo.addEventListener(\n (state: { isConnected: boolean | null }) => {\n const wasOffline = !this.isOnline;\n this.isOnline = state.isConnected !== false;\n\n if (wasOffline && this.isOnline) {\n void this.core.flushAsync().catch(() => {});\n }\n }\n );\n } catch {\n // NetInfo not available — assume always online\n }\n }\n}\n\n// --- AsyncStorage persistence backend ---\n\nasync function createAsyncStoragePersistence(appId: string): Promise<PersistenceBackend> {\n const prefix = `layers_sdk_${appId}_`;\n const memoryStore = new Map<string, Uint8Array>();\n\n // Pre-load from AsyncStorage so that events persisted in a prior session\n // are available synchronously when the core hydrates on init.\n try {\n const AsyncStorage = await loadAsyncStorage();\n if (AsyncStorage) {\n const allKeys = await AsyncStorage.getAllKeys();\n const layersKeys = allKeys.filter((k) => k.startsWith(prefix));\n if (layersKeys.length > 0) {\n const pairs = await AsyncStorage.multiGet(layersKeys);\n for (const [key, value] of pairs) {\n if (value) {\n const shortKey = key.slice(prefix.length);\n memoryStore.set(shortKey, base64Decode(value));\n }\n }\n }\n }\n } catch {\n // Pre-load is best-effort; memoryStore stays empty\n }\n\n return {\n write(key: string, data: Uint8Array): void {\n memoryStore.set(key, new Uint8Array(data));\n // Fire-and-forget async write to AsyncStorage\n void writeToAsyncStorage(prefix + key, data);\n },\n read(key: string): Uint8Array | null {\n return memoryStore.get(key) ?? null;\n },\n delete(key: string): void {\n memoryStore.delete(key);\n void deleteFromAsyncStorage(prefix + key);\n },\n listKeys(keyPrefix: string): string[] {\n const keys: string[] = [];\n for (const k of memoryStore.keys()) {\n if (k.startsWith(keyPrefix)) {\n keys.push(k);\n }\n }\n keys.sort();\n return keys;\n }\n };\n}\n\n// Binary-safe base64 encoding that handles large arrays without stack overflow.\n// btoa(String.fromCharCode(...data)) spreads the entire array onto the call stack,\n// which crashes for event batches larger than ~125 KB.\nconst B64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nconst B64_LOOKUP = new Uint8Array(128);\nfor (let _i = 0; _i < B64_CHARS.length; _i += 1) {\n B64_LOOKUP[B64_CHARS.charCodeAt(_i)] = _i;\n}\n\nfunction base64Decode(str: string): Uint8Array {\n const lookup = B64_LOOKUP;\n // Strip padding to determine decoded length\n let len = str.length;\n if (str[len - 1] === '=') len -= 1;\n if (str[len - 1] === '=') len -= 1;\n const bytes = new Uint8Array(Math.floor((len * 3) / 4));\n let p = 0;\n for (let i = 0; i < len; i += 4) {\n const b0 = lookup[str.charCodeAt(i)]!;\n const b1 = lookup[str.charCodeAt(i + 1)]!;\n const b2 = i + 2 < len ? lookup[str.charCodeAt(i + 2)]! : 0;\n const b3 = i + 3 < len ? lookup[str.charCodeAt(i + 3)]! : 0;\n bytes[p] = (b0 << 2) | (b1 >> 4);\n p += 1;\n if (i + 2 < len) {\n bytes[p] = ((b1 & 0x0f) << 4) | (b2 >> 2);\n p += 1;\n }\n if (i + 3 < len) {\n bytes[p] = ((b2 & 0x03) << 6) | b3;\n p += 1;\n }\n }\n return bytes;\n}\n\nfunction base64Encode(bytes: Uint8Array): string {\n let result = '';\n const len = bytes.length;\n for (let i = 0; i < len; i += 3) {\n const b0 = bytes[i]!;\n const b1 = i + 1 < len ? bytes[i + 1]! : 0;\n const b2 = i + 2 < len ? bytes[i + 2]! : 0;\n result += B64_CHARS[(b0 >> 2)!]!;\n result += B64_CHARS[((b0 & 0x03) << 4) | (b1 >> 4)]!;\n result += i + 1 < len ? B64_CHARS[((b1 & 0x0f) << 2) | (b2 >> 6)]! : '=';\n result += i + 2 < len ? B64_CHARS[b2 & 0x3f]! : '=';\n }\n return result;\n}\n\nasync function writeToAsyncStorage(key: string, data: Uint8Array): Promise<void> {\n try {\n const AsyncStorage = await loadAsyncStorage();\n if (!AsyncStorage) return;\n const encoded = base64Encode(data);\n await AsyncStorage.setItem(key, encoded);\n } catch {\n // Best effort\n }\n}\n\nasync function deleteFromAsyncStorage(key: string): Promise<void> {\n try {\n const AsyncStorage = await loadAsyncStorage();\n if (!AsyncStorage) return;\n await AsyncStorage.removeItem(key);\n } catch {\n // Best effort\n }\n}\n\ninterface AsyncStorageStatic {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n getAllKeys(): Promise<readonly string[]>;\n multiGet(keys: readonly string[]): Promise<readonly [string, string | null][]>;\n}\n\nlet _asyncStorage: AsyncStorageStatic | undefined = undefined;\nlet _asyncStoragePromise: Promise<AsyncStorageStatic | null> | null = null;\n\nasync function loadAsyncStorage(): Promise<AsyncStorageStatic | null> {\n if (_asyncStorage) return _asyncStorage;\n if (!_asyncStoragePromise) {\n _asyncStoragePromise = import('@react-native-async-storage/async-storage')\n .then((mod) => {\n _asyncStorage = mod.default ?? mod;\n return _asyncStorage;\n })\n .catch(() => null);\n }\n return _asyncStoragePromise;\n}\n\n// --- Locale helper ---\n\nfunction getLocale(): string {\n try {\n const { Platform, NativeModules } = require('react-native');\n if (Platform.OS === 'ios') {\n return (\n NativeModules.SettingsManager?.settings?.AppleLocale ??\n NativeModules.SettingsManager?.settings?.AppleLanguages?.[0] ??\n 'en-US'\n );\n }\n if (Platform.OS === 'android') {\n return NativeModules.I18nManager?.localeIdentifier ?? 'en-US';\n }\n } catch {\n // Fallback\n }\n return 'en-US';\n}\n\n// --- Install ID via AsyncStorage ---\n\nconst INSTALL_ID_KEY = 'layers_install_id';\n\nexport async function getOrSetInstallId(): Promise<string> {\n try {\n const AsyncStorage = await loadAsyncStorage();\n if (!AsyncStorage) return generateUUID();\n\n const existing = await AsyncStorage.getItem(INSTALL_ID_KEY);\n if (existing) return existing;\n\n const newId = generateUUID();\n await AsyncStorage.setItem(INSTALL_ID_KEY, newId);\n return newId;\n } catch {\n return generateUUID();\n }\n}\n\nfunction generateUUID(): string {\n if (typeof crypto !== 'undefined' && crypto.randomUUID) {\n return crypto.randomUUID();\n }\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n// --- Clipboard Attribution (iOS-only deferred deep links) ---\n\nexport interface ClipboardAttribution {\n clickUrl: string;\n clickId: string;\n}\n\nconst CLIPBOARD_CHECKED_KEY = '@layers/clipboard_checked';\n\nexport async function readClipboardAttribution(): Promise<ClipboardAttribution | null> {\n try {\n const { Platform } = require('react-native');\n if (Platform.OS !== 'ios') return null;\n } catch {\n return null;\n }\n\n // Check if we've already read clipboard (once per install)\n try {\n const AS = await loadAsyncStorage();\n if (AS) {\n const flag = await AS.getItem(CLIPBOARD_CHECKED_KEY);\n if (flag === 'true') return null;\n }\n } catch {}\n\n let text: string | null = null;\n try {\n // Try @react-native-clipboard/clipboard first (recommended)\n const Clipboard = await import('@react-native-clipboard/clipboard')\n .then((m) => m.default)\n .catch(() => null);\n if (Clipboard) {\n text = await Clipboard.getString();\n } else {\n // Fallback to deprecated RN Clipboard\n const { Clipboard: RNClipboard } = require('react-native');\n if (RNClipboard) {\n text = await RNClipboard.getString();\n }\n }\n } catch {}\n\n // Mark as checked regardless of result\n try {\n const AS = await loadAsyncStorage();\n if (AS) await AS.setItem(CLIPBOARD_CHECKED_KEY, 'true');\n } catch {}\n\n if (!text) return null;\n\n // Check for Layers click URL pattern\n const match = text.match(/https?:\\/\\/(in\\.layers\\.com|link\\.layers\\.com)\\/c\\/([^?\\s]+)/);\n if (!match) return null;\n\n return { clickUrl: text, clickId: match[2]! };\n}\n\n// --- Deep Links ---\n\nexport interface DeepLinkData {\n url: string;\n scheme: string;\n host: string;\n path: string;\n queryParams: Record<string, string>;\n timestamp: number;\n}\n\nexport function setupDeepLinkListener(onDeepLink: (data: DeepLinkData) => void): () => void {\n try {\n const { Linking } = require('react-native');\n\n const handler = (event: { url: string }) => {\n const parsed = parseDeepLink(event.url);\n if (parsed) onDeepLink(parsed);\n };\n\n const subscription = Linking.addEventListener('url', handler);\n\n // Check initial URL\n void Linking.getInitialURL().then((url: string | null) => {\n if (url) {\n const parsed = parseDeepLink(url);\n if (parsed) onDeepLink(parsed);\n }\n });\n\n return () => {\n if (subscription?.remove) {\n subscription.remove();\n }\n };\n } catch {\n return () => {};\n }\n}\n\nexport function parseDeepLink(url: string): DeepLinkData | null {\n try {\n const parsed = new URL(url);\n const params: Record<string, string> = {};\n parsed.searchParams.forEach((value, key) => {\n params[key] = value;\n });\n return {\n url,\n scheme: parsed.protocol.replace(':', ''),\n host: parsed.hostname,\n path: parsed.pathname,\n queryParams: params,\n timestamp: Date.now()\n };\n } catch {\n return null;\n }\n}\n\n// --- Expo Router Integration ---\n\nexport function useLayersExpoRouterTracking(\n layersInstance: LayersReactNative,\n usePathname: () => string,\n useGlobalSearchParams: () => Record<string, string | string[]>\n): void {\n const { useEffect } = require('react');\n const pathname = usePathname();\n const params = useGlobalSearchParams();\n const paramsString = JSON.stringify(params);\n\n useEffect(() => {\n if (pathname) {\n const properties: Record<string, unknown> = {};\n Object.entries(params).forEach(([key, value]) => {\n properties[key] = Array.isArray(value) ? value.join(',') : value;\n });\n void layersInstance.screen(pathname, properties);\n }\n }, [pathname, paramsString]);\n}\n"],"mappings":";;;;;;AA+EA,MAAMA,cACJ,OAAO,0BAA0B,cAAc,wBAAwB;AAIzE,IAAa,oBAAb,MAA+B;CAC7B,AAAQ;CACR,AAAQ;CACR,AAAQ,WAAW;CACnB,AAAiB;CACjB,AAAQ,uBAAkD;CAC1D,AAAQ,qBAA0C;CAClD,AAAiB;CAIjB,AAAQ,eAAe;CAGvB,AAAiB,iCAAqC,IAAI,KAAK;CAG/D,AAAQ,eAAuC;CAG/C,AAAQ,sBAA2C;CAEnD,YAAY,QAAwB;AAClC,OAAK,cAAc,OAAO,eAAe;AACzC,OAAK,YAAY,OAAO;AACxB,OAAK,SAAS;EAKd,MAAM,aAAa,IAAI,iBAAiB;AACxC,OAAK,OAAO,WAAW,KAAK;GAC1B,QAAQ;IACN,O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