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