@layers/react-native 2.2.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/android/build.gradle +62 -0
  2. package/android/src/main/AndroidManifest.xml +2 -0
  3. package/android/src/main/java/io/layers/sdk/reactnative/LayersAdvertisingIdModule.java +70 -0
  4. package/android/src/main/java/io/layers/sdk/reactnative/LayersDeviceInfoModule.java +54 -0
  5. package/android/src/main/java/io/layers/sdk/reactnative/LayersInstallReferrerModule.java +116 -0
  6. package/android/src/main/java/io/layers/sdk/reactnative/LayersReactNativePackage.java +36 -0
  7. package/dist/att-BDPyE-Gs.d.mts.map +1 -1
  8. package/dist/debug-overlay.d.mts +3 -3
  9. package/dist/debug-overlay.d.mts.map +1 -1
  10. package/dist/debug-overlay.d.ts +3 -3
  11. package/dist/debug-overlay.d.ts.map +1 -1
  12. package/dist/debug-overlay.js +18 -18
  13. package/dist/debug-overlay.mjs +18 -18
  14. package/dist/debug-overlay.mjs.map +1 -1
  15. package/dist/{index-BlYXUV-h.d.mts → index-BqcbQZEP.d.mts} +323 -47
  16. package/dist/index-BqcbQZEP.d.mts.map +1 -0
  17. package/dist/{index-BaaQSCs5.d.ts → index-fU6euPnq.d.ts} +323 -47
  18. package/dist/index-fU6euPnq.d.ts.map +1 -0
  19. package/dist/index.d.mts +2 -2
  20. package/dist/index.d.ts +2 -2
  21. package/dist/index.js +54 -1
  22. package/dist/index.mjs +2 -2
  23. package/dist/react.d.mts +1 -1
  24. package/dist/react.d.ts +1 -1
  25. package/dist/react.js +1 -1
  26. package/dist/react.mjs +1 -1
  27. package/dist/{src-8aNaNJz3.mjs → src-BNoj1E-e.mjs} +677 -90
  28. package/dist/src-BNoj1E-e.mjs.map +1 -0
  29. package/dist/{src-CP6aZ_iI.js → src-ym3bM4JE.js} +704 -87
  30. package/ios/LayersAdServices.m +8 -0
  31. package/ios/LayersAdServices.swift +41 -0
  32. package/ios/LayersDeviceInfo.m +14 -0
  33. package/ios/LayersDeviceInfo.swift +53 -0
  34. package/ios/LayersSKAN.m +45 -0
  35. package/ios/LayersSKAN.swift +188 -0
  36. package/ios/LayersSKANCompat.h +22 -0
  37. package/ios/LayersSKANCompat.m +118 -0
  38. package/layers-react-native.podspec +34 -0
  39. package/package.json +6 -3
  40. package/dist/index-BaaQSCs5.d.ts.map +0 -1
  41. package/dist/index-BlYXUV-h.d.mts.map +0 -1
  42. package/dist/src-8aNaNJz3.mjs.map +0 -1
@@ -1,7 +1,7 @@
1
1
  import { t as __require } from "./chunk-COTuXS2J.mjs";
2
2
  import { a as requestTrackingAuthorization, n as getAdvertisingId, r as getVendorId } from "./att-CnlG_CuV.mjs";
3
3
  import { t as SKANManager } from "./skan-CoG9kfO3.mjs";
4
- import { FetchHttpClient, LayersCore, LayersError as LayersError$1, MemoryPersistence } from "@layers/core-wasm";
4
+ import { FetchHttpClient, LayersCore, LayersError as LayersError$1, LayersEvent, MemoryPersistence, addToCartEvent as buildAddToCartEvent, beginCheckoutEvent as buildBeginCheckoutEvent, purchaseEvent as buildPurchaseEvent, refundEvent as buildRefundEvent, startTrialEvent as buildStartTrialEvent, subscribeEvent as buildSubscribeEvent, viewItemEvent as buildViewItemEvent } from "@layers/core-wasm";
5
5
 
6
6
  //#region src/standard-events.ts
7
7
  /**
@@ -215,27 +215,27 @@ function screenViewEvent(name, screenClass) {
215
215
  *
216
216
  * Superwall.instance.setDelegate({
217
217
  * handleSuperwallEvent(eventInfo) {
218
- * superwallOnEvent(layers, eventInfo);
218
+ * superwallOnEvent(sdk, eventInfo);
219
219
  * }
220
220
  * });
221
221
  * ```
222
222
  */
223
- function superwallOnEvent(layers, eventInfo) {
223
+ function superwallOnEvent(sdk, eventInfo) {
224
224
  try {
225
225
  const eventName = eventInfo.event.rawName ?? eventInfo.event.type ?? "unknown";
226
226
  const properties = { source: "superwall" };
227
227
  if (eventInfo.params) Object.assign(properties, eventInfo.params);
228
- layers.track(`superwall_${eventName}`, properties);
228
+ sdk.track(`superwall_${eventName}`, properties);
229
229
  } catch {}
230
230
  }
231
231
  /**
232
232
  * Track that a paywall was presented to the user.
233
233
  *
234
234
  * ```ts
235
- * superwallTrackPresentation(layers, paywallInfo);
235
+ * superwallTrackPresentation(sdk, paywallInfo);
236
236
  * ```
237
237
  */
238
- function superwallTrackPresentation(layers, paywallInfo) {
238
+ function superwallTrackPresentation(sdk, paywallInfo) {
239
239
  try {
240
240
  if (!paywallInfo) return;
241
241
  const properties = {
@@ -248,20 +248,20 @@ function superwallTrackPresentation(layers, paywallInfo) {
248
248
  id: paywallInfo.experiment.id,
249
249
  variant: paywallInfo.experiment.variantId
250
250
  };
251
- layers.track("paywall_show", properties);
251
+ sdk.track("paywall_show", properties);
252
252
  } catch {}
253
253
  }
254
254
  /**
255
255
  * Track that a paywall was dismissed.
256
256
  *
257
257
  * ```ts
258
- * superwallTrackDismiss(layers, paywallInfo);
258
+ * superwallTrackDismiss(sdk, paywallInfo);
259
259
  * ```
260
260
  */
261
- function superwallTrackDismiss(layers, paywallInfo) {
261
+ function superwallTrackDismiss(sdk, paywallInfo) {
262
262
  try {
263
263
  if (!paywallInfo) return;
264
- layers.track("paywall_dismiss", {
264
+ sdk.track("paywall_dismiss", {
265
265
  paywall_id: paywallInfo.identifier,
266
266
  source: "superwall"
267
267
  });
@@ -271,10 +271,10 @@ function superwallTrackDismiss(layers, paywallInfo) {
271
271
  * Track a purchase initiated from a Superwall paywall.
272
272
  *
273
273
  * ```ts
274
- * superwallTrackPurchase(layers, paywallInfo, product);
274
+ * superwallTrackPurchase(sdk, paywallInfo, product);
275
275
  * ```
276
276
  */
277
- function superwallTrackPurchase(layers, paywallInfo, product) {
277
+ function superwallTrackPurchase(sdk, paywallInfo, product) {
278
278
  try {
279
279
  const properties = {
280
280
  paywall_id: paywallInfo?.identifier ?? "unknown",
@@ -287,19 +287,19 @@ function superwallTrackPurchase(layers, paywallInfo, product) {
287
287
  const currency = product.currencyCode ?? product.currency;
288
288
  if (currency) properties.currency = currency;
289
289
  }
290
- layers.track("paywall_purchase", properties);
290
+ sdk.track("paywall_purchase", properties);
291
291
  } catch {}
292
292
  }
293
293
  /**
294
294
  * Track that a paywall was skipped (e.g. holdout, no rule match).
295
295
  *
296
296
  * ```ts
297
- * superwallTrackSkip(layers, paywallInfo, 'holdout');
297
+ * superwallTrackSkip(sdk, paywallInfo, 'holdout');
298
298
  * ```
299
299
  */
300
- function superwallTrackSkip(layers, paywallInfo, reason) {
300
+ function superwallTrackSkip(sdk, paywallInfo, reason) {
301
301
  try {
302
- layers.track("paywall_skip", {
302
+ sdk.track("paywall_skip", {
303
303
  paywall_id: paywallInfo?.identifier ?? "unknown",
304
304
  reason,
305
305
  source: "superwall"
@@ -311,16 +311,16 @@ function superwallTrackSkip(layers, paywallInfo, reason) {
311
311
  *
312
312
  * Pass the returned object to `Superwall.instance.setUserAttributes()`:
313
313
  * ```ts
314
- * const attrs = superwallUserAttributes(layers);
314
+ * const attrs = superwallUserAttributes(sdk);
315
315
  * Superwall.instance.setUserAttributes(attrs);
316
316
  * ```
317
317
  */
318
- function superwallUserAttributes(layers) {
318
+ function superwallUserAttributes(sdk) {
319
319
  const attrs = {};
320
320
  try {
321
- const sessionId = layers.getSessionId();
321
+ const sessionId = sdk.getSessionId();
322
322
  if (sessionId) attrs.layers_session_id = sessionId;
323
- const userId = layers.getAppUserId();
323
+ const userId = sdk.getAppUserId();
324
324
  if (userId) attrs.layers_user_id = userId;
325
325
  } catch {}
326
326
  return attrs;
@@ -334,7 +334,7 @@ function superwallUserAttributes(layers) {
334
334
  * ```ts
335
335
  * import { trackPurchase } from '@layers/react-native';
336
336
  *
337
- * trackPurchase(layers, {
337
+ * trackPurchase(sdk, {
338
338
  * productId: 'premium_monthly',
339
339
  * price: 9.99,
340
340
  * currency: 'USD',
@@ -342,7 +342,7 @@ function superwallUserAttributes(layers) {
342
342
  * });
343
343
  * ```
344
344
  */
345
- function trackPurchase(layers, params) {
345
+ function trackPurchase(sdk, params) {
346
346
  const quantity = params.quantity ?? 1;
347
347
  const props = {
348
348
  product_id: params.productId,
@@ -355,12 +355,12 @@ function trackPurchase(layers, params) {
355
355
  if (params.transactionId !== void 0) props.transaction_id = params.transactionId;
356
356
  if (params.isRestored !== void 0) props.is_restored = params.isRestored;
357
357
  if (params.store !== void 0) props.store = params.store;
358
- layers.track("purchase_success", props);
358
+ sdk.track("purchase_success", props);
359
359
  }
360
360
  /**
361
361
  * Track a failed purchase attempt.
362
362
  */
363
- function trackPurchaseFailed(layers, params) {
363
+ function trackPurchaseFailed(sdk, params) {
364
364
  const props = {
365
365
  product_id: params.productId,
366
366
  currency: params.currency,
@@ -368,7 +368,7 @@ function trackPurchaseFailed(layers, params) {
368
368
  ...params.properties
369
369
  };
370
370
  if (params.errorMessage !== void 0) props.error_message = params.errorMessage;
371
- layers.track("purchase_failed", props);
371
+ sdk.track("purchase_failed", props);
372
372
  }
373
373
  /**
374
374
  * Track a subscription purchase or renewal.
@@ -376,7 +376,7 @@ function trackPurchaseFailed(layers, params) {
376
376
  * ```ts
377
377
  * import { trackSubscription } from '@layers/react-native';
378
378
  *
379
- * trackSubscription(layers, {
379
+ * trackSubscription(sdk, {
380
380
  * productId: 'pro_annual',
381
381
  * price: 49.99,
382
382
  * currency: 'USD',
@@ -384,7 +384,7 @@ function trackPurchaseFailed(layers, params) {
384
384
  * });
385
385
  * ```
386
386
  */
387
- function trackSubscription(layers, params) {
387
+ function trackSubscription(sdk, params) {
388
388
  const props = {
389
389
  product_id: params.productId,
390
390
  price: params.price,
@@ -399,12 +399,12 @@ function trackSubscription(layers, params) {
399
399
  if (params.isTrial !== void 0) props.is_trial = params.isTrial;
400
400
  if (params.subscriptionGroupId !== void 0) props.subscription_group_id = params.subscriptionGroupId;
401
401
  if (params.originalTransactionId !== void 0) props.original_transaction_id = params.originalTransactionId;
402
- layers.track("subscribe", props);
402
+ sdk.track("subscribe", props);
403
403
  }
404
404
  /**
405
405
  * Track a completed order with multiple line items.
406
406
  */
407
- function trackOrder(layers, params) {
407
+ function trackOrder(sdk, params) {
408
408
  const currency = params.currency ?? "USD";
409
409
  let total = params.subtotal;
410
410
  if (params.tax !== void 0) total += params.tax;
@@ -424,12 +424,12 @@ function trackOrder(layers, params) {
424
424
  if (params.shipping !== void 0) props.shipping = params.shipping;
425
425
  if (params.discount !== void 0) props.discount = params.discount;
426
426
  if (params.couponCode !== void 0) props.coupon_code = params.couponCode;
427
- layers.track("purchase_success", props);
427
+ sdk.track("purchase_success", props);
428
428
  }
429
429
  /**
430
430
  * Track an item being added to the cart.
431
431
  */
432
- function trackAddToCart(layers, item, properties) {
432
+ function trackAddToCart(sdk, item, properties) {
433
433
  const quantity = item.quantity ?? 1;
434
434
  const props = {
435
435
  product_id: item.productId,
@@ -440,12 +440,12 @@ function trackAddToCart(layers, item, properties) {
440
440
  ...properties
441
441
  };
442
442
  if (item.category !== void 0) props.category = item.category;
443
- layers.track("add_to_cart", props);
443
+ sdk.track("add_to_cart", props);
444
444
  }
445
445
  /**
446
446
  * Track an item being removed from the cart.
447
447
  */
448
- function trackRemoveFromCart(layers, item, properties) {
448
+ function trackRemoveFromCart(sdk, item, properties) {
449
449
  const quantity = item.quantity ?? 1;
450
450
  const props = {
451
451
  product_id: item.productId,
@@ -455,12 +455,12 @@ function trackRemoveFromCart(layers, item, properties) {
455
455
  ...properties
456
456
  };
457
457
  if (item.category !== void 0) props.category = item.category;
458
- layers.track("remove_from_cart", props);
458
+ sdk.track("remove_from_cart", props);
459
459
  }
460
460
  /**
461
461
  * Track beginning the checkout flow.
462
462
  */
463
- function trackBeginCheckout(layers, items, currency = "USD", properties) {
463
+ function trackBeginCheckout(sdk, items, currency = "USD", properties) {
464
464
  const total = items.reduce((sum, item) => sum + item.price * (item.quantity ?? 1), 0);
465
465
  const props = {
466
466
  item_count: items.length,
@@ -469,12 +469,12 @@ function trackBeginCheckout(layers, items, currency = "USD", properties) {
469
469
  product_ids: items.map((i) => i.productId).join(","),
470
470
  ...properties
471
471
  };
472
- layers.track("begin_checkout", props);
472
+ sdk.track("begin_checkout", props);
473
473
  }
474
474
  /**
475
475
  * Track viewing a product detail page.
476
476
  */
477
- function trackViewProduct(layers, productId, name, price, currency = "USD", category, properties) {
477
+ function trackViewProduct(sdk, productId, name, price, currency = "USD", category, properties) {
478
478
  const props = {
479
479
  product_id: productId,
480
480
  product_name: name,
@@ -483,12 +483,12 @@ function trackViewProduct(layers, productId, name, price, currency = "USD", cate
483
483
  ...properties
484
484
  };
485
485
  if (category !== void 0) props.category = category;
486
- layers.track("view_item", props);
486
+ sdk.track("view_item", props);
487
487
  }
488
488
  /**
489
489
  * Track a refund.
490
490
  */
491
- function trackRefund(layers, params) {
491
+ function trackRefund(sdk, params) {
492
492
  const props = {
493
493
  transaction_id: params.transactionId,
494
494
  amount: params.amount,
@@ -496,7 +496,7 @@ function trackRefund(layers, params) {
496
496
  ...params.properties
497
497
  };
498
498
  if (params.reason !== void 0) props.reason = params.reason;
499
- layers.track("refund", props);
499
+ sdk.track("refund", props);
500
500
  }
501
501
 
502
502
  //#endregion
@@ -504,7 +504,7 @@ function trackRefund(layers, params) {
504
504
  let _isConnected = false;
505
505
  let _activeSubscriptions = /* @__PURE__ */ new Set();
506
506
  let _isInitialLoadDone = false;
507
- let _connectedLayers = null;
507
+ let _connectedSDK = null;
508
508
  /**
509
509
  * Connect Layers to your existing RevenueCat Purchases instance.
510
510
  *
@@ -516,16 +516,16 @@ let _connectedLayers = null;
516
516
  * import Purchases from 'react-native-purchases';
517
517
  * import { LayersReactNative, connectRevenueCat } from '@layers/react-native';
518
518
  *
519
- * const layers = new LayersReactNative();
519
+ * const sdk = new LayersReactNative();
520
520
  * await layers.init({ appId: 'your-app-id', environment: 'production' });
521
521
  *
522
522
  * connectRevenueCat({
523
- * layers,
523
+ * sdk,
524
524
  * purchases: Purchases,
525
525
  * });
526
526
  * ```
527
527
  *
528
- * @param config - Configuration including the Layers instance.
528
+ * @param config - Configuration including the SDK instance.
529
529
  * @param purchases - The RevenueCat Purchases instance (duck-typed to avoid hard dependency).
530
530
  */
531
531
  function connectRevenueCat(config, purchases) {
@@ -534,7 +534,7 @@ function connectRevenueCat(config, purchases) {
534
534
  if (!purchases) return;
535
535
  if (typeof purchases.addCustomerInfoUpdateListener !== "function") return;
536
536
  if (typeof purchases.getCustomerInfo !== "function") return;
537
- _connectedLayers = config.layers;
537
+ _connectedSDK = config.sdk;
538
538
  purchases.addCustomerInfoUpdateListener((info) => {
539
539
  handleCustomerInfoUpdate(config, info, false);
540
540
  });
@@ -551,10 +551,10 @@ function connectRevenueCat(config, purchases) {
551
551
  * ```ts
552
552
  * const offerings = await Purchases.getOfferings();
553
553
  * const pkg = offerings.current?.availablePackages[0];
554
- * if (pkg) trackRevenueCatPurchase(layers, pkg);
554
+ * if (pkg) trackRevenueCatPurchase(sdk, pkg);
555
555
  * ```
556
556
  */
557
- function trackRevenueCatPurchase(layers, rcPackage, store) {
557
+ function trackRevenueCatPurchase(sdk, rcPackage, store) {
558
558
  try {
559
559
  if (!rcPackage?.product) return;
560
560
  let resolvedStore = store ?? "app_store";
@@ -562,7 +562,7 @@ function trackRevenueCatPurchase(layers, rcPackage, store) {
562
562
  const { Platform } = __require("react-native");
563
563
  resolvedStore = Platform.OS === "ios" ? "app_store" : "play_store";
564
564
  } catch {}
565
- layers.track("purchase_success", {
565
+ sdk.track("purchase_success", {
566
566
  product_id: rcPackage.product.identifier ?? "",
567
567
  price: rcPackage.product.price ?? 0,
568
568
  currency: rcPackage.product.currencyCode ?? "USD",
@@ -577,11 +577,11 @@ function trackRevenueCatPurchase(layers, rcPackage, store) {
577
577
  * This is called automatically when using `connectRevenueCat()`, but can also
578
578
  * be called manually if needed.
579
579
  */
580
- function syncRevenueCatAttributes(layers, customerInfo) {
580
+ function syncRevenueCatAttributes(sdk, customerInfo) {
581
581
  try {
582
582
  const userProps = { is_subscriber: Array.isArray(customerInfo.activeSubscriptions) && customerInfo.activeSubscriptions.length > 0 };
583
583
  if (customerInfo.originalAppUserId) userProps.revenuecat_original_app_user_id = customerInfo.originalAppUserId;
584
- layers.setUserProperties(userProps);
584
+ sdk.setUserProperties(userProps);
585
585
  } catch {}
586
586
  }
587
587
  /**
@@ -591,7 +591,7 @@ function resetRevenueCatForTesting() {
591
591
  _isConnected = false;
592
592
  _activeSubscriptions = /* @__PURE__ */ new Set();
593
593
  _isInitialLoadDone = false;
594
- _connectedLayers = null;
594
+ _connectedSDK = null;
595
595
  }
596
596
  /**
597
597
  * Whether the RevenueCat integration is currently connected.
@@ -603,10 +603,10 @@ function handleCustomerInfoUpdate(config, info, isInitialLoad) {
603
603
  try {
604
604
  const currentSubs = new Set(Array.isArray(info.activeSubscriptions) ? info.activeSubscriptions : []);
605
605
  if (isInitialLoad && _isInitialLoadDone) return;
606
- if (!isInitialLoad && _isInitialLoadDone && _connectedLayers) {
606
+ if (!isInitialLoad && _isInitialLoadDone && _connectedSDK) {
607
607
  for (const subId of currentSubs) if (!_activeSubscriptions.has(subId)) {
608
608
  if (config.onSubscriptionStart !== null) if (config.onSubscriptionStart) config.onSubscriptionStart(subId);
609
- else _connectedLayers.track("subscription_start", {
609
+ else _connectedSDK.track("subscription_start", {
610
610
  product_id: subId,
611
611
  source: "revenuecat"
612
612
  });
@@ -614,7 +614,7 @@ function handleCustomerInfoUpdate(config, info, isInitialLoad) {
614
614
  }
615
615
  _activeSubscriptions = currentSubs;
616
616
  _isInitialLoadDone = true;
617
- if (_connectedLayers) syncRevenueCatAttributes(_connectedLayers, info);
617
+ if (_connectedSDK) syncRevenueCatAttributes(_connectedSDK, info);
618
618
  } catch {}
619
619
  }
620
620
 
@@ -641,21 +641,21 @@ const BACKGROUND_FLUSH_MIN_INTERVAL_MINUTES = 15;
641
641
  * will flush any queued events via the Layers SDK. It is safe to call even
642
642
  * if the SDK is not initialized (it will silently no-op).
643
643
  *
644
- * @param getLayers - A getter that returns the current LayersReactNative
644
+ * @param getSDK - A getter that returns the current LayersReactNative
645
645
  * instance, or `null` if the SDK is not yet initialized.
646
646
  * @returns An async handler suitable for use with background task libraries.
647
647
  *
648
648
  * @example
649
649
  * ```typescript
650
- * const handler = createBackgroundFlushHandler(() => myLayersInstance);
650
+ * const handler = createBackgroundFlushHandler(() => mySDKInstance);
651
651
  * ```
652
652
  */
653
- function createBackgroundFlushHandler(getLayers) {
653
+ function createBackgroundFlushHandler(getSDK) {
654
654
  return async () => {
655
- const layers = getLayers();
656
- if (!layers) return { success: false };
655
+ const sdk = getSDK();
656
+ if (!sdk) return { success: false };
657
657
  try {
658
- await layers.flush();
658
+ await sdk.flush();
659
659
  return { success: true };
660
660
  } catch {
661
661
  return { success: false };
@@ -669,7 +669,7 @@ function createBackgroundFlushHandler(getLayers) {
669
669
  * `expo-task-manager` requires tasks to be defined before the app mounts.
670
670
  *
671
671
  * @param taskManager - The `expo-task-manager` module (import * as TaskManager from 'expo-task-manager').
672
- * @param getLayers - A getter that returns the current LayersReactNative
672
+ * @param getSDK - A getter that returns the current LayersReactNative
673
673
  * instance, or `null` if the SDK is not yet initialized.
674
674
  *
675
675
  * @example
@@ -677,21 +677,236 @@ function createBackgroundFlushHandler(getLayers) {
677
677
  * import * as TaskManager from 'expo-task-manager';
678
678
  * import { registerExpoBackgroundFlush } from '@layers/expo';
679
679
  *
680
- * let layers: LayersReactNative | null = null;
681
- * registerExpoBackgroundFlush(TaskManager, () => layers);
680
+ * let sdk: LayersReactNative | null = null;
681
+ * registerExpoBackgroundFlush(TaskManager, () => sdk);
682
682
  *
683
683
  * // Later, in your app initialization:
684
- * layers = new LayersReactNative({ appId: '...', environment: 'production' });
684
+ * sdk = new LayersReactNative({ appId: '...', environment: 'production' });
685
685
  * await layers.init();
686
686
  * ```
687
687
  */
688
- function registerExpoBackgroundFlush(taskManager, getLayers) {
689
- const handler = createBackgroundFlushHandler(getLayers);
688
+ function registerExpoBackgroundFlush(taskManager, getSDK) {
689
+ const handler = createBackgroundFlushHandler(getSDK);
690
690
  taskManager.defineTask(BACKGROUND_FLUSH_TASK_NAME, async () => {
691
691
  await handler();
692
692
  });
693
693
  }
694
694
 
695
+ //#endregion
696
+ //#region src/navigation-tracking.ts
697
+ /**
698
+ * Build a stateful listener that emits `$screen_view` whenever the active
699
+ * route changes. The returned function should be passed to React
700
+ * Navigation's `onStateChange` prop or `navigationRef.addListener('state',
701
+ * cb)`. It returns nothing — the SDK records the event side-effecting.
702
+ *
703
+ * The listener:
704
+ * - resolves the deepest active route via `getActiveRouteName()`
705
+ * semantics so nested stack/tab navigators correctly report the
706
+ * leaf screen
707
+ * - de-dupes consecutive identical names (some RN versions emit the
708
+ * same state twice on re-renders)
709
+ * - attaches route params + previous screen on the screen event
710
+ */
711
+ function createNavigationListener(sdk) {
712
+ let previousScreen = null;
713
+ return function onStateChange(state) {
714
+ if (!state) return;
715
+ const currentRoute = resolveActiveRoute(state);
716
+ if (!currentRoute) return;
717
+ if (currentRoute.name === previousScreen) return;
718
+ const properties = {
719
+ ...currentRoute.params ?? {},
720
+ screen_name: currentRoute.name
721
+ };
722
+ if (previousScreen) properties.previous_screen_name = previousScreen;
723
+ try {
724
+ sdk.screen(currentRoute.name, properties);
725
+ if (sdk.enableDebug) console.log(`[Layers] $screen_view: ${currentRoute.name}`);
726
+ } catch {}
727
+ previousScreen = currentRoute.name;
728
+ };
729
+ }
730
+ /**
731
+ * React hook that subscribes to a React Navigation NavigationContainerRef
732
+ * and emits a `$screen_view` for each route change. Pass the SDK instance
733
+ * and the same `navigationRef` you give to `<NavigationContainer ref={...}>`.
734
+ *
735
+ * ```tsx
736
+ * import { createNavigationContainerRef } from '@react-navigation/native';
737
+ * const navigationRef = createNavigationContainerRef();
738
+ *
739
+ * function Root() {
740
+ * useLayersNavigationTracking(layers, navigationRef);
741
+ * return <NavigationContainer ref={navigationRef}>...</NavigationContainer>;
742
+ * }
743
+ * ```
744
+ *
745
+ * The hook is implemented via a lazy `require('react')` so it only fails
746
+ * if React itself is unavailable — consumers without React Navigation can
747
+ * still call it and it will silently no-op.
748
+ */
749
+ function useLayersNavigationTracking(sdk, navigationRef) {
750
+ let useEffect = null;
751
+ try {
752
+ useEffect = __require("react").useEffect;
753
+ } catch {
754
+ return;
755
+ }
756
+ if (!useEffect) return;
757
+ useEffect(() => {
758
+ if (!navigationRef?.addListener) return void 0;
759
+ const listener = createNavigationListener(sdk);
760
+ const unsubscribe = navigationRef.addListener("state", (event) => {
761
+ listener((event?.data)?.state ?? event);
762
+ });
763
+ return () => {
764
+ try {
765
+ if (typeof unsubscribe === "function") unsubscribe();
766
+ } catch {}
767
+ };
768
+ }, [sdk, navigationRef]);
769
+ }
770
+ /**
771
+ * Walk a NavigationState tree and return the active leaf route. Mirrors
772
+ * React Navigation's own `getActiveRouteName()` helper without taking a
773
+ * peer-dep on `@react-navigation/native`.
774
+ *
775
+ * Exported for testing.
776
+ * @internal
777
+ */
778
+ function resolveActiveRoute(state) {
779
+ if (!state || !Array.isArray(state.routes) || state.routes.length === 0) return null;
780
+ const idx = typeof state.index === "number" ? state.index : state.routes.length - 1;
781
+ const route = state.routes[idx];
782
+ if (!route) return null;
783
+ if (route.state) {
784
+ const inner = resolveActiveRoute(route.state);
785
+ if (inner) return inner;
786
+ }
787
+ return {
788
+ name: route.name,
789
+ ...route.params != null && { params: route.params }
790
+ };
791
+ }
792
+
793
+ //#endregion
794
+ //#region src/surveys.ts
795
+ const SHOW_HISTORY_STORAGE_KEY = "layers:surveys:show-history";
796
+ /**
797
+ * Public surveys API exposed via `LayersReactNative.surveys`.
798
+ *
799
+ * Render the actual chrome by mounting `<LayersSurveyModal />` from
800
+ * `@layers/react-native/surveys-component` somewhere in your app tree
801
+ * and binding it to the eligible survey via `surveys.getActive()`.
802
+ */
803
+ var SurveysModule = class {
804
+ hydrated = false;
805
+ listeners = /* @__PURE__ */ new Set();
806
+ constructor(core, options = {}) {
807
+ this.core = core;
808
+ this.options = options;
809
+ if (this.options.persistence) this.hydrate();
810
+ else this.hydrated = true;
811
+ }
812
+ get enabled() {
813
+ return this.options.enabled !== false;
814
+ }
815
+ knownIds() {
816
+ return this.core.knownSurveyIds();
817
+ }
818
+ /**
819
+ * Return surveys currently eligible to show. Builds the targeting context
820
+ * from caller-supplied person properties + feature flag values. URL
821
+ * targeting is web-only so it's omitted.
822
+ */
823
+ getActive() {
824
+ if (!this.enabled) return [];
825
+ return this.core.getActiveSurveys(this.buildContext());
826
+ }
827
+ /** Mark a survey as shown — emits `survey shown` auto-event. */
828
+ markShown(surveyId) {
829
+ this.core.markSurveyShown(surveyId);
830
+ this.persistShowHistory();
831
+ this.notify();
832
+ }
833
+ /** Mark a survey as dismissed — emits `survey dismissed` auto-event. */
834
+ markDismissed(surveyId) {
835
+ this.core.markSurveyDismissed(surveyId);
836
+ this.notify();
837
+ }
838
+ /** Submit a survey response — emits `survey sent` auto-event. */
839
+ submit(surveyId, response) {
840
+ this.core.submitSurveyResponse(surveyId, response);
841
+ this.notify();
842
+ }
843
+ /**
844
+ * Subscribe to changes in the eligible-surveys list. The callback fires
845
+ * after every show/dismiss/submit and after the show-history is hydrated
846
+ * from persistence on init.
847
+ */
848
+ subscribe(listener) {
849
+ this.listeners.add(listener);
850
+ try {
851
+ listener(this.getActive());
852
+ } catch {}
853
+ return () => {
854
+ this.listeners.delete(listener);
855
+ };
856
+ }
857
+ configure(patch) {
858
+ Object.assign(this.options, patch);
859
+ this.notify();
860
+ }
861
+ buildContext() {
862
+ const featureFlagValues = {};
863
+ const resolver = this.options.resolveFeatureFlag;
864
+ if (resolver) for (const def of this.allDefinitions()) {
865
+ const flag = def?.targeting?.feature_flag;
866
+ if (flag) {
867
+ const v = resolver(flag);
868
+ if (typeof v === "boolean") featureFlagValues[flag] = v;
869
+ else if (typeof v === "string") featureFlagValues[flag] = v.length > 0 && v !== "false";
870
+ }
871
+ }
872
+ return {
873
+ person_properties: this.options.personProperties ?? {},
874
+ feature_flag_values: featureFlagValues
875
+ };
876
+ }
877
+ allDefinitions() {
878
+ try {
879
+ return JSON.parse(this.core.surveyDefinitionsJson());
880
+ } catch {
881
+ return [];
882
+ }
883
+ }
884
+ async hydrate() {
885
+ if (this.hydrated) return;
886
+ try {
887
+ const raw = await this.options.persistence?.read(SHOW_HISTORY_STORAGE_KEY);
888
+ if (raw) this.core.seedSurveyShowHistory(raw);
889
+ } catch {} finally {
890
+ this.hydrated = true;
891
+ this.notify();
892
+ }
893
+ }
894
+ async persistShowHistory() {
895
+ if (!this.options.persistence) return;
896
+ try {
897
+ const json = this.core.surveyShowHistoryJson();
898
+ await this.options.persistence.write(SHOW_HISTORY_STORAGE_KEY, json);
899
+ } catch {}
900
+ }
901
+ notify() {
902
+ if (this.listeners.size === 0) return;
903
+ const actives = this.getActive();
904
+ for (const l of this.listeners) try {
905
+ l(actives);
906
+ } catch {}
907
+ }
908
+ };
909
+
695
910
  //#endregion
696
911
  //#region src/index.ts
697
912
  const SDK_VERSION = typeof __LAYERS_RN_VERSION__ !== "undefined" ? __LAYERS_RN_VERSION__ : "0.1.0";
@@ -715,6 +930,7 @@ var LayersReactNative = class LayersReactNative {
715
930
  static CONFIG_POLL_INTERVAL_MS = 3e5;
716
931
  _adServicesToken = null;
717
932
  _installReferrer = null;
933
+ _installReferrerParams = null;
718
934
  _hadPriorSdkState = false;
719
935
  _attributionDeeplinkId = null;
720
936
  _attributionGclid = null;
@@ -743,7 +959,8 @@ var LayersReactNative = class LayersReactNative {
743
959
  ...config.flushIntervalMs != null && { flushIntervalMs: config.flushIntervalMs },
744
960
  ...config.flushThreshold != null && { flushThreshold: config.flushThreshold },
745
961
  ...config.maxQueueSize != null && { maxQueueSize: config.maxQueueSize },
746
- sdkVersion: `react-native/${SDK_VERSION}`
962
+ sdkVersion: `react-native/${SDK_VERSION}`,
963
+ ...config.bootstrap != null && { bootstrap: config.bootstrap }
747
964
  },
748
965
  httpClient,
749
966
  persistence: new MemoryPersistence()
@@ -765,21 +982,23 @@ var LayersReactNative = class LayersReactNative {
765
982
  environment: this.config.environment,
766
983
  ...this.config.baseUrl != null && { baseUrl: this.config.baseUrl },
767
984
  ...this.config.enableDebug != null && { enableDebug: this.config.enableDebug },
985
+ ...this.config.debug != null && { debug: this.config.debug },
768
986
  ...this.config.flushIntervalMs != null && { flushIntervalMs: this.config.flushIntervalMs },
769
987
  ...this.config.flushThreshold != null && { flushThreshold: this.config.flushThreshold },
770
988
  ...this.config.maxQueueSize != null && { maxQueueSize: this.config.maxQueueSize },
771
- sdkVersion: `react-native/${SDK_VERSION}`
989
+ sdkVersion: `react-native/${SDK_VERSION}`,
990
+ ...this.config.bootstrap != null && { bootstrap: this.config.bootstrap }
772
991
  },
773
992
  httpClient,
774
993
  persistence
775
994
  });
776
995
  if (this.appUserId) this.core.identify(this.appUserId);
777
996
  } catch {}
997
+ await this.restoreAttributionData();
778
998
  await this.initializeDeviceInfo();
779
999
  this.setupAppStateListener();
780
1000
  this.setupNetInfoListener();
781
1001
  const mainThreadDurationMs = Date.now() - initStartTime;
782
- await this.restoreAttributionData();
783
1002
  await this.core.fetchRemoteConfig().catch(() => {});
784
1003
  await this.configureSkanFromRemoteConfig();
785
1004
  this.startConfigPolling();
@@ -806,6 +1025,10 @@ var LayersReactNative = class LayersReactNative {
806
1025
  } catch {}
807
1026
  const isFirstLaunch = await shouldTreatAsNewInstall(isFirstLaunchByFlag, this._hadPriorSdkState, this.enableDebug);
808
1027
  appOpenProps.is_first_launch = isFirstLaunch;
1028
+ let hasAttribution = this._attributionFbclid != null || this._attributionGclid != null || this._attributionTtclid != null || this._attributionMsclkid != null;
1029
+ if (isFirstLaunch && !hasAttribution) try {
1030
+ await this.resolveClickFromFingerprint();
1031
+ } catch {}
809
1032
  if (isFirstLaunch) try {
810
1033
  const AsyncStorage = await loadAsyncStorage();
811
1034
  if (AsyncStorage) await AsyncStorage.setItem(FIRST_LAUNCH_TRACKED_KEY, "true");
@@ -820,8 +1043,25 @@ var LayersReactNative = class LayersReactNative {
820
1043
  if (this._installReferrer.referrerClickTimestamp) appOpenProps.install_referrer_click_timestamp = this._installReferrer.referrerClickTimestamp;
821
1044
  if (this._installReferrer.installBeginTimestamp) appOpenProps.install_referrer_install_timestamp = this._installReferrer.installBeginTimestamp;
822
1045
  }
1046
+ if (this._installReferrerParams) {
1047
+ for (const [key, value] of Object.entries(this._installReferrerParams)) if (appOpenProps[key] === void 0) appOpenProps[key] = value;
1048
+ }
823
1049
  if (isFirstLaunch) this.track("app_install", appOpenProps);
824
1050
  this.track("app_open", appOpenProps);
1051
+ if (this.config.autoTrackAppUpdate !== false) try {
1052
+ const currentVersion = this.core.getDeviceContext().appVersion ?? appOpenProps.app_version;
1053
+ if (currentVersion && typeof currentVersion === "string") {
1054
+ const AsyncStorage = await loadAsyncStorage();
1055
+ if (AsyncStorage) {
1056
+ const previousVersion = await AsyncStorage.getItem(LAST_APP_VERSION_KEY);
1057
+ if (previousVersion && previousVersion !== currentVersion) this.track("$app_update", {
1058
+ previous_version: previousVersion,
1059
+ current_version: currentVersion
1060
+ });
1061
+ await AsyncStorage.setItem(LAST_APP_VERSION_KEY, currentVersion);
1062
+ }
1063
+ }
1064
+ } catch {}
825
1065
  }
826
1066
  if (this.config.autoTrackDeepLinks !== false) this.setupDeepLinkAutoTracking();
827
1067
  this._isInitialized = true;
@@ -871,6 +1111,193 @@ var LayersReactNative = class LayersReactNative {
871
1111
  async setConsent(consent) {
872
1112
  this.core.setConsent(consent);
873
1113
  }
1114
+ /** Evaluate a feature flag. Emits `$feature_flag_called` (deduped per session). */
1115
+ getFeatureFlag(flagKey) {
1116
+ return this.core.getFeatureFlag(flagKey);
1117
+ }
1118
+ /** Convenience: returns true iff `getFeatureFlag(flagKey)` is truthy. */
1119
+ isFeatureEnabled(flagKey) {
1120
+ return this.core.isFeatureEnabled(flagKey);
1121
+ }
1122
+ /** Look up the JSON payload attached to a flag. Does NOT emit exposure events. */
1123
+ getFeatureFlagPayload(flagKey) {
1124
+ return this.core.getFeatureFlagPayload(flagKey);
1125
+ }
1126
+ /** Snapshot every accessible flag's current value. */
1127
+ getAllFlags() {
1128
+ return this.core.getAllFlags();
1129
+ }
1130
+ /** Force a /config refresh and re-fire any registered listeners. */
1131
+ async reloadFeatureFlags() {
1132
+ return this.core.reloadFeatureFlags();
1133
+ }
1134
+ /** Override person properties used for flag evaluation only. */
1135
+ setPersonPropertiesForFlags(properties) {
1136
+ try {
1137
+ this.core.setPersonPropertiesForFlags(properties);
1138
+ } catch (e) {
1139
+ this.emitError(e);
1140
+ }
1141
+ }
1142
+ /** Merge additional person properties into the flag-evaluation map. */
1143
+ mergePersonPropertiesForFlags(properties) {
1144
+ try {
1145
+ this.core.mergePersonPropertiesForFlags(properties);
1146
+ } catch (e) {
1147
+ this.emitError(e);
1148
+ }
1149
+ }
1150
+ /** Subscribe to feature-flag refreshes. Returns an unsubscribe function. */
1151
+ onFeatureFlags(callback) {
1152
+ return this.core.onFeatureFlags(callback);
1153
+ }
1154
+ /** Seed bootstrap flag values + payloads after init. */
1155
+ setFeatureFlagBootstrap(bootstrap) {
1156
+ this.core.setFeatureFlagBootstrap(bootstrap);
1157
+ }
1158
+ /**
1159
+ * Register one or more super-properties — auto-merged into every track /
1160
+ * screen call until cleared. Super-properties carry app-wide context
1161
+ * (plan tier, region, experiment bucket).
1162
+ */
1163
+ setSuperProperties(properties) {
1164
+ try {
1165
+ this.core.setSuperProperties(properties);
1166
+ } catch (e) {
1167
+ this.emitError(e);
1168
+ }
1169
+ }
1170
+ /** Register super-properties only if their keys have not been set before. */
1171
+ setSuperPropertiesOnce(properties) {
1172
+ try {
1173
+ this.core.setSuperPropertiesOnce(properties);
1174
+ } catch (e) {
1175
+ this.emitError(e);
1176
+ }
1177
+ }
1178
+ /** Remove a single super-property by key. */
1179
+ unregisterSuperProperty(key) {
1180
+ try {
1181
+ this.core.unregisterSuperProperty(key);
1182
+ } catch (e) {
1183
+ this.emitError(e);
1184
+ }
1185
+ }
1186
+ /** Clear all registered super-properties. */
1187
+ clearSuperProperties() {
1188
+ try {
1189
+ this.core.clearSuperProperties();
1190
+ } catch (e) {
1191
+ this.emitError(e);
1192
+ }
1193
+ }
1194
+ /** Snapshot the currently-registered super-properties. */
1195
+ getSuperProperties() {
1196
+ return this.core.getSuperProperties();
1197
+ }
1198
+ /** Start a duration timer for the next `track(name)` call. */
1199
+ timeEvent(eventName) {
1200
+ try {
1201
+ this.core.timeEvent(eventName);
1202
+ } catch (e) {
1203
+ this.emitError(e);
1204
+ }
1205
+ }
1206
+ /** Cancel a timed event without emitting it. Returns elapsed ms (0 if none). */
1207
+ cancelTimedEvent(eventName) {
1208
+ try {
1209
+ return this.core.cancelTimedEvent(eventName);
1210
+ } catch (e) {
1211
+ this.emitError(e);
1212
+ return 0;
1213
+ }
1214
+ }
1215
+ /** Set membership for a single group_type. Empty `groupId` removes the type. */
1216
+ setGroup(groupType, groupId) {
1217
+ try {
1218
+ this.core.setGroup(groupType, groupId);
1219
+ } catch (e) {
1220
+ this.emitError(e);
1221
+ }
1222
+ }
1223
+ /** Add a group membership without overwriting other types (alias for setGroup). */
1224
+ addGroup(groupType, groupId) {
1225
+ try {
1226
+ this.core.addGroup(groupType, groupId);
1227
+ } catch (e) {
1228
+ this.emitError(e);
1229
+ }
1230
+ }
1231
+ /** Remove a group_type from the membership map. */
1232
+ removeGroup(groupType) {
1233
+ try {
1234
+ this.core.removeGroup(groupType);
1235
+ } catch (e) {
1236
+ this.emitError(e);
1237
+ }
1238
+ }
1239
+ /** Snapshot the current $groups membership map. */
1240
+ getGroups() {
1241
+ return this.core.getGroups();
1242
+ }
1243
+ /** Increment a numeric user property by `delta`. */
1244
+ increment(key, delta = 1) {
1245
+ try {
1246
+ this.core.increment(key, delta);
1247
+ } catch (e) {
1248
+ this.emitError(e);
1249
+ }
1250
+ }
1251
+ /** Append a single value to a list-typed user property. */
1252
+ append(key, value) {
1253
+ try {
1254
+ this.core.append(key, value);
1255
+ } catch (e) {
1256
+ this.emitError(e);
1257
+ }
1258
+ }
1259
+ /** Union (set-add) values into a list-typed user property. */
1260
+ union(key, values) {
1261
+ try {
1262
+ this.core.union(key, values);
1263
+ } catch (e) {
1264
+ this.emitError(e);
1265
+ }
1266
+ }
1267
+ /** Remove a user property by key. */
1268
+ unset(key) {
1269
+ try {
1270
+ this.core.unset(key);
1271
+ } catch (e) {
1272
+ this.emitError(e);
1273
+ }
1274
+ }
1275
+ /** Returns the current anonymous ID, rotated on `reset()`. */
1276
+ getAnonymousId() {
1277
+ return this.core.getAnonymousId();
1278
+ }
1279
+ /** Returns the current device ID (stable per install, rotated on `reset()`). */
1280
+ getDeviceId() {
1281
+ return this.core.getDeviceId();
1282
+ }
1283
+ /** Returns the monotonically-increasing session number. */
1284
+ getSessionNumber() {
1285
+ return this.core.getSessionNumber();
1286
+ }
1287
+ /** Returns the SDK first-open RFC3339 timestamp, or null. */
1288
+ getFirstOpenTime() {
1289
+ return this.core.getFirstOpenTime();
1290
+ }
1291
+ /**
1292
+ * Register a synchronous filter callback called for every track / screen
1293
+ * before the event reaches the queue. Return `null` to drop, or a modified
1294
+ * `BeforeSendEvent` to forward.
1295
+ *
1296
+ * Pass `null` to clear the hook.
1297
+ */
1298
+ setBeforeSend(hook) {
1299
+ this.core.setBeforeSend(hook);
1300
+ }
874
1301
  /**
875
1302
  * Request App Tracking Transparency authorization (iOS only).
876
1303
  * After the user responds, this method automatically:
@@ -929,24 +1356,19 @@ var LayersReactNative = class LayersReactNative {
929
1356
  this.userIdLocked = false;
930
1357
  }
931
1358
  /**
932
- * Reset the SDK state: clears the user ID, unlocks set-user-once,
933
- * clears user properties, and starts a new session.
1359
+ * Reset the SDK state: clears the user ID, unlocks set-user-once, drops
1360
+ * super-properties + multi-group memberships, rotates device / anonymous
1361
+ * IDs, and starts a new session.
934
1362
  *
935
- * After reset(), the SDK behaves as if no user has been identified.
936
- * A new anonymous session is started. Events tracked after reset()
937
- * will not carry the previous user's identity.
1363
+ * After reset(), the SDK behaves as if no user has been identified. Events
1364
+ * tracked after reset() will not carry the previous user's identity.
938
1365
  */
939
1366
  reset() {
940
1367
  if (this.enableDebug) console.log("[Layers] reset()");
941
1368
  this.appUserId = void 0;
942
1369
  this.userIdLocked = false;
943
1370
  try {
944
- this.core.setUserProperties({});
945
- } catch (e) {
946
- this.emitError(e);
947
- }
948
- try {
949
- this.core.startNewSession();
1371
+ this.core.reset();
950
1372
  } catch (e) {
951
1373
  this.emitError(e);
952
1374
  }
@@ -1074,6 +1496,17 @@ var LayersReactNative = class LayersReactNative {
1074
1496
  getQueueDepth() {
1075
1497
  return this.core.queueDepth();
1076
1498
  }
1499
+ /**
1500
+ * Return the per-device DebugView token, or null if `debug` was not enabled
1501
+ * in the constructor config.
1502
+ *
1503
+ * When debug mode is on the SDK persists a stable UUID via AsyncStorage
1504
+ * and sends it in the `X-Debug-Token` header on every event upload. This
1505
+ * lets dashboard UIs filter the live tail to events from this device only.
1506
+ */
1507
+ getDebugToken() {
1508
+ return this.core.getDebugToken();
1509
+ }
1077
1510
  /** Current device context from the core. */
1078
1511
  getDeviceContext() {
1079
1512
  return this.core.getDeviceContext();
@@ -1094,6 +1527,72 @@ var LayersReactNative = class LayersReactNative {
1094
1527
  return this._recentEvents;
1095
1528
  }
1096
1529
  /**
1530
+ * POST a device fingerprint to /clicks/resolve so the server can match this
1531
+ * first-launch install to a recent /c/:appId click captured in the browser
1532
+ * before the App Store / Play Store redirect. On a successful match, persist
1533
+ * the returned click IDs via setAttributionData so every subsequent event
1534
+ * (app_open, purchase_success, etc.) carries fbclid / gclid / ttclid / etc.
1535
+ *
1536
+ * This is the primary iOS web-to-app attribution path, since iOS has no
1537
+ * equivalent of Android's Play Install Referrer. Also serves as a fallback
1538
+ * for Android installs where the Install Referrer API returned nothing
1539
+ * (sideload, Amazon Appstore, testing).
1540
+ *
1541
+ * Best-effort: all errors are swallowed — this must never block app_open.
1542
+ */
1543
+ async resolveClickFromFingerprint() {
1544
+ const baseUrl = (this.config.baseUrl ?? "https://in.layers.com").replace(/\/$/, "");
1545
+ const deviceContext = this.core.getDeviceContext();
1546
+ let platform;
1547
+ try {
1548
+ const { Platform } = __require("react-native");
1549
+ platform = Platform.OS;
1550
+ } catch {
1551
+ platform = void 0;
1552
+ }
1553
+ const fingerprint = {
1554
+ app_id: this.config.appId,
1555
+ platform,
1556
+ device_model: deviceContext.deviceModel ?? null,
1557
+ os_version: deviceContext.osVersion ?? null,
1558
+ locale: deviceContext.locale ?? null,
1559
+ timezone: deviceContext.timezone ?? null,
1560
+ screen_size: deviceContext.screenSize ?? null
1561
+ };
1562
+ const controller = new AbortController();
1563
+ const timeoutId = setTimeout(() => controller.abort(), 3e3);
1564
+ let response;
1565
+ try {
1566
+ response = await fetch(`${baseUrl}/clicks/resolve`, {
1567
+ method: "POST",
1568
+ headers: {
1569
+ "Content-Type": "application/json",
1570
+ "X-App-Id": this.config.appId,
1571
+ "X-SDK-Version": `react-native/${SDK_VERSION}`
1572
+ },
1573
+ body: JSON.stringify(fingerprint),
1574
+ signal: controller.signal
1575
+ });
1576
+ } finally {
1577
+ clearTimeout(timeoutId);
1578
+ }
1579
+ if (!response.ok) {
1580
+ if (this.enableDebug) console.log(`[Layers] /clicks/resolve status=${response.status}`);
1581
+ return;
1582
+ }
1583
+ const body = await response.json();
1584
+ if (!body?.success || !body.data?.matched) {
1585
+ if (this.enableDebug) console.log("[Layers] /clicks/resolve no-match");
1586
+ return;
1587
+ }
1588
+ const { fbclid, gclid, ttclid, msclkid, method, confidence } = body.data;
1589
+ if (!fbclid && !gclid && !ttclid && !msclkid) return;
1590
+ try {
1591
+ await this.setAttributionData(this._attributionDeeplinkId, gclid ?? this._attributionGclid, fbclid ?? this._attributionFbclid, ttclid ?? this._attributionTtclid, msclkid ?? this._attributionMsclkid);
1592
+ if (this.enableDebug) console.log(`[Layers] /clicks/resolve matched method=${String(method)} confidence=${String(confidence)} fbclid=${String(fbclid)}`);
1593
+ } catch {}
1594
+ }
1595
+ /**
1097
1596
  * Fire-and-forget POST to /users/properties.
1098
1597
  * Best-effort: errors are silently swallowed.
1099
1598
  */
@@ -1377,6 +1876,7 @@ var LayersReactNative = class LayersReactNative {
1377
1876
  } catch {}
1378
1877
  this.core.setDeviceContext(context);
1379
1878
  }
1879
+ this._installReferrerParams = null;
1380
1880
  try {
1381
1881
  const { Platform } = __require("react-native");
1382
1882
  if (Platform.OS === "ios") try {
@@ -1385,16 +1885,37 @@ var LayersReactNative = class LayersReactNative {
1385
1885
  } catch {}
1386
1886
  if (Platform.OS === "android") try {
1387
1887
  const referrer = await getInstallReferrer();
1388
- if (referrer) this._installReferrer = referrer;
1888
+ if (referrer) {
1889
+ this._installReferrer = referrer;
1890
+ const parsed = parseInstallReferrerUrl(referrer.referrerUrl);
1891
+ this._installReferrerParams = Object.keys(parsed).length > 0 ? parsed : null;
1892
+ if (parsed.fbclid || parsed.gclid || parsed.ttclid || parsed.msclkid) try {
1893
+ await this.setAttributionData(this._attributionDeeplinkId, parsed.gclid ?? this._attributionGclid, parsed.fbclid ?? this._attributionFbclid, parsed.ttclid ?? this._attributionTtclid, parsed.msclkid ?? this._attributionMsclkid);
1894
+ } catch {}
1895
+ }
1389
1896
  } catch {}
1390
1897
  } catch {}
1391
1898
  }
1392
1899
  setupAppStateListener() {
1393
1900
  try {
1394
1901
  const { AppState } = __require("react-native");
1902
+ let lastEmittedState = null;
1395
1903
  this.appStateSubscription = AppState.addEventListener("change", (nextAppState) => {
1396
- if (nextAppState === "background" || nextAppState === "inactive") this.core.flush();
1397
- if (nextAppState === "active" && this.isOnline) this.core.flushAsync().catch(() => {});
1904
+ if (nextAppState === "background" || nextAppState === "inactive") {
1905
+ if (this.config.autoTrackAppLifecycle !== false && lastEmittedState !== "background") try {
1906
+ this.track("$app_background");
1907
+ lastEmittedState = "background";
1908
+ } catch {}
1909
+ this.core.flush();
1910
+ }
1911
+ if (nextAppState === "active") {
1912
+ if (this.config.autoTrackAppLifecycle !== false && lastEmittedState !== null && lastEmittedState !== "active") try {
1913
+ this.track("$app_foreground");
1914
+ lastEmittedState = "active";
1915
+ } catch {}
1916
+ else if (lastEmittedState === null) lastEmittedState = "active";
1917
+ if (this.isOnline) this.core.flushAsync().catch(() => {});
1918
+ }
1398
1919
  });
1399
1920
  } catch {}
1400
1921
  }
@@ -1462,9 +1983,9 @@ async function createAsyncStoragePersistence(appId) {
1462
1983
  try {
1463
1984
  const AsyncStorage = await loadAsyncStorage();
1464
1985
  if (AsyncStorage) {
1465
- const layersKeys = (await AsyncStorage.getAllKeys()).filter((k) => k.startsWith(prefix));
1466
- if (layersKeys.length > 0) {
1467
- const pairs = await AsyncStorage.multiGet(layersKeys);
1986
+ const sdkKeys = (await AsyncStorage.getAllKeys()).filter((k) => k.startsWith(prefix));
1987
+ if (sdkKeys.length > 0) {
1988
+ const pairs = await AsyncStorage.multiGet(sdkKeys);
1468
1989
  for (const [key, value] of pairs) if (value) {
1469
1990
  const shortKey = key.slice(prefix.length);
1470
1991
  memoryStore.set(shortKey, base64Decode(value));
@@ -1571,6 +2092,11 @@ function getLocale() {
1571
2092
  const INSTALL_ID_KEY = "layers_install_id";
1572
2093
  const FIRST_LAUNCH_TRACKED_KEY = "@layers/first_launch_tracked";
1573
2094
  /**
2095
+ * Last-known app_version persisted across launches. Used to detect
2096
+ * `$app_update` (version increment) vs. `$first_open` (no prior value).
2097
+ */
2098
+ const LAST_APP_VERSION_KEY = "@layers/last_app_version";
2099
+ /**
1574
2100
  * Maximum age of an app installation (in milliseconds) for which the SDK
1575
2101
  * will consider the first launch as a genuine new install. If the app was
1576
2102
  * installed more than 24 hours ago AND no prior Layers SDK state exists,
@@ -1749,6 +2275,54 @@ async function getAdServicesToken() {
1749
2275
  }
1750
2276
  }
1751
2277
  /**
2278
+ * Known attribution params extracted from the Play Install Referrer string.
2279
+ * Keep in sync with layers sdk-ingest routes/click.ts::buildAndroidReferrerUrl
2280
+ * and the parallel allowlists in kotlin / unity / flutter SDKs.
2281
+ */
2282
+ const INSTALL_REFERRER_ATTRIBUTION_PARAMS = new Set([
2283
+ "utm_source",
2284
+ "utm_medium",
2285
+ "utm_campaign",
2286
+ "utm_content",
2287
+ "utm_term",
2288
+ "gclid",
2289
+ "gbraid",
2290
+ "wbraid",
2291
+ "fbclid",
2292
+ "ttclid",
2293
+ "twclid",
2294
+ "msclkid",
2295
+ "li_fat_id",
2296
+ "sclid",
2297
+ "rclid",
2298
+ "irclickid",
2299
+ "click_id"
2300
+ ]);
2301
+ /**
2302
+ * Parse a raw Play Install Referrer string into a map of recognized attribution
2303
+ * params. Accepts either a bare query string (`a=1&b=2`) or a full URL.
2304
+ * Returns an empty object on parse failure.
2305
+ */
2306
+ function parseInstallReferrerUrl(referrer) {
2307
+ const out = {};
2308
+ if (!referrer) return out;
2309
+ try {
2310
+ let qs = referrer;
2311
+ const qIdx = qs.indexOf("?");
2312
+ if (qIdx >= 0) qs = qs.slice(qIdx + 1);
2313
+ if (!qs.includes("=") && qs.includes("%3D")) qs = decodeURIComponent(qs);
2314
+ for (const pair of qs.split("&")) {
2315
+ const eq = pair.indexOf("=");
2316
+ if (eq >= 0) try {
2317
+ const key = decodeURIComponent(pair.slice(0, eq));
2318
+ const value = decodeURIComponent(pair.slice(eq + 1));
2319
+ if (value && INSTALL_REFERRER_ATTRIBUTION_PARAMS.has(key)) out[key] = value;
2320
+ } catch {}
2321
+ }
2322
+ } catch {}
2323
+ return out;
2324
+ }
2325
+ /**
1752
2326
  * Fetch the Google Play install referrer on Android via NativeModules.
1753
2327
  * Requires the `com.android.installreferrer` library on the native side.
1754
2328
  * Returns null on iOS or when the native module is not available.
@@ -1822,7 +2396,17 @@ function parseDeepLink(url) {
1822
2396
  return null;
1823
2397
  }
1824
2398
  }
1825
- function useLayersExpoRouterTracking(layersInstance, usePathname, useGlobalSearchParams) {
2399
+ const _expoRouterPreviousPath = /* @__PURE__ */ new WeakMap();
2400
+ /**
2401
+ * Hook that emits `$screen_view` for every Expo Router pathname change.
2402
+ *
2403
+ * The hook also tracks the previous pathname so the emitted event carries
2404
+ * `previous_screen_name`, matching the React Navigation observer in
2405
+ * `useLayersNavigationTracking`. This makes funnel analysis trivial
2406
+ * server-side: every screen event has a self-contained pair `(from, to)`
2407
+ * — no need to join adjacent rows.
2408
+ */
2409
+ function useLayersExpoRouterTracking(sdkInstance, usePathname, useGlobalSearchParams) {
1826
2410
  const { useEffect } = __require("react");
1827
2411
  const pathname = usePathname();
1828
2412
  const params = useGlobalSearchParams();
@@ -1832,11 +2416,14 @@ function useLayersExpoRouterTracking(layersInstance, usePathname, useGlobalSearc
1832
2416
  Object.entries(params).forEach(([key, value]) => {
1833
2417
  properties[key] = Array.isArray(value) ? value.join(",") : value;
1834
2418
  });
1835
- layersInstance.screen(pathname, properties);
2419
+ const previous = _expoRouterPreviousPath.get(sdkInstance);
2420
+ if (previous && previous !== pathname) properties.previous_screen_name = previous;
2421
+ sdkInstance.screen(pathname, properties);
2422
+ _expoRouterPreviousPath.set(sdkInstance, pathname);
1836
2423
  }
1837
2424
  }, [pathname, JSON.stringify(params)]);
1838
2425
  }
1839
2426
 
1840
2427
  //#endregion
1841
- export { tutorialCompleteEvent as $, trackSubscription as A, addToWishlistEvent as B, trackAddToCart as C, trackPurchaseFailed as D, trackPurchase as E, superwallTrackPurchase as F, purchaseEvent as G, levelCompleteEvent as H, superwallTrackSkip as I, searchEvent as J, registerEvent as K, superwallUserAttributes as L, superwallOnEvent as M, superwallTrackDismiss as N, trackRefund as O, superwallTrackPresentation as P, subscribeEvent as Q, StandardEvents as R, trackRevenueCatPurchase as S, trackOrder as T, levelStartEvent as U, initiateCheckoutEvent as V, loginEvent as W, signUpEvent as X, shareEvent as Y, startTrialEvent as Z, registerExpoBackgroundFlush as _, getFirstInstallTime as a, resetRevenueCatForTesting as b, getOrSetInstallId as c, setupDeepLinkListener as d, viewContentEvent as et, shouldTreatAsNewInstall as f, createBackgroundFlushHandler as g, BACKGROUND_FLUSH_TASK_NAME as h, getAdServicesToken as i, trackViewProduct as j, trackRemoveFromCart as k, parseDeepLink as l, BACKGROUND_FLUSH_MIN_INTERVAL_MINUTES as m, LayersReactNative as n, getGoogleAdvertisingId as o, useLayersExpoRouterTracking as p, screenViewEvent as q, formatFbc as r, getInstallReferrer as s, LayersError$1 as t, viewItemEvent as tt, readClipboardAttribution as u, connectRevenueCat as v, trackBeginCheckout as w, syncRevenueCatAttributes as x, isRevenueCatConnected as y, addToCartEvent as z };
1842
- //# sourceMappingURL=src-8aNaNJz3.mjs.map
2428
+ export { addToWishlistEvent as $, registerExpoBackgroundFlush as A, trackPurchaseFailed as B, SurveysModule as C, BACKGROUND_FLUSH_MIN_INTERVAL_MINUTES as D, useLayersNavigationTracking as E, trackRevenueCatPurchase as F, superwallOnEvent as G, trackRemoveFromCart as H, trackAddToCart as I, superwallTrackPurchase as J, superwallTrackDismiss as K, trackBeginCheckout as L, isRevenueCatConnected as M, resetRevenueCatForTesting as N, BACKGROUND_FLUSH_TASK_NAME as O, syncRevenueCatAttributes as P, addToCartEvent as Q, trackOrder as R, useLayersExpoRouterTracking as S, resolveActiveRoute as T, trackSubscription as U, trackRefund as V, trackViewProduct as W, superwallUserAttributes as X, superwallTrackSkip as Y, StandardEvents as Z, parseDeepLink as _, buildBeginCheckoutEvent as a, registerEvent as at, setupDeepLinkListener as b, buildStartTrialEvent as c, shareEvent as ct, formatFbc as d, subscribeEvent as dt, initiateCheckoutEvent as et, getAdServicesToken as f, tutorialCompleteEvent as ft, getOrSetInstallId as g, getInstallReferrer as h, buildAddToCartEvent as i, purchaseEvent as it, connectRevenueCat as j, createBackgroundFlushHandler as k, buildSubscribeEvent as l, signUpEvent as lt, getGoogleAdvertisingId as m, viewItemEvent as mt, LayersEvent as n, levelStartEvent as nt, buildPurchaseEvent as o, screenViewEvent as ot, getFirstInstallTime as p, viewContentEvent as pt, superwallTrackPresentation as q, LayersReactNative as r, loginEvent as rt, buildRefundEvent as s, searchEvent as st, LayersError$1 as t, levelCompleteEvent as tt, buildViewItemEvent as u, startTrialEvent as ut, parseInstallReferrerUrl as v, createNavigationListener as w, shouldTreatAsNewInstall as x, readClipboardAttribution as y, trackPurchase as z };
2429
+ //# sourceMappingURL=src-BNoj1E-e.mjs.map