@layers/react-native 3.3.2 → 3.3.4

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.
@@ -712,8 +712,9 @@ function connectRevenueCat(config, purchases) {
712
712
  purchases.addCustomerInfoUpdateListener((info) => {
713
713
  handleCustomerInfoUpdate(config, info, false);
714
714
  });
715
- purchases.getCustomerInfo().then(({ customerInfo }) => {
716
- handleCustomerInfoUpdate(config, customerInfo, true);
715
+ purchases.getCustomerInfo().then((result) => {
716
+ const customerInfo = unwrapCustomerInfo(result);
717
+ if (customerInfo) handleCustomerInfoUpdate(config, customerInfo, true);
717
718
  }).catch(() => {});
718
719
  _isConnected = true;
719
720
  } catch {}
@@ -773,6 +774,18 @@ function resetRevenueCatForTesting() {
773
774
  function isRevenueCatConnected() {
774
775
  return _isConnected;
775
776
  }
777
+ /**
778
+ * Accept both shapes `getCustomerInfo()` can resolve to: the `CustomerInfo`
779
+ * object `react-native-purchases` actually returns, and a `{ customerInfo }`
780
+ * wrapper. Destructuring `{ customerInfo }` from the real return read
781
+ * `undefined`, so the first subscriber sync never ran.
782
+ */
783
+ function unwrapCustomerInfo(result) {
784
+ if (!result || typeof result !== "object") return null;
785
+ const wrapped = result.customerInfo;
786
+ if (wrapped && typeof wrapped === "object") return wrapped;
787
+ return result;
788
+ }
776
789
  function handleCustomerInfoUpdate(config, info, isInitialLoad) {
777
790
  try {
778
791
  const currentSubs = new Set(Array.isArray(info.activeSubscriptions) ? info.activeSubscriptions : []);
@@ -1110,16 +1123,21 @@ function hostAppIsRegisteredOn(rn) {
1110
1123
  }
1111
1124
  }
1112
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'.";
1113
- const SDK_VERSION = "3.3.2";
1126
+ const SDK_VERSION = "3.3.4";
1114
1127
  var LayersReactNative = class LayersReactNative {
1115
1128
  core;
1116
- eagerPersistence;
1129
+ eager;
1130
+ get eagerPersistence() {
1131
+ return this.eager.backend;
1132
+ }
1117
1133
  appUserId;
1118
1134
  isOnline = true;
1119
1135
  enableDebug;
1120
1136
  appStateSubscription = null;
1121
1137
  exceptionUninstall = null;
1122
1138
  persistenceSettle = null;
1139
+ _persistTimer = null;
1140
+ _wrapperFlushes = /* @__PURE__ */ new Set();
1123
1141
  _lifecycleCheckTimer = null;
1124
1142
  netInfoUnsubscribe = null;
1125
1143
  config;
@@ -1136,10 +1154,13 @@ var LayersReactNative = class LayersReactNative {
1136
1154
  _runtimeGeneration = 0;
1137
1155
  _configPollTimer = null;
1138
1156
  static CONFIG_POLL_INTERVAL_MS = 3e5;
1157
+ static PERSIST_THROTTLE_MS = 1e3;
1139
1158
  _adServicesToken = null;
1140
1159
  _installReferrer = null;
1160
+ _gaid = null;
1141
1161
  _installReferrerParams = null;
1142
1162
  _hadPriorSdkState = false;
1163
+ _hadPriorAppIdentity = false;
1143
1164
  _attributionDeeplinkId = null;
1144
1165
  _attributionGclid = null;
1145
1166
  _attributionFbclid = null;
@@ -1158,7 +1179,7 @@ var LayersReactNative = class LayersReactNative {
1158
1179
  this.appUserId = config.appUserId;
1159
1180
  this.config = config;
1160
1181
  const httpClient = new __layers_core_wasm.FetchHttpClient();
1161
- this.eagerPersistence = new __layers_core_wasm.MemoryPersistence();
1182
+ this.eager = createEagerPersistence(config.appId);
1162
1183
  this.core = __layers_core_wasm.LayersCore.init({
1163
1184
  config: {
1164
1185
  appId: config.appId,
@@ -1302,12 +1323,20 @@ var LayersReactNative = class LayersReactNative {
1302
1323
  const initStartTime = Date.now();
1303
1324
  if (typeof WebAssembly !== "undefined") await (0, __layers_core_wasm.initWasm)();
1304
1325
  if (this.initAborted(generation)) return;
1326
+ this._hadPriorAppIdentity = false;
1305
1327
  try {
1306
- const { backend: persistence, settle: persistenceSettle } = await createAsyncStoragePersistence(this.config.appId);
1328
+ const { backend: persistence, settle: persistenceSettle, forget: forgetPreloaded } = await createAsyncStoragePersistence(this.config.appId);
1329
+ try {
1330
+ const record = persistence.read("identity_state");
1331
+ this._hadPriorAppIdentity = record != null && record.length > 0;
1332
+ } catch {
1333
+ this._hadPriorAppIdentity = false;
1334
+ }
1307
1335
  if (this.initAborted(generation)) return;
1308
1336
  this.persistenceSettle = persistenceSettle;
1309
1337
  const httpClient = new __layers_core_wasm.FetchHttpClient();
1310
1338
  const migrationState = this.core.exportMigrationState();
1339
+ this.eager.stopMirroring();
1311
1340
  this.core.shutdown();
1312
1341
  try {
1313
1342
  let migrated = 0;
@@ -1320,6 +1349,7 @@ var LayersReactNative = class LayersReactNative {
1320
1349
  this.eagerPersistence.delete(key);
1321
1350
  }
1322
1351
  } catch {}
1352
+ forgetPreloaded(this.eager.mirrorKeyPrefix);
1323
1353
  this.core = __layers_core_wasm.LayersCore.init({
1324
1354
  config: {
1325
1355
  appId: this.config.appId,
@@ -1340,6 +1370,10 @@ var LayersReactNative = class LayersReactNative {
1340
1370
  this._runtimeGeneration = generation;
1341
1371
  require_skan.setSkanCore(this.core);
1342
1372
  if (this.appUserId) this.core.identify(this.appUserId);
1373
+ try {
1374
+ this.core.flush();
1375
+ } catch {}
1376
+ persistenceSettle().then(() => this.eager.discardMirror()).catch(() => void 0);
1343
1377
  } catch {}
1344
1378
  await this.restoreAttributionData();
1345
1379
  await this.initializeDeviceInfo();
@@ -1373,6 +1407,7 @@ var LayersReactNative = class LayersReactNative {
1373
1407
  if (this.config.autoTrackAppOpen !== false) {
1374
1408
  const appOpenProps = {};
1375
1409
  let isFirstLaunchByFlag = true;
1410
+ let priorLaunchDecided = false;
1376
1411
  try {
1377
1412
  const AsyncStorage = await loadAsyncStorage();
1378
1413
  if (AsyncStorage) {
@@ -1387,14 +1422,16 @@ var LayersReactNative = class LayersReactNative {
1387
1422
  }
1388
1423
  }
1389
1424
  if (flag === "true") isFirstLaunchByFlag = false;
1425
+ if (isFirstLaunchByFlag && this._hadPriorAppIdentity) priorLaunchDecided = await AsyncStorage.getItem(LAST_APP_VERSION_KEY) !== null;
1390
1426
  if (adoptLegacy) try {
1391
1427
  await AsyncStorage.setItem(scopedKey, "true");
1392
1428
  await AsyncStorage.removeItem(FIRST_LAUNCH_TRACKED_KEY_LEGACY);
1393
1429
  } catch {}
1394
1430
  }
1395
1431
  } catch {}
1396
- const isFirstLaunch = await shouldTreatAsNewInstall(isFirstLaunchByFlag, this._hadPriorSdkState, this.enableDebug);
1432
+ const isFirstLaunch = await shouldTreatAsNewInstall(isFirstLaunchByFlag, this._hadPriorSdkState, this.enableDebug, () => this.readFirstInstallTime(), priorLaunchDecided);
1397
1433
  appOpenProps.is_first_launch = isFirstLaunch;
1434
+ if (isFirstLaunchByFlag && !isFirstLaunch) await this.persistFirstLaunchHandled();
1398
1435
  let hasAttribution = this._attributionFbclid != null || this._attributionGclid != null || this._attributionTtclid != null || this._attributionMsclkid != null;
1399
1436
  if (fingerprintResolveEnabled && isFirstLaunch && !hasAttribution) try {
1400
1437
  await this.resolveClickFromFingerprint();
@@ -1415,10 +1452,7 @@ var LayersReactNative = class LayersReactNative {
1415
1452
  if (this.initAborted(generation)) return;
1416
1453
  if (isFirstLaunch) this.track("app_install", appOpenProps);
1417
1454
  this.track("app_open", appOpenProps);
1418
- if (isFirstLaunch) try {
1419
- const AsyncStorage = await loadAsyncStorage();
1420
- if (AsyncStorage) await AsyncStorage.setItem(firstLaunchTrackedKey(this.config.appId), "true");
1421
- } catch {}
1455
+ if (isFirstLaunch) await this.persistFirstLaunchHandled();
1422
1456
  if (this.config.autoTrackAppUpdate !== false) try {
1423
1457
  const currentVersion = this.core.getDeviceContext().appVersion ?? appOpenProps.app_version;
1424
1458
  if (currentVersion && typeof currentVersion === "string") {
@@ -1445,6 +1479,7 @@ var LayersReactNative = class LayersReactNative {
1445
1479
  ...typeof __DEV__ !== "undefined" && __DEV__ === true ? {} : { onFatal: () => this.persistForCrash() }
1446
1480
  });
1447
1481
  this._isInitialized = true;
1482
+ this.persistThenSend();
1448
1483
  const totalDurationMs = Date.now() - initStartTime;
1449
1484
  if (this.enableDebug) console.log(`[Layers] Init timing: mainThread=${String(mainThreadDurationMs)}ms, total=${String(totalDurationMs)}ms`);
1450
1485
  if (this._initListener) try {
@@ -1460,6 +1495,7 @@ var LayersReactNative = class LayersReactNative {
1460
1495
  const depthBefore = this.core.queueDepth();
1461
1496
  this.core.track(eventName, merged, this.appUserId);
1462
1497
  const depthAfter = this.core.queueDepth();
1498
+ this.schedulePersist();
1463
1499
  if (depthAfter <= depthBefore && this.enableDebug) console.warn(`[Layers] track("${eventName}") — event may not have been queued (depth before=${String(depthBefore)}, after=${String(depthAfter)})`);
1464
1500
  this.recordRecentEvent(eventName, properties);
1465
1501
  if (this._skanManager) this._skanManager.processEvent(eventName, merged ?? {}).catch(() => {});
@@ -1488,6 +1524,7 @@ var LayersReactNative = class LayersReactNative {
1488
1524
  const depthBefore = this.core.queueDepth();
1489
1525
  this.core.screen(screenName, merged, this.appUserId);
1490
1526
  const depthAfter = this.core.queueDepth();
1527
+ this.schedulePersist();
1491
1528
  if (depthAfter <= depthBefore && this.enableDebug) console.warn(`[Layers] screen("${screenName}") — event may not have been queued (depth before=${String(depthBefore)}, after=${String(depthAfter)})`);
1492
1529
  this.recordRecentEvent(`screen:${screenName}`, properties);
1493
1530
  if (forwardToSkan && this._skanManager) {
@@ -1509,6 +1546,47 @@ var LayersReactNative = class LayersReactNative {
1509
1546
  }
1510
1547
  async setConsent(consent) {
1511
1548
  this.core.setConsent(consent);
1549
+ this.applyGaidConsent();
1550
+ }
1551
+ /**
1552
+ * Whether the app has explicitly denied advertising consent
1553
+ * (`adStorage: false`, or the legacy `advertising: false`). Unset means
1554
+ * allowed, the same default as the engine's ad gate and the Kotlin SDK.
1555
+ */
1556
+ advertisingConsentDenied() {
1557
+ try {
1558
+ const consent = this.core.getConsentState();
1559
+ return (consent.adStorage ?? consent.advertising) === false;
1560
+ } catch {
1561
+ return false;
1562
+ }
1563
+ }
1564
+ /**
1565
+ * Keep the Google Advertising ID on the device context unless the app has
1566
+ * explicitly denied advertising consent, and take it off when it has.
1567
+ *
1568
+ * The GAID is sent by default, as mobile measurement partners and the
1569
+ * Kotlin SDK do. It honours two opt-outs: the user's Limit Ad Tracking
1570
+ * setting (applied where the GAID is read) and the app's consent API.
1571
+ * Revoking removes it from later events and re-granting restores it. No
1572
+ * `att_status` is set on Android: that field carries Apple's ATT answer.
1573
+ */
1574
+ applyGaidConsent() {
1575
+ const gaid = this._gaid;
1576
+ if (!gaid) return;
1577
+ try {
1578
+ const context = this.core.getDeviceContext();
1579
+ const granted = !this.advertisingConsentDenied();
1580
+ if (granted && context.idfa !== gaid) this.core.setDeviceContext({
1581
+ ...context,
1582
+ idfa: gaid
1583
+ });
1584
+ else if (!granted && context.idfa === gaid) {
1585
+ const next = { ...context };
1586
+ delete next.idfa;
1587
+ this.core.setDeviceContext(next);
1588
+ }
1589
+ } catch {}
1512
1590
  }
1513
1591
  /** Evaluate a feature flag. Emits `$feature_flag_called` (deduped per session). */
1514
1592
  getFeatureFlag(flagKey) {
@@ -1808,6 +1886,7 @@ var LayersReactNative = class LayersReactNative {
1808
1886
  this.core.setDeviceContext(next);
1809
1887
  }
1810
1888
  async flush() {
1889
+ await this.waitForWrapperFlush();
1811
1890
  try {
1812
1891
  await this.core.flushAsync();
1813
1892
  } catch (e) {
@@ -2080,10 +2159,90 @@ var LayersReactNative = class LayersReactNative {
2080
2159
  * held open only for the write.
2081
2160
  */
2082
2161
  async persistForCrash() {
2162
+ this.cancelPersist();
2083
2163
  try {
2084
2164
  this.core.flush();
2085
2165
  } catch {}
2086
- if (this.persistenceSettle) await this.persistenceSettle();
2166
+ await this.settleWrites();
2167
+ }
2168
+ /**
2169
+ * Resolves once every AsyncStorage write started so far has landed: the
2170
+ * durable backend's, and the eager store's mirror (the only durable copy of
2171
+ * pre-init events until the core swap).
2172
+ */
2173
+ async settleWrites() {
2174
+ await Promise.all([this.eager.settle(), this.persistenceSettle?.()]);
2175
+ }
2176
+ /**
2177
+ * Snapshot the queue to disk within {@link PERSIST_THROTTLE_MS} of an
2178
+ * accepted event.
2179
+ *
2180
+ * The engine writes its crash-safety snapshot only at the flush threshold,
2181
+ * on a delivery verdict, on background and at shutdown. A short session
2182
+ * (the typical lost Android install: 13 events in 13 seconds) reached none
2183
+ * of those before the process died, so its events never left memory.
2184
+ * Throttled rather than per event: each snapshot serializes the whole
2185
+ * queue, and one write per burst also keeps same-key writes apart on
2186
+ * AsyncStorage v3, which does not order them.
2187
+ */
2188
+ schedulePersist() {
2189
+ if (this._persistTimer !== null) return;
2190
+ this._persistTimer = setTimeout(() => {
2191
+ this._persistTimer = null;
2192
+ try {
2193
+ this.core.flush();
2194
+ } catch {}
2195
+ }, LayersReactNative.PERSIST_THROTTLE_MS);
2196
+ }
2197
+ cancelPersist() {
2198
+ if (this._persistTimer !== null) {
2199
+ clearTimeout(this._persistTimer);
2200
+ this._persistTimer = null;
2201
+ }
2202
+ }
2203
+ /**
2204
+ * Start a send owned by the wrapper: optionally wait on `before` (the
2205
+ * background path waits for its snapshot to land), then deliver if online.
2206
+ * Failures are reported through the error listeners and never thrown into
2207
+ * the AppState callback that started it.
2208
+ */
2209
+ startWrapperFlush(before) {
2210
+ const tracked = (async () => {
2211
+ if (before) await before();
2212
+ if (!this.isOnline) return;
2213
+ await this.core.flushAsync();
2214
+ })().catch((e) => {
2215
+ if (e?.code === "SHUT_DOWN") return;
2216
+ this.emitError(e);
2217
+ }).finally(() => {
2218
+ this._wrapperFlushes.delete(tracked);
2219
+ });
2220
+ this._wrapperFlushes.add(tracked);
2221
+ }
2222
+ async waitForWrapperFlush() {
2223
+ if (this._wrapperFlushes.size === 0) return;
2224
+ await Promise.all(Array.from(this._wrapperFlushes));
2225
+ }
2226
+ /**
2227
+ * Make the queue durable, then try to send it. Used at the end of init()
2228
+ * and on the background transition.
2229
+ *
2230
+ * The snapshot is taken synchronously, and the send starts only once that
2231
+ * write has landed. The order matters: the send drains the batch out of the
2232
+ * queue, and a process killed mid-request must still find it on disk next
2233
+ * launch. Before this the background path took the snapshot and stopped,
2234
+ * so nothing was delivered until the app came back to the foreground, and
2235
+ * an Android app is usually killed rather than resumed.
2236
+ */
2237
+ persistThenSend() {
2238
+ this.cancelPersist();
2239
+ try {
2240
+ this.core.flush();
2241
+ } catch (e) {
2242
+ this.emitError(e);
2243
+ return;
2244
+ }
2245
+ this.startWrapperFlush(() => this.settleWrites());
2087
2246
  }
2088
2247
  /**
2089
2248
  * Remove every listener and timer this instance installed, then shut the
@@ -2093,6 +2252,7 @@ var LayersReactNative = class LayersReactNative {
2093
2252
  */
2094
2253
  teardownRuntime() {
2095
2254
  this.stopConfigPolling();
2255
+ this.cancelPersist();
2096
2256
  this.cancelLifecycleReachabilityCheck();
2097
2257
  if (this.appStateSubscription) {
2098
2258
  this.appStateSubscription.remove();
@@ -2277,7 +2437,31 @@ var LayersReactNative = class LayersReactNative {
2277
2437
  }
2278
2438
  });
2279
2439
  }
2440
+ /**
2441
+ * Record that this install's first launch has been decided, whichever way.
2442
+ * Best-effort: without AsyncStorage nothing persists anyway.
2443
+ */
2444
+ async persistFirstLaunchHandled() {
2445
+ try {
2446
+ const AsyncStorage = await loadAsyncStorage();
2447
+ if (AsyncStorage) await AsyncStorage.setItem(firstLaunchTrackedKey(this.config.appId), "true");
2448
+ } catch {}
2449
+ }
2450
+ /**
2451
+ * The package's first install time, for the 24-hour install gate. A method
2452
+ * so tests can drive the gate: the native module sits behind a real CJS
2453
+ * `require('react-native')` (same seam as `collectInstallReferrer`).
2454
+ */
2455
+ readFirstInstallTime() {
2456
+ return getFirstInstallTime();
2457
+ }
2280
2458
  async initializeDeviceInfo() {
2459
+ try {
2460
+ const gaid = await this.collectGoogleAdvertisingId();
2461
+ this._gaid = gaid && !gaid.isLimitAdTrackingEnabled ? gaid.id : null;
2462
+ } catch {
2463
+ this._gaid = null;
2464
+ }
2281
2465
  try {
2282
2466
  const { Platform, Dimensions, NativeModules } = require("react-native");
2283
2467
  const window = Dimensions.get("window");
@@ -2311,11 +2495,7 @@ var LayersReactNative = class LayersReactNative {
2311
2495
  const idfv = await require_att.getVendorId();
2312
2496
  if (idfv) context.idfv = idfv;
2313
2497
  } catch {}
2314
- if (Platform.OS === "android") try {
2315
- const gaid = await getGoogleAdvertisingId();
2316
- if (gaid) context.idfa = gaid.id;
2317
- if (gaid && gaid.isLimitAdTrackingEnabled != null) context.attStatus = gaid.isLimitAdTrackingEnabled ? "denied" : "authorized";
2318
- } catch {}
2498
+ if (this._gaid && !this.advertisingConsentDenied()) context.idfa = this._gaid;
2319
2499
  try {
2320
2500
  const AsyncStorage = await loadAsyncStorage();
2321
2501
  if (AsyncStorage) this._hadPriorSdkState = await AsyncStorage.getItem(INSTALL_ID_KEY) != null;
@@ -2340,6 +2520,7 @@ var LayersReactNative = class LayersReactNative {
2340
2520
  const installId = await getOrSetInstallId();
2341
2521
  if (installId) context.installId = installId;
2342
2522
  } catch {}
2523
+ if (this._gaid && !this.advertisingConsentDenied()) context.idfa = this._gaid;
2343
2524
  this.core.setDeviceContext(context);
2344
2525
  }
2345
2526
  this._installReferrerParams = null;
@@ -2374,6 +2555,10 @@ var LayersReactNative = class LayersReactNative {
2374
2555
  collectInstallReferrer() {
2375
2556
  return getInstallReferrer();
2376
2557
  }
2558
+ /** Read the Google Advertising ID. A method for the same test seam. */
2559
+ collectGoogleAdvertisingId() {
2560
+ return getGoogleAdvertisingId();
2561
+ }
2377
2562
  /**
2378
2563
  * Emit the canonical `install_referrer` event (Android only).
2379
2564
  *
@@ -2434,7 +2619,7 @@ var LayersReactNative = class LayersReactNative {
2434
2619
  this.track("$app_background");
2435
2620
  lastEmittedState = "background";
2436
2621
  } catch {}
2437
- this.core.flush();
2622
+ this.persistThenSend();
2438
2623
  }
2439
2624
  if (nextAppState === "active") {
2440
2625
  if (this.config.autoTrackAppLifecycle !== false && lastEmittedState !== null && lastEmittedState !== "active") try {
@@ -2536,18 +2721,26 @@ var LayersReactNative = class LayersReactNative {
2536
2721
  } catch {}
2537
2722
  }
2538
2723
  };
2724
+ function createKeyedStorageQueue() {
2725
+ const tails = /* @__PURE__ */ new Map();
2726
+ const inFlight = /* @__PURE__ */ new Set();
2727
+ return {
2728
+ run(fullKey, operation) {
2729
+ const entry = (tails.get(fullKey) ?? Promise.resolve()).then(operation, operation).then(() => void 0, () => void 0);
2730
+ tails.set(fullKey, entry);
2731
+ inFlight.add(entry);
2732
+ entry.then(() => {
2733
+ inFlight.delete(entry);
2734
+ if (tails.get(fullKey) === entry) tails.delete(fullKey);
2735
+ });
2736
+ },
2737
+ settle: () => Promise.all(Array.from(inFlight)).then(() => void 0)
2738
+ };
2739
+ }
2539
2740
  async function createAsyncStoragePersistence(appId) {
2540
2741
  const prefix = `layers_sdk_${appId}_`;
2541
2742
  const memoryStore = /* @__PURE__ */ new Map();
2542
- const inFlight = /* @__PURE__ */ new Set();
2543
- const trackInFlight = (operation) => {
2544
- const entry = operation.then(() => {
2545
- inFlight.delete(entry);
2546
- }, () => {
2547
- inFlight.delete(entry);
2548
- });
2549
- inFlight.add(entry);
2550
- };
2743
+ const queue = createKeyedStorageQueue();
2551
2744
  try {
2552
2745
  const AsyncStorage = await loadAsyncStorage();
2553
2746
  if (AsyncStorage) {
@@ -2566,15 +2759,16 @@ async function createAsyncStoragePersistence(appId) {
2566
2759
  return {
2567
2760
  backend: {
2568
2761
  write(key, data) {
2569
- memoryStore.set(key, new Uint8Array(data));
2570
- trackInFlight(writeToAsyncStorage(prefix + key, data));
2762
+ const copy = new Uint8Array(data);
2763
+ memoryStore.set(key, copy);
2764
+ queue.run(prefix + key, () => writeToAsyncStorage(prefix + key, copy));
2571
2765
  },
2572
2766
  read(key) {
2573
2767
  return memoryStore.get(key) ?? null;
2574
2768
  },
2575
2769
  delete(key) {
2576
2770
  memoryStore.delete(key);
2577
- trackInFlight(deleteFromAsyncStorage(prefix + key));
2771
+ queue.run(prefix + key, () => deleteFromAsyncStorage(prefix + key));
2578
2772
  },
2579
2773
  listKeys(keyPrefix) {
2580
2774
  const keys = [];
@@ -2583,7 +2777,57 @@ async function createAsyncStoragePersistence(appId) {
2583
2777
  return keys;
2584
2778
  }
2585
2779
  },
2586
- settle: () => Promise.all(Array.from(inFlight)).then(() => void 0)
2780
+ settle: queue.settle,
2781
+ forget: (keyPrefix) => {
2782
+ for (const key of [...memoryStore.keys()]) if (key.startsWith(keyPrefix)) memoryStore.delete(key);
2783
+ }
2784
+ };
2785
+ }
2786
+ function createEagerPersistence(appId) {
2787
+ const prefix = `layers_sdk_${appId}_`;
2788
+ const mirrorKeyPrefix = `events_eager_${`${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`}_`;
2789
+ const memoryStore = /* @__PURE__ */ new Map();
2790
+ const mirrored = /* @__PURE__ */ new Set();
2791
+ const queue = createKeyedStorageQueue();
2792
+ let mirroring = true;
2793
+ return {
2794
+ backend: {
2795
+ write(key, data) {
2796
+ const copy = new Uint8Array(data);
2797
+ memoryStore.set(key, copy);
2798
+ if (mirroring && key.startsWith("events_")) {
2799
+ const fullKey = prefix + mirrorKeyPrefix + key;
2800
+ mirrored.add(fullKey);
2801
+ queue.run(fullKey, () => writeToAsyncStorage(fullKey, copy));
2802
+ }
2803
+ },
2804
+ read(key) {
2805
+ return memoryStore.get(key) ?? null;
2806
+ },
2807
+ delete(key) {
2808
+ memoryStore.delete(key);
2809
+ if (mirroring && key.startsWith("events_")) {
2810
+ const fullKey = prefix + mirrorKeyPrefix + key;
2811
+ queue.run(fullKey, () => deleteFromAsyncStorage(fullKey));
2812
+ }
2813
+ },
2814
+ listKeys(keyPrefix) {
2815
+ const keys = [];
2816
+ for (const k of memoryStore.keys()) if (k.startsWith(keyPrefix)) keys.push(k);
2817
+ keys.sort();
2818
+ return keys;
2819
+ }
2820
+ },
2821
+ mirrorKeyPrefix,
2822
+ stopMirroring: () => {
2823
+ mirroring = false;
2824
+ },
2825
+ settle: queue.settle,
2826
+ discardMirror: async () => {
2827
+ for (const key of mirrored) queue.run(key, () => deleteFromAsyncStorage(key));
2828
+ mirrored.clear();
2829
+ await queue.settle();
2830
+ }
2587
2831
  };
2588
2832
  }
2589
2833
  const B64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
@@ -2808,8 +3052,11 @@ async function getFirstInstallTime() {
2808
3052
  * 1. If `isFirstLaunchByFlag` is `false` (flag already tracked), return `false`.
2809
3053
  * 2. If the SDK had prior state (`install_id` already existed in
2810
3054
  * AsyncStorage), trust the flag — this is a returning user whose
2811
- * first-launch flag was not yet written (e.g. upgrade from an older
2812
- * SDK version). Return `true`.
3055
+ * first-launch flag was not yet written (e.g. a first launch that died
3056
+ * before the flag write). Return `true` — UNLESS `priorLaunchDecided`
3057
+ * says an earlier launch already reached the decision and did not record
3058
+ * it (a launch on 3.3.2 or earlier that suppressed `app_install`, see the
3059
+ * caller). Then return `false`.
2813
3060
  * 3. If the SDK had NO prior state AND the app was installed more than
2814
3061
  * 24 hours ago, this is an existing app getting the SDK for the first
2815
3062
  * time — suppress `is_first_launch`. Return `false`.
@@ -2820,10 +3067,12 @@ async function getFirstInstallTime() {
2820
3067
  * @param isFirstLaunchByFlag Whether the first_launch flag has NOT been set yet (true = not yet tracked).
2821
3068
  * @param hadPriorSdkState Whether `install_id` already existed before init.
2822
3069
  * @param enableDebug Whether to log debug info.
3070
+ * @param priorLaunchDecided Whether an earlier launch already made the
3071
+ * install decision without writing the flag.
2823
3072
  */
2824
- async function shouldTreatAsNewInstall(isFirstLaunchByFlag, hadPriorSdkState, enableDebug = false, _getInstallTime = getFirstInstallTime) {
3073
+ async function shouldTreatAsNewInstall(isFirstLaunchByFlag, hadPriorSdkState, enableDebug = false, _getInstallTime = getFirstInstallTime, priorLaunchDecided = false) {
2825
3074
  if (!isFirstLaunchByFlag) return false;
2826
- if (hadPriorSdkState) return true;
3075
+ if (hadPriorSdkState) return !priorLaunchDecided;
2827
3076
  try {
2828
3077
  const firstInstallTime = await _getInstallTime();
2829
3078
  if (firstInstallTime != null) {