@layers/react-native 1.4.0 → 1.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/TrackingTransparency-D6ybvQzE.js +328 -0
  2. package/dist/{TrackingTransparency-CMedp3bh.js → TrackingTransparency-DunpgkgS.mjs} +1 -1
  3. package/dist/TrackingTransparency-DunpgkgS.mjs.map +1 -0
  4. package/dist/{att-DaUoQWpj.js → att-B6KTrEU7.mjs} +2 -2
  5. package/dist/att-B6KTrEU7.mjs.map +1 -0
  6. package/dist/att-BDPyE-Gs.d.mts +10 -0
  7. package/dist/att-BDPyE-Gs.d.mts.map +1 -0
  8. package/dist/{att-BlUZv4_u.d.ts → att-BFy6dcWE.d.ts} +1 -1
  9. package/dist/{att-BlUZv4_u.d.ts.map → att-BFy6dcWE.d.ts.map} +1 -1
  10. package/dist/att-CauvkIKr.js +69 -0
  11. package/dist/att.d.mts +2 -0
  12. package/dist/att.d.ts +1 -1
  13. package/dist/att.js +6 -2
  14. package/dist/att.mjs +3 -0
  15. package/dist/chunk-nOFOJqeH.js +30 -0
  16. package/dist/index-Ct99z5MX.d.mts +187 -0
  17. package/dist/index-Ct99z5MX.d.mts.map +1 -0
  18. package/dist/{index-nttdlILS.d.ts → index-DtN6DP29.d.ts} +3 -3
  19. package/dist/{index-nttdlILS.d.ts.map → index-DtN6DP29.d.ts.map} +1 -1
  20. package/dist/index.d.mts +4 -0
  21. package/dist/index.d.ts +3 -3
  22. package/dist/index.js +27 -4
  23. package/dist/index.mjs +5 -0
  24. package/dist/react.d.mts +108 -0
  25. package/dist/react.d.mts.map +1 -0
  26. package/dist/react.d.ts +4 -4
  27. package/dist/react.js +25 -18
  28. package/dist/react.mjs +146 -0
  29. package/dist/react.mjs.map +1 -0
  30. package/dist/skan-CAN-v1eU.d.mts +50 -0
  31. package/dist/skan-CAN-v1eU.d.mts.map +1 -0
  32. package/dist/{skan-DFFAN4wu.js → skan-CBE6_mjp.mjs} +2 -2
  33. package/dist/skan-CBE6_mjp.mjs.map +1 -0
  34. package/dist/skan-DqDVGZkX.js +256 -0
  35. package/dist/{skan-DvnRgJo1.d.ts → skan-DupmPyTn.d.ts} +1 -1
  36. package/dist/{skan-DvnRgJo1.d.ts.map → skan-DupmPyTn.d.ts.map} +1 -1
  37. package/dist/skan.d.mts +2 -0
  38. package/dist/skan.d.ts +1 -1
  39. package/dist/skan.js +2 -2
  40. package/dist/skan.mjs +3 -0
  41. package/dist/{src-CYaAvWR2.js → src-DFnL34cK.mjs} +5 -5
  42. package/dist/src-DFnL34cK.mjs.map +1 -0
  43. package/dist/src-DQCNfyUc.js +825 -0
  44. package/package.json +12 -5
  45. package/dist/TrackingTransparency-CMedp3bh.js.map +0 -1
  46. package/dist/att-DaUoQWpj.js.map +0 -1
  47. package/dist/react.js.map +0 -1
  48. package/dist/skan-DFFAN4wu.js.map +0 -1
  49. package/dist/src-CYaAvWR2.js.map +0 -1
  50. /package/dist/{chunk-DyChAoct.js → chunk-DmmLNhcN.mjs} +0 -0
@@ -0,0 +1,825 @@
1
+ const require_chunk = require('./chunk-nOFOJqeH.js');
2
+ const require_att = require('./att-CauvkIKr.js');
3
+ const require_skan = require('./skan-DqDVGZkX.js');
4
+ let __layers_core_wasm = require("@layers/core-wasm");
5
+ __layers_core_wasm = require_chunk.__toESM(__layers_core_wasm);
6
+
7
+ //#region src/index.ts
8
+ const SDK_VERSION = typeof __LAYERS_RN_VERSION__ !== "undefined" ? __LAYERS_RN_VERSION__ : "0.1.0";
9
+ var LayersReactNative = class LayersReactNative {
10
+ core;
11
+ appUserId;
12
+ isOnline = true;
13
+ enableDebug;
14
+ appStateSubscription = null;
15
+ netInfoUnsubscribe = null;
16
+ config;
17
+ userIdLocked = false;
18
+ errorListeners = /* @__PURE__ */ new Set();
19
+ _skanManager = null;
20
+ _lastSkanConfigStr = null;
21
+ deepLinkUnsubscribe = null;
22
+ _configPollTimer = null;
23
+ static CONFIG_POLL_INTERVAL_MS = 3e5;
24
+ _adServicesToken = null;
25
+ _installReferrer = null;
26
+ constructor(config) {
27
+ this.enableDebug = config.enableDebug ?? false;
28
+ this.appUserId = config.appUserId;
29
+ this.config = config;
30
+ const httpClient = new __layers_core_wasm.FetchHttpClient();
31
+ this.core = __layers_core_wasm.LayersCore.init({
32
+ config: {
33
+ appId: config.appId,
34
+ environment: config.environment,
35
+ ...config.baseUrl != null && { baseUrl: config.baseUrl },
36
+ ...config.enableDebug != null && { enableDebug: config.enableDebug },
37
+ ...config.flushIntervalMs != null && { flushIntervalMs: config.flushIntervalMs },
38
+ ...config.flushThreshold != null && { flushThreshold: config.flushThreshold },
39
+ ...config.maxQueueSize != null && { maxQueueSize: config.maxQueueSize },
40
+ sdkVersion: `react-native/${SDK_VERSION}`
41
+ },
42
+ httpClient,
43
+ persistence: new __layers_core_wasm.MemoryPersistence()
44
+ });
45
+ if (this.appUserId) {
46
+ this.core.identify(this.appUserId);
47
+ this.userIdLocked = true;
48
+ }
49
+ }
50
+ async init() {
51
+ try {
52
+ const persistence = await createAsyncStoragePersistence(this.config.appId);
53
+ const httpClient = new __layers_core_wasm.FetchHttpClient();
54
+ this.core.shutdown();
55
+ this.core = __layers_core_wasm.LayersCore.init({
56
+ config: {
57
+ appId: this.config.appId,
58
+ environment: this.config.environment,
59
+ ...this.config.baseUrl != null && { baseUrl: this.config.baseUrl },
60
+ ...this.config.enableDebug != null && { enableDebug: this.config.enableDebug },
61
+ ...this.config.flushIntervalMs != null && { flushIntervalMs: this.config.flushIntervalMs },
62
+ ...this.config.flushThreshold != null && { flushThreshold: this.config.flushThreshold },
63
+ ...this.config.maxQueueSize != null && { maxQueueSize: this.config.maxQueueSize },
64
+ sdkVersion: `react-native/${SDK_VERSION}`
65
+ },
66
+ httpClient,
67
+ persistence
68
+ });
69
+ if (this.appUserId) this.core.identify(this.appUserId);
70
+ } catch {}
71
+ await this.initializeDeviceInfo();
72
+ this.setupAppStateListener();
73
+ this.setupNetInfoListener();
74
+ await this.core.fetchRemoteConfig().catch(() => {});
75
+ await this.configureSkanFromRemoteConfig();
76
+ this.startConfigPolling();
77
+ let clipboardData = null;
78
+ try {
79
+ const { Platform } = require("react-native");
80
+ if (Platform.OS === "ios") {
81
+ let clipboardEnabled = false;
82
+ try {
83
+ const configJson = this.core.getRemoteConfigJson?.();
84
+ if (configJson) clipboardEnabled = JSON.parse(configJson)?.clipboard_attribution_enabled === true;
85
+ } catch {}
86
+ if (clipboardEnabled) clipboardData = await readClipboardAttribution();
87
+ }
88
+ } catch {}
89
+ if (this.config.autoTrackAppOpen !== false) {
90
+ const appOpenProps = {};
91
+ if (clipboardData) {
92
+ appOpenProps.clipboard_attribution_url = clipboardData.clickUrl;
93
+ appOpenProps.clipboard_click_id = clipboardData.clickId;
94
+ }
95
+ if (this._adServicesToken) appOpenProps.adservices_token = this._adServicesToken;
96
+ if (this._installReferrer) {
97
+ appOpenProps.install_referrer_url = this._installReferrer.referrerUrl;
98
+ if (this._installReferrer.referrerClickTimestamp) appOpenProps.install_referrer_click_timestamp = this._installReferrer.referrerClickTimestamp;
99
+ if (this._installReferrer.installBeginTimestamp) appOpenProps.install_referrer_install_timestamp = this._installReferrer.installBeginTimestamp;
100
+ }
101
+ this.track("app_open", appOpenProps);
102
+ }
103
+ if (this.config.autoTrackDeepLinks !== false) this.setupDeepLinkAutoTracking();
104
+ }
105
+ track(eventName, properties) {
106
+ if (this.enableDebug) console.log(`[Layers] track("${eventName}", ${Object.keys(properties ?? {}).length} properties)`);
107
+ try {
108
+ this.core.track(eventName, properties, this.appUserId);
109
+ if (this._skanManager) this._skanManager.processEvent(eventName, properties ?? {}).catch(() => {});
110
+ } catch (e) {
111
+ this.emitError(e);
112
+ }
113
+ }
114
+ screen(screenName, properties) {
115
+ if (this.enableDebug) console.log(`[Layers] screen("${screenName}", ${Object.keys(properties ?? {}).length} properties)`);
116
+ try {
117
+ this.core.screen(screenName, properties, this.appUserId);
118
+ } catch (e) {
119
+ this.emitError(e);
120
+ }
121
+ }
122
+ async setUserProperties(properties) {
123
+ this.core.setUserProperties(properties);
124
+ }
125
+ async setUserPropertiesOnce(properties) {
126
+ this.core.setUserPropertiesOnce(properties);
127
+ }
128
+ async setConsent(consent) {
129
+ this.core.setConsent(consent);
130
+ }
131
+ /**
132
+ * Request App Tracking Transparency authorization (iOS only).
133
+ * After the user responds, this method automatically:
134
+ * - Collects IDFA if authorized
135
+ * - Updates device info with IDFA and ATT status
136
+ * - Sets advertising consent based on ATT result
137
+ *
138
+ * Returns the ATT status string.
139
+ */
140
+ async requestTrackingPermission() {
141
+ let status;
142
+ try {
143
+ const ExpoTT = await Promise.resolve().then(() => require("./TrackingTransparency-D6ybvQzE.js")).catch(() => null);
144
+ if (ExpoTT) {
145
+ const { status: expoStatus } = await ExpoTT.requestTrackingPermissionsAsync();
146
+ status = {
147
+ granted: "authorized",
148
+ denied: "denied",
149
+ restricted: "restricted",
150
+ undetermined: "not_determined"
151
+ }[expoStatus] ?? "not_determined";
152
+ } else status = await require_att.requestTrackingAuthorization();
153
+ } catch {
154
+ status = await require_att.requestTrackingAuthorization();
155
+ }
156
+ const updates = {
157
+ ...this.core.getDeviceContext(),
158
+ attStatus: status
159
+ };
160
+ if (status === "authorized") try {
161
+ const idfa = await require_att.getAdvertisingId();
162
+ if (idfa) updates.idfa = idfa;
163
+ } catch {}
164
+ this.core.setDeviceContext(updates);
165
+ const advertisingAllowed = status === "authorized";
166
+ this.core.setConsent({ advertising: advertisingAllowed });
167
+ if (this.enableDebug) console.log(`[Layers] ATT status: ${status}, advertising consent: ${String(advertisingAllowed)}`);
168
+ return status;
169
+ }
170
+ /**
171
+ * Set the app user ID. Uses set-user-once semantics:
172
+ * once set, subsequent calls are ignored until clearAppUserId() is called.
173
+ */
174
+ setAppUserId(appUserId) {
175
+ if (this.enableDebug) console.log(`[Layers] setAppUserId("${appUserId}")`);
176
+ if (this.userIdLocked && this.appUserId) {
177
+ if (this.enableDebug) console.warn("[Layers] appUserId already set. Call clearAppUserId() first to change it.");
178
+ return;
179
+ }
180
+ this.appUserId = appUserId;
181
+ this.userIdLocked = true;
182
+ this.core.identify(appUserId);
183
+ }
184
+ clearAppUserId() {
185
+ this.appUserId = void 0;
186
+ this.userIdLocked = false;
187
+ }
188
+ /**
189
+ * Reset the SDK state: clears the user ID, unlocks set-user-once,
190
+ * clears user properties, and starts a new session.
191
+ *
192
+ * After reset(), the SDK behaves as if no user has been identified.
193
+ * A new anonymous session is started. Events tracked after reset()
194
+ * will not carry the previous user's identity.
195
+ */
196
+ reset() {
197
+ if (this.enableDebug) console.log("[Layers] reset()");
198
+ this.appUserId = void 0;
199
+ this.userIdLocked = false;
200
+ try {
201
+ this.core.setUserProperties({});
202
+ } catch (e) {
203
+ this.emitError(e);
204
+ }
205
+ try {
206
+ this.core.startNewSession();
207
+ } catch (e) {
208
+ this.emitError(e);
209
+ }
210
+ }
211
+ getAppUserId() {
212
+ return this.appUserId;
213
+ }
214
+ getSessionId() {
215
+ return this.core.getSessionId();
216
+ }
217
+ getConsentState() {
218
+ return this.core.getConsentState();
219
+ }
220
+ setDeviceInfo(deviceInfo) {
221
+ this.core.setDeviceContext(deviceInfo);
222
+ }
223
+ async flush() {
224
+ try {
225
+ await this.core.flushAsync();
226
+ } catch (e) {
227
+ this.emitError(e);
228
+ this.core.flush();
229
+ }
230
+ }
231
+ /**
232
+ * Flush all queued events synchronously (blocking).
233
+ *
234
+ * Drains all batches from the queue and sends them via HTTP, awaiting
235
+ * each batch before proceeding. Does not return until all batches have
236
+ * been sent or failed.
237
+ *
238
+ * This is useful for AppState background transitions where the app may
239
+ * be suspended shortly after the call returns.
240
+ */
241
+ async flushBlocking() {
242
+ try {
243
+ let depth = this.core.queueDepth();
244
+ while (depth > 0) {
245
+ await this.core.flushAsync();
246
+ const newDepth = this.core.queueDepth();
247
+ if (newDepth >= depth) break;
248
+ depth = newDepth;
249
+ }
250
+ } catch (e) {
251
+ this.emitError(e);
252
+ }
253
+ }
254
+ /**
255
+ * Register an error listener. Errors from track/screen/flush
256
+ * that would otherwise be silently dropped are forwarded here.
257
+ */
258
+ on(event, listener) {
259
+ if (event === "error") this.errorListeners.add(listener);
260
+ return this;
261
+ }
262
+ /**
263
+ * Remove a previously registered error listener.
264
+ */
265
+ off(event, listener) {
266
+ if (event === "error") this.errorListeners.delete(listener);
267
+ return this;
268
+ }
269
+ /**
270
+ * Returns the AdServices attribution token (iOS only), or null if not
271
+ * available. Collected automatically during init() on iOS 14.3+.
272
+ * Does NOT require ATT consent.
273
+ */
274
+ getAdServicesToken() {
275
+ return this._adServicesToken;
276
+ }
277
+ /**
278
+ * Returns the Google Play install referrer data (Android only), or null
279
+ * if not available. Collected automatically during init() on Android.
280
+ */
281
+ getInstallReferrer() {
282
+ return this._installReferrer;
283
+ }
284
+ /**
285
+ * Returns the auto-configured SKANManager instance, or null if SKAN was not
286
+ * configured by the server's remote config.
287
+ * On iOS, when remote config contains a `skan` section with `preset` or
288
+ * `customRules`, the SDK automatically creates and configures a SKANManager.
289
+ * Every `track()` call is automatically forwarded to SKAN rule evaluation.
290
+ */
291
+ getSkanManager() {
292
+ return this._skanManager;
293
+ }
294
+ emitError(error) {
295
+ const err = error instanceof Error ? error : new Error(String(error));
296
+ for (const listener of this.errorListeners) try {
297
+ listener(err);
298
+ } catch {}
299
+ if (this.enableDebug && this.errorListeners.size === 0) console.warn("[Layers]", err.message);
300
+ }
301
+ shutdown() {
302
+ this.stopConfigPolling();
303
+ if (this.appStateSubscription) {
304
+ this.appStateSubscription.remove();
305
+ this.appStateSubscription = null;
306
+ }
307
+ if (this.netInfoUnsubscribe) {
308
+ this.netInfoUnsubscribe();
309
+ this.netInfoUnsubscribe = null;
310
+ }
311
+ if (this.deepLinkUnsubscribe) {
312
+ this.deepLinkUnsubscribe();
313
+ this.deepLinkUnsubscribe = null;
314
+ }
315
+ this.core.shutdown();
316
+ }
317
+ _trackedDeepLinkUrls = /* @__PURE__ */ new Set();
318
+ setupDeepLinkAutoTracking() {
319
+ this.deepLinkUnsubscribe = setupDeepLinkListener((data) => {
320
+ if (this._trackedDeepLinkUrls.has(data.url)) return;
321
+ this._trackedDeepLinkUrls.add(data.url);
322
+ setTimeout(() => this._trackedDeepLinkUrls.delete(data.url), 2e3);
323
+ try {
324
+ const properties = {
325
+ ...data.queryParams,
326
+ url: data.url,
327
+ scheme: data.scheme,
328
+ host: data.host,
329
+ path: data.path
330
+ };
331
+ this.track("deep_link_opened", properties);
332
+ if (this.enableDebug) console.log(`[Layers] auto-tracked deep_link_opened: ${data.url}`);
333
+ } catch (e) {
334
+ this.emitError(e);
335
+ }
336
+ });
337
+ }
338
+ async initializeDeviceInfo() {
339
+ try {
340
+ const { Platform, Dimensions, NativeModules } = require("react-native");
341
+ const window = Dimensions.get("window");
342
+ const platform = Platform.OS === "ios" ? "ios" : Platform.OS === "android" ? "android" : "react-native";
343
+ const osVersion = typeof Platform.Version === "string" ? Platform.Version : String(Platform.Version);
344
+ let deviceModel;
345
+ if (Platform.OS === "android") {
346
+ const brand = Platform.constants?.Brand ?? "";
347
+ const model = Platform.constants?.Model ?? "";
348
+ deviceModel = brand && model ? `${brand} ${model}` : model || brand || "Android";
349
+ } else if (Platform.OS === "ios") try {
350
+ deviceModel = await NativeModules.LayersDeviceInfo?.getModelIdentifier() || "iPhone";
351
+ } catch {
352
+ deviceModel = "iPhone";
353
+ }
354
+ else deviceModel = "unknown";
355
+ let appVersion;
356
+ try {
357
+ appVersion = await getAppVersion(Platform, NativeModules);
358
+ } catch {}
359
+ const context = {
360
+ platform,
361
+ osVersion,
362
+ deviceModel,
363
+ locale: getLocale(),
364
+ screenSize: `${Math.round(window.width)}x${Math.round(window.height)}`,
365
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
366
+ ...appVersion != null && { appVersion }
367
+ };
368
+ if (Platform.OS === "ios") try {
369
+ const idfv = await require_att.getVendorId();
370
+ if (idfv) context.idfv = idfv;
371
+ } catch {}
372
+ if (Platform.OS === "android") try {
373
+ const gaid = await getGoogleAdvertisingId();
374
+ if (gaid) context.idfa = gaid.id;
375
+ if (gaid && gaid.isLimitAdTrackingEnabled != null) context.attStatus = gaid.isLimitAdTrackingEnabled ? "denied" : "authorized";
376
+ } catch {}
377
+ try {
378
+ const installId = await getOrSetInstallId();
379
+ if (installId) context.installId = installId;
380
+ } catch {}
381
+ this.core.setDeviceContext(context);
382
+ } catch {
383
+ const context = {
384
+ platform: "react-native",
385
+ osVersion: "unknown",
386
+ deviceModel: "unknown",
387
+ locale: "en-US"
388
+ };
389
+ try {
390
+ const installId = await getOrSetInstallId();
391
+ if (installId) context.installId = installId;
392
+ } catch {}
393
+ this.core.setDeviceContext(context);
394
+ }
395
+ try {
396
+ const { Platform } = require("react-native");
397
+ if (Platform.OS === "ios") try {
398
+ const token = await getAdServicesToken();
399
+ if (token) this._adServicesToken = token;
400
+ } catch {}
401
+ if (Platform.OS === "android") try {
402
+ const referrer = await getInstallReferrer();
403
+ if (referrer) this._installReferrer = referrer;
404
+ } catch {}
405
+ } catch {}
406
+ }
407
+ setupAppStateListener() {
408
+ try {
409
+ const { AppState } = require("react-native");
410
+ this.appStateSubscription = AppState.addEventListener("change", (nextAppState) => {
411
+ if (nextAppState === "background" || nextAppState === "inactive") this.core.flush();
412
+ if (nextAppState === "active" && this.isOnline) this.core.flushAsync().catch(() => {});
413
+ });
414
+ } catch {}
415
+ }
416
+ async configureSkanFromRemoteConfig() {
417
+ try {
418
+ const { Platform } = require("react-native");
419
+ if (Platform.OS !== "ios") return;
420
+ } catch {}
421
+ try {
422
+ const configJson = this.core.getRemoteConfigJson?.();
423
+ if (!configJson) return;
424
+ const skanConfig = JSON.parse(configJson)?.skan;
425
+ if (!skanConfig || skanConfig.enabled === false) {
426
+ this._skanManager = null;
427
+ this._lastSkanConfigStr = null;
428
+ return;
429
+ }
430
+ const skanConfigStr = JSON.stringify(skanConfig);
431
+ if (this._skanManager && this._lastSkanConfigStr === skanConfigStr) return;
432
+ const manager = new require_skan.SKANManager();
433
+ if (skanConfig.preset) manager.setPreset(skanConfig.preset);
434
+ else if (skanConfig.customRules && Array.isArray(skanConfig.customRules)) manager.setCustomRules(skanConfig.customRules);
435
+ else return;
436
+ await manager.initialize();
437
+ this._skanManager = manager;
438
+ this._lastSkanConfigStr = skanConfigStr;
439
+ if (this.enableDebug) {
440
+ const metrics = manager.getMetrics();
441
+ console.log(`[Layers] SKAN auto-configured from remote config: preset=${metrics.currentPreset}, rules=${String(metrics.ruleCount)}`);
442
+ }
443
+ } catch {}
444
+ }
445
+ startConfigPolling() {
446
+ this.stopConfigPolling();
447
+ this._configPollTimer = setInterval(() => {
448
+ this.pollRemoteConfig();
449
+ }, LayersReactNative.CONFIG_POLL_INTERVAL_MS);
450
+ }
451
+ stopConfigPolling() {
452
+ if (this._configPollTimer) {
453
+ clearInterval(this._configPollTimer);
454
+ this._configPollTimer = null;
455
+ }
456
+ }
457
+ async pollRemoteConfig() {
458
+ try {
459
+ await this.core.fetchRemoteConfig();
460
+ await this.configureSkanFromRemoteConfig();
461
+ if (this.enableDebug) console.log("[Layers] Remote config updated (poll)");
462
+ } catch {}
463
+ }
464
+ setupNetInfoListener() {
465
+ try {
466
+ this.netInfoUnsubscribe = require("@react-native-community/netinfo").addEventListener((state) => {
467
+ const wasOffline = !this.isOnline;
468
+ this.isOnline = state.isConnected !== false;
469
+ if (wasOffline && this.isOnline) this.core.flushAsync().catch(() => {});
470
+ });
471
+ } catch {}
472
+ }
473
+ };
474
+ async function createAsyncStoragePersistence(appId) {
475
+ const prefix = `layers_sdk_${appId}_`;
476
+ const memoryStore = /* @__PURE__ */ new Map();
477
+ try {
478
+ const AsyncStorage = await loadAsyncStorage();
479
+ if (AsyncStorage) {
480
+ const layersKeys = (await AsyncStorage.getAllKeys()).filter((k) => k.startsWith(prefix));
481
+ if (layersKeys.length > 0) {
482
+ const pairs = await AsyncStorage.multiGet(layersKeys);
483
+ for (const [key, value] of pairs) if (value) {
484
+ const shortKey = key.slice(prefix.length);
485
+ memoryStore.set(shortKey, base64Decode(value));
486
+ }
487
+ }
488
+ }
489
+ } catch {}
490
+ return {
491
+ write(key, data) {
492
+ memoryStore.set(key, new Uint8Array(data));
493
+ writeToAsyncStorage(prefix + key, data);
494
+ },
495
+ read(key) {
496
+ return memoryStore.get(key) ?? null;
497
+ },
498
+ delete(key) {
499
+ memoryStore.delete(key);
500
+ deleteFromAsyncStorage(prefix + key);
501
+ },
502
+ listKeys(keyPrefix) {
503
+ const keys = [];
504
+ for (const k of memoryStore.keys()) if (k.startsWith(keyPrefix)) keys.push(k);
505
+ keys.sort();
506
+ return keys;
507
+ }
508
+ };
509
+ }
510
+ const B64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
511
+ const B64_LOOKUP = new Uint8Array(128);
512
+ for (let _i = 0; _i < 64; _i += 1) B64_LOOKUP[B64_CHARS.charCodeAt(_i)] = _i;
513
+ function base64Decode(str) {
514
+ const lookup = B64_LOOKUP;
515
+ let len = str.length;
516
+ if (str[len - 1] === "=") len -= 1;
517
+ if (str[len - 1] === "=") len -= 1;
518
+ const bytes = new Uint8Array(Math.floor(len * 3 / 4));
519
+ let p = 0;
520
+ for (let i = 0; i < len; i += 4) {
521
+ const b0 = lookup[str.charCodeAt(i)];
522
+ const b1 = lookup[str.charCodeAt(i + 1)];
523
+ const b2 = i + 2 < len ? lookup[str.charCodeAt(i + 2)] : 0;
524
+ const b3 = i + 3 < len ? lookup[str.charCodeAt(i + 3)] : 0;
525
+ bytes[p] = b0 << 2 | b1 >> 4;
526
+ p += 1;
527
+ if (i + 2 < len) {
528
+ bytes[p] = (b1 & 15) << 4 | b2 >> 2;
529
+ p += 1;
530
+ }
531
+ if (i + 3 < len) {
532
+ bytes[p] = (b2 & 3) << 6 | b3;
533
+ p += 1;
534
+ }
535
+ }
536
+ return bytes;
537
+ }
538
+ function base64Encode(bytes) {
539
+ let result = "";
540
+ const len = bytes.length;
541
+ for (let i = 0; i < len; i += 3) {
542
+ const b0 = bytes[i];
543
+ const b1 = i + 1 < len ? bytes[i + 1] : 0;
544
+ const b2 = i + 2 < len ? bytes[i + 2] : 0;
545
+ result += B64_CHARS[b0 >> 2];
546
+ result += B64_CHARS[(b0 & 3) << 4 | b1 >> 4];
547
+ result += i + 1 < len ? B64_CHARS[(b1 & 15) << 2 | b2 >> 6] : "=";
548
+ result += i + 2 < len ? B64_CHARS[b2 & 63] : "=";
549
+ }
550
+ return result;
551
+ }
552
+ async function writeToAsyncStorage(key, data) {
553
+ try {
554
+ const AsyncStorage = await loadAsyncStorage();
555
+ if (!AsyncStorage) return;
556
+ const encoded = base64Encode(data);
557
+ await AsyncStorage.setItem(key, encoded);
558
+ } catch {}
559
+ }
560
+ async function deleteFromAsyncStorage(key) {
561
+ try {
562
+ const AsyncStorage = await loadAsyncStorage();
563
+ if (!AsyncStorage) return;
564
+ await AsyncStorage.removeItem(key);
565
+ } catch {}
566
+ }
567
+ let _asyncStorage = void 0;
568
+ let _asyncStoragePromise = null;
569
+ async function loadAsyncStorage() {
570
+ if (_asyncStorage) return _asyncStorage;
571
+ if (!_asyncStoragePromise) _asyncStoragePromise = import("@react-native-async-storage/async-storage").then((mod) => {
572
+ _asyncStorage = mod.default ?? mod;
573
+ return _asyncStorage;
574
+ }).catch(() => null);
575
+ return _asyncStoragePromise;
576
+ }
577
+ function getLocale() {
578
+ try {
579
+ const { Platform, NativeModules } = require("react-native");
580
+ if (Platform.OS === "ios") return NativeModules.SettingsManager?.settings?.AppleLocale ?? NativeModules.SettingsManager?.settings?.AppleLanguages?.[0] ?? "en-US";
581
+ if (Platform.OS === "android") return NativeModules.I18nManager?.localeIdentifier ?? "en-US";
582
+ } catch {}
583
+ return "en-US";
584
+ }
585
+ const INSTALL_ID_KEY = "layers_install_id";
586
+ async function getOrSetInstallId() {
587
+ try {
588
+ const AsyncStorage = await loadAsyncStorage();
589
+ if (!AsyncStorage) return generateUUID();
590
+ const existing = await AsyncStorage.getItem(INSTALL_ID_KEY);
591
+ if (existing) return existing;
592
+ const newId = generateUUID();
593
+ await AsyncStorage.setItem(INSTALL_ID_KEY, newId);
594
+ return newId;
595
+ } catch {
596
+ return generateUUID();
597
+ }
598
+ }
599
+ function generateUUID() {
600
+ if (typeof crypto !== "undefined" && crypto.randomUUID) return crypto.randomUUID();
601
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
602
+ const r = Math.random() * 16 | 0;
603
+ return (c === "x" ? r : r & 3 | 8).toString(16);
604
+ });
605
+ }
606
+ const CLIPBOARD_CHECKED_KEY = "@layers/clipboard_checked";
607
+ async function readClipboardAttribution() {
608
+ try {
609
+ const { Platform } = require("react-native");
610
+ if (Platform.OS !== "ios") return null;
611
+ } catch {
612
+ return null;
613
+ }
614
+ try {
615
+ const AS = await loadAsyncStorage();
616
+ if (AS) {
617
+ if (await AS.getItem(CLIPBOARD_CHECKED_KEY) === "true") return null;
618
+ }
619
+ } catch {}
620
+ let text = null;
621
+ try {
622
+ const Clipboard = await import("@react-native-clipboard/clipboard").then((m) => m.default).catch(() => null);
623
+ if (Clipboard) text = await Clipboard.getString();
624
+ else {
625
+ const { Clipboard: RNClipboard } = require("react-native");
626
+ if (RNClipboard) text = await RNClipboard.getString();
627
+ }
628
+ } catch {}
629
+ try {
630
+ const AS = await loadAsyncStorage();
631
+ if (AS) await AS.setItem(CLIPBOARD_CHECKED_KEY, "true");
632
+ } catch {}
633
+ if (!text) return null;
634
+ const match = text.match(/https?:\/\/(in\.layers\.com|link\.layers\.com)\/c\/([^?\s]+)/);
635
+ if (!match) return null;
636
+ return {
637
+ clickUrl: text,
638
+ clickId: match[2]
639
+ };
640
+ }
641
+ /**
642
+ * Attempt to read the host app version from platform-specific APIs.
643
+ * On Android, reads from PackageInfo via Platform.constants or a native module.
644
+ * On iOS, reads from the LayersDeviceInfo native module which can access the Info.plist.
645
+ */
646
+ async function getAppVersion(Platform, NativeModules) {
647
+ try {
648
+ if (Platform.OS === "android") {
649
+ const mod = NativeModules.LayersDeviceInfo;
650
+ if (mod?.getAppVersion) {
651
+ const version = await mod.getAppVersion();
652
+ if (version) return version;
653
+ }
654
+ }
655
+ if (Platform.OS === "ios") {
656
+ const mod = NativeModules.LayersDeviceInfo;
657
+ if (mod?.getAppVersion) {
658
+ const version = await mod.getAppVersion();
659
+ if (version) return version;
660
+ }
661
+ }
662
+ } catch {}
663
+ }
664
+ /**
665
+ * Fetch the Google Advertising ID (GAID) on Android via NativeModules.
666
+ * Returns null on iOS or when the native module is not available.
667
+ */
668
+ async function getGoogleAdvertisingId() {
669
+ try {
670
+ const { NativeModules, Platform } = require("react-native");
671
+ if (Platform.OS !== "android") return null;
672
+ const mod = NativeModules.LayersAdvertisingId;
673
+ if (!mod?.getAdvertisingInfo) return null;
674
+ const info = await mod.getAdvertisingInfo();
675
+ if (!info || !info.id || info.id === "00000000-0000-0000-0000-000000000000") return null;
676
+ return info;
677
+ } catch {
678
+ return null;
679
+ }
680
+ }
681
+ /**
682
+ * Request the AdServices attribution token on iOS 14.3+.
683
+ * Uses the LayersAdServices native module which calls AAAttribution.attributionToken().
684
+ * Does NOT require ATT consent.
685
+ * Returns null on Android or when the native module is not available.
686
+ */
687
+ async function getAdServicesToken() {
688
+ try {
689
+ const { NativeModules, Platform } = require("react-native");
690
+ if (Platform.OS !== "ios") return null;
691
+ const mod = NativeModules.LayersAdServices;
692
+ if (!mod?.getAttributionToken) return null;
693
+ return await mod.getAttributionToken();
694
+ } catch {
695
+ return null;
696
+ }
697
+ }
698
+ /**
699
+ * Fetch the Google Play install referrer on Android via NativeModules.
700
+ * Requires the `com.android.installreferrer` library on the native side.
701
+ * Returns null on iOS or when the native module is not available.
702
+ */
703
+ async function getInstallReferrer() {
704
+ try {
705
+ const { NativeModules, Platform } = require("react-native");
706
+ if (Platform.OS !== "android") return null;
707
+ const mod = NativeModules.LayersInstallReferrer;
708
+ if (!mod?.getInstallReferrer) return null;
709
+ const data = await mod.getInstallReferrer();
710
+ if (!data || !data.referrerUrl) return null;
711
+ return data;
712
+ } catch {
713
+ return null;
714
+ }
715
+ }
716
+ function setupDeepLinkListener(onDeepLink) {
717
+ try {
718
+ const { Linking } = require("react-native");
719
+ const handler = (event) => {
720
+ const parsed = parseDeepLink(event.url);
721
+ if (parsed) onDeepLink(parsed);
722
+ };
723
+ const subscription = Linking.addEventListener("url", handler);
724
+ Linking.getInitialURL().then((url) => {
725
+ if (url) {
726
+ const parsed = parseDeepLink(url);
727
+ if (parsed) onDeepLink(parsed);
728
+ }
729
+ });
730
+ return () => {
731
+ if (subscription?.remove) subscription.remove();
732
+ };
733
+ } catch {
734
+ return () => {};
735
+ }
736
+ }
737
+ function parseDeepLink(url) {
738
+ try {
739
+ const parsed = new URL(url);
740
+ const params = {};
741
+ parsed.searchParams.forEach((value, key) => {
742
+ params[key] = value;
743
+ });
744
+ return {
745
+ url,
746
+ scheme: parsed.protocol.replace(":", ""),
747
+ host: parsed.hostname,
748
+ path: parsed.pathname,
749
+ queryParams: params,
750
+ timestamp: Date.now()
751
+ };
752
+ } catch {
753
+ return null;
754
+ }
755
+ }
756
+ function useLayersExpoRouterTracking(layersInstance, usePathname, useGlobalSearchParams) {
757
+ const { useEffect } = require("react");
758
+ const pathname = usePathname();
759
+ const params = useGlobalSearchParams();
760
+ useEffect(() => {
761
+ if (pathname) {
762
+ const properties = {};
763
+ Object.entries(params).forEach(([key, value]) => {
764
+ properties[key] = Array.isArray(value) ? value.join(",") : value;
765
+ });
766
+ layersInstance.screen(pathname, properties);
767
+ }
768
+ }, [pathname, JSON.stringify(params)]);
769
+ }
770
+
771
+ //#endregion
772
+ Object.defineProperty(exports, 'LayersReactNative', {
773
+ enumerable: true,
774
+ get: function () {
775
+ return LayersReactNative;
776
+ }
777
+ });
778
+ Object.defineProperty(exports, 'getAdServicesToken', {
779
+ enumerable: true,
780
+ get: function () {
781
+ return getAdServicesToken;
782
+ }
783
+ });
784
+ Object.defineProperty(exports, 'getGoogleAdvertisingId', {
785
+ enumerable: true,
786
+ get: function () {
787
+ return getGoogleAdvertisingId;
788
+ }
789
+ });
790
+ Object.defineProperty(exports, 'getInstallReferrer', {
791
+ enumerable: true,
792
+ get: function () {
793
+ return getInstallReferrer;
794
+ }
795
+ });
796
+ Object.defineProperty(exports, 'getOrSetInstallId', {
797
+ enumerable: true,
798
+ get: function () {
799
+ return getOrSetInstallId;
800
+ }
801
+ });
802
+ Object.defineProperty(exports, 'parseDeepLink', {
803
+ enumerable: true,
804
+ get: function () {
805
+ return parseDeepLink;
806
+ }
807
+ });
808
+ Object.defineProperty(exports, 'readClipboardAttribution', {
809
+ enumerable: true,
810
+ get: function () {
811
+ return readClipboardAttribution;
812
+ }
813
+ });
814
+ Object.defineProperty(exports, 'setupDeepLinkListener', {
815
+ enumerable: true,
816
+ get: function () {
817
+ return setupDeepLinkListener;
818
+ }
819
+ });
820
+ Object.defineProperty(exports, 'useLayersExpoRouterTracking', {
821
+ enumerable: true,
822
+ get: function () {
823
+ return useLayersExpoRouterTracking;
824
+ }
825
+ });