@layers/react-native 3.3.3 → 3.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.
@@ -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 { r as setSkanCore, t as SKANManager } from "./skan-DO7MLv2w.mjs";
4
- import { FetchHttpClient, LayersCore, LayersError as LayersError$1, LayersEvent, MemoryPersistence, addToCartEvent as buildAddToCartEvent, beginCheckoutEvent as buildBeginCheckoutEvent, initWasm, onboardingCompleteEvent as buildOnboardingCompleteEvent, onboardingStartEvent as buildOnboardingStartEvent, paywallShowEvent as buildPaywallShowEvent, purchaseEvent as buildPurchaseEvent, refundEvent as buildRefundEvent, startTrialEvent as buildStartTrialEvent, subscribeEvent as buildSubscribeEvent, viewItemEvent as buildViewItemEvent } from "@layers/core-wasm";
4
+ import { FetchHttpClient, LayersCore, LayersError as LayersError$1, LayersEvent, addToCartEvent as buildAddToCartEvent, beginCheckoutEvent as buildBeginCheckoutEvent, initWasm, onboardingCompleteEvent as buildOnboardingCompleteEvent, onboardingStartEvent as buildOnboardingStartEvent, paywallShowEvent as buildPaywallShowEvent, 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/exceptions.ts
7
7
  /** Cap on the serialized stack length to keep payloads sane. */
@@ -1122,16 +1122,21 @@ function hostAppIsRegisteredOn(rn) {
1122
1122
  }
1123
1123
  }
1124
1124
  const DUPLICATE_REACT_NATIVE_MESSAGE = "[Layers] The SDK resolved a SECOND copy of react-native, not the one your app runs. React Native delivers native lifecycle events to a single copy, so this listener can never fire: $app_background and $app_foreground will not be emitted and the background crash-safety snapshot will not run, which loses every event queued since the last flush on any launch that ends in a kill. Fix the duplicate in your bundler — in a Metro monorepo set `resolver.disableHierarchicalLookup = true` and list every workspace node_modules in `resolver.nodeModulesPaths` — or hand the SDK your app's module: `new LayersReactNative({ ..., appState: AppState })` with AppState imported from 'react-native'.";
1125
- const SDK_VERSION = "3.3.3";
1125
+ const SDK_VERSION = "3.4.0";
1126
1126
  var LayersReactNative = class LayersReactNative {
1127
1127
  core;
1128
- eagerPersistence;
1128
+ eager;
1129
+ get eagerPersistence() {
1130
+ return this.eager.backend;
1131
+ }
1129
1132
  appUserId;
1130
1133
  isOnline = true;
1131
1134
  enableDebug;
1132
1135
  appStateSubscription = null;
1133
1136
  exceptionUninstall = null;
1134
1137
  persistenceSettle = null;
1138
+ _persistTimer = null;
1139
+ _wrapperFlushes = /* @__PURE__ */ new Set();
1135
1140
  _lifecycleCheckTimer = null;
1136
1141
  netInfoUnsubscribe = null;
1137
1142
  config;
@@ -1148,12 +1153,19 @@ var LayersReactNative = class LayersReactNative {
1148
1153
  _runtimeGeneration = 0;
1149
1154
  _configPollTimer = null;
1150
1155
  static CONFIG_POLL_INTERVAL_MS = 3e5;
1156
+ static PERSIST_THROTTLE_MS = 1e3;
1151
1157
  _adServicesToken = null;
1152
1158
  _installReferrer = null;
1153
1159
  _gaid = null;
1154
1160
  _installReferrerParams = null;
1155
1161
  _hadPriorSdkState = false;
1156
1162
  _hadPriorAppIdentity = false;
1163
+ _deferredDeepLink = null;
1164
+ _deferredDeepLinkDelivered = false;
1165
+ _deferredDeepLinkRestore = null;
1166
+ _deferredDeepLinkResolve = null;
1167
+ deferredDeepLinkListeners = /* @__PURE__ */ new Set();
1168
+ _clickResolveClaimed = false;
1157
1169
  _attributionDeeplinkId = null;
1158
1170
  _attributionGclid = null;
1159
1171
  _attributionFbclid = null;
@@ -1172,7 +1184,7 @@ var LayersReactNative = class LayersReactNative {
1172
1184
  this.appUserId = config.appUserId;
1173
1185
  this.config = config;
1174
1186
  const httpClient = new FetchHttpClient();
1175
- this.eagerPersistence = new MemoryPersistence();
1187
+ this.eager = createEagerPersistence(config.appId);
1176
1188
  this.core = LayersCore.init({
1177
1189
  config: {
1178
1190
  appId: config.appId,
@@ -1318,7 +1330,7 @@ var LayersReactNative = class LayersReactNative {
1318
1330
  if (this.initAborted(generation)) return;
1319
1331
  this._hadPriorAppIdentity = false;
1320
1332
  try {
1321
- const { backend: persistence, settle: persistenceSettle } = await createAsyncStoragePersistence(this.config.appId);
1333
+ const { backend: persistence, settle: persistenceSettle, forget: forgetPreloaded } = await createAsyncStoragePersistence(this.config.appId);
1322
1334
  try {
1323
1335
  const record = persistence.read("identity_state");
1324
1336
  this._hadPriorAppIdentity = record != null && record.length > 0;
@@ -1329,6 +1341,7 @@ var LayersReactNative = class LayersReactNative {
1329
1341
  this.persistenceSettle = persistenceSettle;
1330
1342
  const httpClient = new FetchHttpClient();
1331
1343
  const migrationState = this.core.exportMigrationState();
1344
+ this.eager.stopMirroring();
1332
1345
  this.core.shutdown();
1333
1346
  try {
1334
1347
  let migrated = 0;
@@ -1341,6 +1354,7 @@ var LayersReactNative = class LayersReactNative {
1341
1354
  this.eagerPersistence.delete(key);
1342
1355
  }
1343
1356
  } catch {}
1357
+ forgetPreloaded(this.eager.mirrorKeyPrefix);
1344
1358
  this.core = LayersCore.init({
1345
1359
  config: {
1346
1360
  appId: this.config.appId,
@@ -1361,8 +1375,13 @@ var LayersReactNative = class LayersReactNative {
1361
1375
  this._runtimeGeneration = generation;
1362
1376
  setSkanCore(this.core);
1363
1377
  if (this.appUserId) this.core.identify(this.appUserId);
1378
+ try {
1379
+ this.core.flush();
1380
+ } catch {}
1381
+ persistenceSettle().then(() => this.eager.discardMirror()).catch(() => void 0);
1364
1382
  } catch {}
1365
1383
  await this.restoreAttributionData();
1384
+ await this.ensureDeferredDeepLinkRestored();
1366
1385
  await this.initializeDeviceInfo();
1367
1386
  if (this.initAborted(generation)) return;
1368
1387
  this._runtimeGeneration = generation;
@@ -1373,16 +1392,7 @@ var LayersReactNative = class LayersReactNative {
1373
1392
  await this.configureSkanFromRemoteConfig();
1374
1393
  if (this.initAborted(generation)) return;
1375
1394
  this.startConfigPolling();
1376
- let clipboardEnabled = false;
1377
- let fingerprintResolveEnabled = false;
1378
- try {
1379
- const configJson = this.core.getRemoteConfigJson?.();
1380
- if (configJson) {
1381
- const config = JSON.parse(configJson);
1382
- clipboardEnabled = config?.clipboard_attribution_enabled === true;
1383
- fingerprintResolveEnabled = config?.fingerprint_resolve_enabled === true;
1384
- }
1385
- } catch {}
1395
+ const { clipboardEnabled, fingerprintResolveEnabled } = this.readPrivacySwitches();
1386
1396
  let clipboardData = null;
1387
1397
  try {
1388
1398
  const { Platform } = __require("react-native");
@@ -1466,6 +1476,7 @@ var LayersReactNative = class LayersReactNative {
1466
1476
  ...typeof __DEV__ !== "undefined" && __DEV__ === true ? {} : { onFatal: () => this.persistForCrash() }
1467
1477
  });
1468
1478
  this._isInitialized = true;
1479
+ this.persistThenSend();
1469
1480
  const totalDurationMs = Date.now() - initStartTime;
1470
1481
  if (this.enableDebug) console.log(`[Layers] Init timing: mainThread=${String(mainThreadDurationMs)}ms, total=${String(totalDurationMs)}ms`);
1471
1482
  if (this._initListener) try {
@@ -1481,6 +1492,7 @@ var LayersReactNative = class LayersReactNative {
1481
1492
  const depthBefore = this.core.queueDepth();
1482
1493
  this.core.track(eventName, merged, this.appUserId);
1483
1494
  const depthAfter = this.core.queueDepth();
1495
+ this.schedulePersist();
1484
1496
  if (depthAfter <= depthBefore && this.enableDebug) console.warn(`[Layers] track("${eventName}") — event may not have been queued (depth before=${String(depthBefore)}, after=${String(depthAfter)})`);
1485
1497
  this.recordRecentEvent(eventName, properties);
1486
1498
  if (this._skanManager) this._skanManager.processEvent(eventName, merged ?? {}).catch(() => {});
@@ -1509,6 +1521,7 @@ var LayersReactNative = class LayersReactNative {
1509
1521
  const depthBefore = this.core.queueDepth();
1510
1522
  this.core.screen(screenName, merged, this.appUserId);
1511
1523
  const depthAfter = this.core.queueDepth();
1524
+ this.schedulePersist();
1512
1525
  if (depthAfter <= depthBefore && this.enableDebug) console.warn(`[Layers] screen("${screenName}") — event may not have been queued (depth before=${String(depthBefore)}, after=${String(depthAfter)})`);
1513
1526
  this.recordRecentEvent(`screen:${screenName}`, properties);
1514
1527
  if (forwardToSkan && this._skanManager) {
@@ -1870,6 +1883,7 @@ var LayersReactNative = class LayersReactNative {
1870
1883
  this.core.setDeviceContext(next);
1871
1884
  }
1872
1885
  async flush() {
1886
+ await this.waitForWrapperFlush();
1873
1887
  try {
1874
1888
  await this.core.flushAsync();
1875
1889
  } catch (e) {
@@ -1943,6 +1957,199 @@ var LayersReactNative = class LayersReactNative {
1943
1957
  return this._installReferrer;
1944
1958
  }
1945
1959
  /**
1960
+ * The deferred deep link for this install — the payload of the Layers
1961
+ * tracking link (`in.layers.com/l/tlnk_…`) the user tapped before installing —
1962
+ * or null.
1963
+ *
1964
+ * One-shot per install: the first call (or {@link onDeferredDeepLink}
1965
+ * listener) that receives it marks it delivered, persistently, and every
1966
+ * later call on this install returns null. A link found on one launch and
1967
+ * not yet taken stays pending across launches until something takes it.
1968
+ *
1969
+ * Waits for an in-flight `init()` or {@link resolveDeferredDeepLink} first,
1970
+ * so calling it straight after `init()` sees what init found.
1971
+ */
1972
+ async getDeferredDeepLink() {
1973
+ if (this._initPromise) await this._initPromise.catch(() => {});
1974
+ if (this._deferredDeepLinkResolve) await this._deferredDeepLinkResolve.catch(() => {});
1975
+ await this.ensureDeferredDeepLinkRestored();
1976
+ const link = this._deferredDeepLink;
1977
+ if (!link || this._deferredDeepLinkDelivered) return null;
1978
+ this._deferredDeepLinkDelivered = true;
1979
+ await this.persistDeferredDeepLink();
1980
+ return copyDeferredDeepLink(link);
1981
+ }
1982
+ /**
1983
+ * Call `listener` once, when this install's deferred deep link becomes known
1984
+ * — immediately (asynchronously) if it was already known and not yet
1985
+ * delivered when you subscribed. Fires at most once per install across all
1986
+ * listeners and {@link getDeferredDeepLink}: whichever receives it first
1987
+ * marks it delivered. Returns an unsubscribe function.
1988
+ */
1989
+ onDeferredDeepLink(listener) {
1990
+ this.deferredDeepLinkListeners.add(listener);
1991
+ this.ensureDeferredDeepLinkRestored().then(() => this.deliverDeferredDeepLinkToListeners());
1992
+ return () => {
1993
+ this.deferredDeepLinkListeners.delete(listener);
1994
+ };
1995
+ }
1996
+ /**
1997
+ * Look for this install's deferred deep link, then return it as
1998
+ * {@link getDeferredDeepLink} does (consuming it).
1999
+ *
2000
+ * `init()` already does this work when `autoTrackAppOpen` is on (the
2001
+ * default). Apps that turn `autoTrackAppOpen` off call this after `init()`:
2002
+ *
2003
+ * 1. Android: reads the Play install referrer's `deeplink` param (local, no
2004
+ * network).
2005
+ * 2. Only where the existing gates already allow it: `POST /clicks/resolve`
2006
+ * on a fresh install (installed within 24 hours, no prior probe, no click
2007
+ * id already known). That probe sends device signals, so it runs only when
2008
+ * the server's `fingerprint_resolve_enabled` remote config is `true`
2009
+ * (default off) AND the core's consent / DNT / Retry-After / circuit
2010
+ * breaker gate is open. This method opens neither gate.
2011
+ *
2012
+ * Safe to call more than once; concurrent calls share one run, and the
2013
+ * probe goes out at most once per install.
2014
+ */
2015
+ async resolveDeferredDeepLink() {
2016
+ if (!this._deferredDeepLinkResolve) {
2017
+ const run = this.runDeferredDeepLinkResolve().finally(() => {
2018
+ if (this._deferredDeepLinkResolve === run) this._deferredDeepLinkResolve = null;
2019
+ });
2020
+ this._deferredDeepLinkResolve = run;
2021
+ }
2022
+ await this._deferredDeepLinkResolve.catch(() => {});
2023
+ return this.getDeferredDeepLink();
2024
+ }
2025
+ async runDeferredDeepLinkResolve() {
2026
+ if (this._initPromise) await this._initPromise.catch(() => {});
2027
+ if (!this._isInitialized) {
2028
+ if (this.enableDebug) console.log("[Layers] resolveDeferredDeepLink: call init() first");
2029
+ return;
2030
+ }
2031
+ await this.ensureDeferredDeepLinkRestored();
2032
+ if (this._deferredDeepLink || this._deferredDeepLinkDelivered) return;
2033
+ try {
2034
+ const referrer = this._installReferrer ?? await this.collectInstallReferrer();
2035
+ if (referrer) await this.recordReferrerDeepLink(referrer);
2036
+ } catch {}
2037
+ if (this._deferredDeepLink) return;
2038
+ const { fingerprintResolveEnabled } = this.readPrivacySwitches();
2039
+ if (!fingerprintResolveEnabled) return;
2040
+ if (this._attributionFbclid != null || this._attributionGclid != null || this._attributionTtclid != null || this._attributionMsclkid != null) return;
2041
+ try {
2042
+ const AsyncStorage = await loadAsyncStorage();
2043
+ if (AsyncStorage) {
2044
+ if (await AsyncStorage.getItem(deferredClickResolveAttemptedKey(this.config.appId)) === "true") return;
2045
+ if (!await shouldTreatAsNewInstall(await AsyncStorage.getItem(firstLaunchTrackedKey(this.config.appId)) !== "true", false, this.enableDebug, () => this.readFirstInstallTime())) return;
2046
+ }
2047
+ await this.resolveClickFromFingerprint();
2048
+ } catch {}
2049
+ }
2050
+ /**
2051
+ * Claim this install's single `/clicks/resolve` probe. The in-memory flag is
2052
+ * taken synchronously, before any await, so two overlapping callers cannot
2053
+ * both pass; the persisted flag carries the claim across launches and is
2054
+ * written before the request, so a timeout or a kill mid-flight cannot earn
2055
+ * the install a second fingerprint.
2056
+ */
2057
+ async claimClickResolveProbe() {
2058
+ if (this._clickResolveClaimed) return false;
2059
+ this._clickResolveClaimed = true;
2060
+ try {
2061
+ const AsyncStorage = await loadAsyncStorage();
2062
+ if (AsyncStorage) {
2063
+ const key = deferredClickResolveAttemptedKey(this.config.appId);
2064
+ if (await AsyncStorage.getItem(key) === "true") return false;
2065
+ await AsyncStorage.setItem(key, "true");
2066
+ }
2067
+ } catch {}
2068
+ return true;
2069
+ }
2070
+ /** The server-driven privacy switches, read from the core's cached config. */
2071
+ readPrivacySwitches() {
2072
+ let clipboardEnabled = false;
2073
+ let fingerprintResolveEnabled = false;
2074
+ try {
2075
+ const configJson = this.core.getRemoteConfigJson?.();
2076
+ if (configJson) {
2077
+ const config = JSON.parse(configJson);
2078
+ clipboardEnabled = config?.clipboard_attribution_enabled === true;
2079
+ fingerprintResolveEnabled = config?.fingerprint_resolve_enabled === true;
2080
+ }
2081
+ } catch {}
2082
+ return {
2083
+ clipboardEnabled,
2084
+ fingerprintResolveEnabled
2085
+ };
2086
+ }
2087
+ ensureDeferredDeepLinkRestored() {
2088
+ if (!this._deferredDeepLinkRestore) this._deferredDeepLinkRestore = this.restoreDeferredDeepLink();
2089
+ return this._deferredDeepLinkRestore;
2090
+ }
2091
+ async restoreDeferredDeepLink() {
2092
+ try {
2093
+ const raw = await (await loadAsyncStorage())?.getItem(deferredDeepLinkKey(this.config.appId));
2094
+ if (!raw) return;
2095
+ const stored = JSON.parse(raw);
2096
+ if (stored.delivered === true) this._deferredDeepLinkDelivered = true;
2097
+ const payload = normalizeDeferredDeepLinkPayload(stored.payload);
2098
+ const source = DEFERRED_DEEPLINK_SOURCES.find((s) => s === stored.source);
2099
+ if (payload && source && !this._deferredDeepLink) this._deferredDeepLink = {
2100
+ payload,
2101
+ source,
2102
+ ...typeof stored.clickId === "string" && stored.clickId ? { clickId: stored.clickId } : {}
2103
+ };
2104
+ } catch {}
2105
+ }
2106
+ async persistDeferredDeepLink() {
2107
+ try {
2108
+ const AsyncStorage = await loadAsyncStorage();
2109
+ if (!AsyncStorage) return;
2110
+ await AsyncStorage.setItem(deferredDeepLinkKey(this.config.appId), JSON.stringify({
2111
+ ...this._deferredDeepLink ?? {},
2112
+ delivered: this._deferredDeepLinkDelivered
2113
+ }));
2114
+ } catch {}
2115
+ }
2116
+ /** Record the referrer's `deeplink` payload, if it carries one. Never throws. */
2117
+ async recordReferrerDeepLink(referrer) {
2118
+ try {
2119
+ const payload = parseInstallReferrerDeepLink(referrer.referrerUrl);
2120
+ if (!payload) return;
2121
+ const clickId = parseInstallReferrerUrl(referrer.referrerUrl).click_id;
2122
+ await this.recordDeferredDeepLink({
2123
+ payload,
2124
+ source: "install_referrer",
2125
+ ...clickId ? { clickId } : {}
2126
+ });
2127
+ } catch {}
2128
+ }
2129
+ /**
2130
+ * Keep the first deferred deep link this install finds. A later source never
2131
+ * replaces it, and an install that already delivered one records nothing.
2132
+ */
2133
+ async recordDeferredDeepLink(link) {
2134
+ await this.ensureDeferredDeepLinkRestored();
2135
+ if (this._deferredDeepLink || this._deferredDeepLinkDelivered) return;
2136
+ this._deferredDeepLink = copyDeferredDeepLink(link);
2137
+ if (this.enableDebug) console.log(`[Layers] deferred deep link found source=${link.source} keys=${Object.keys(link.payload).length}`);
2138
+ await this.persistDeferredDeepLink();
2139
+ this.deliverDeferredDeepLinkToListeners();
2140
+ }
2141
+ deliverDeferredDeepLinkToListeners() {
2142
+ const link = this._deferredDeepLink;
2143
+ if (!link || this._deferredDeepLinkDelivered || this.deferredDeepLinkListeners.size === 0) return;
2144
+ this._deferredDeepLinkDelivered = true;
2145
+ this.persistDeferredDeepLink();
2146
+ for (const listener of Array.from(this.deferredDeepLinkListeners)) try {
2147
+ listener(copyDeferredDeepLink(link));
2148
+ } catch (e) {
2149
+ this.emitError(e);
2150
+ }
2151
+ }
2152
+ /**
1946
2153
  * Returns the auto-configured SKANManager instance, or null if SKAN was not
1947
2154
  * configured by the server's remote config.
1948
2155
  * On iOS, when remote config contains a `skan` section with `preset` or
@@ -2024,6 +2231,10 @@ var LayersReactNative = class LayersReactNative {
2024
2231
  if (this.enableDebug) console.log("[Layers] /clicks/resolve skipped — core delivery gate closed");
2025
2232
  return;
2026
2233
  }
2234
+ if (!await this.claimClickResolveProbe()) {
2235
+ if (this.enableDebug) console.log("[Layers] /clicks/resolve skipped — this install already sent its one probe");
2236
+ return;
2237
+ }
2027
2238
  const baseUrl = (this.config.baseUrl ?? "https://in.layers.com").replace(/\/$/, "");
2028
2239
  const deviceContext = this.core.getDeviceContext();
2029
2240
  let platform;
@@ -2069,6 +2280,15 @@ var LayersReactNative = class LayersReactNative {
2069
2280
  return;
2070
2281
  }
2071
2282
  const { fbclid, gclid, ttclid, msclkid, method, confidence } = body.data;
2283
+ const payload = normalizeDeferredDeepLinkPayload(body.data.deeplink);
2284
+ if (payload) {
2285
+ const clickId = typeof body.data.click_id === "string" ? body.data.click_id : null;
2286
+ await this.recordDeferredDeepLink({
2287
+ payload,
2288
+ source: "click_resolve",
2289
+ ...clickId ? { clickId } : {}
2290
+ });
2291
+ }
2072
2292
  if (!fbclid && !gclid && !ttclid && !msclkid) return;
2073
2293
  try {
2074
2294
  await this.setAttributionData(this._attributionDeeplinkId, gclid ?? this._attributionGclid, fbclid ?? this._attributionFbclid, ttclid ?? this._attributionTtclid, msclkid ?? this._attributionMsclkid);
@@ -2142,10 +2362,90 @@ var LayersReactNative = class LayersReactNative {
2142
2362
  * held open only for the write.
2143
2363
  */
2144
2364
  async persistForCrash() {
2365
+ this.cancelPersist();
2145
2366
  try {
2146
2367
  this.core.flush();
2147
2368
  } catch {}
2148
- if (this.persistenceSettle) await this.persistenceSettle();
2369
+ await this.settleWrites();
2370
+ }
2371
+ /**
2372
+ * Resolves once every AsyncStorage write started so far has landed: the
2373
+ * durable backend's, and the eager store's mirror (the only durable copy of
2374
+ * pre-init events until the core swap).
2375
+ */
2376
+ async settleWrites() {
2377
+ await Promise.all([this.eager.settle(), this.persistenceSettle?.()]);
2378
+ }
2379
+ /**
2380
+ * Snapshot the queue to disk within {@link PERSIST_THROTTLE_MS} of an
2381
+ * accepted event.
2382
+ *
2383
+ * The engine writes its crash-safety snapshot only at the flush threshold,
2384
+ * on a delivery verdict, on background and at shutdown. A short session
2385
+ * (the typical lost Android install: 13 events in 13 seconds) reached none
2386
+ * of those before the process died, so its events never left memory.
2387
+ * Throttled rather than per event: each snapshot serializes the whole
2388
+ * queue, and one write per burst also keeps same-key writes apart on
2389
+ * AsyncStorage v3, which does not order them.
2390
+ */
2391
+ schedulePersist() {
2392
+ if (this._persistTimer !== null) return;
2393
+ this._persistTimer = setTimeout(() => {
2394
+ this._persistTimer = null;
2395
+ try {
2396
+ this.core.flush();
2397
+ } catch {}
2398
+ }, LayersReactNative.PERSIST_THROTTLE_MS);
2399
+ }
2400
+ cancelPersist() {
2401
+ if (this._persistTimer !== null) {
2402
+ clearTimeout(this._persistTimer);
2403
+ this._persistTimer = null;
2404
+ }
2405
+ }
2406
+ /**
2407
+ * Start a send owned by the wrapper: optionally wait on `before` (the
2408
+ * background path waits for its snapshot to land), then deliver if online.
2409
+ * Failures are reported through the error listeners and never thrown into
2410
+ * the AppState callback that started it.
2411
+ */
2412
+ startWrapperFlush(before) {
2413
+ const tracked = (async () => {
2414
+ if (before) await before();
2415
+ if (!this.isOnline) return;
2416
+ await this.core.flushAsync();
2417
+ })().catch((e) => {
2418
+ if (e?.code === "SHUT_DOWN") return;
2419
+ this.emitError(e);
2420
+ }).finally(() => {
2421
+ this._wrapperFlushes.delete(tracked);
2422
+ });
2423
+ this._wrapperFlushes.add(tracked);
2424
+ }
2425
+ async waitForWrapperFlush() {
2426
+ if (this._wrapperFlushes.size === 0) return;
2427
+ await Promise.all(Array.from(this._wrapperFlushes));
2428
+ }
2429
+ /**
2430
+ * Make the queue durable, then try to send it. Used at the end of init()
2431
+ * and on the background transition.
2432
+ *
2433
+ * The snapshot is taken synchronously, and the send starts only once that
2434
+ * write has landed. The order matters: the send drains the batch out of the
2435
+ * queue, and a process killed mid-request must still find it on disk next
2436
+ * launch. Before this the background path took the snapshot and stopped,
2437
+ * so nothing was delivered until the app came back to the foreground, and
2438
+ * an Android app is usually killed rather than resumed.
2439
+ */
2440
+ persistThenSend() {
2441
+ this.cancelPersist();
2442
+ try {
2443
+ this.core.flush();
2444
+ } catch (e) {
2445
+ this.emitError(e);
2446
+ return;
2447
+ }
2448
+ this.startWrapperFlush(() => this.settleWrites());
2149
2449
  }
2150
2450
  /**
2151
2451
  * Remove every listener and timer this instance installed, then shut the
@@ -2155,6 +2455,7 @@ var LayersReactNative = class LayersReactNative {
2155
2455
  */
2156
2456
  teardownRuntime() {
2157
2457
  this.stopConfigPolling();
2458
+ this.cancelPersist();
2158
2459
  this.cancelLifecycleReachabilityCheck();
2159
2460
  if (this.appStateSubscription) {
2160
2461
  this.appStateSubscription.remove();
@@ -2439,6 +2740,7 @@ var LayersReactNative = class LayersReactNative {
2439
2740
  this._installReferrer = referrer;
2440
2741
  const parsed = parseInstallReferrerUrl(referrer.referrerUrl);
2441
2742
  this._installReferrerParams = Object.keys(parsed).length > 0 ? parsed : null;
2743
+ await this.recordReferrerDeepLink(referrer);
2442
2744
  if (parsed.fbclid || parsed.gclid || parsed.ttclid || parsed.msclkid) try {
2443
2745
  await this.setAttributionData(this._attributionDeeplinkId, parsed.gclid ?? this._attributionGclid, parsed.fbclid ?? this._attributionFbclid, parsed.ttclid ?? this._attributionTtclid, parsed.msclkid ?? this._attributionMsclkid);
2444
2746
  } catch {}
@@ -2521,7 +2823,7 @@ var LayersReactNative = class LayersReactNative {
2521
2823
  this.track("$app_background");
2522
2824
  lastEmittedState = "background";
2523
2825
  } catch {}
2524
- this.core.flush();
2826
+ this.persistThenSend();
2525
2827
  }
2526
2828
  if (nextAppState === "active") {
2527
2829
  if (this.config.autoTrackAppLifecycle !== false && lastEmittedState !== null && lastEmittedState !== "active") try {
@@ -2623,18 +2925,26 @@ var LayersReactNative = class LayersReactNative {
2623
2925
  } catch {}
2624
2926
  }
2625
2927
  };
2928
+ function createKeyedStorageQueue() {
2929
+ const tails = /* @__PURE__ */ new Map();
2930
+ const inFlight = /* @__PURE__ */ new Set();
2931
+ return {
2932
+ run(fullKey, operation) {
2933
+ const entry = (tails.get(fullKey) ?? Promise.resolve()).then(operation, operation).then(() => void 0, () => void 0);
2934
+ tails.set(fullKey, entry);
2935
+ inFlight.add(entry);
2936
+ entry.then(() => {
2937
+ inFlight.delete(entry);
2938
+ if (tails.get(fullKey) === entry) tails.delete(fullKey);
2939
+ });
2940
+ },
2941
+ settle: () => Promise.all(Array.from(inFlight)).then(() => void 0)
2942
+ };
2943
+ }
2626
2944
  async function createAsyncStoragePersistence(appId) {
2627
2945
  const prefix = `layers_sdk_${appId}_`;
2628
2946
  const memoryStore = /* @__PURE__ */ new Map();
2629
- const inFlight = /* @__PURE__ */ new Set();
2630
- const trackInFlight = (operation) => {
2631
- const entry = operation.then(() => {
2632
- inFlight.delete(entry);
2633
- }, () => {
2634
- inFlight.delete(entry);
2635
- });
2636
- inFlight.add(entry);
2637
- };
2947
+ const queue = createKeyedStorageQueue();
2638
2948
  try {
2639
2949
  const AsyncStorage = await loadAsyncStorage();
2640
2950
  if (AsyncStorage) {
@@ -2653,15 +2963,16 @@ async function createAsyncStoragePersistence(appId) {
2653
2963
  return {
2654
2964
  backend: {
2655
2965
  write(key, data) {
2656
- memoryStore.set(key, new Uint8Array(data));
2657
- trackInFlight(writeToAsyncStorage(prefix + key, data));
2966
+ const copy = new Uint8Array(data);
2967
+ memoryStore.set(key, copy);
2968
+ queue.run(prefix + key, () => writeToAsyncStorage(prefix + key, copy));
2658
2969
  },
2659
2970
  read(key) {
2660
2971
  return memoryStore.get(key) ?? null;
2661
2972
  },
2662
2973
  delete(key) {
2663
2974
  memoryStore.delete(key);
2664
- trackInFlight(deleteFromAsyncStorage(prefix + key));
2975
+ queue.run(prefix + key, () => deleteFromAsyncStorage(prefix + key));
2665
2976
  },
2666
2977
  listKeys(keyPrefix) {
2667
2978
  const keys = [];
@@ -2670,7 +2981,57 @@ async function createAsyncStoragePersistence(appId) {
2670
2981
  return keys;
2671
2982
  }
2672
2983
  },
2673
- settle: () => Promise.all(Array.from(inFlight)).then(() => void 0)
2984
+ settle: queue.settle,
2985
+ forget: (keyPrefix) => {
2986
+ for (const key of [...memoryStore.keys()]) if (key.startsWith(keyPrefix)) memoryStore.delete(key);
2987
+ }
2988
+ };
2989
+ }
2990
+ function createEagerPersistence(appId) {
2991
+ const prefix = `layers_sdk_${appId}_`;
2992
+ const mirrorKeyPrefix = `events_eager_${`${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`}_`;
2993
+ const memoryStore = /* @__PURE__ */ new Map();
2994
+ const mirrored = /* @__PURE__ */ new Set();
2995
+ const queue = createKeyedStorageQueue();
2996
+ let mirroring = true;
2997
+ return {
2998
+ backend: {
2999
+ write(key, data) {
3000
+ const copy = new Uint8Array(data);
3001
+ memoryStore.set(key, copy);
3002
+ if (mirroring && key.startsWith("events_")) {
3003
+ const fullKey = prefix + mirrorKeyPrefix + key;
3004
+ mirrored.add(fullKey);
3005
+ queue.run(fullKey, () => writeToAsyncStorage(fullKey, copy));
3006
+ }
3007
+ },
3008
+ read(key) {
3009
+ return memoryStore.get(key) ?? null;
3010
+ },
3011
+ delete(key) {
3012
+ memoryStore.delete(key);
3013
+ if (mirroring && key.startsWith("events_")) {
3014
+ const fullKey = prefix + mirrorKeyPrefix + key;
3015
+ queue.run(fullKey, () => deleteFromAsyncStorage(fullKey));
3016
+ }
3017
+ },
3018
+ listKeys(keyPrefix) {
3019
+ const keys = [];
3020
+ for (const k of memoryStore.keys()) if (k.startsWith(keyPrefix)) keys.push(k);
3021
+ keys.sort();
3022
+ return keys;
3023
+ }
3024
+ },
3025
+ mirrorKeyPrefix,
3026
+ stopMirroring: () => {
3027
+ mirroring = false;
3028
+ },
3029
+ settle: queue.settle,
3030
+ discardMirror: async () => {
3031
+ for (const key of mirrored) queue.run(key, () => deleteFromAsyncStorage(key));
3032
+ mirrored.clear();
3033
+ await queue.settle();
3034
+ }
2674
3035
  };
2675
3036
  }
2676
3037
  const B64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
@@ -3070,6 +3431,18 @@ function decodeFormUrlComponent(encoded) {
3070
3431
  }
3071
3432
  }
3072
3433
  /**
3434
+ * The query-string part of a raw Play Install Referrer string. Accepts either a
3435
+ * bare query string (`a=1&b=2`) or a full URL. Throws only on a malformed
3436
+ * envelope escape; callers catch.
3437
+ */
3438
+ function installReferrerQueryString(referrer) {
3439
+ let qs = referrer;
3440
+ const qIdx = qs.indexOf("?");
3441
+ if (qIdx >= 0) qs = qs.slice(qIdx + 1);
3442
+ if (!qs.includes("=") && qs.includes("%3D")) qs = decodeURIComponent(qs);
3443
+ return qs;
3444
+ }
3445
+ /**
3073
3446
  * Parse a raw Play Install Referrer string into a map of recognized attribution
3074
3447
  * params. Accepts either a bare query string (`a=1&b=2`) or a full URL.
3075
3448
  * Returns an empty object on parse failure.
@@ -3078,10 +3451,7 @@ function parseInstallReferrerUrl(referrer) {
3078
3451
  const out = {};
3079
3452
  if (!referrer) return out;
3080
3453
  try {
3081
- let qs = referrer;
3082
- const qIdx = qs.indexOf("?");
3083
- if (qIdx >= 0) qs = qs.slice(qIdx + 1);
3084
- if (!qs.includes("=") && qs.includes("%3D")) qs = decodeURIComponent(qs);
3454
+ const qs = installReferrerQueryString(referrer);
3085
3455
  for (const pair of qs.split("&")) {
3086
3456
  const eq = pair.indexOf("=");
3087
3457
  if (eq >= 0) {
@@ -3121,6 +3491,73 @@ function buildInstallReferrerProperties(referrer) {
3121
3491
  Object.assign(props, parseInstallReferrerUrl(referrer.referrerUrl));
3122
3492
  return props;
3123
3493
  }
3494
+ const DEFERRED_DEEPLINK_SOURCES = [
3495
+ "install_referrer",
3496
+ "click_resolve",
3497
+ "clipboard"
3498
+ ];
3499
+ /**
3500
+ * A tracking-link payload as a flat `Record<string, string>`, or null when it
3501
+ * holds nothing usable.
3502
+ *
3503
+ * Accepts the object `/clicks/resolve` returns or the JSON string the install
3504
+ * referrer carries. The server stores a flat string map; a finite number or a
3505
+ * boolean is kept as its string form, and anything nested is dropped rather
3506
+ * than stringified, so an app never receives a value it has to parse twice.
3507
+ */
3508
+ function normalizeDeferredDeepLinkPayload(raw) {
3509
+ let value = raw;
3510
+ if (typeof value === "string") try {
3511
+ value = JSON.parse(value);
3512
+ } catch {
3513
+ return null;
3514
+ }
3515
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return null;
3516
+ const out = {};
3517
+ for (const [key, v] of Object.entries(value)) if (typeof v === "string") out[key] = v;
3518
+ else if (typeof v === "number" && Number.isFinite(v)) out[key] = String(v);
3519
+ else if (typeof v === "boolean") out[key] = String(v);
3520
+ return Object.keys(out).length > 0 ? out : null;
3521
+ }
3522
+ /**
3523
+ * The tracking-link payload carried in a Play Install Referrer string's
3524
+ * `deeplink` param (JSON, form-urlencoded, as the Layers click page writes it),
3525
+ * or null when there is none.
3526
+ *
3527
+ * Kept apart from {@link parseInstallReferrerUrl} on purpose: that map feeds
3528
+ * the `install_referrer` event and `app_open` properties, whose shape is pinned
3529
+ * by `schema/fixtures/install-referrer-event.json` across every SDK.
3530
+ */
3531
+ function parseInstallReferrerDeepLink(referrer) {
3532
+ if (!referrer) return null;
3533
+ try {
3534
+ const qs = installReferrerQueryString(referrer);
3535
+ for (const pair of qs.split("&")) {
3536
+ const eq = pair.indexOf("=");
3537
+ if (eq >= 0 && decodeFormUrlComponent(pair.slice(0, eq)) === "deeplink") return normalizeDeferredDeepLinkPayload(decodeFormUrlComponent(pair.slice(eq + 1)));
3538
+ }
3539
+ } catch {}
3540
+ return null;
3541
+ }
3542
+ /** The persisted deferred deep link for this appId, and whether it was delivered. */
3543
+ function deferredDeepLinkKey(appId) {
3544
+ return `@layers/deferred_deeplink_${appId}`;
3545
+ }
3546
+ /**
3547
+ * Set once a `/clicks/resolve` probe has gone out for this appId, so
3548
+ * `resolveDeferredDeepLink()` never sends a second one for the same install.
3549
+ */
3550
+ function deferredClickResolveAttemptedKey(appId) {
3551
+ return `@layers/deferred_click_resolve_attempted_${appId}`;
3552
+ }
3553
+ function copyDeferredDeepLink(link) {
3554
+ const out = {
3555
+ payload: { ...link.payload },
3556
+ source: link.source
3557
+ };
3558
+ if (link.clickId) out.clickId = link.clickId;
3559
+ return out;
3560
+ }
3124
3561
  /**
3125
3562
  * Fetch the Google Play install referrer on Android via NativeModules.
3126
3563
  * Requires the `com.android.installreferrer` library on the native side.
@@ -3247,5 +3684,5 @@ function useLayersExpoRouterTracking(sdkInstance, usePathname, useGlobalSearchPa
3247
3684
  }
3248
3685
 
3249
3686
  //#endregion
3250
- export { superwallTrackSkip as $, useLayersNavigationTracking as A, trackAddToCart as B, readClipboardAttribution as C, installExceptionAutoCapture as Ct, SurveysModule as D, useLayersExpoRouterTracking as E, connectRevenueCat as F, trackRefund as G, trackOrder as H, isRevenueCatConnected as I, trackViewProduct as J, trackRemoveFromCart as K, resetRevenueCatForTesting as L, BACKGROUND_FLUSH_TASK_NAME as M, createBackgroundFlushHandler as N, createNavigationListener as O, registerExpoBackgroundFlush as P, superwallTrackPurchase as Q, syncRevenueCatAttributes as R, parseInstallReferrerUrl as S, buildExceptionProperties as St, shouldTreatAsNewInstall as T, trackPurchase as U, trackBeginCheckout as V, trackPurchaseFailed as W, superwallTrackDismiss as X, superwallOnEvent as Y, superwallTrackPresentation as Z, getFirstInstallTime as _, startTrialEvent as _t, buildBeginCheckoutEvent as a, levelCompleteEvent as at, getOrSetInstallId as b, viewContentEvent as bt, buildOnboardingStartEvent as c, onboardingCompleteEvent as ct, buildRefundEvent as d, purchaseEvent as dt, superwallUserAttributes as et, buildStartTrialEvent as f, registerEvent as ft, getAdServicesToken as g, signUpEvent as gt, formatFbc as h, shareEvent as ht, buildAddToCartEvent as i, initiateCheckoutEvent as it, BACKGROUND_FLUSH_MIN_INTERVAL_MINUTES as j, resolveActiveRoute as k, buildPaywallShowEvent as l, onboardingStartEvent as lt, buildViewItemEvent as m, searchEvent as mt, LayersEvent as n, addToCartEvent as nt, buildInstallReferrerProperties as o, levelStartEvent as ot, buildSubscribeEvent as p, screenViewEvent as pt, trackSubscription as q, LayersReactNative as r, addToWishlistEvent as rt, buildOnboardingCompleteEvent as s, loginEvent as st, LayersError$1 as t, StandardEvents as tt, buildPurchaseEvent as u, paywallShowEvent as ut, getGoogleAdvertisingId as v, subscribeEvent as vt, setupDeepLinkListener as w, parseDeepLink as x, viewItemEvent as xt, getInstallReferrer as y, tutorialCompleteEvent as yt, trackRevenueCatPurchase as z };
3251
- //# sourceMappingURL=src-BhzpYUDb.mjs.map
3687
+ export { superwallTrackPurchase as $, resolveActiveRoute as A, trackRevenueCatPurchase as B, parseInstallReferrerUrl as C, buildExceptionProperties as Ct, useLayersExpoRouterTracking as D, shouldTreatAsNewInstall as E, registerExpoBackgroundFlush as F, trackPurchaseFailed as G, trackBeginCheckout as H, connectRevenueCat as I, trackSubscription as J, trackRefund as K, isRevenueCatConnected as L, BACKGROUND_FLUSH_MIN_INTERVAL_MINUTES as M, BACKGROUND_FLUSH_TASK_NAME as N, SurveysModule as O, createBackgroundFlushHandler as P, superwallTrackPresentation as Q, resetRevenueCatForTesting as R, parseInstallReferrerDeepLink as S, viewItemEvent as St, setupDeepLinkListener as T, trackOrder as U, trackAddToCart as V, trackPurchase as W, superwallOnEvent as X, trackViewProduct as Y, superwallTrackDismiss as Z, getFirstInstallTime as _, signUpEvent as _t, buildBeginCheckoutEvent as a, initiateCheckoutEvent as at, getOrSetInstallId as b, tutorialCompleteEvent as bt, buildOnboardingStartEvent as c, loginEvent as ct, buildRefundEvent as d, paywallShowEvent as dt, superwallTrackSkip as et, buildStartTrialEvent as f, purchaseEvent as ft, getAdServicesToken as g, shareEvent as gt, formatFbc as h, searchEvent as ht, buildAddToCartEvent as i, addToWishlistEvent as it, useLayersNavigationTracking as j, createNavigationListener as k, buildPaywallShowEvent as l, onboardingCompleteEvent as lt, buildViewItemEvent as m, screenViewEvent as mt, LayersEvent as n, StandardEvents as nt, buildInstallReferrerProperties as o, levelCompleteEvent as ot, buildSubscribeEvent as p, registerEvent as pt, trackRemoveFromCart as q, LayersReactNative as r, addToCartEvent as rt, buildOnboardingCompleteEvent as s, levelStartEvent as st, LayersError$1 as t, superwallUserAttributes as tt, buildPurchaseEvent as u, onboardingStartEvent as ut, getGoogleAdvertisingId as v, startTrialEvent as vt, readClipboardAttribution as w, installExceptionAutoCapture as wt, parseDeepLink as x, viewContentEvent as xt, getInstallReferrer as y, subscribeEvent as yt, syncRevenueCatAttributes as z };
3688
+ //# sourceMappingURL=src-bqgkPFIj.mjs.map