@app-swiss-knife/react-native-sdk 0.3.2 → 0.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.
@@ -91,7 +91,13 @@ const FATAL_SEND_TIMEOUT_MS = 2_000;
91
91
  const DEFAULT_MAX_CACHE_ITEMS = 30;
92
92
  const OFFLINE_QUEUE_KEY = "@swissknife:crash:queue";
93
93
  const OFFLINE_SESSION_KEY = "@swissknife:crash:session";
94
+ /** Started/ended session events waiting on a retry (see Session Outbox). */
95
+ const OFFLINE_SESSIONS_KEY = "@swissknife:crash:sessions";
96
+ /** Cap on queued session events — drop-oldest beyond this. */
97
+ const MAX_PENDING_SESSIONS = 50;
94
98
  const OFFLINE_SCREENSHOTS_KEY = "@swissknife:crash:screenshots";
99
+ /** JS-side install id, only for apps without the native Identity bridge. */
100
+ const INSTALL_ID_KEY = "@swissknife:crash:install_id";
95
101
 
96
102
  // MARK: - Stack Trace Parsing
97
103
 
@@ -171,6 +177,8 @@ let _breadcrumbs = new RingBuffer(100);
171
177
  let _tags = {};
172
178
  let _extra = {};
173
179
  let _user = null;
180
+ /** Scope-level fingerprint (configureScope → setFingerprint). */
181
+ let _fingerprint = null;
174
182
  let _pendingEvents = [];
175
183
  /**
176
184
  * Events handed to an in-flight POST: already out of `_pendingEvents`, not
@@ -236,8 +244,20 @@ let _screenshotCaptureOverride;
236
244
  // `Identity.current()` also carries an `anonymousId`, and stamping it into
237
245
  // `user.id` would make "affected users" non-zero for every app that never
238
246
  // logs in. That both inflates the number and diverges from Analytics, whose
239
- // `user_id` is the identified subject only. The anonymous id already travels
240
- // separately on the ingest envelope. Only `userId` is used here.
247
+ // `user_id` is the identified subject only. The anonymous id travels
248
+ // separately, as the wire event's `installId` (see below) — the server counts
249
+ // affected users by user id, else install id, without conflating the two.
250
+
251
+ // ## installId — the stable per-install id
252
+ //
253
+ // Most crashes have no identified subject, so the server counts affected
254
+ // users by `installId` when `user.id` is absent. It is the Identity bridge's
255
+ // `anonymousId` (`$SKAnonymousID:<device id>` — the same value native crashes
256
+ // carry on their ingest envelope and `app_users.anonymous_id` stores, so the
257
+ // dashboard can link an anonymous install to its profile). Apps without the
258
+ // native Identity bridge get a random id persisted in AsyncStorage; without
259
+ // AsyncStorage no installId is sent at all, because a per-launch id would
260
+ // count every relaunch as a new user.
241
261
 
242
262
  /**
243
263
  * Last resolved identified subject id from the native Identity bridge.
@@ -246,6 +266,14 @@ let _screenshotCaptureOverride;
246
266
  * stamped, which is exactly today's behaviour for apps that never log in.
247
267
  */
248
268
  let _identityUserId = null;
269
+ /** Last resolved `Identity.current().anonymousId` (stable per install). */
270
+ let _identityAnonymousId = null;
271
+ /** AsyncStorage-persisted install id; used only when no Identity bridge. */
272
+ let _jsInstallId = null;
273
+ /** In-flight `loadJsInstallId`, so a flush racing init can wait for it. */
274
+ let _jsInstallIdLoad = null;
275
+ /** `_jsInstallIdLoad` has settled — flush skips the wait (and its hops). */
276
+ let _jsInstallIdSettled = false;
249
277
  /** In-flight read, so N events in a burst share one bridge hop. */
250
278
  let _identityRefresh = null;
251
279
  /** Monotonic read counter — a superseded read must not clobber a newer one. */
@@ -259,6 +287,8 @@ let _identityGeneration = 0;
259
287
  */
260
288
  let _identityResolverOverride;
261
289
 
290
+ /** The fields of the native `Identity.current()` snapshot this module reads. */
291
+
262
292
  /** Budget for the send-time identity re-resolve. Kept well under
263
293
  * FATAL_SEND_TIMEOUT_MS so a slow bridge can never eat the fatal path's
264
294
  * one chance to deliver before the process dies. */
@@ -306,6 +336,11 @@ function startIdentityRead() {
306
336
  if (generation !== _identityGeneration) return; // superseded
307
337
  const userId = snapshot?.userId;
308
338
  _identityUserId = typeof userId === "string" && userId.length > 0 ? userId : null;
339
+ // Never blanked by a later empty answer: the id is per install.
340
+ const anonymousId = snapshot?.anonymousId;
341
+ if (typeof anonymousId === "string" && anonymousId.length > 0) {
342
+ _identityAnonymousId = anonymousId;
343
+ }
309
344
  } catch {
310
345
  // Bridge hiccup — keep the last known subject.
311
346
  } finally {
@@ -384,6 +419,61 @@ function mergeIdentityInto(user) {
384
419
  };
385
420
  }
386
421
 
422
+ /** Resolve when `p` settles or after `ms`, whichever is first. Never rejects. */
423
+ function withTimeout(p, ms) {
424
+ return new Promise(resolve => {
425
+ const timer = setTimeout(resolve, ms);
426
+ void p.then(() => {
427
+ clearTimeout(timer);
428
+ resolve();
429
+ }, () => {
430
+ clearTimeout(timer);
431
+ resolve();
432
+ });
433
+ });
434
+ }
435
+
436
+ /**
437
+ * The install id to stamp on outgoing events, or undefined when none is
438
+ * known. The Identity bridge's anonymous id wins; the JS-persisted id is used
439
+ * only when there is no bridge at all — mixing the two on one device (e.g. a
440
+ * slow bridge read) would count that device twice.
441
+ */
442
+ function resolveInstallId() {
443
+ if (_identityAnonymousId) return _identityAnonymousId;
444
+ if (getIdentityResolver() !== null) return undefined;
445
+ return _jsInstallId ?? undefined;
446
+ }
447
+
448
+ /**
449
+ * Load (or mint and persist) the JS-side install id. Only for apps without
450
+ * the Identity bridge; a no-op without AsyncStorage. Never throws.
451
+ */
452
+ function loadJsInstallId() {
453
+ _jsInstallIdLoad ??= readOrMintJsInstallId().finally(() => {
454
+ _jsInstallIdSettled = true;
455
+ });
456
+ return _jsInstallIdLoad;
457
+ }
458
+ async function readOrMintJsInstallId() {
459
+ if (_jsInstallId || getIdentityResolver() !== null) return;
460
+ const storage = getOfflineStorage();
461
+ if (!storage) return;
462
+ try {
463
+ const stored = await storage.getItem(INSTALL_ID_KEY);
464
+ if (stored) {
465
+ _jsInstallId = stored;
466
+ return;
467
+ }
468
+ const minted = generateUUID();
469
+ await storage.setItem(INSTALL_ID_KEY, minted);
470
+ // Only use an id that made it to disk — see the module note above.
471
+ _jsInstallId = minted;
472
+ } catch {
473
+ // Storage hiccup: send no installId rather than a per-launch one.
474
+ }
475
+ }
476
+
387
477
  // MARK: - Pending Queue (memory + best-effort disk mirror)
388
478
 
389
479
  function enqueueEvent(event) {
@@ -648,6 +738,21 @@ function clearAmbiguousStreak() {
648
738
 
649
739
  // MARK: - Session Tracking
650
740
 
741
+ /**
742
+ * Request headers for every `/api/sdk/errors/*` call. Carries the install id
743
+ * (when known) so the server's per-device rate limit buckets this install
744
+ * separately from every other device of the app.
745
+ */
746
+ function requestHeaders(apiKey) {
747
+ const installId = resolveInstallId();
748
+ return {
749
+ "Content-Type": "application/json",
750
+ "X-API-Key": apiKey,
751
+ ...(installId ? {
752
+ "X-SK-Install-Id": installId
753
+ } : {})
754
+ };
755
+ }
651
756
  function buildSessionPayload(status) {
652
757
  const duration = _sessionStartTime !== null ? (Date.now() - _sessionStartTime) / 1000 : 0;
653
758
  const contexts = getStaticContexts();
@@ -675,8 +780,24 @@ function buildSessionPayload(status) {
675
780
  } : {})
676
781
  };
677
782
  }
783
+
784
+ /**
785
+ * Outcome of one session POST. `retryable` covers 429, 5xx and transport
786
+ * errors — the server (or network) may answer differently in a moment;
787
+ * any other 4xx is a permanent reject. `retryAfterMs` is the server's
788
+ * `Retry-After`, when it sent one.
789
+ */
790
+
791
+ function parseRetryAfterMs(header) {
792
+ const sec = header ? Number(header) : NaN;
793
+ return Number.isFinite(sec) && sec >= 0 ? sec * 1000 : null;
794
+ }
678
795
  async function postSessionPayload(payload, timeoutMs) {
679
- if (!_config) return false;
796
+ if (!_config) return {
797
+ ok: false,
798
+ retryable: false,
799
+ retryAfterMs: null
800
+ };
680
801
  const baseURL = _config.serverURL || "https://api.swiss-knife.dev";
681
802
  const url = `${baseURL}/api/sdk/errors/session`;
682
803
  let controller = null;
@@ -688,24 +809,106 @@ async function postSessionPayload(payload, timeoutMs) {
688
809
  try {
689
810
  const res = await fetch(url, {
690
811
  method: "POST",
691
- headers: {
692
- "Content-Type": "application/json",
693
- "X-API-Key": _config.apiKey
694
- },
812
+ headers: requestHeaders(_config.apiKey),
695
813
  body: JSON.stringify(payload),
696
814
  ...(controller ? {
697
815
  signal: controller.signal
698
816
  } : {})
699
817
  });
700
- return res.ok;
818
+ if (res.ok) return {
819
+ ok: true
820
+ };
821
+ return {
822
+ ok: false,
823
+ retryable: res.status === 429 || res.status >= 500,
824
+ retryAfterMs: parseRetryAfterMs(res.headers.get("Retry-After"))
825
+ };
701
826
  } catch (e) {
702
827
  console.warn("[SwissKnife CrashReporting] session event error:", e);
703
- return false;
828
+ return {
829
+ ok: false,
830
+ retryable: true,
831
+ retryAfterMs: null
832
+ };
704
833
  } finally {
705
834
  if (timer) clearTimeout(timer);
706
835
  }
707
836
  }
708
837
 
838
+ // MARK: - Session Outbox
839
+ //
840
+ // `started` / `ended` session events used to be fire-and-forget: a 429 or a
841
+ // 5xx dropped them, and crash-free-session rates quietly lost their
842
+ // denominator. A failed retryable send now waits here — in order, persisted
843
+ // to the offline store, capped — and is retried after the server's
844
+ // `Retry-After` (or an exponential backoff when it sent none). The crashed
845
+ // session keeps its own dedicated persistence (`OFFLINE_SESSION_KEY`).
846
+
847
+ /** Session events awaiting a retry, oldest first. */
848
+ let _pendingSessions = [];
849
+ let _sessionRetryTimer = null;
850
+ let _sessionBackoffMs = BACKOFF_INITIAL_MS;
851
+ let _sessionDrainInFlight = false;
852
+ /**
853
+ * False from `init` until `restorePersistedState` has merged the previous
854
+ * launch's outbox. Until then this launch must not WRITE `OFFLINE_SESSIONS_KEY`
855
+ * (it would overwrite the stored outbox before restore reads it) nor drain
856
+ * (the older events must go first). Restore persists + drains once merged.
857
+ */
858
+ let _sessionsRestored = true;
859
+ function persistPendingSessions() {
860
+ if (!_sessionsRestored) return;
861
+ const storage = getOfflineStorage();
862
+ if (!storage) return;
863
+ const write = _pendingSessions.length === 0 ? storage.removeItem(OFFLINE_SESSIONS_KEY) : storage.setItem(OFFLINE_SESSIONS_KEY, JSON.stringify(_pendingSessions));
864
+ void write.catch(() => {});
865
+ }
866
+ function scheduleSessionRetry(retryAfterMs) {
867
+ const delayMs = retryAfterMs ?? _sessionBackoffMs;
868
+ _sessionBackoffMs = Math.min(_sessionBackoffMs * 2, BACKOFF_MAX_MS);
869
+ if (_sessionRetryTimer !== null) clearTimeout(_sessionRetryTimer);
870
+ _sessionRetryTimer = setTimeout(() => {
871
+ _sessionRetryTimer = null;
872
+ void drainPendingSessions();
873
+ }, delayMs);
874
+ }
875
+ function queueSessionForRetry(payload, retryAfterMs) {
876
+ _pendingSessions.push(payload);
877
+ if (_pendingSessions.length > MAX_PENDING_SESSIONS) {
878
+ _pendingSessions.splice(0, _pendingSessions.length - MAX_PENDING_SESSIONS);
879
+ }
880
+ // Before restore has merged the stored outbox, just hold it in memory:
881
+ // restore persists and drains the merged queue.
882
+ if (!_sessionsRestored) return;
883
+ persistPendingSessions();
884
+ // A drain in flight, or a retry already booked, will pick this one up.
885
+ if (!_sessionDrainInFlight && _sessionRetryTimer === null) {
886
+ scheduleSessionRetry(retryAfterMs);
887
+ }
888
+ }
889
+
890
+ /** Send queued session events in order until one fails retryably. */
891
+ async function drainPendingSessions() {
892
+ if (_sessionDrainInFlight || !_config || !_sessionsRestored) return;
893
+ _sessionDrainInFlight = true;
894
+ try {
895
+ while (_pendingSessions.length > 0) {
896
+ const head = _pendingSessions[0];
897
+ const result = await postSessionPayload(head);
898
+ if (!result.ok && result.retryable) {
899
+ scheduleSessionRetry(result.retryAfterMs);
900
+ return;
901
+ }
902
+ // Delivered, or permanently rejected (a retry would only spin).
903
+ if (_pendingSessions[0] === head) _pendingSessions.shift();
904
+ _sessionBackoffMs = BACKOFF_INITIAL_MS;
905
+ persistPendingSessions();
906
+ }
907
+ } finally {
908
+ _sessionDrainInFlight = false;
909
+ }
910
+ }
911
+
709
912
  /**
710
913
  * Deliberately has NO `await` before `postSessionPayload` — not even to
711
914
  * re-resolve the identity. `endSession` nulls `_sessionId` and zeroes the
@@ -716,7 +919,18 @@ async function postSessionPayload(payload, timeoutMs) {
716
919
  */
717
920
  async function sendSessionEvent(status) {
718
921
  if (!_config || !_sessionId) return;
719
- await postSessionPayload(buildSessionPayload(status));
922
+ const payload = buildSessionPayload(status);
923
+ // Something is already waiting on a backoff: queue behind it so the
924
+ // server still sees `started` before `ended`, and so we do not hammer a
925
+ // server that just told us to wait.
926
+ if (_pendingSessions.length > 0 || _sessionDrainInFlight) {
927
+ queueSessionForRetry(payload, null);
928
+ return;
929
+ }
930
+ const result = await postSessionPayload(payload);
931
+ if (!result.ok && result.retryable) {
932
+ queueSessionForRetry(payload, result.retryAfterMs);
933
+ }
720
934
  }
721
935
  function startSession() {
722
936
  _sessionId = generateUUID();
@@ -756,7 +970,9 @@ async function deliverCrashedSession() {
756
970
  _sessionStartTime = null;
757
971
  _sessionErrorCount = 0;
758
972
  if (!payload) return;
759
- const ok = await postSessionPayload(payload, FATAL_SEND_TIMEOUT_MS);
973
+ const {
974
+ ok
975
+ } = await postSessionPayload(payload, FATAL_SEND_TIMEOUT_MS);
760
976
  if (ok) {
761
977
  const storage = getOfflineStorage();
762
978
  if (storage) void storage.removeItem(OFFLINE_SESSION_KEY).catch(() => {});
@@ -803,19 +1019,56 @@ function installAppStateListener() {
803
1019
  */
804
1020
  function restorePersistedState() {
805
1021
  const storage = getOfflineStorage();
806
- if (!storage) return;
1022
+ if (!storage) {
1023
+ _sessionsRestored = true;
1024
+ return;
1025
+ }
1026
+ _sessionsRestored = false;
807
1027
  _restorePromise = (async () => {
1028
+ // Read the stored session outbox FIRST, before any other await: nothing
1029
+ // this launch does may replace it before it is merged (see
1030
+ // `_sessionsRestored`).
1031
+ let storedSessions = [];
1032
+ try {
1033
+ const rawSessions = await storage.getItem(OFFLINE_SESSIONS_KEY);
1034
+ if (rawSessions) {
1035
+ const restored = JSON.parse(rawSessions);
1036
+ if (Array.isArray(restored)) {
1037
+ storedSessions = restored.filter(p => p && typeof p.sessionId === "string");
1038
+ }
1039
+ }
1040
+ } catch {
1041
+ // Unreadable outbox: dropped; the merged persist below overwrites it.
1042
+ }
1043
+ // Earlier launch's sessions go first; anything this launch has already
1044
+ // queued stays behind them. Dedupe on (sessionId, status).
1045
+ const seen = new Set();
1046
+ _pendingSessions = [...storedSessions, ..._pendingSessions].filter(p => {
1047
+ const k = `${p.sessionId}|${p.status}`;
1048
+ if (seen.has(k)) return false;
1049
+ seen.add(k);
1050
+ return true;
1051
+ }).slice(-MAX_PENDING_SESSIONS);
1052
+ _sessionsRestored = true;
1053
+ persistPendingSessions();
808
1054
  try {
809
1055
  const rawSession = await storage.getItem(OFFLINE_SESSION_KEY);
810
1056
  if (rawSession) {
811
1057
  const payload = JSON.parse(rawSession);
812
- if (payload?.sessionId && (await postSessionPayload(payload))) {
1058
+ if (payload?.sessionId && (await postSessionPayload(payload)).ok) {
813
1059
  await storage.removeItem(OFFLINE_SESSION_KEY);
814
1060
  }
815
1061
  }
816
1062
  } catch {
817
1063
  // undeliverable this launch — keep for the next one
818
1064
  }
1065
+ if (_pendingSessions.length > 0 && _sessionRetryTimer === null) {
1066
+ try {
1067
+ await drainPendingSessions();
1068
+ } catch {
1069
+ // retried on the next backoff / launch
1070
+ }
1071
+ }
819
1072
  try {
820
1073
  const rawShots = await storage.getItem(OFFLINE_SCREENSHOTS_KEY);
821
1074
  if (rawShots) {
@@ -1037,6 +1290,12 @@ function getStaticContexts() {
1037
1290
 
1038
1291
  // MARK: - Build Event
1039
1292
 
1293
+ /** A usable fingerprint: the string entries, or null when none remain. */
1294
+ function normalizeFingerprint(fingerprint) {
1295
+ if (!Array.isArray(fingerprint)) return null;
1296
+ const entries = fingerprint.filter(entry => typeof entry === "string" && entry.length > 0);
1297
+ return entries.length > 0 ? entries : null;
1298
+ }
1040
1299
  function buildEvent(level, partial = {}) {
1041
1300
  const contexts = {
1042
1301
  ...getStaticContexts()
@@ -1064,6 +1323,9 @@ function buildEvent(level, partial = {}) {
1064
1323
  },
1065
1324
  user: resolveSubject(),
1066
1325
  breadcrumbs: _breadcrumbs.snapshot(),
1326
+ ...(_fingerprint ? {
1327
+ fingerprint: [..._fingerprint]
1328
+ } : {}),
1067
1329
  ...partial,
1068
1330
  contexts
1069
1331
  };
@@ -1408,6 +1670,7 @@ export const CrashReporting = {
1408
1670
  // path re-resolves anyway — this only shortens the window in which an
1409
1671
  // early event has to fall back to the send-time pull.
1410
1672
  void refreshIdentitySubject();
1673
+ void loadJsInstallId();
1411
1674
  // Every global-slot install is best-effort. `initSwissKnife()` is normally
1412
1675
  // called in module scope, so anything that throws here takes the host's
1413
1676
  // root module down with it and the app never boots (v0.2.3 did exactly
@@ -1453,6 +1716,7 @@ export const CrashReporting = {
1453
1716
  eventId: fallbackId
1454
1717
  };
1455
1718
  _sessionErrorCount++;
1719
+ const fingerprint = normalizeFingerprint(options?.fingerprint);
1456
1720
  let event = buildEvent("error", {
1457
1721
  exceptionType: error.name,
1458
1722
  exceptionValue: error.message,
@@ -1462,7 +1726,10 @@ export const CrashReporting = {
1462
1726
  ...options.tags
1463
1727
  } : {
1464
1728
  ..._tags
1465
- }
1729
+ },
1730
+ ...(fingerprint ? {
1731
+ fingerprint
1732
+ } : {})
1466
1733
  });
1467
1734
  event = applyBeforeSend(event);
1468
1735
  if (!event) return {
@@ -1517,10 +1784,7 @@ export const CrashReporting = {
1517
1784
  const url = `${baseURL}/api/sdk/errors/feedback`;
1518
1785
  fetch(url, {
1519
1786
  method: "POST",
1520
- headers: {
1521
- "Content-Type": "application/json",
1522
- "X-API-Key": _config.apiKey
1523
- },
1787
+ headers: requestHeaders(_config.apiKey),
1524
1788
  body: JSON.stringify(feedback)
1525
1789
  }).catch(e => {
1526
1790
  console.warn("[SwissKnife CrashReporting] feedback error:", e);
@@ -1557,7 +1821,9 @@ export const CrashReporting = {
1557
1821
  message: crumb.message,
1558
1822
  level: crumb.level
1559
1823
  });
1560
- } catch {/* non-fatal */}
1824
+ } catch {
1825
+ /* non-fatal */
1826
+ }
1561
1827
  }
1562
1828
  },
1563
1829
  /**
@@ -1600,7 +1866,9 @@ export const CrashReporting = {
1600
1866
  if (nativeMod) {
1601
1867
  try {
1602
1868
  nativeMod.setUser(user);
1603
- } catch {/* non-fatal */}
1869
+ } catch {
1870
+ /* non-fatal */
1871
+ }
1604
1872
  }
1605
1873
  },
1606
1874
  setTag(key, value) {
@@ -1610,7 +1878,9 @@ export const CrashReporting = {
1610
1878
  if (nativeMod) {
1611
1879
  try {
1612
1880
  nativeMod.setTag(key, value);
1613
- } catch {/* non-fatal */}
1881
+ } catch {
1882
+ /* non-fatal */
1883
+ }
1614
1884
  }
1615
1885
  },
1616
1886
  setExtra(key, value) {
@@ -1626,6 +1896,9 @@ export const CrashReporting = {
1626
1896
  },
1627
1897
  setUser: user => {
1628
1898
  _user = user;
1899
+ },
1900
+ setFingerprint: fingerprint => {
1901
+ _fingerprint = normalizeFingerprint(fingerprint);
1629
1902
  }
1630
1903
  });
1631
1904
  },
@@ -1656,11 +1929,17 @@ export const CrashReporting = {
1656
1929
  // `init` and `init` before `logIn` both end up stamped. Bounded by
1657
1930
  // IDENTITY_RESOLVE_TIMEOUT_MS so the fatal path keeps its budget.
1658
1931
  await resolveIdentitySubjectNow();
1932
+ // A flush racing `init` waits for the AsyncStorage read, bounded like the
1933
+ // identity pull (no timer when there is nothing in flight).
1934
+ if (_jsInstallIdLoad && !_jsInstallIdSettled) {
1935
+ await withTimeout(_jsInstallIdLoad, IDENTITY_RESOLVE_TIMEOUT_MS);
1936
+ }
1659
1937
 
1660
1938
  // The /api/sdk/errors/event/batch endpoint:
1661
1939
  // - expects `timestamp` as an ISO string (SDK builds it as Date.now() number)
1662
1940
  // - rejects `user: null` (schema marks `user` optional, not nullable)
1663
1941
  // Coerce both on the wire so the internal SDK shape stays ergonomic.
1942
+ const installId = resolveInstallId();
1664
1943
  const serialized = batch.map(e => {
1665
1944
  const {
1666
1945
  user: builtUser,
@@ -1673,6 +1952,11 @@ export const CrashReporting = {
1673
1952
  ...(user ? {
1674
1953
  user
1675
1954
  } : {}),
1955
+ // Stamped at send time, like the subject: an event captured before
1956
+ // the bridge first answered still ships with it.
1957
+ ...(installId ? {
1958
+ installId
1959
+ } : {}),
1676
1960
  timestamp: typeof e.timestamp === "number" ? new Date(e.timestamp).toISOString() : e.timestamp
1677
1961
  };
1678
1962
  });
@@ -1685,10 +1969,7 @@ export const CrashReporting = {
1685
1969
  try {
1686
1970
  const res = await fetch(url, {
1687
1971
  method: "POST",
1688
- headers: {
1689
- "Content-Type": "application/json",
1690
- "X-API-Key": _config.apiKey
1691
- },
1972
+ headers: requestHeaders(_config.apiKey),
1692
1973
  body: JSON.stringify({
1693
1974
  events: serialized
1694
1975
  }),
@@ -1796,6 +2077,7 @@ export const CrashReporting = {
1796
2077
  _tags = {};
1797
2078
  _extra = {};
1798
2079
  _user = null;
2080
+ _fingerprint = null;
1799
2081
  _pendingEvents = [];
1800
2082
  _inFlightEvents = new Map();
1801
2083
  if (_flushTimer !== null) {
@@ -1808,6 +2090,14 @@ export const CrashReporting = {
1808
2090
  _sessionErrorCount = 0;
1809
2091
  _backoffMs = BACKOFF_INITIAL_MS;
1810
2092
  _backoffUntil = 0;
2093
+ _pendingSessions = [];
2094
+ if (_sessionRetryTimer !== null) {
2095
+ clearTimeout(_sessionRetryTimer);
2096
+ _sessionRetryTimer = null;
2097
+ }
2098
+ _sessionBackoffMs = BACKOFF_INITIAL_MS;
2099
+ _sessionDrainInFlight = false;
2100
+ _sessionsRestored = true;
1811
2101
  clearAmbiguousStreak();
1812
2102
  if (_disableRejectionTracking) {
1813
2103
  // Teardown is the mirror image of install and can fail the same way —
@@ -1824,6 +2114,10 @@ export const CrashReporting = {
1824
2114
  _screenshotCaptureOverride = undefined;
1825
2115
  _nativeCrashModuleOverride = undefined;
1826
2116
  _identityUserId = null;
2117
+ _identityAnonymousId = null;
2118
+ _jsInstallId = null;
2119
+ _jsInstallIdLoad = null;
2120
+ _jsInstallIdSettled = false;
1827
2121
  _identityRefresh = null;
1828
2122
  // Bump the generation so a read still in flight cannot land after the
1829
2123
  // reset and repopulate the subject the reset just cleared.
@@ -1865,6 +2159,12 @@ export const CrashReporting = {
1865
2159
  _snapshotSessionId() {
1866
2160
  return _sessionId;
1867
2161
  },
2162
+ _snapshotPendingSessions() {
2163
+ return _pendingSessions.map(p => ({
2164
+ sessionId: p.sessionId,
2165
+ status: p.status
2166
+ }));
2167
+ },
1868
2168
  _restorePromiseForTests() {
1869
2169
  return _restorePromise;
1870
2170
  },
@@ -1893,6 +2193,7 @@ export const CrashReporting = {
1893
2193
  _setIdentityResolverForTests(resolver) {
1894
2194
  _identityResolverOverride = resolver;
1895
2195
  _identityUserId = null;
2196
+ _identityAnonymousId = null;
1896
2197
  _identityRefresh = null;
1897
2198
  _identityGeneration++;
1898
2199
  },