@app-swiss-knife/react-native-sdk 0.3.1 → 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.
Files changed (28) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  3. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +315 -41
  4. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +13 -4
  5. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +229 -36
  6. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +6 -0
  7. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  8. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +186 -56
  9. package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +182 -0
  10. package/ios/vendor/SwissKnifeiOS/Net/BackendHttpClient.swift +164 -8
  11. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +418 -58
  12. package/lib/commonjs/index.js.map +1 -1
  13. package/lib/commonjs/modules/crash-reporting.js +525 -35
  14. package/lib/commonjs/modules/crash-reporting.js.map +1 -1
  15. package/lib/module/index.js.map +1 -1
  16. package/lib/module/modules/crash-reporting.js +525 -35
  17. package/lib/module/modules/crash-reporting.js.map +1 -1
  18. package/lib/typescript/commonjs/index.d.ts +1 -1
  19. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  20. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +32 -7
  21. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
  22. package/lib/typescript/module/index.d.ts +1 -1
  23. package/lib/typescript/module/index.d.ts.map +1 -1
  24. package/lib/typescript/module/modules/crash-reporting.d.ts +32 -7
  25. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
  26. package/package.json +2 -1
  27. package/src/index.ts +2 -0
  28. package/src/modules/crash-reporting.ts +625 -68
@@ -97,7 +97,13 @@ const FATAL_SEND_TIMEOUT_MS = 2_000;
97
97
  const DEFAULT_MAX_CACHE_ITEMS = 30;
98
98
  const OFFLINE_QUEUE_KEY = "@swissknife:crash:queue";
99
99
  const OFFLINE_SESSION_KEY = "@swissknife:crash:session";
100
+ /** Started/ended session events waiting on a retry (see Session Outbox). */
101
+ const OFFLINE_SESSIONS_KEY = "@swissknife:crash:sessions";
102
+ /** Cap on queued session events — drop-oldest beyond this. */
103
+ const MAX_PENDING_SESSIONS = 50;
100
104
  const OFFLINE_SCREENSHOTS_KEY = "@swissknife:crash:screenshots";
105
+ /** JS-side install id, only for apps without the native Identity bridge. */
106
+ const INSTALL_ID_KEY = "@swissknife:crash:install_id";
101
107
 
102
108
  // MARK: - Stack Trace Parsing
103
109
 
@@ -177,7 +183,24 @@ let _breadcrumbs = new RingBuffer(100);
177
183
  let _tags = {};
178
184
  let _extra = {};
179
185
  let _user = null;
186
+ /** Scope-level fingerprint (configureScope → setFingerprint). */
187
+ let _fingerprint = null;
180
188
  let _pendingEvents = [];
189
+ /**
190
+ * Events handed to an in-flight POST: already out of `_pendingEvents`, not
191
+ * yet acknowledged by the server. Keyed by `eventId` because two flushes
192
+ * can be in the air at once — the fatal path fires its own bounded send
193
+ * while a debounced one is still running — and each must settle only its
194
+ * own batch.
195
+ *
196
+ * This exists because `persistQueue()` mirrors the whole queue by
197
+ * overwriting a single storage key. Deriving that snapshot from
198
+ * `_pendingEvents` alone made an in-flight batch invisible to it, so the
199
+ * next `enqueueEvent()` — one more tap, landing mid-send — rewrote the key
200
+ * WITHOUT it. The first event then existed only in a local `const batch`
201
+ * and died with the process: two taps, two captured errors, one row.
202
+ */
203
+ let _inFlightEvents = new Map();
181
204
  let _flushTimer = null;
182
205
  let _originalGlobalHandler = null;
183
206
  let _sessionId = null;
@@ -227,8 +250,20 @@ let _screenshotCaptureOverride;
227
250
  // `Identity.current()` also carries an `anonymousId`, and stamping it into
228
251
  // `user.id` would make "affected users" non-zero for every app that never
229
252
  // logs in. That both inflates the number and diverges from Analytics, whose
230
- // `user_id` is the identified subject only. The anonymous id already travels
231
- // separately on the ingest envelope. Only `userId` is used here.
253
+ // `user_id` is the identified subject only. The anonymous id travels
254
+ // separately, as the wire event's `installId` (see below) — the server counts
255
+ // affected users by user id, else install id, without conflating the two.
256
+
257
+ // ## installId — the stable per-install id
258
+ //
259
+ // Most crashes have no identified subject, so the server counts affected
260
+ // users by `installId` when `user.id` is absent. It is the Identity bridge's
261
+ // `anonymousId` (`$SKAnonymousID:<device id>` — the same value native crashes
262
+ // carry on their ingest envelope and `app_users.anonymous_id` stores, so the
263
+ // dashboard can link an anonymous install to its profile). Apps without the
264
+ // native Identity bridge get a random id persisted in AsyncStorage; without
265
+ // AsyncStorage no installId is sent at all, because a per-launch id would
266
+ // count every relaunch as a new user.
232
267
 
233
268
  /**
234
269
  * Last resolved identified subject id from the native Identity bridge.
@@ -237,6 +272,14 @@ let _screenshotCaptureOverride;
237
272
  * stamped, which is exactly today's behaviour for apps that never log in.
238
273
  */
239
274
  let _identityUserId = null;
275
+ /** Last resolved `Identity.current().anonymousId` (stable per install). */
276
+ let _identityAnonymousId = null;
277
+ /** AsyncStorage-persisted install id; used only when no Identity bridge. */
278
+ let _jsInstallId = null;
279
+ /** In-flight `loadJsInstallId`, so a flush racing init can wait for it. */
280
+ let _jsInstallIdLoad = null;
281
+ /** `_jsInstallIdLoad` has settled — flush skips the wait (and its hops). */
282
+ let _jsInstallIdSettled = false;
240
283
  /** In-flight read, so N events in a burst share one bridge hop. */
241
284
  let _identityRefresh = null;
242
285
  /** Monotonic read counter — a superseded read must not clobber a newer one. */
@@ -250,6 +293,8 @@ let _identityGeneration = 0;
250
293
  */
251
294
  let _identityResolverOverride;
252
295
 
296
+ /** The fields of the native `Identity.current()` snapshot this module reads. */
297
+
253
298
  /** Budget for the send-time identity re-resolve. Kept well under
254
299
  * FATAL_SEND_TIMEOUT_MS so a slow bridge can never eat the fatal path's
255
300
  * one chance to deliver before the process dies. */
@@ -297,6 +342,11 @@ function startIdentityRead() {
297
342
  if (generation !== _identityGeneration) return; // superseded
298
343
  const userId = snapshot?.userId;
299
344
  _identityUserId = typeof userId === "string" && userId.length > 0 ? userId : null;
345
+ // Never blanked by a later empty answer: the id is per install.
346
+ const anonymousId = snapshot?.anonymousId;
347
+ if (typeof anonymousId === "string" && anonymousId.length > 0) {
348
+ _identityAnonymousId = anonymousId;
349
+ }
300
350
  } catch {
301
351
  // Bridge hiccup — keep the last known subject.
302
352
  } finally {
@@ -375,6 +425,61 @@ function mergeIdentityInto(user) {
375
425
  };
376
426
  }
377
427
 
428
+ /** Resolve when `p` settles or after `ms`, whichever is first. Never rejects. */
429
+ function withTimeout(p, ms) {
430
+ return new Promise(resolve => {
431
+ const timer = setTimeout(resolve, ms);
432
+ void p.then(() => {
433
+ clearTimeout(timer);
434
+ resolve();
435
+ }, () => {
436
+ clearTimeout(timer);
437
+ resolve();
438
+ });
439
+ });
440
+ }
441
+
442
+ /**
443
+ * The install id to stamp on outgoing events, or undefined when none is
444
+ * known. The Identity bridge's anonymous id wins; the JS-persisted id is used
445
+ * only when there is no bridge at all — mixing the two on one device (e.g. a
446
+ * slow bridge read) would count that device twice.
447
+ */
448
+ function resolveInstallId() {
449
+ if (_identityAnonymousId) return _identityAnonymousId;
450
+ if (getIdentityResolver() !== null) return undefined;
451
+ return _jsInstallId ?? undefined;
452
+ }
453
+
454
+ /**
455
+ * Load (or mint and persist) the JS-side install id. Only for apps without
456
+ * the Identity bridge; a no-op without AsyncStorage. Never throws.
457
+ */
458
+ function loadJsInstallId() {
459
+ _jsInstallIdLoad ??= readOrMintJsInstallId().finally(() => {
460
+ _jsInstallIdSettled = true;
461
+ });
462
+ return _jsInstallIdLoad;
463
+ }
464
+ async function readOrMintJsInstallId() {
465
+ if (_jsInstallId || getIdentityResolver() !== null) return;
466
+ const storage = (0, _offlineStore.getOfflineStorage)();
467
+ if (!storage) return;
468
+ try {
469
+ const stored = await storage.getItem(INSTALL_ID_KEY);
470
+ if (stored) {
471
+ _jsInstallId = stored;
472
+ return;
473
+ }
474
+ const minted = (0, _ids.generateUUID)();
475
+ await storage.setItem(INSTALL_ID_KEY, minted);
476
+ // Only use an id that made it to disk — see the module note above.
477
+ _jsInstallId = minted;
478
+ } catch {
479
+ // Storage hiccup: send no installId rather than a per-launch one.
480
+ }
481
+ }
482
+
378
483
  // MARK: - Pending Queue (memory + best-effort disk mirror)
379
484
 
380
485
  function enqueueEvent(event) {
@@ -388,12 +493,41 @@ function enqueueEvent(event) {
388
493
 
389
494
  /** Put failed sends back AHEAD of anything captured since; drop-oldest beyond cap. */
390
495
  function requeueEvents(events) {
496
+ // Back on the pending queue means no longer in flight. Clear first, or
497
+ // `persistQueue()` below counts them from both sides and the mirror
498
+ // carries each event twice.
499
+ clearInFlight(events);
391
500
  const merged = [...events, ..._pendingEvents];
392
501
  discardScreenshotsFor(merged.slice(0, -MAX_PENDING_EVENTS));
393
502
  _pendingEvents = merged.slice(-MAX_PENDING_EVENTS);
394
503
  persistQueue();
395
504
  }
396
505
 
506
+ /**
507
+ * A batch has reached a terminal outcome — acknowledged, requeued, or
508
+ * deliberately dropped — so it stops counting towards the disk mirror.
509
+ *
510
+ * Deliberately does NOT persist: every caller is about to write the
511
+ * mirror itself (via `requeueEvents` or its own `persistQueue`), and two
512
+ * overlapping fire-and-forget `setItem` calls on one key can land out of
513
+ * order.
514
+ */
515
+ function clearInFlight(events) {
516
+ for (const event of events) _inFlightEvents.delete(event.eventId);
517
+ }
518
+
519
+ /** First occurrence wins, so in-flight events keep their place at the front. */
520
+ function dedupeEventsById(events) {
521
+ const seen = new Set();
522
+ const out = [];
523
+ for (const event of events) {
524
+ if (seen.has(event.eventId)) continue;
525
+ seen.add(event.eventId);
526
+ out.push(event);
527
+ }
528
+ return out;
529
+ }
530
+
397
531
  /** Events that will never deliver must not pin their screenshots in memory. */
398
532
  function discardScreenshotsFor(dropped) {
399
533
  for (const event of dropped) {
@@ -418,13 +552,24 @@ function maxCacheItems() {
418
552
  * The slice respects `maxCacheItems`: persisted screenshots occupy cache
419
553
  * slots too, so the event slice shrinks by however many screenshots are
420
554
  * currently stored (newest events win — drop-oldest).
555
+ *
556
+ * IN-FLIGHT EVENTS COUNT. This writes the whole queue to one key, so
557
+ * whatever it leaves out is erased. An event that a POST is currently
558
+ * carrying is not delivered yet — until the server acknowledges it, it
559
+ * still has to survive a process kill exactly like a pending one. Leaving
560
+ * those out is what lost an event: capture, flush, capture again, and the
561
+ * second capture's `persistQueue()` overwrote the key without the first.
421
562
  */
422
563
  function persistQueue() {
423
564
  const storage = (0, _offlineStore.getOfflineStorage)();
424
565
  if (!storage) return;
425
566
  const eventCap = Math.max(0, maxCacheItems() - _offlineScreenshots.length);
567
+ // In-flight events are older than anything pending, so they lead and
568
+ // drop-oldest still trims from the front. Dedupe defensively: a batch
569
+ // mid-requeue can briefly be reachable from both sides.
570
+ const live = dedupeEventsById([..._inFlightEvents.values(), ..._pendingEvents]);
426
571
  // NB: slice(-0) would return the WHOLE array — guard the zero-cap case.
427
- const snapshot = eventCap > 0 ? _pendingEvents.slice(-eventCap) : [];
572
+ const snapshot = eventCap > 0 ? live.slice(-eventCap) : [];
428
573
  void (async () => {
429
574
  try {
430
575
  if (_restorePromise) await _restorePromise;
@@ -490,20 +635,58 @@ function applyBackoff(retryAfterHeader) {
490
635
  // MARK: - Batch Response
491
636
 
492
637
  /**
493
- * Parse the batch response `{ accepted, results: [{index, eventId, status}] }`
638
+ * What we managed to learn from a 2xx batch response.
639
+ *
640
+ * `undecodable` is deliberately NOT folded into `parsed` with an empty
641
+ * `retryable` list: "the server accepted everything" and "we could not read
642
+ * the server's answer" are different facts, and only the first one licenses
643
+ * deleting the batch.
644
+ */
645
+
646
+ /**
647
+ * Read the batch response `{ accepted, results: [{index, eventId, status}] }`
494
648
  * and map 'retryable' entries back to their events (by eventId, falling back
495
- * to index). Anything else — 'accepted', 'duplicate', 'rejected', a legacy
496
- * response shape, or an unparseable body on HTTP 200 — is treated as terminal.
649
+ * to index). 'accepted', 'duplicate', 'rejected' and a legacy response shape
650
+ * are all terminal.
651
+ *
652
+ * A NON-EMPTY body that will not parse returns `undecodable`. It used to
653
+ * return "nothing is retryable", which the caller could not tell apart from a
654
+ * clean ack — so a truncated or corrupted 200 silently destroyed the batch.
655
+ * An empty body still counts as an ack: some deployments answer 200 with no
656
+ * content, and there is nothing there to have been a rejection.
497
657
  */
498
- async function extractRetryableEvents(res, batch) {
658
+ async function readBatchOutcome(res, batch) {
659
+ // Read as text first — `res.json()` cannot distinguish "empty body" from
660
+ // "malformed body", and that distinction is the whole point here.
661
+ let raw;
662
+ try {
663
+ raw = await res.text();
664
+ } catch (e) {
665
+ // The body stream itself failed mid-read: a truncated response by
666
+ // another name, so it is ambiguous for the same reason.
667
+ return {
668
+ kind: "undecodable",
669
+ preview: String(e).slice(0, 200)
670
+ };
671
+ }
672
+ if (raw.trim() === "") return {
673
+ kind: "parsed",
674
+ retryable: []
675
+ };
499
676
  let parsed = null;
500
677
  try {
501
- parsed = await res.json();
678
+ parsed = JSON.parse(raw);
502
679
  } catch {
503
- return [];
680
+ return {
681
+ kind: "undecodable",
682
+ preview: raw.slice(0, 200)
683
+ };
504
684
  }
505
685
  const results = parsed?.results;
506
- if (!Array.isArray(results)) return [];
686
+ if (!Array.isArray(results)) return {
687
+ kind: "parsed",
688
+ retryable: []
689
+ };
507
690
  const retryable = [];
508
691
  for (const entry of results) {
509
692
  if (!entry || entry.status !== "retryable") continue;
@@ -512,11 +695,70 @@ async function extractRetryableEvents(res, batch) {
512
695
  const event = byId ?? byIndex;
513
696
  if (event && !retryable.includes(event)) retryable.push(event);
514
697
  }
515
- return retryable;
698
+ return {
699
+ kind: "parsed",
700
+ retryable
701
+ };
702
+ }
703
+
704
+ // MARK: - Ambiguous-response budget
705
+
706
+ /**
707
+ * How many consecutive undecodable-2xx responses the SAME batch may collect
708
+ * before we stop retrying it.
709
+ *
710
+ * The bound is deliberate. Without it a backend permanently answering 200
711
+ * with garbage would keep the batch in `_pendingEvents` forever, re-sending
712
+ * it on every scheduled flush, while newly captured crashes pile in behind it
713
+ * until `maxCacheItems` starts dropping the OLDEST — reintroducing silent
714
+ * loss from the other end. 5 attempts, each spaced by the existing
715
+ * exponential backoff (1s doubling to a 60s ceiling), is several minutes of
716
+ * retrying before anything is given up on.
717
+ */
718
+ const MAX_AMBIGUOUS_ATTEMPTS = 5;
719
+
720
+ /** Consecutive undecodable-2xx answers for `_ambiguousBatchKey`. */
721
+ let _ambiguousAttempts = 0;
722
+ /** Identity of the batch those attempts belong to — the budget is per-batch,
723
+ * not a global "server has been flaky lately" tally. */
724
+ let _ambiguousBatchKey = null;
725
+ function batchKey(batch) {
726
+ return batch.map(e => e.eventId).join(",");
727
+ }
728
+
729
+ /** Record one ambiguous answer for `batch`; returns the running count. */
730
+ function noteAmbiguousResponse(batch) {
731
+ const key = batchKey(batch);
732
+ if (key === _ambiguousBatchKey) {
733
+ _ambiguousAttempts += 1;
734
+ } else {
735
+ _ambiguousBatchKey = key;
736
+ _ambiguousAttempts = 1;
737
+ }
738
+ return _ambiguousAttempts;
739
+ }
740
+ function clearAmbiguousStreak() {
741
+ _ambiguousAttempts = 0;
742
+ _ambiguousBatchKey = null;
516
743
  }
517
744
 
518
745
  // MARK: - Session Tracking
519
746
 
747
+ /**
748
+ * Request headers for every `/api/sdk/errors/*` call. Carries the install id
749
+ * (when known) so the server's per-device rate limit buckets this install
750
+ * separately from every other device of the app.
751
+ */
752
+ function requestHeaders(apiKey) {
753
+ const installId = resolveInstallId();
754
+ return {
755
+ "Content-Type": "application/json",
756
+ "X-API-Key": apiKey,
757
+ ...(installId ? {
758
+ "X-SK-Install-Id": installId
759
+ } : {})
760
+ };
761
+ }
520
762
  function buildSessionPayload(status) {
521
763
  const duration = _sessionStartTime !== null ? (Date.now() - _sessionStartTime) / 1000 : 0;
522
764
  const contexts = getStaticContexts();
@@ -544,8 +786,24 @@ function buildSessionPayload(status) {
544
786
  } : {})
545
787
  };
546
788
  }
789
+
790
+ /**
791
+ * Outcome of one session POST. `retryable` covers 429, 5xx and transport
792
+ * errors — the server (or network) may answer differently in a moment;
793
+ * any other 4xx is a permanent reject. `retryAfterMs` is the server's
794
+ * `Retry-After`, when it sent one.
795
+ */
796
+
797
+ function parseRetryAfterMs(header) {
798
+ const sec = header ? Number(header) : NaN;
799
+ return Number.isFinite(sec) && sec >= 0 ? sec * 1000 : null;
800
+ }
547
801
  async function postSessionPayload(payload, timeoutMs) {
548
- if (!_config) return false;
802
+ if (!_config) return {
803
+ ok: false,
804
+ retryable: false,
805
+ retryAfterMs: null
806
+ };
549
807
  const baseURL = _config.serverURL || "https://api.swiss-knife.dev";
550
808
  const url = `${baseURL}/api/sdk/errors/session`;
551
809
  let controller = null;
@@ -557,24 +815,106 @@ async function postSessionPayload(payload, timeoutMs) {
557
815
  try {
558
816
  const res = await fetch(url, {
559
817
  method: "POST",
560
- headers: {
561
- "Content-Type": "application/json",
562
- "X-API-Key": _config.apiKey
563
- },
818
+ headers: requestHeaders(_config.apiKey),
564
819
  body: JSON.stringify(payload),
565
820
  ...(controller ? {
566
821
  signal: controller.signal
567
822
  } : {})
568
823
  });
569
- return res.ok;
824
+ if (res.ok) return {
825
+ ok: true
826
+ };
827
+ return {
828
+ ok: false,
829
+ retryable: res.status === 429 || res.status >= 500,
830
+ retryAfterMs: parseRetryAfterMs(res.headers.get("Retry-After"))
831
+ };
570
832
  } catch (e) {
571
833
  console.warn("[SwissKnife CrashReporting] session event error:", e);
572
- return false;
834
+ return {
835
+ ok: false,
836
+ retryable: true,
837
+ retryAfterMs: null
838
+ };
573
839
  } finally {
574
840
  if (timer) clearTimeout(timer);
575
841
  }
576
842
  }
577
843
 
844
+ // MARK: - Session Outbox
845
+ //
846
+ // `started` / `ended` session events used to be fire-and-forget: a 429 or a
847
+ // 5xx dropped them, and crash-free-session rates quietly lost their
848
+ // denominator. A failed retryable send now waits here — in order, persisted
849
+ // to the offline store, capped — and is retried after the server's
850
+ // `Retry-After` (or an exponential backoff when it sent none). The crashed
851
+ // session keeps its own dedicated persistence (`OFFLINE_SESSION_KEY`).
852
+
853
+ /** Session events awaiting a retry, oldest first. */
854
+ let _pendingSessions = [];
855
+ let _sessionRetryTimer = null;
856
+ let _sessionBackoffMs = BACKOFF_INITIAL_MS;
857
+ let _sessionDrainInFlight = false;
858
+ /**
859
+ * False from `init` until `restorePersistedState` has merged the previous
860
+ * launch's outbox. Until then this launch must not WRITE `OFFLINE_SESSIONS_KEY`
861
+ * (it would overwrite the stored outbox before restore reads it) nor drain
862
+ * (the older events must go first). Restore persists + drains once merged.
863
+ */
864
+ let _sessionsRestored = true;
865
+ function persistPendingSessions() {
866
+ if (!_sessionsRestored) return;
867
+ const storage = (0, _offlineStore.getOfflineStorage)();
868
+ if (!storage) return;
869
+ const write = _pendingSessions.length === 0 ? storage.removeItem(OFFLINE_SESSIONS_KEY) : storage.setItem(OFFLINE_SESSIONS_KEY, JSON.stringify(_pendingSessions));
870
+ void write.catch(() => {});
871
+ }
872
+ function scheduleSessionRetry(retryAfterMs) {
873
+ const delayMs = retryAfterMs ?? _sessionBackoffMs;
874
+ _sessionBackoffMs = Math.min(_sessionBackoffMs * 2, BACKOFF_MAX_MS);
875
+ if (_sessionRetryTimer !== null) clearTimeout(_sessionRetryTimer);
876
+ _sessionRetryTimer = setTimeout(() => {
877
+ _sessionRetryTimer = null;
878
+ void drainPendingSessions();
879
+ }, delayMs);
880
+ }
881
+ function queueSessionForRetry(payload, retryAfterMs) {
882
+ _pendingSessions.push(payload);
883
+ if (_pendingSessions.length > MAX_PENDING_SESSIONS) {
884
+ _pendingSessions.splice(0, _pendingSessions.length - MAX_PENDING_SESSIONS);
885
+ }
886
+ // Before restore has merged the stored outbox, just hold it in memory:
887
+ // restore persists and drains the merged queue.
888
+ if (!_sessionsRestored) return;
889
+ persistPendingSessions();
890
+ // A drain in flight, or a retry already booked, will pick this one up.
891
+ if (!_sessionDrainInFlight && _sessionRetryTimer === null) {
892
+ scheduleSessionRetry(retryAfterMs);
893
+ }
894
+ }
895
+
896
+ /** Send queued session events in order until one fails retryably. */
897
+ async function drainPendingSessions() {
898
+ if (_sessionDrainInFlight || !_config || !_sessionsRestored) return;
899
+ _sessionDrainInFlight = true;
900
+ try {
901
+ while (_pendingSessions.length > 0) {
902
+ const head = _pendingSessions[0];
903
+ const result = await postSessionPayload(head);
904
+ if (!result.ok && result.retryable) {
905
+ scheduleSessionRetry(result.retryAfterMs);
906
+ return;
907
+ }
908
+ // Delivered, or permanently rejected (a retry would only spin).
909
+ if (_pendingSessions[0] === head) _pendingSessions.shift();
910
+ _sessionBackoffMs = BACKOFF_INITIAL_MS;
911
+ persistPendingSessions();
912
+ }
913
+ } finally {
914
+ _sessionDrainInFlight = false;
915
+ }
916
+ }
917
+
578
918
  /**
579
919
  * Deliberately has NO `await` before `postSessionPayload` — not even to
580
920
  * re-resolve the identity. `endSession` nulls `_sessionId` and zeroes the
@@ -585,7 +925,18 @@ async function postSessionPayload(payload, timeoutMs) {
585
925
  */
586
926
  async function sendSessionEvent(status) {
587
927
  if (!_config || !_sessionId) return;
588
- await postSessionPayload(buildSessionPayload(status));
928
+ const payload = buildSessionPayload(status);
929
+ // Something is already waiting on a backoff: queue behind it so the
930
+ // server still sees `started` before `ended`, and so we do not hammer a
931
+ // server that just told us to wait.
932
+ if (_pendingSessions.length > 0 || _sessionDrainInFlight) {
933
+ queueSessionForRetry(payload, null);
934
+ return;
935
+ }
936
+ const result = await postSessionPayload(payload);
937
+ if (!result.ok && result.retryable) {
938
+ queueSessionForRetry(payload, result.retryAfterMs);
939
+ }
589
940
  }
590
941
  function startSession() {
591
942
  _sessionId = (0, _ids.generateUUID)();
@@ -625,7 +976,9 @@ async function deliverCrashedSession() {
625
976
  _sessionStartTime = null;
626
977
  _sessionErrorCount = 0;
627
978
  if (!payload) return;
628
- const ok = await postSessionPayload(payload, FATAL_SEND_TIMEOUT_MS);
979
+ const {
980
+ ok
981
+ } = await postSessionPayload(payload, FATAL_SEND_TIMEOUT_MS);
629
982
  if (ok) {
630
983
  const storage = (0, _offlineStore.getOfflineStorage)();
631
984
  if (storage) void storage.removeItem(OFFLINE_SESSION_KEY).catch(() => {});
@@ -672,19 +1025,56 @@ function installAppStateListener() {
672
1025
  */
673
1026
  function restorePersistedState() {
674
1027
  const storage = (0, _offlineStore.getOfflineStorage)();
675
- if (!storage) return;
1028
+ if (!storage) {
1029
+ _sessionsRestored = true;
1030
+ return;
1031
+ }
1032
+ _sessionsRestored = false;
676
1033
  _restorePromise = (async () => {
1034
+ // Read the stored session outbox FIRST, before any other await: nothing
1035
+ // this launch does may replace it before it is merged (see
1036
+ // `_sessionsRestored`).
1037
+ let storedSessions = [];
1038
+ try {
1039
+ const rawSessions = await storage.getItem(OFFLINE_SESSIONS_KEY);
1040
+ if (rawSessions) {
1041
+ const restored = JSON.parse(rawSessions);
1042
+ if (Array.isArray(restored)) {
1043
+ storedSessions = restored.filter(p => p && typeof p.sessionId === "string");
1044
+ }
1045
+ }
1046
+ } catch {
1047
+ // Unreadable outbox: dropped; the merged persist below overwrites it.
1048
+ }
1049
+ // Earlier launch's sessions go first; anything this launch has already
1050
+ // queued stays behind them. Dedupe on (sessionId, status).
1051
+ const seen = new Set();
1052
+ _pendingSessions = [...storedSessions, ..._pendingSessions].filter(p => {
1053
+ const k = `${p.sessionId}|${p.status}`;
1054
+ if (seen.has(k)) return false;
1055
+ seen.add(k);
1056
+ return true;
1057
+ }).slice(-MAX_PENDING_SESSIONS);
1058
+ _sessionsRestored = true;
1059
+ persistPendingSessions();
677
1060
  try {
678
1061
  const rawSession = await storage.getItem(OFFLINE_SESSION_KEY);
679
1062
  if (rawSession) {
680
1063
  const payload = JSON.parse(rawSession);
681
- if (payload?.sessionId && (await postSessionPayload(payload))) {
1064
+ if (payload?.sessionId && (await postSessionPayload(payload)).ok) {
682
1065
  await storage.removeItem(OFFLINE_SESSION_KEY);
683
1066
  }
684
1067
  }
685
1068
  } catch {
686
1069
  // undeliverable this launch — keep for the next one
687
1070
  }
1071
+ if (_pendingSessions.length > 0 && _sessionRetryTimer === null) {
1072
+ try {
1073
+ await drainPendingSessions();
1074
+ } catch {
1075
+ // retried on the next backoff / launch
1076
+ }
1077
+ }
688
1078
  try {
689
1079
  const rawShots = await storage.getItem(OFFLINE_SCREENSHOTS_KEY);
690
1080
  if (rawShots) {
@@ -906,6 +1296,12 @@ function getStaticContexts() {
906
1296
 
907
1297
  // MARK: - Build Event
908
1298
 
1299
+ /** A usable fingerprint: the string entries, or null when none remain. */
1300
+ function normalizeFingerprint(fingerprint) {
1301
+ if (!Array.isArray(fingerprint)) return null;
1302
+ const entries = fingerprint.filter(entry => typeof entry === "string" && entry.length > 0);
1303
+ return entries.length > 0 ? entries : null;
1304
+ }
909
1305
  function buildEvent(level, partial = {}) {
910
1306
  const contexts = {
911
1307
  ...getStaticContexts()
@@ -933,6 +1329,9 @@ function buildEvent(level, partial = {}) {
933
1329
  },
934
1330
  user: resolveSubject(),
935
1331
  breadcrumbs: _breadcrumbs.snapshot(),
1332
+ ...(_fingerprint ? {
1333
+ fingerprint: [..._fingerprint]
1334
+ } : {}),
936
1335
  ...partial,
937
1336
  contexts
938
1337
  };
@@ -1277,6 +1676,7 @@ const CrashReporting = exports.CrashReporting = {
1277
1676
  // path re-resolves anyway — this only shortens the window in which an
1278
1677
  // early event has to fall back to the send-time pull.
1279
1678
  void refreshIdentitySubject();
1679
+ void loadJsInstallId();
1280
1680
  // Every global-slot install is best-effort. `initSwissKnife()` is normally
1281
1681
  // called in module scope, so anything that throws here takes the host's
1282
1682
  // root module down with it and the app never boots (v0.2.3 did exactly
@@ -1322,6 +1722,7 @@ const CrashReporting = exports.CrashReporting = {
1322
1722
  eventId: fallbackId
1323
1723
  };
1324
1724
  _sessionErrorCount++;
1725
+ const fingerprint = normalizeFingerprint(options?.fingerprint);
1325
1726
  let event = buildEvent("error", {
1326
1727
  exceptionType: error.name,
1327
1728
  exceptionValue: error.message,
@@ -1331,7 +1732,10 @@ const CrashReporting = exports.CrashReporting = {
1331
1732
  ...options.tags
1332
1733
  } : {
1333
1734
  ..._tags
1334
- }
1735
+ },
1736
+ ...(fingerprint ? {
1737
+ fingerprint
1738
+ } : {})
1335
1739
  });
1336
1740
  event = applyBeforeSend(event);
1337
1741
  if (!event) return {
@@ -1386,10 +1790,7 @@ const CrashReporting = exports.CrashReporting = {
1386
1790
  const url = `${baseURL}/api/sdk/errors/feedback`;
1387
1791
  fetch(url, {
1388
1792
  method: "POST",
1389
- headers: {
1390
- "Content-Type": "application/json",
1391
- "X-API-Key": _config.apiKey
1392
- },
1793
+ headers: requestHeaders(_config.apiKey),
1393
1794
  body: JSON.stringify(feedback)
1394
1795
  }).catch(e => {
1395
1796
  console.warn("[SwissKnife CrashReporting] feedback error:", e);
@@ -1426,7 +1827,9 @@ const CrashReporting = exports.CrashReporting = {
1426
1827
  message: crumb.message,
1427
1828
  level: crumb.level
1428
1829
  });
1429
- } catch {/* non-fatal */}
1830
+ } catch {
1831
+ /* non-fatal */
1832
+ }
1430
1833
  }
1431
1834
  },
1432
1835
  /**
@@ -1469,7 +1872,9 @@ const CrashReporting = exports.CrashReporting = {
1469
1872
  if (nativeMod) {
1470
1873
  try {
1471
1874
  nativeMod.setUser(user);
1472
- } catch {/* non-fatal */}
1875
+ } catch {
1876
+ /* non-fatal */
1877
+ }
1473
1878
  }
1474
1879
  },
1475
1880
  setTag(key, value) {
@@ -1479,7 +1884,9 @@ const CrashReporting = exports.CrashReporting = {
1479
1884
  if (nativeMod) {
1480
1885
  try {
1481
1886
  nativeMod.setTag(key, value);
1482
- } catch {/* non-fatal */}
1887
+ } catch {
1888
+ /* non-fatal */
1889
+ }
1483
1890
  }
1484
1891
  },
1485
1892
  setExtra(key, value) {
@@ -1495,6 +1902,9 @@ const CrashReporting = exports.CrashReporting = {
1495
1902
  },
1496
1903
  setUser: user => {
1497
1904
  _user = user;
1905
+ },
1906
+ setFingerprint: fingerprint => {
1907
+ _fingerprint = normalizeFingerprint(fingerprint);
1498
1908
  }
1499
1909
  });
1500
1910
  },
@@ -1510,6 +1920,10 @@ const CrashReporting = exports.CrashReporting = {
1510
1920
  }
1511
1921
  const batch = [..._pendingEvents];
1512
1922
  _pendingEvents = [];
1923
+ // The batch has left `_pendingEvents` but nothing has acknowledged it
1924
+ // yet, so it must stay in the disk mirror. Every exit below settles
1925
+ // it — see the `finally` for the backstop.
1926
+ for (const event of batch) _inFlightEvents.set(event.eventId, event);
1513
1927
  const baseURL = _config.serverURL || "https://api.swiss-knife.dev";
1514
1928
  const url = `${baseURL}/api/sdk/errors/event/batch`;
1515
1929
 
@@ -1521,11 +1935,17 @@ const CrashReporting = exports.CrashReporting = {
1521
1935
  // `init` and `init` before `logIn` both end up stamped. Bounded by
1522
1936
  // IDENTITY_RESOLVE_TIMEOUT_MS so the fatal path keeps its budget.
1523
1937
  await resolveIdentitySubjectNow();
1938
+ // A flush racing `init` waits for the AsyncStorage read, bounded like the
1939
+ // identity pull (no timer when there is nothing in flight).
1940
+ if (_jsInstallIdLoad && !_jsInstallIdSettled) {
1941
+ await withTimeout(_jsInstallIdLoad, IDENTITY_RESOLVE_TIMEOUT_MS);
1942
+ }
1524
1943
 
1525
1944
  // The /api/sdk/errors/event/batch endpoint:
1526
1945
  // - expects `timestamp` as an ISO string (SDK builds it as Date.now() number)
1527
1946
  // - rejects `user: null` (schema marks `user` optional, not nullable)
1528
1947
  // Coerce both on the wire so the internal SDK shape stays ergonomic.
1948
+ const installId = resolveInstallId();
1529
1949
  const serialized = batch.map(e => {
1530
1950
  const {
1531
1951
  user: builtUser,
@@ -1538,6 +1958,11 @@ const CrashReporting = exports.CrashReporting = {
1538
1958
  ...(user ? {
1539
1959
  user
1540
1960
  } : {}),
1961
+ // Stamped at send time, like the subject: an event captured before
1962
+ // the bridge first answered still ships with it.
1963
+ ...(installId ? {
1964
+ installId
1965
+ } : {}),
1541
1966
  timestamp: typeof e.timestamp === "number" ? new Date(e.timestamp).toISOString() : e.timestamp
1542
1967
  };
1543
1968
  });
@@ -1550,10 +1975,7 @@ const CrashReporting = exports.CrashReporting = {
1550
1975
  try {
1551
1976
  const res = await fetch(url, {
1552
1977
  method: "POST",
1553
- headers: {
1554
- "Content-Type": "application/json",
1555
- "X-API-Key": _config.apiKey
1556
- },
1978
+ headers: requestHeaders(_config.apiKey),
1557
1979
  body: JSON.stringify({
1558
1980
  events: serialized
1559
1981
  }),
@@ -1562,11 +1984,47 @@ const CrashReporting = exports.CrashReporting = {
1562
1984
  } : {})
1563
1985
  });
1564
1986
  if (res.ok) {
1987
+ const outcome = await readBatchOutcome(res, batch);
1988
+ if (outcome.kind === "undecodable") {
1989
+ // A 2xx we cannot read is NOT an ack. We have no evidence the
1990
+ // server stored anything, so the batch goes back on the queue and
1991
+ // is retried under the normal backoff — the same treatment a 5xx
1992
+ // gets, because we know exactly as much as we do about a 5xx.
1993
+ //
1994
+ // Note the backoff reset stays in the decodable branch below: an
1995
+ // ambiguous answer must not reset the schedule it is about to use.
1996
+ const attempts = noteAmbiguousResponse(batch);
1997
+ if (attempts >= MAX_AMBIGUOUS_ATTEMPTS) {
1998
+ // Budget spent. Unlike the native SDKs there is no dead-letter
1999
+ // file to park these in, so the batch is dropped — but LOUDLY
2000
+ // and only after a bounded, documented number of attempts,
2001
+ // rather than silently on the first bad byte.
2002
+ clearAmbiguousStreak();
2003
+ console.warn(`[SwissKnife CrashReporting] dropping ${batch.length} event(s) after ` + `${attempts} undecodable HTTP ${res.status} responses; last body: ${outcome.preview}`);
2004
+ for (const e of batch) {
2005
+ _screenshotPromises.delete(e.eventId);
2006
+ removeOfflineScreenshot(e.eventId);
2007
+ }
2008
+ clearInFlight(batch);
2009
+ persistQueue();
2010
+ return;
2011
+ }
2012
+ console.warn(`[SwissKnife CrashReporting] undecodable HTTP ${res.status} response ` + `(attempt ${attempts}/${MAX_AMBIGUOUS_ATTEMPTS}) — requeueing ${batch.length} event(s); ` + `body: ${outcome.preview}`);
2013
+ const delayMs = applyBackoff(res.headers.get("Retry-After"));
2014
+ requeueEvents(batch);
2015
+ if (!options?.timeoutMs) scheduledFlush(delayMs);
2016
+ return;
2017
+ }
1565
2018
  _backoffMs = BACKOFF_INITIAL_MS;
1566
2019
  _backoffUntil = 0;
2020
+ clearAmbiguousStreak();
1567
2021
  // Per-event statuses: requeue ONLY 'retryable' (transient server
1568
2022
  // failure); 'accepted'/'duplicate'/'rejected' are terminal.
1569
- const retryable = await extractRetryableEvents(res, batch);
2023
+ const retryable = outcome.retryable;
2024
+ // The server has answered on the whole batch, so nothing in it is
2025
+ // in flight any more — including the retryable part, which
2026
+ // `requeueEvents` is about to put back on the pending queue.
2027
+ clearInFlight(batch);
1570
2028
  if (retryable.length > 0) {
1571
2029
  requeueEvents(retryable);
1572
2030
  scheduledFlush();
@@ -1597,6 +2055,7 @@ const CrashReporting = exports.CrashReporting = {
1597
2055
  _screenshotPromises.delete(e.eventId);
1598
2056
  removeOfflineScreenshot(e.eventId);
1599
2057
  }
2058
+ clearInFlight(batch);
1600
2059
  persistQueue();
1601
2060
  } catch (e) {
1602
2061
  console.warn("[SwissKnife CrashReporting] flush error:", e);
@@ -1605,6 +2064,15 @@ const CrashReporting = exports.CrashReporting = {
1605
2064
  if (!options?.timeoutMs) scheduledFlush(delayMs);
1606
2065
  } finally {
1607
2066
  if (timer) clearTimeout(timer);
2067
+ // Backstop. Every branch above settles the batch, but an entry left
2068
+ // behind by one that does not would pin its event in the disk
2069
+ // mirror forever and re-deliver it on every launch. Requeue rather
2070
+ // than drop: the same trade the native SDKs make — a duplicate is
2071
+ // visible and deduped server-side by the `errorEventSeen` ledger, a
2072
+ // silently lost crash report is neither.
2073
+ if (batch.some(event => _inFlightEvents.has(event.eventId))) {
2074
+ requeueEvents(batch);
2075
+ }
1608
2076
  }
1609
2077
  },
1610
2078
  // MARK: - Test Hooks
@@ -1615,7 +2083,9 @@ const CrashReporting = exports.CrashReporting = {
1615
2083
  _tags = {};
1616
2084
  _extra = {};
1617
2085
  _user = null;
2086
+ _fingerprint = null;
1618
2087
  _pendingEvents = [];
2088
+ _inFlightEvents = new Map();
1619
2089
  if (_flushTimer !== null) {
1620
2090
  clearTimeout(_flushTimer);
1621
2091
  _flushTimer = null;
@@ -1626,6 +2096,15 @@ const CrashReporting = exports.CrashReporting = {
1626
2096
  _sessionErrorCount = 0;
1627
2097
  _backoffMs = BACKOFF_INITIAL_MS;
1628
2098
  _backoffUntil = 0;
2099
+ _pendingSessions = [];
2100
+ if (_sessionRetryTimer !== null) {
2101
+ clearTimeout(_sessionRetryTimer);
2102
+ _sessionRetryTimer = null;
2103
+ }
2104
+ _sessionBackoffMs = BACKOFF_INITIAL_MS;
2105
+ _sessionDrainInFlight = false;
2106
+ _sessionsRestored = true;
2107
+ clearAmbiguousStreak();
1629
2108
  if (_disableRejectionTracking) {
1630
2109
  // Teardown is the mirror image of install and can fail the same way —
1631
2110
  // restoring a slot on a frozen host object, or an engine `enable` that
@@ -1641,6 +2120,10 @@ const CrashReporting = exports.CrashReporting = {
1641
2120
  _screenshotCaptureOverride = undefined;
1642
2121
  _nativeCrashModuleOverride = undefined;
1643
2122
  _identityUserId = null;
2123
+ _identityAnonymousId = null;
2124
+ _jsInstallId = null;
2125
+ _jsInstallIdLoad = null;
2126
+ _jsInstallIdSettled = false;
1644
2127
  _identityRefresh = null;
1645
2128
  // Bump the generation so a read still in flight cannot land after the
1646
2129
  // reset and repopulate the subject the reset just cleared.
@@ -1682,6 +2165,12 @@ const CrashReporting = exports.CrashReporting = {
1682
2165
  _snapshotSessionId() {
1683
2166
  return _sessionId;
1684
2167
  },
2168
+ _snapshotPendingSessions() {
2169
+ return _pendingSessions.map(p => ({
2170
+ sessionId: p.sessionId,
2171
+ status: p.status
2172
+ }));
2173
+ },
1685
2174
  _restorePromiseForTests() {
1686
2175
  return _restorePromise;
1687
2176
  },
@@ -1710,6 +2199,7 @@ const CrashReporting = exports.CrashReporting = {
1710
2199
  _setIdentityResolverForTests(resolver) {
1711
2200
  _identityResolverOverride = resolver;
1712
2201
  _identityUserId = null;
2202
+ _identityAnonymousId = null;
1713
2203
  _identityRefresh = null;
1714
2204
  _identityGeneration++;
1715
2205
  },