@app-swiss-knife/react-native-sdk 0.3.2 → 0.5.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 (177) hide show
  1. package/CHANGELOG.md +465 -0
  2. package/LICENSE +21 -0
  3. package/README.md +229 -42
  4. package/SwissKnifePurchases.podspec +1 -1
  5. package/android/build.gradle +24 -2
  6. package/android/consumer-rules.pro +12 -0
  7. package/android/src/main/AndroidManifest.xml +15 -1
  8. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +5 -4
  9. package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +7 -2
  10. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +168 -6
  11. package/android/src/play/java/com/swissknife/purchases/StoreIntentHandler.kt +7 -0
  12. package/android/src/rustore/java/com/swissknife/purchases/StoreIntentHandler.kt +9 -0
  13. package/android/vendor/java/com/appswissknife/SwissKnife.kt +107 -38
  14. package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +180 -115
  15. package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +16 -18
  16. package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +13 -13
  17. package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +56 -25
  18. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  19. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +641 -208
  20. package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +195 -26
  21. package/android/vendor/java/com/appswissknife/identity/Identity.kt +31 -6
  22. package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +5 -0
  23. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +69 -35
  24. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +756 -98
  25. package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +214 -30
  26. package/android/vendor/java/com/appswissknife/notifications/NotificationRenderer.kt +195 -0
  27. package/android/vendor/java/com/appswissknife/notifications/PermissionRequestActivity.kt +60 -0
  28. package/android/vendor/java/com/appswissknife/notifications/PermissionStatus.kt +41 -0
  29. package/android/vendor/java/com/appswissknife/notifications/PushEventQueue.kt +143 -0
  30. package/android/vendor/java/com/appswissknife/notifications/PushPayload.kt +72 -0
  31. package/android/vendor/java/com/appswissknife/notifications/PushRegistration.kt +89 -0
  32. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeMessagingService.kt +57 -0
  33. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeNotifications.kt +438 -0
  34. package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +266 -64
  35. package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +1 -0
  36. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +545 -88
  37. package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +55 -24
  38. package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +21 -0
  39. package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +14 -0
  40. package/android/vendor-rustore/AndroidManifest.xml +59 -0
  41. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreGateway.kt +428 -0
  42. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreInitProvider.kt +43 -0
  43. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStorePriceEnrichmentProvider.kt +85 -0
  44. package/app.plugin.js +287 -0
  45. package/ios/SwissKnifePurchases.m +20 -0
  46. package/ios/SwissKnifePurchases.swift +97 -3
  47. package/ios/SwissKnifePushBootstrap.m +34 -0
  48. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +138 -89
  49. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  50. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +531 -100
  51. package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +43 -2
  52. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +495 -16
  53. package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +231 -23
  54. package/ios/vendor/SwissKnifeiOS/Notifications/PushPayload.swift +87 -0
  55. package/ios/vendor/SwissKnifeiOS/Notifications/PushRegistrar.swift +322 -0
  56. package/ios/vendor/SwissKnifeiOS/Notifications/SwissKnife+Notifications.swift +403 -0
  57. package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +1 -0
  58. package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +11 -7
  59. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +38 -7
  60. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +34 -6
  61. package/lib/commonjs/attribution.js +4 -3
  62. package/lib/commonjs/attribution.js.map +1 -1
  63. package/lib/commonjs/identity.js +12 -11
  64. package/lib/commonjs/identity.js.map +1 -1
  65. package/lib/commonjs/index.js +16 -5
  66. package/lib/commonjs/index.js.map +1 -1
  67. package/lib/commonjs/internal/config.js +105 -8
  68. package/lib/commonjs/internal/config.js.map +1 -1
  69. package/lib/commonjs/internal/telemetry-context.js +70 -0
  70. package/lib/commonjs/internal/telemetry-context.js.map +1 -0
  71. package/lib/commonjs/modules/analytics.js +18 -25
  72. package/lib/commonjs/modules/analytics.js.map +1 -1
  73. package/lib/commonjs/modules/crash-reporting.js +353 -31
  74. package/lib/commonjs/modules/crash-reporting.js.map +1 -1
  75. package/lib/commonjs/modules/log.js +1 -1
  76. package/lib/commonjs/modules/notifications.js +500 -0
  77. package/lib/commonjs/modules/notifications.js.map +1 -0
  78. package/lib/commonjs/modules/performance.js +57 -8
  79. package/lib/commonjs/modules/performance.js.map +1 -1
  80. package/lib/commonjs/native/module.js +6 -0
  81. package/lib/commonjs/native/module.js.map +1 -1
  82. package/lib/commonjs/native/spec.js +12 -5
  83. package/lib/commonjs/native/spec.js.map +1 -1
  84. package/lib/commonjs/purchases.js +4 -4
  85. package/lib/commonjs/types.js +12 -15
  86. package/lib/commonjs/types.js.map +1 -1
  87. package/lib/module/attribution.js +4 -3
  88. package/lib/module/attribution.js.map +1 -1
  89. package/lib/module/identity.js +12 -11
  90. package/lib/module/identity.js.map +1 -1
  91. package/lib/module/index.js +8 -4
  92. package/lib/module/index.js.map +1 -1
  93. package/lib/module/internal/config.js +103 -8
  94. package/lib/module/internal/config.js.map +1 -1
  95. package/lib/module/internal/telemetry-context.js +63 -0
  96. package/lib/module/internal/telemetry-context.js.map +1 -0
  97. package/lib/module/modules/analytics.js +18 -25
  98. package/lib/module/modules/analytics.js.map +1 -1
  99. package/lib/module/modules/crash-reporting.js +353 -31
  100. package/lib/module/modules/crash-reporting.js.map +1 -1
  101. package/lib/module/modules/log.js +1 -1
  102. package/lib/module/modules/notifications.js +491 -0
  103. package/lib/module/modules/notifications.js.map +1 -0
  104. package/lib/module/modules/performance.js +57 -8
  105. package/lib/module/modules/performance.js.map +1 -1
  106. package/lib/module/native/module.js +6 -1
  107. package/lib/module/native/module.js.map +1 -1
  108. package/lib/module/native/spec.js +11 -4
  109. package/lib/module/native/spec.js.map +1 -1
  110. package/lib/module/purchases.js +4 -4
  111. package/lib/module/types.js +12 -15
  112. package/lib/module/types.js.map +1 -1
  113. package/lib/typescript/commonjs/attribution.d.ts +3 -2
  114. package/lib/typescript/commonjs/attribution.d.ts.map +1 -1
  115. package/lib/typescript/commonjs/identity.d.ts.map +1 -1
  116. package/lib/typescript/commonjs/index.d.ts +3 -1
  117. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  118. package/lib/typescript/commonjs/internal/config.d.ts +16 -2
  119. package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
  120. package/lib/typescript/commonjs/internal/telemetry-context.d.ts +22 -0
  121. package/lib/typescript/commonjs/internal/telemetry-context.d.ts.map +1 -0
  122. package/lib/typescript/commonjs/modules/analytics.d.ts +8 -11
  123. package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -1
  124. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +50 -12
  125. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
  126. package/lib/typescript/commonjs/modules/notifications.d.ts +110 -0
  127. package/lib/typescript/commonjs/modules/notifications.d.ts.map +1 -0
  128. package/lib/typescript/commonjs/modules/performance.d.ts +13 -0
  129. package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -1
  130. package/lib/typescript/commonjs/native/module.d.ts +2 -0
  131. package/lib/typescript/commonjs/native/module.d.ts.map +1 -1
  132. package/lib/typescript/commonjs/native/spec.d.ts +33 -4
  133. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
  134. package/lib/typescript/commonjs/purchases.d.ts +4 -4
  135. package/lib/typescript/commonjs/types.d.ts +4 -5
  136. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  137. package/lib/typescript/module/attribution.d.ts +3 -2
  138. package/lib/typescript/module/attribution.d.ts.map +1 -1
  139. package/lib/typescript/module/identity.d.ts.map +1 -1
  140. package/lib/typescript/module/index.d.ts +3 -1
  141. package/lib/typescript/module/index.d.ts.map +1 -1
  142. package/lib/typescript/module/internal/config.d.ts +16 -2
  143. package/lib/typescript/module/internal/config.d.ts.map +1 -1
  144. package/lib/typescript/module/internal/telemetry-context.d.ts +22 -0
  145. package/lib/typescript/module/internal/telemetry-context.d.ts.map +1 -0
  146. package/lib/typescript/module/modules/analytics.d.ts +8 -11
  147. package/lib/typescript/module/modules/analytics.d.ts.map +1 -1
  148. package/lib/typescript/module/modules/crash-reporting.d.ts +50 -12
  149. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
  150. package/lib/typescript/module/modules/notifications.d.ts +110 -0
  151. package/lib/typescript/module/modules/notifications.d.ts.map +1 -0
  152. package/lib/typescript/module/modules/performance.d.ts +13 -0
  153. package/lib/typescript/module/modules/performance.d.ts.map +1 -1
  154. package/lib/typescript/module/native/module.d.ts +2 -0
  155. package/lib/typescript/module/native/module.d.ts.map +1 -1
  156. package/lib/typescript/module/native/spec.d.ts +33 -4
  157. package/lib/typescript/module/native/spec.d.ts.map +1 -1
  158. package/lib/typescript/module/purchases.d.ts +4 -4
  159. package/lib/typescript/module/types.d.ts +4 -5
  160. package/lib/typescript/module/types.d.ts.map +1 -1
  161. package/package.json +13 -4
  162. package/src/attribution.ts +4 -3
  163. package/src/identity.ts +12 -11
  164. package/src/index.ts +18 -4
  165. package/src/internal/config.ts +113 -8
  166. package/src/internal/telemetry-context.ts +76 -0
  167. package/src/modules/analytics.ts +24 -33
  168. package/src/modules/crash-reporting.ts +476 -67
  169. package/src/modules/log.ts +1 -1
  170. package/src/modules/notifications.ts +557 -0
  171. package/src/modules/performance.ts +94 -14
  172. package/src/native/module.ts +6 -0
  173. package/src/native/spec.ts +45 -10
  174. package/src/purchases.ts +4 -4
  175. package/src/types.ts +12 -15
  176. package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +0 -326
  177. package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +0 -296
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", {
6
6
  exports.SKErrorBoundary = exports.CrashReporting = void 0;
7
7
  exports.buildStaticContexts = buildStaticContexts;
8
8
  exports.parseStackTrace = parseStackTrace;
9
+ var _telemetryContext = require("../internal/telemetry-context.js");
9
10
  var _react = _interopRequireDefault(require("react"));
10
11
  var _ids = require("./ids.js");
11
12
  var _offlineStore = require("./offline-store.js");
@@ -38,7 +39,7 @@ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e
38
39
  // require new native impls on both platforms + spec.ts + tests, well
39
40
  // beyond Round-D's "wrap-up the audit" scope.
40
41
  //
41
- // Native crash capture (Mach exceptions, signal crashes, ANR, NDK)
42
+ // Native crash capture (iOS signals + NSException, ANR, Android NDK)
42
43
  // already goes through the native `SKCrashReporting` module (see the
43
44
  // `getNativeCrashModule()` branch below) — those native-side captures
44
45
  // ARE on the unified transport. JS-captured errors stay on this fetch
@@ -49,8 +50,9 @@ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e
49
50
  /**
50
51
  * Optional native module for crash reporting. If the host app has linked
51
52
  * the SwissKnife iOS/Android native crash SDKs, this module delegates
52
- * init/setUser/addBreadcrumb to the native layer — catching Mach exceptions,
53
- * signal crashes (iOS), and NDK native crashes (Android) that JS can't see.
53
+ * init/setUser/addBreadcrumb to the native layer — catching signal crashes and
54
+ * uncaught NSExceptions (iOS) and NDK native crashes (Android) that JS can't
55
+ * see. iOS installs no Mach exception handler.
54
56
  */
55
57
 
56
58
  /** Test seam (same shape as `_screenshotCaptureOverride`): `undefined` =
@@ -97,7 +99,13 @@ const FATAL_SEND_TIMEOUT_MS = 2_000;
97
99
  const DEFAULT_MAX_CACHE_ITEMS = 30;
98
100
  const OFFLINE_QUEUE_KEY = "@swissknife:crash:queue";
99
101
  const OFFLINE_SESSION_KEY = "@swissknife:crash:session";
102
+ /** Started/ended session events waiting on a retry (see Session Outbox). */
103
+ const OFFLINE_SESSIONS_KEY = "@swissknife:crash:sessions";
104
+ /** Cap on queued session events — drop-oldest beyond this. */
105
+ const MAX_PENDING_SESSIONS = 50;
100
106
  const OFFLINE_SCREENSHOTS_KEY = "@swissknife:crash:screenshots";
107
+ /** JS-side install id, only for apps without the native Identity bridge. */
108
+ const INSTALL_ID_KEY = "@swissknife:crash:install_id";
101
109
 
102
110
  // MARK: - Stack Trace Parsing
103
111
 
@@ -177,6 +185,8 @@ let _breadcrumbs = new RingBuffer(100);
177
185
  let _tags = {};
178
186
  let _extra = {};
179
187
  let _user = null;
188
+ /** Scope-level fingerprint (configureScope → setFingerprint). */
189
+ let _fingerprint = null;
180
190
  let _pendingEvents = [];
181
191
  /**
182
192
  * Events handed to an in-flight POST: already out of `_pendingEvents`, not
@@ -242,8 +252,20 @@ let _screenshotCaptureOverride;
242
252
  // `Identity.current()` also carries an `anonymousId`, and stamping it into
243
253
  // `user.id` would make "affected users" non-zero for every app that never
244
254
  // logs in. That both inflates the number and diverges from Analytics, whose
245
- // `user_id` is the identified subject only. The anonymous id already travels
246
- // separately on the ingest envelope. Only `userId` is used here.
255
+ // `user_id` is the identified subject only. The anonymous id travels
256
+ // separately, as the wire event's `installId` (see below) — the server counts
257
+ // affected users by user id, else install id, without conflating the two.
258
+
259
+ // ## installId — the stable per-install id
260
+ //
261
+ // Most crashes have no identified subject, so the server counts affected
262
+ // users by `installId` when `user.id` is absent. It is the Identity bridge's
263
+ // `anonymousId` (`$SKAnonymousID:<device id>` — the same value native crashes
264
+ // carry on their ingest envelope and `app_users.anonymous_id` stores, so the
265
+ // dashboard can link an anonymous install to its profile). Apps without the
266
+ // native Identity bridge get a random id persisted in AsyncStorage; without
267
+ // AsyncStorage no installId is sent at all, because a per-launch id would
268
+ // count every relaunch as a new user.
247
269
 
248
270
  /**
249
271
  * Last resolved identified subject id from the native Identity bridge.
@@ -252,6 +274,14 @@ let _screenshotCaptureOverride;
252
274
  * stamped, which is exactly today's behaviour for apps that never log in.
253
275
  */
254
276
  let _identityUserId = null;
277
+ /** Last resolved `Identity.current().anonymousId` (stable per install). */
278
+ let _identityAnonymousId = null;
279
+ /** AsyncStorage-persisted install id; used only when no Identity bridge. */
280
+ let _jsInstallId = null;
281
+ /** In-flight `loadJsInstallId`, so a flush racing init can wait for it. */
282
+ let _jsInstallIdLoad = null;
283
+ /** `_jsInstallIdLoad` has settled — flush skips the wait (and its hops). */
284
+ let _jsInstallIdSettled = false;
255
285
  /** In-flight read, so N events in a burst share one bridge hop. */
256
286
  let _identityRefresh = null;
257
287
  /** Monotonic read counter — a superseded read must not clobber a newer one. */
@@ -265,6 +295,8 @@ let _identityGeneration = 0;
265
295
  */
266
296
  let _identityResolverOverride;
267
297
 
298
+ /** The fields of the native `Identity.current()` snapshot this module reads. */
299
+
268
300
  /** Budget for the send-time identity re-resolve. Kept well under
269
301
  * FATAL_SEND_TIMEOUT_MS so a slow bridge can never eat the fatal path's
270
302
  * one chance to deliver before the process dies. */
@@ -312,6 +344,11 @@ function startIdentityRead() {
312
344
  if (generation !== _identityGeneration) return; // superseded
313
345
  const userId = snapshot?.userId;
314
346
  _identityUserId = typeof userId === "string" && userId.length > 0 ? userId : null;
347
+ // Never blanked by a later empty answer: the id is per install.
348
+ const anonymousId = snapshot?.anonymousId;
349
+ if (typeof anonymousId === "string" && anonymousId.length > 0) {
350
+ _identityAnonymousId = anonymousId;
351
+ }
315
352
  } catch {
316
353
  // Bridge hiccup — keep the last known subject.
317
354
  } finally {
@@ -390,9 +427,71 @@ function mergeIdentityInto(user) {
390
427
  };
391
428
  }
392
429
 
430
+ /** Resolve when `p` settles or after `ms`, whichever is first. Never rejects. */
431
+ function withTimeout(p, ms) {
432
+ return new Promise(resolve => {
433
+ const timer = setTimeout(resolve, ms);
434
+ void p.then(() => {
435
+ clearTimeout(timer);
436
+ resolve();
437
+ }, () => {
438
+ clearTimeout(timer);
439
+ resolve();
440
+ });
441
+ });
442
+ }
443
+
444
+ /**
445
+ * The install id to stamp on outgoing events, or undefined when none is
446
+ * known. The Identity bridge's anonymous id wins; the JS-persisted id is used
447
+ * only when there is no bridge at all — mixing the two on one device (e.g. a
448
+ * slow bridge read) would count that device twice.
449
+ */
450
+ function resolveInstallId() {
451
+ if (_identityAnonymousId) return _identityAnonymousId;
452
+ if (getIdentityResolver() !== null) return undefined;
453
+ return _jsInstallId ?? undefined;
454
+ }
455
+
456
+ /**
457
+ * Load (or mint and persist) the JS-side install id. Only for apps without
458
+ * the Identity bridge; a no-op without AsyncStorage. Never throws.
459
+ */
460
+ function loadJsInstallId() {
461
+ _jsInstallIdLoad ??= readOrMintJsInstallId().finally(() => {
462
+ _jsInstallIdSettled = true;
463
+ });
464
+ return _jsInstallIdLoad;
465
+ }
466
+ async function readOrMintJsInstallId() {
467
+ if (_jsInstallId || getIdentityResolver() !== null) return;
468
+ const storage = (0, _offlineStore.getOfflineStorage)();
469
+ if (!storage) return;
470
+ try {
471
+ const stored = await storage.getItem(INSTALL_ID_KEY);
472
+ if (stored) {
473
+ _jsInstallId = stored;
474
+ return;
475
+ }
476
+ const minted = (0, _ids.generateUUID)();
477
+ await storage.setItem(INSTALL_ID_KEY, minted);
478
+ // Only use an id that made it to disk — see the module note above.
479
+ _jsInstallId = minted;
480
+ } catch {
481
+ // Storage hiccup: send no installId rather than a per-launch one.
482
+ }
483
+ }
484
+
393
485
  // MARK: - Pending Queue (memory + best-effort disk mirror)
394
486
 
487
+ const capturedContexts = new WeakMap();
395
488
  function enqueueEvent(event) {
489
+ event.traceId ??= (0, _telemetryContext.currentTelemetryTraceId)();
490
+ const captured = (0, _telemetryContext.captureTelemetryContext)().then(context => {
491
+ event.sessionId ??= context.sessionId;
492
+ persistQueue();
493
+ });
494
+ capturedContexts.set(event, captured);
396
495
  _pendingEvents.push(event);
397
496
  if (_pendingEvents.length > MAX_PENDING_EVENTS) {
398
497
  const dropped = _pendingEvents.splice(0, _pendingEvents.length - MAX_PENDING_EVENTS);
@@ -654,6 +753,21 @@ function clearAmbiguousStreak() {
654
753
 
655
754
  // MARK: - Session Tracking
656
755
 
756
+ /**
757
+ * Request headers for every `/api/sdk/errors/*` call. Carries the install id
758
+ * (when known) so the server's per-device rate limit buckets this install
759
+ * separately from every other device of the app.
760
+ */
761
+ function requestHeaders(apiKey) {
762
+ const installId = resolveInstallId();
763
+ return {
764
+ "Content-Type": "application/json",
765
+ "X-API-Key": apiKey,
766
+ ...(installId ? {
767
+ "X-SK-Install-Id": installId
768
+ } : {})
769
+ };
770
+ }
657
771
  function buildSessionPayload(status) {
658
772
  const duration = _sessionStartTime !== null ? (Date.now() - _sessionStartTime) / 1000 : 0;
659
773
  const contexts = getStaticContexts();
@@ -681,8 +795,24 @@ function buildSessionPayload(status) {
681
795
  } : {})
682
796
  };
683
797
  }
798
+
799
+ /**
800
+ * Outcome of one session POST. `retryable` covers 429, 5xx and transport
801
+ * errors — the server (or network) may answer differently in a moment;
802
+ * any other 4xx is a permanent reject. `retryAfterMs` is the server's
803
+ * `Retry-After`, when it sent one.
804
+ */
805
+
806
+ function parseRetryAfterMs(header) {
807
+ const sec = header ? Number(header) : NaN;
808
+ return Number.isFinite(sec) && sec >= 0 ? sec * 1000 : null;
809
+ }
684
810
  async function postSessionPayload(payload, timeoutMs) {
685
- if (!_config) return false;
811
+ if (!_config) return {
812
+ ok: false,
813
+ retryable: false,
814
+ retryAfterMs: null
815
+ };
686
816
  const baseURL = _config.serverURL || "https://api.swiss-knife.dev";
687
817
  const url = `${baseURL}/api/sdk/errors/session`;
688
818
  let controller = null;
@@ -694,24 +824,106 @@ async function postSessionPayload(payload, timeoutMs) {
694
824
  try {
695
825
  const res = await fetch(url, {
696
826
  method: "POST",
697
- headers: {
698
- "Content-Type": "application/json",
699
- "X-API-Key": _config.apiKey
700
- },
827
+ headers: requestHeaders(_config.apiKey),
701
828
  body: JSON.stringify(payload),
702
829
  ...(controller ? {
703
830
  signal: controller.signal
704
831
  } : {})
705
832
  });
706
- return res.ok;
833
+ if (res.ok) return {
834
+ ok: true
835
+ };
836
+ return {
837
+ ok: false,
838
+ retryable: res.status === 429 || res.status >= 500,
839
+ retryAfterMs: parseRetryAfterMs(res.headers.get("Retry-After"))
840
+ };
707
841
  } catch (e) {
708
842
  console.warn("[SwissKnife CrashReporting] session event error:", e);
709
- return false;
843
+ return {
844
+ ok: false,
845
+ retryable: true,
846
+ retryAfterMs: null
847
+ };
710
848
  } finally {
711
849
  if (timer) clearTimeout(timer);
712
850
  }
713
851
  }
714
852
 
853
+ // MARK: - Session Outbox
854
+ //
855
+ // `started` / `ended` session events used to be fire-and-forget: a 429 or a
856
+ // 5xx dropped them, and crash-free-session rates quietly lost their
857
+ // denominator. A failed retryable send now waits here — in order, persisted
858
+ // to the offline store, capped — and is retried after the server's
859
+ // `Retry-After` (or an exponential backoff when it sent none). The crashed
860
+ // session keeps its own dedicated persistence (`OFFLINE_SESSION_KEY`).
861
+
862
+ /** Session events awaiting a retry, oldest first. */
863
+ let _pendingSessions = [];
864
+ let _sessionRetryTimer = null;
865
+ let _sessionBackoffMs = BACKOFF_INITIAL_MS;
866
+ let _sessionDrainInFlight = false;
867
+ /**
868
+ * False from `init` until `restorePersistedState` has merged the previous
869
+ * launch's outbox. Until then this launch must not WRITE `OFFLINE_SESSIONS_KEY`
870
+ * (it would overwrite the stored outbox before restore reads it) nor drain
871
+ * (the older events must go first). Restore persists + drains once merged.
872
+ */
873
+ let _sessionsRestored = true;
874
+ function persistPendingSessions() {
875
+ if (!_sessionsRestored) return;
876
+ const storage = (0, _offlineStore.getOfflineStorage)();
877
+ if (!storage) return;
878
+ const write = _pendingSessions.length === 0 ? storage.removeItem(OFFLINE_SESSIONS_KEY) : storage.setItem(OFFLINE_SESSIONS_KEY, JSON.stringify(_pendingSessions));
879
+ void write.catch(() => {});
880
+ }
881
+ function scheduleSessionRetry(retryAfterMs) {
882
+ const delayMs = retryAfterMs ?? _sessionBackoffMs;
883
+ _sessionBackoffMs = Math.min(_sessionBackoffMs * 2, BACKOFF_MAX_MS);
884
+ if (_sessionRetryTimer !== null) clearTimeout(_sessionRetryTimer);
885
+ _sessionRetryTimer = setTimeout(() => {
886
+ _sessionRetryTimer = null;
887
+ void drainPendingSessions();
888
+ }, delayMs);
889
+ }
890
+ function queueSessionForRetry(payload, retryAfterMs) {
891
+ _pendingSessions.push(payload);
892
+ if (_pendingSessions.length > MAX_PENDING_SESSIONS) {
893
+ _pendingSessions.splice(0, _pendingSessions.length - MAX_PENDING_SESSIONS);
894
+ }
895
+ // Before restore has merged the stored outbox, just hold it in memory:
896
+ // restore persists and drains the merged queue.
897
+ if (!_sessionsRestored) return;
898
+ persistPendingSessions();
899
+ // A drain in flight, or a retry already booked, will pick this one up.
900
+ if (!_sessionDrainInFlight && _sessionRetryTimer === null) {
901
+ scheduleSessionRetry(retryAfterMs);
902
+ }
903
+ }
904
+
905
+ /** Send queued session events in order until one fails retryably. */
906
+ async function drainPendingSessions() {
907
+ if (_sessionDrainInFlight || !_config || !_sessionsRestored) return;
908
+ _sessionDrainInFlight = true;
909
+ try {
910
+ while (_pendingSessions.length > 0) {
911
+ const head = _pendingSessions[0];
912
+ const result = await postSessionPayload(head);
913
+ if (!result.ok && result.retryable) {
914
+ scheduleSessionRetry(result.retryAfterMs);
915
+ return;
916
+ }
917
+ // Delivered, or permanently rejected (a retry would only spin).
918
+ if (_pendingSessions[0] === head) _pendingSessions.shift();
919
+ _sessionBackoffMs = BACKOFF_INITIAL_MS;
920
+ persistPendingSessions();
921
+ }
922
+ } finally {
923
+ _sessionDrainInFlight = false;
924
+ }
925
+ }
926
+
715
927
  /**
716
928
  * Deliberately has NO `await` before `postSessionPayload` — not even to
717
929
  * re-resolve the identity. `endSession` nulls `_sessionId` and zeroes the
@@ -722,7 +934,18 @@ async function postSessionPayload(payload, timeoutMs) {
722
934
  */
723
935
  async function sendSessionEvent(status) {
724
936
  if (!_config || !_sessionId) return;
725
- await postSessionPayload(buildSessionPayload(status));
937
+ const payload = buildSessionPayload(status);
938
+ // Something is already waiting on a backoff: queue behind it so the
939
+ // server still sees `started` before `ended`, and so we do not hammer a
940
+ // server that just told us to wait.
941
+ if (_pendingSessions.length > 0 || _sessionDrainInFlight) {
942
+ queueSessionForRetry(payload, null);
943
+ return;
944
+ }
945
+ const result = await postSessionPayload(payload);
946
+ if (!result.ok && result.retryable) {
947
+ queueSessionForRetry(payload, result.retryAfterMs);
948
+ }
726
949
  }
727
950
  function startSession() {
728
951
  _sessionId = (0, _ids.generateUUID)();
@@ -762,7 +985,9 @@ async function deliverCrashedSession() {
762
985
  _sessionStartTime = null;
763
986
  _sessionErrorCount = 0;
764
987
  if (!payload) return;
765
- const ok = await postSessionPayload(payload, FATAL_SEND_TIMEOUT_MS);
988
+ const {
989
+ ok
990
+ } = await postSessionPayload(payload, FATAL_SEND_TIMEOUT_MS);
766
991
  if (ok) {
767
992
  const storage = (0, _offlineStore.getOfflineStorage)();
768
993
  if (storage) void storage.removeItem(OFFLINE_SESSION_KEY).catch(() => {});
@@ -809,19 +1034,56 @@ function installAppStateListener() {
809
1034
  */
810
1035
  function restorePersistedState() {
811
1036
  const storage = (0, _offlineStore.getOfflineStorage)();
812
- if (!storage) return;
1037
+ if (!storage) {
1038
+ _sessionsRestored = true;
1039
+ return;
1040
+ }
1041
+ _sessionsRestored = false;
813
1042
  _restorePromise = (async () => {
1043
+ // Read the stored session outbox FIRST, before any other await: nothing
1044
+ // this launch does may replace it before it is merged (see
1045
+ // `_sessionsRestored`).
1046
+ let storedSessions = [];
1047
+ try {
1048
+ const rawSessions = await storage.getItem(OFFLINE_SESSIONS_KEY);
1049
+ if (rawSessions) {
1050
+ const restored = JSON.parse(rawSessions);
1051
+ if (Array.isArray(restored)) {
1052
+ storedSessions = restored.filter(p => p && typeof p.sessionId === "string");
1053
+ }
1054
+ }
1055
+ } catch {
1056
+ // Unreadable outbox: dropped; the merged persist below overwrites it.
1057
+ }
1058
+ // Earlier launch's sessions go first; anything this launch has already
1059
+ // queued stays behind them. Dedupe on (sessionId, status).
1060
+ const seen = new Set();
1061
+ _pendingSessions = [...storedSessions, ..._pendingSessions].filter(p => {
1062
+ const k = `${p.sessionId}|${p.status}`;
1063
+ if (seen.has(k)) return false;
1064
+ seen.add(k);
1065
+ return true;
1066
+ }).slice(-MAX_PENDING_SESSIONS);
1067
+ _sessionsRestored = true;
1068
+ persistPendingSessions();
814
1069
  try {
815
1070
  const rawSession = await storage.getItem(OFFLINE_SESSION_KEY);
816
1071
  if (rawSession) {
817
1072
  const payload = JSON.parse(rawSession);
818
- if (payload?.sessionId && (await postSessionPayload(payload))) {
1073
+ if (payload?.sessionId && (await postSessionPayload(payload)).ok) {
819
1074
  await storage.removeItem(OFFLINE_SESSION_KEY);
820
1075
  }
821
1076
  }
822
1077
  } catch {
823
1078
  // undeliverable this launch — keep for the next one
824
1079
  }
1080
+ if (_pendingSessions.length > 0 && _sessionRetryTimer === null) {
1081
+ try {
1082
+ await drainPendingSessions();
1083
+ } catch {
1084
+ // retried on the next backoff / launch
1085
+ }
1086
+ }
825
1087
  try {
826
1088
  const rawShots = await storage.getItem(OFFLINE_SCREENSHOTS_KEY);
827
1089
  if (rawShots) {
@@ -1043,6 +1305,12 @@ function getStaticContexts() {
1043
1305
 
1044
1306
  // MARK: - Build Event
1045
1307
 
1308
+ /** A usable fingerprint: the string entries, or null when none remain. */
1309
+ function normalizeFingerprint(fingerprint) {
1310
+ if (!Array.isArray(fingerprint)) return null;
1311
+ const entries = fingerprint.filter(entry => typeof entry === "string" && entry.length > 0);
1312
+ return entries.length > 0 ? entries : null;
1313
+ }
1046
1314
  function buildEvent(level, partial = {}) {
1047
1315
  const contexts = {
1048
1316
  ...getStaticContexts()
@@ -1070,6 +1338,9 @@ function buildEvent(level, partial = {}) {
1070
1338
  },
1071
1339
  user: resolveSubject(),
1072
1340
  breadcrumbs: _breadcrumbs.snapshot(),
1341
+ ...(_fingerprint ? {
1342
+ fingerprint: [..._fingerprint]
1343
+ } : {}),
1073
1344
  ...partial,
1074
1345
  contexts
1075
1346
  };
@@ -1394,6 +1665,18 @@ function installConsoleBreadcrumbs() {
1394
1665
 
1395
1666
  const CrashReporting = exports.CrashReporting = {
1396
1667
  init(config) {
1668
+ // An empty key (typically a build-time env var that was not set) can
1669
+ // never authenticate. Same rule as `configure()` (internal/config.ts
1670
+ // assertApiKey), but logged instead of thrown: `init` usually runs in
1671
+ // module scope, where a throw keeps the app from booting. Nothing is
1672
+ // installed and the native crash module is not started, so the native
1673
+ // layer is not wired with the empty key and a later `init` with the real
1674
+ // key works.
1675
+ const apiKey = config?.apiKey;
1676
+ if (typeof apiKey !== "string" || apiKey.trim() === "") {
1677
+ console.error(`[SwissKnife CrashReporting] init requires a non-empty apiKey (got ${typeof apiKey === "string" ? JSON.stringify(apiKey) : String(apiKey)}); crash reporting is off.`);
1678
+ return;
1679
+ }
1397
1680
  // Defaults keep today's behaviour byte-for-byte: every handler is on
1398
1681
  // unless the host explicitly opts out. The opt-outs exist for apps whose
1399
1682
  // incumbent reporter owns a given global — see each field's doc comment
@@ -1414,6 +1697,7 @@ const CrashReporting = exports.CrashReporting = {
1414
1697
  // path re-resolves anyway — this only shortens the window in which an
1415
1698
  // early event has to fall back to the send-time pull.
1416
1699
  void refreshIdentitySubject();
1700
+ void loadJsInstallId();
1417
1701
  // Every global-slot install is best-effort. `initSwissKnife()` is normally
1418
1702
  // called in module scope, so anything that throws here takes the host's
1419
1703
  // root module down with it and the app never boots (v0.2.3 did exactly
@@ -1429,15 +1713,14 @@ const CrashReporting = exports.CrashReporting = {
1429
1713
  if (_config.enableAppStateTracking) installAppStateListener();
1430
1714
 
1431
1715
  // Initialize native crash handler if the native module is linked.
1432
- // This catches Mach exceptions + signal crashes (iOS) and NDK native
1433
- // crashes + system ANRs (Android) that pure JS cannot observe.
1716
+ // This catches signal crashes + uncaught NSExceptions (iOS) and NDK
1717
+ // native crashes + system ANRs (Android) that pure JS cannot observe.
1434
1718
  const nativeMod = _config.enableNativeCrashHandler ? getNativeCrashModule() : null;
1435
1719
  if (nativeMod) {
1436
1720
  try {
1437
1721
  nativeMod.start({
1438
1722
  apiKey: config.apiKey,
1439
1723
  serverURL: config.serverURL || "",
1440
- ingestURL: config.ingestURL,
1441
1724
  environment: config.environment || "production",
1442
1725
  release: config.release || ""
1443
1726
  });
@@ -1459,6 +1742,7 @@ const CrashReporting = exports.CrashReporting = {
1459
1742
  eventId: fallbackId
1460
1743
  };
1461
1744
  _sessionErrorCount++;
1745
+ const fingerprint = normalizeFingerprint(options?.fingerprint);
1462
1746
  let event = buildEvent("error", {
1463
1747
  exceptionType: error.name,
1464
1748
  exceptionValue: error.message,
@@ -1468,7 +1752,10 @@ const CrashReporting = exports.CrashReporting = {
1468
1752
  ...options.tags
1469
1753
  } : {
1470
1754
  ..._tags
1471
- }
1755
+ },
1756
+ ...(fingerprint ? {
1757
+ fingerprint
1758
+ } : {})
1472
1759
  });
1473
1760
  event = applyBeforeSend(event);
1474
1761
  if (!event) return {
@@ -1523,10 +1810,7 @@ const CrashReporting = exports.CrashReporting = {
1523
1810
  const url = `${baseURL}/api/sdk/errors/feedback`;
1524
1811
  fetch(url, {
1525
1812
  method: "POST",
1526
- headers: {
1527
- "Content-Type": "application/json",
1528
- "X-API-Key": _config.apiKey
1529
- },
1813
+ headers: requestHeaders(_config.apiKey),
1530
1814
  body: JSON.stringify(feedback)
1531
1815
  }).catch(e => {
1532
1816
  console.warn("[SwissKnife CrashReporting] feedback error:", e);
@@ -1563,7 +1847,9 @@ const CrashReporting = exports.CrashReporting = {
1563
1847
  message: crumb.message,
1564
1848
  level: crumb.level
1565
1849
  });
1566
- } catch {/* non-fatal */}
1850
+ } catch {
1851
+ /* non-fatal */
1852
+ }
1567
1853
  }
1568
1854
  },
1569
1855
  /**
@@ -1606,7 +1892,9 @@ const CrashReporting = exports.CrashReporting = {
1606
1892
  if (nativeMod) {
1607
1893
  try {
1608
1894
  nativeMod.setUser(user);
1609
- } catch {/* non-fatal */}
1895
+ } catch {
1896
+ /* non-fatal */
1897
+ }
1610
1898
  }
1611
1899
  },
1612
1900
  setTag(key, value) {
@@ -1616,7 +1904,9 @@ const CrashReporting = exports.CrashReporting = {
1616
1904
  if (nativeMod) {
1617
1905
  try {
1618
1906
  nativeMod.setTag(key, value);
1619
- } catch {/* non-fatal */}
1907
+ } catch {
1908
+ /* non-fatal */
1909
+ }
1620
1910
  }
1621
1911
  },
1622
1912
  setExtra(key, value) {
@@ -1632,6 +1922,9 @@ const CrashReporting = exports.CrashReporting = {
1632
1922
  },
1633
1923
  setUser: user => {
1634
1924
  _user = user;
1925
+ },
1926
+ setFingerprint: fingerprint => {
1927
+ _fingerprint = normalizeFingerprint(fingerprint);
1635
1928
  }
1636
1929
  });
1637
1930
  },
@@ -1662,11 +1955,18 @@ const CrashReporting = exports.CrashReporting = {
1662
1955
  // `init` and `init` before `logIn` both end up stamped. Bounded by
1663
1956
  // IDENTITY_RESOLVE_TIMEOUT_MS so the fatal path keeps its budget.
1664
1957
  await resolveIdentitySubjectNow();
1958
+ // A flush racing `init` waits for the AsyncStorage read, bounded like the
1959
+ // identity pull (no timer when there is nothing in flight).
1960
+ if (_jsInstallIdLoad && !_jsInstallIdSettled) {
1961
+ await withTimeout(_jsInstallIdLoad, IDENTITY_RESOLVE_TIMEOUT_MS);
1962
+ }
1665
1963
 
1666
1964
  // The /api/sdk/errors/event/batch endpoint:
1667
1965
  // - expects `timestamp` as an ISO string (SDK builds it as Date.now() number)
1668
1966
  // - rejects `user: null` (schema marks `user` optional, not nullable)
1669
1967
  // Coerce both on the wire so the internal SDK shape stays ergonomic.
1968
+ await Promise.all(batch.map(event => capturedContexts.get(event)));
1969
+ const installId = resolveInstallId();
1670
1970
  const serialized = batch.map(e => {
1671
1971
  const {
1672
1972
  user: builtUser,
@@ -1679,6 +1979,11 @@ const CrashReporting = exports.CrashReporting = {
1679
1979
  ...(user ? {
1680
1980
  user
1681
1981
  } : {}),
1982
+ // Stamped at send time, like the subject: an event captured before
1983
+ // the bridge first answered still ships with it.
1984
+ ...(installId ? {
1985
+ installId
1986
+ } : {}),
1682
1987
  timestamp: typeof e.timestamp === "number" ? new Date(e.timestamp).toISOString() : e.timestamp
1683
1988
  };
1684
1989
  });
@@ -1691,10 +1996,7 @@ const CrashReporting = exports.CrashReporting = {
1691
1996
  try {
1692
1997
  const res = await fetch(url, {
1693
1998
  method: "POST",
1694
- headers: {
1695
- "Content-Type": "application/json",
1696
- "X-API-Key": _config.apiKey
1697
- },
1999
+ headers: requestHeaders(_config.apiKey),
1698
2000
  body: JSON.stringify({
1699
2001
  events: serialized
1700
2002
  }),
@@ -1802,6 +2104,7 @@ const CrashReporting = exports.CrashReporting = {
1802
2104
  _tags = {};
1803
2105
  _extra = {};
1804
2106
  _user = null;
2107
+ _fingerprint = null;
1805
2108
  _pendingEvents = [];
1806
2109
  _inFlightEvents = new Map();
1807
2110
  if (_flushTimer !== null) {
@@ -1814,6 +2117,14 @@ const CrashReporting = exports.CrashReporting = {
1814
2117
  _sessionErrorCount = 0;
1815
2118
  _backoffMs = BACKOFF_INITIAL_MS;
1816
2119
  _backoffUntil = 0;
2120
+ _pendingSessions = [];
2121
+ if (_sessionRetryTimer !== null) {
2122
+ clearTimeout(_sessionRetryTimer);
2123
+ _sessionRetryTimer = null;
2124
+ }
2125
+ _sessionBackoffMs = BACKOFF_INITIAL_MS;
2126
+ _sessionDrainInFlight = false;
2127
+ _sessionsRestored = true;
1817
2128
  clearAmbiguousStreak();
1818
2129
  if (_disableRejectionTracking) {
1819
2130
  // Teardown is the mirror image of install and can fail the same way —
@@ -1830,6 +2141,10 @@ const CrashReporting = exports.CrashReporting = {
1830
2141
  _screenshotCaptureOverride = undefined;
1831
2142
  _nativeCrashModuleOverride = undefined;
1832
2143
  _identityUserId = null;
2144
+ _identityAnonymousId = null;
2145
+ _jsInstallId = null;
2146
+ _jsInstallIdLoad = null;
2147
+ _jsInstallIdSettled = false;
1833
2148
  _identityRefresh = null;
1834
2149
  // Bump the generation so a read still in flight cannot land after the
1835
2150
  // reset and repopulate the subject the reset just cleared.
@@ -1871,6 +2186,12 @@ const CrashReporting = exports.CrashReporting = {
1871
2186
  _snapshotSessionId() {
1872
2187
  return _sessionId;
1873
2188
  },
2189
+ _snapshotPendingSessions() {
2190
+ return _pendingSessions.map(p => ({
2191
+ sessionId: p.sessionId,
2192
+ status: p.status
2193
+ }));
2194
+ },
1874
2195
  _restorePromiseForTests() {
1875
2196
  return _restorePromise;
1876
2197
  },
@@ -1899,6 +2220,7 @@ const CrashReporting = exports.CrashReporting = {
1899
2220
  _setIdentityResolverForTests(resolver) {
1900
2221
  _identityResolverOverride = resolver;
1901
2222
  _identityUserId = null;
2223
+ _identityAnonymousId = null;
1902
2224
  _identityRefresh = null;
1903
2225
  _identityGeneration++;
1904
2226
  },