@app-swiss-knife/react-native-sdk 0.2.3 → 0.2.5

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.
@@ -200,6 +200,181 @@ let _offlineScreenshots = [];
200
200
  /** Test seam: `undefined` = resolve from NativeModules; else use override. */
201
201
  let _screenshotCaptureOverride;
202
202
 
203
+ // MARK: - Identity-derived Subject
204
+ //
205
+ // ## Why the subject is PULLED, never pushed
206
+ //
207
+ // Attaching a person to a crash used to require a `CrashReporting.setUser(...)`
208
+ // call that nothing enforced and nothing validated. Forget it and every crash
209
+ // arrives with `user.id === ""`; the dashboard then reports "Affected users:
210
+ // No identified users" and the integration looks like broken crash reporting
211
+ // when it is actually complete. `Identity.logIn(...)` — the canonical "this is
212
+ // who this is" statement — did not reach this module at all.
213
+ //
214
+ // `modules/analytics.ts` already fixed this exact bug class (see the comment
215
+ // above its `buildEvent`, and `identity.ts` lines 8-16): `user_id` is derived
216
+ // from the native `Identity.current()` snapshot at event-build time rather
217
+ // than being pushed in by whoever calls `logIn`. A pull is immune to
218
+ // initialisation order, and crash reporting is precisely the module that
219
+ // starts before the identity is known — you want the handler armed on the
220
+ // first frame, long before auth state has been read.
221
+ //
222
+ // So: the crash subject is resolved from Identity at report time (and
223
+ // re-resolved at send time, see `flush`), not at login time.
224
+ //
225
+ // ## Deliberately not the anonymous id
226
+ //
227
+ // `Identity.current()` also carries an `anonymousId`, and stamping it into
228
+ // `user.id` would make "affected users" non-zero for every app that never
229
+ // 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.
232
+
233
+ /**
234
+ * Last resolved identified subject id from the native Identity bridge.
235
+ * `null` means "no identified subject" — either genuinely anonymous, or the
236
+ * bridge has not answered yet. Both cases are treated the same: nothing is
237
+ * stamped, which is exactly today's behaviour for apps that never log in.
238
+ */
239
+ let _identityUserId = null;
240
+ /** In-flight read, so N events in a burst share one bridge hop. */
241
+ let _identityRefresh = null;
242
+ /** Monotonic read counter — a superseded read must not clobber a newer one. */
243
+ let _identityGeneration = 0;
244
+ /**
245
+ * Test seam (same shape as `_nativeCrashModuleOverride`): `undefined` =
246
+ * resolve from the native bridge, `null` = pretend the Identity bridge is
247
+ * absent. Needed because `require("react-native")` under vitest reaches the
248
+ * real Flow-syntax entry point and throws, so the bridge branch is otherwise
249
+ * unreachable and "we did read Identity" would pass vacuously.
250
+ */
251
+ let _identityResolverOverride;
252
+
253
+ /** Budget for the send-time identity re-resolve. Kept well under
254
+ * FATAL_SEND_TIMEOUT_MS so a slow bridge can never eat the fatal path's
255
+ * one chance to deliver before the process dies. */
256
+ const IDENTITY_RESOLVE_TIMEOUT_MS = 250;
257
+ function getIdentityResolver() {
258
+ if (_identityResolverOverride !== undefined) {
259
+ return _identityResolverOverride;
260
+ }
261
+ try {
262
+ // Lazy require for the same reason as `getNativeCrashModule()` — a static
263
+ // import would drag react-native's Flow entry point into plain-Node and
264
+ // vitest contexts where this module must stay importable.
265
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
266
+ const mod = require("../native/module");
267
+ const native = mod.getNativeModule();
268
+ if (typeof native?.identityCurrent !== "function") return null;
269
+ return () => native.identityCurrent();
270
+ } catch {
271
+ // Identity bridge not linked (bare Expo app, tests, plain Node).
272
+ return null;
273
+ }
274
+ }
275
+
276
+ /**
277
+ * Issue a FRESH read of `Identity.current()` into `_identityUserId`.
278
+ *
279
+ * Never throws and never rejects — a failed read leaves the previous value in
280
+ * place rather than blanking a subject we already knew about.
281
+ *
282
+ * A generation counter discards the answer of any read that a newer read has
283
+ * already superseded, so two overlapping reads can never let the older one's
284
+ * (pre-`logIn`) snapshot win on arrival order.
285
+ */
286
+ function startIdentityRead() {
287
+ const resolver = getIdentityResolver();
288
+ if (!resolver) return Promise.resolve();
289
+ const generation = ++_identityGeneration;
290
+ // `p` is only read inside the `finally`, which cannot run before the
291
+ // assignment below completes — TS can't see that, hence the explicit
292
+ // `undefined` seed rather than a definite-assignment lie.
293
+ let p;
294
+ p = (async () => {
295
+ try {
296
+ const snapshot = await resolver();
297
+ if (generation !== _identityGeneration) return; // superseded
298
+ const userId = snapshot?.userId;
299
+ _identityUserId = typeof userId === "string" && userId.length > 0 ? userId : null;
300
+ } catch {
301
+ // Bridge hiccup — keep the last known subject.
302
+ } finally {
303
+ if (_identityRefresh === p) _identityRefresh = null;
304
+ }
305
+ })();
306
+ _identityRefresh = p;
307
+ return p;
308
+ }
309
+
310
+ /**
311
+ * Warm the cache. Joins a read that is already in flight — this is only ever
312
+ * used for the opportunistic warm-up at `init`, where an answer a few
313
+ * milliseconds old is fine.
314
+ */
315
+ function refreshIdentitySubject() {
316
+ return _identityRefresh ?? startIdentityRead();
317
+ }
318
+
319
+ /**
320
+ * Send-time resolve, capped at `IDENTITY_RESOLVE_TIMEOUT_MS`.
321
+ *
322
+ * Deliberately does NOT join an in-flight read. `init` kicks a warm-up read
323
+ * immediately, and the host typically calls `Identity.logIn(...)` a moment
324
+ * later — a send that piggybacked on that warm-up would be answered with the
325
+ * pre-`logIn` snapshot and ship a subject-less crash, which is the exact bug
326
+ * this whole pull exists to kill. (Found by evaluating the built bundle in
327
+ * Node, not by the unit suite: a `settle()` in the test masked the race.)
328
+ * One fresh read per flush — not per event.
329
+ *
330
+ * Returns an already-resolved promise (and arms no timer) when there is no
331
+ * Identity bridge to ask — apps without the native module, and every test
332
+ * that has not installed the seam, must not pay a timer or a scheduling hop
333
+ * for a question that has no answer.
334
+ */
335
+ function resolveIdentitySubjectNow() {
336
+ if (getIdentityResolver() === null) return Promise.resolve();
337
+ const read = startIdentityRead();
338
+ return new Promise(resolve => {
339
+ const timer = setTimeout(resolve, IDENTITY_RESOLVE_TIMEOUT_MS);
340
+ void read.then(() => {
341
+ clearTimeout(timer);
342
+ resolve();
343
+ });
344
+ });
345
+ }
346
+
347
+ /**
348
+ * Merge the explicit `setUser` override with the Identity-derived subject.
349
+ *
350
+ * Precedence is **field-by-field, explicit wins**:
351
+ * - `id` — `setUser`'s id if set, else `Identity.current().userId`
352
+ * - `email` — explicit only (Identity has no such field)
353
+ * - `username` — explicit only
354
+ *
355
+ * When nothing resolves, `null` is returned and the `user` key is omitted
356
+ * from the wire payload entirely — byte-identical to today for an app that
357
+ * neither logs in nor calls `setUser`.
358
+ */
359
+ function resolveSubject() {
360
+ return mergeIdentityInto(_user);
361
+ }
362
+
363
+ /**
364
+ * Fill in the Identity-derived `id` on a subject that does not already carry
365
+ * one. Idempotent: a subject that already has an `id` is returned untouched,
366
+ * so applying this at build time and again at send time cannot change it.
367
+ */
368
+ function mergeIdentityInto(user) {
369
+ if (user?.id) return user;
370
+ const id = _identityUserId;
371
+ if (!id) return user ?? null;
372
+ return {
373
+ ...(user ?? {}),
374
+ id
375
+ };
376
+ }
377
+
203
378
  // MARK: - Pending Queue (memory + best-effort disk mirror)
204
379
 
205
380
  function enqueueEvent(event) {
@@ -347,6 +522,9 @@ function buildSessionPayload(status) {
347
522
  const contexts = getStaticContexts();
348
523
  const os = contexts.os;
349
524
  const device = contexts.device;
525
+ // Same pull as events: explicit `setUser` id wins, else the Identity
526
+ // subject. Synchronous, so it reads the cache `flush`/`init` keep warm.
527
+ const subject = resolveSubject();
350
528
  return {
351
529
  sessionId: _sessionId,
352
530
  status,
@@ -354,8 +532,8 @@ function buildSessionPayload(status) {
354
532
  errorsCount: _sessionErrorCount,
355
533
  releaseVersion: _config?.release,
356
534
  environment: _config?.environment,
357
- ...(_user?.id ? {
358
- userId: _user.id
535
+ ...(subject?.id ? {
536
+ userId: subject.id
359
537
  } : {}),
360
538
  ...(os?.name ? {
361
539
  osName: os.name,
@@ -396,6 +574,15 @@ async function postSessionPayload(payload, timeoutMs) {
396
574
  if (timer) clearTimeout(timer);
397
575
  }
398
576
  }
577
+
578
+ /**
579
+ * Deliberately has NO `await` before `postSessionPayload` — not even to
580
+ * re-resolve the identity. `endSession` nulls `_sessionId` and zeroes the
581
+ * error count the instant this function yields, and callers rely on the POST
582
+ * being issued in the same tick. Session payloads therefore take the subject
583
+ * from the warm cache only (see `buildSessionPayload`); the authoritative
584
+ * re-resolve happens on the event path in `flush`.
585
+ */
399
586
  async function sendSessionEvent(status) {
400
587
  if (!_config || !_sessionId) return;
401
588
  await postSessionPayload(buildSessionPayload(status));
@@ -744,7 +931,7 @@ function buildEvent(level, partial = {}) {
744
931
  extra: {
745
932
  ..._extra
746
933
  },
747
- user: _user,
934
+ user: resolveSubject(),
748
935
  breadcrumbs: _breadcrumbs.snapshot(),
749
936
  ...partial,
750
937
  contexts
@@ -830,8 +1017,65 @@ function onUnhandledRejection(_id, rejection) {
830
1017
  }
831
1018
  }
832
1019
  /**
833
- * Wrap a single-slot `enable(options)` entry point so a LATER caller composes
834
- * with us instead of evicting us.
1020
+ * Run a global-slot installer so that a failure costs that one feature and
1021
+ * nothing else. Crash reporting is strictly an add-on to the host app; there
1022
+ * is no failure here worth taking the app down for.
1023
+ */
1024
+ function neverThrow(what, fn) {
1025
+ try {
1026
+ fn();
1027
+ } catch (e) {
1028
+ console.warn(`[SwissKnife CrashReporting] ${what} unavailable:`, e);
1029
+ }
1030
+ }
1031
+
1032
+ /**
1033
+ * Replace a property on an object we do not own, without ever throwing.
1034
+ *
1035
+ * A bare `target.key = value` is not safe on host objects. `HermesInternal` is
1036
+ * **frozen** on every real Hermes build, so its properties are non-writable
1037
+ * and non-configurable; because this module is strict-mode (ES module), the
1038
+ * assignment throws `TypeError: Cannot assign to read-only property` rather
1039
+ * than failing silently. That throw propagated out of `CrashReporting.init`
1040
+ * and — since `initSwissKnife()` is normally called in module scope — aborted
1041
+ * evaluation of the host's root module, so the app never booted. Frozen host
1042
+ * globals must be *probed*, and a refusal must degrade, never escalate.
1043
+ *
1044
+ * Returns true only if the slot genuinely now holds `value`.
1045
+ */
1046
+ function trySetHostProperty(target, key, value) {
1047
+ try {
1048
+ if (Object.isFrozen(target)) return false;
1049
+ const desc = Object.getOwnPropertyDescriptor(target, key);
1050
+ // Non-configurable data property with writable:false — nothing can
1051
+ // replace it. Bail before we provoke a TypeError.
1052
+ if (desc && !desc.configurable && !desc.writable) return false;
1053
+ if (desc === undefined || desc.configurable) {
1054
+ // defineProperty also covers own accessor properties (a getter with no
1055
+ // setter would silently swallow a plain assignment), and never walks
1056
+ // the prototype chain the way `=` does.
1057
+ Object.defineProperty(target, key, {
1058
+ value,
1059
+ writable: desc?.writable ?? true,
1060
+ enumerable: desc?.enumerable ?? true,
1061
+ configurable: true
1062
+ });
1063
+ } else {
1064
+ // Non-configurable but writable — assignment is the only route.
1065
+ target[key] = value;
1066
+ }
1067
+ // Confirm it actually took. Proxies and exotic host objects can accept a
1068
+ // write and keep the old value; treating that as success would leave us
1069
+ // believing we own a slot we do not.
1070
+ return target[key] === value;
1071
+ } catch {
1072
+ return false;
1073
+ }
1074
+ }
1075
+
1076
+ /**
1077
+ * Build a wrapper around a single-slot `enable(options)` entry point so a
1078
+ * LATER caller composes with us instead of evicting us.
835
1079
  *
836
1080
  * Promise-rejection tracking is the one global in this SDK that offers no way
837
1081
  * to read the incumbent handler back out — see
@@ -847,10 +1091,13 @@ function onUnhandledRejection(_id, rejection) {
847
1091
  * silently forcing it back to true would make the API a lie (our own
848
1092
  * `_disableRejectionTracking` uses it).
849
1093
  *
850
- * Returns the un-wrapped original so the caller can restore it on teardown.
1094
+ * Installing the returned wrapper is the caller's job and is strictly an
1095
+ * enhancement: tracking is already live from the direct `original(options)`
1096
+ * call, so a host that refuses the swap keeps full rejection capture and only
1097
+ * loses the compose-with-a-later-reporter nicety.
851
1098
  */
852
- function composeRejectionEnable(install, original, ours) {
853
- install(theirs => {
1099
+ function makeComposingRejectionEnable(original, ours) {
1100
+ return theirs => {
854
1101
  if (!theirs || theirs.allRejections === false) {
855
1102
  original(theirs);
856
1103
  return;
@@ -874,7 +1121,7 @@ function composeRejectionEnable(install, original, ours) {
874
1121
  theirs.onHandled?.(id);
875
1122
  }
876
1123
  });
877
- });
1124
+ };
878
1125
  }
879
1126
  function installPromiseRejectionTracking() {
880
1127
  if (_rejectionTrackingInstalled) return; // double-init guard
@@ -892,13 +1139,19 @@ function installPromiseRejectionTracking() {
892
1139
  // host's own function object back, not a bound copy of it.
893
1140
  const engineEnable = hermes.enablePromiseRejectionTracker;
894
1141
  const original = engineEnable.bind(hermes);
1142
+ // This one call IS the tracking. Everything below is enhancement.
895
1143
  original(options);
896
- composeRejectionEnable(fn => {
897
- hermes.enablePromiseRejectionTracker = fn;
898
- }, original, options);
899
1144
  _rejectionTrackingInstalled = true;
1145
+
1146
+ // `HermesInternal` is frozen on real devices, so this swap usually fails —
1147
+ // that is expected and harmless. Never let it throw out of init().
1148
+ const composed = trySetHostProperty(hermes, "enablePromiseRejectionTracker", makeComposingRejectionEnable(original, options));
900
1149
  _disableRejectionTracking = () => {
901
- hermes.enablePromiseRejectionTracker = engineEnable;
1150
+ // Mirror image of the install: only restore what we managed to replace,
1151
+ // and go through the same non-throwing path.
1152
+ if (composed) {
1153
+ trySetHostProperty(hermes, "enablePromiseRejectionTracker", engineEnable);
1154
+ }
902
1155
  original({
903
1156
  allRejections: false,
904
1157
  onUnhandled: () => {}
@@ -914,13 +1167,18 @@ function installPromiseRejectionTracking() {
914
1167
  const tracking = require("promise/setimmediate/rejection-tracking");
915
1168
  const moduleEnable = tracking.enable;
916
1169
  const original = moduleEnable.bind(tracking);
1170
+ // As above: this call is the tracking; the swap below is enhancement.
917
1171
  original(options);
918
- composeRejectionEnable(fn => {
919
- tracking.enable = fn;
920
- }, original, options);
921
1172
  _rejectionTrackingInstalled = true;
1173
+
1174
+ // Metro hands back a mutable CommonJS `module.exports` here, but any
1175
+ // bundler that gives this module ES-namespace semantics makes `enable`
1176
+ // read-only — same failure mode as HermesInternal, so same guard.
1177
+ const composed = trySetHostProperty(tracking, "enable", makeComposingRejectionEnable(original, options));
922
1178
  _disableRejectionTracking = () => {
923
- tracking.enable = moduleEnable;
1179
+ if (composed) {
1180
+ trySetHostProperty(tracking, "enable", moduleEnable);
1181
+ }
924
1182
  tracking.disable();
925
1183
  };
926
1184
  } catch {
@@ -1014,8 +1272,21 @@ const CrashReporting = exports.CrashReporting = {
1014
1272
  ...config
1015
1273
  };
1016
1274
  _breadcrumbs = new RingBuffer(_config.maxBreadcrumbs);
1017
- if (_config.enableGlobalErrorHandler) installGlobalHandler();
1018
- if (_config.enablePromiseRejectionTracking) installPromiseRejectionTracking();
1275
+ // Warm the Identity subject cache. Fire-and-forget: crash reporting must
1276
+ // arm on the first frame and cannot wait on a bridge hop, and every send
1277
+ // path re-resolves anyway — this only shortens the window in which an
1278
+ // early event has to fall back to the send-time pull.
1279
+ void refreshIdentitySubject();
1280
+ // Every global-slot install is best-effort. `initSwissKnife()` is normally
1281
+ // called in module scope, so anything that throws here takes the host's
1282
+ // root module down with it and the app never boots (v0.2.3 did exactly
1283
+ // that against frozen `HermesInternal`). Degrade the feature, not the app.
1284
+ if (_config.enableGlobalErrorHandler) {
1285
+ neverThrow("global error handler", installGlobalHandler);
1286
+ }
1287
+ if (_config.enablePromiseRejectionTracking) {
1288
+ neverThrow("promise rejection tracking", installPromiseRejectionTracking);
1289
+ }
1019
1290
  restorePersistedState();
1020
1291
  startSession();
1021
1292
  if (_config.enableAppStateTracking) installAppStateListener();
@@ -1041,8 +1312,8 @@ const CrashReporting = exports.CrashReporting = {
1041
1312
 
1042
1313
  // Install automatic breadcrumbs
1043
1314
  if (_config.enableAutoBreadcrumbs) {
1044
- installHTTPBreadcrumbs();
1045
- installConsoleBreadcrumbs();
1315
+ neverThrow("http breadcrumbs", installHTTPBreadcrumbs);
1316
+ neverThrow("console breadcrumbs", installConsoleBreadcrumbs);
1046
1317
  }
1047
1318
  },
1048
1319
  captureException(error, options) {
@@ -1158,9 +1429,42 @@ const CrashReporting = exports.CrashReporting = {
1158
1429
  } catch {/* non-fatal */}
1159
1430
  }
1160
1431
  },
1432
+ /**
1433
+ * Explicitly override the crash subject.
1434
+ *
1435
+ * **You do not need this to get a subject onto crash reports.** The `id` is
1436
+ * pulled from `Identity.current()` at report time, so a plain
1437
+ * `Identity.logIn("u_42")` is enough — see the "Identity-derived Subject"
1438
+ * section in this file. `setUser` exists for the two things Identity cannot
1439
+ * express: extra fields, and a subject that deliberately differs from the
1440
+ * identity in effect.
1441
+ *
1442
+ * ## Precedence — field-by-field, explicit wins
1443
+ *
1444
+ * | field | source |
1445
+ * | ---------- | --------------------------------------------------- |
1446
+ * | `id` | this call's `id` if set, else `Identity.current().userId` |
1447
+ * | `email` | this call only — Identity has no email |
1448
+ * | `username` | this call only — Identity has no username |
1449
+ *
1450
+ * So `setUser({ email })` after `Identity.logIn("u_42")` yields
1451
+ * `{ id: "u_42", email }`, and `setUser({ id: "other" })` yields
1452
+ * `{ id: "other" }` — the identity is not allowed to overwrite an id the
1453
+ * host stated on purpose.
1454
+ *
1455
+ * `setUser(null)` clears **only this override**. It does not suppress the
1456
+ * Identity-derived id; call `Identity.logOut()` for that. (With no identity
1457
+ * and no override, `user` is omitted from the payload entirely, exactly as
1458
+ * before this pull existed.)
1459
+ *
1460
+ * Resolution happens at report time, never at login time, so the order of
1461
+ * `init` / `logIn` / `setUser` does not matter.
1462
+ */
1161
1463
  setUser(user) {
1162
1464
  _user = user;
1163
- // Forward to native layer for crash-time user context
1465
+ // Forward the EXPLICIT override to native, unmerged. The native crash
1466
+ // SDKs run the same precedence against their own `Identity.current`, so
1467
+ // sending a merged subject here would pin the id and defeat their pull.
1164
1468
  const nativeMod = getNativeCrashModule();
1165
1469
  if (nativeMod) {
1166
1470
  try {
@@ -1209,15 +1513,26 @@ const CrashReporting = exports.CrashReporting = {
1209
1513
  const baseURL = _config.serverURL || "https://api.swiss-knife.dev";
1210
1514
  const url = `${baseURL}/api/sdk/errors/event/batch`;
1211
1515
 
1516
+ // Re-resolve the subject at SEND time. `buildEvent` is synchronous and
1517
+ // can only read the cached snapshot, so an event captured before the
1518
+ // Identity bridge first answered would otherwise ship subject-less —
1519
+ // which is the whole failure mode this pull exists to kill. Doing it
1520
+ // here makes ordering irrelevant in both directions: `logIn` before
1521
+ // `init` and `init` before `logIn` both end up stamped. Bounded by
1522
+ // IDENTITY_RESOLVE_TIMEOUT_MS so the fatal path keeps its budget.
1523
+ await resolveIdentitySubjectNow();
1524
+
1212
1525
  // The /api/sdk/errors/event/batch endpoint:
1213
1526
  // - expects `timestamp` as an ISO string (SDK builds it as Date.now() number)
1214
1527
  // - rejects `user: null` (schema marks `user` optional, not nullable)
1215
1528
  // Coerce both on the wire so the internal SDK shape stays ergonomic.
1216
1529
  const serialized = batch.map(e => {
1217
1530
  const {
1218
- user,
1531
+ user: builtUser,
1219
1532
  ...rest
1220
1533
  } = e;
1534
+ // Idempotent: leaves an id that build time already resolved alone.
1535
+ const user = mergeIdentityInto(builtUser);
1221
1536
  return {
1222
1537
  ...rest,
1223
1538
  ...(user ? {
@@ -1312,7 +1627,10 @@ const CrashReporting = exports.CrashReporting = {
1312
1627
  _backoffMs = BACKOFF_INITIAL_MS;
1313
1628
  _backoffUntil = 0;
1314
1629
  if (_disableRejectionTracking) {
1315
- _disableRejectionTracking();
1630
+ // Teardown is the mirror image of install and can fail the same way —
1631
+ // restoring a slot on a frozen host object, or an engine `enable` that
1632
+ // throws. Drop the reference either way so a failure can't wedge reset.
1633
+ neverThrow("promise rejection teardown", _disableRejectionTracking);
1316
1634
  _disableRejectionTracking = null;
1317
1635
  }
1318
1636
  _rejectionTrackingInstalled = false;
@@ -1322,22 +1640,30 @@ const CrashReporting = exports.CrashReporting = {
1322
1640
  _offlineScreenshots = [];
1323
1641
  _screenshotCaptureOverride = undefined;
1324
1642
  _nativeCrashModuleOverride = undefined;
1643
+ _identityUserId = null;
1644
+ _identityRefresh = null;
1645
+ // Bump the generation so a read still in flight cannot land after the
1646
+ // reset and repopulate the subject the reset just cleared.
1647
+ _identityGeneration++;
1648
+ _identityResolverOverride = undefined;
1325
1649
  _appStateOverride = undefined;
1326
1650
  if (_appStateSubscription) {
1327
1651
  _appStateSubscription.remove();
1328
1652
  _appStateSubscription = null;
1329
1653
  }
1330
- // Restore patched globals
1654
+ // Restore patched globals. These three slots are writable everywhere RN
1655
+ // runs (RN itself repatches them), but restoring is still a write to an
1656
+ // object we do not own, so it goes through the same non-throwing path.
1331
1657
  if (_originalFetch) {
1332
- globalThis.fetch = _originalFetch;
1658
+ trySetHostProperty(globalThis, "fetch", _originalFetch);
1333
1659
  _originalFetch = null;
1334
1660
  }
1335
1661
  if (_originalConsoleWarn) {
1336
- console.warn = _originalConsoleWarn;
1662
+ trySetHostProperty(console, "warn", _originalConsoleWarn);
1337
1663
  _originalConsoleWarn = null;
1338
1664
  }
1339
1665
  if (_originalConsoleError) {
1340
- console.error = _originalConsoleError;
1666
+ trySetHostProperty(console, "error", _originalConsoleError);
1341
1667
  _originalConsoleError = null;
1342
1668
  }
1343
1669
  },
@@ -1378,6 +1704,19 @@ const CrashReporting = exports.CrashReporting = {
1378
1704
  _setNativeCrashModuleForTests(mod) {
1379
1705
  _nativeCrashModuleOverride = mod;
1380
1706
  },
1707
+ /** Test seam: stand in for the native `Identity.current()` bridge call.
1708
+ * `null` = Identity bridge absent; `undefined` = resolve from react-native.
1709
+ * Clears the cached subject so the next resolve goes through the seam. */
1710
+ _setIdentityResolverForTests(resolver) {
1711
+ _identityResolverOverride = resolver;
1712
+ _identityUserId = null;
1713
+ _identityRefresh = null;
1714
+ _identityGeneration++;
1715
+ },
1716
+ /** @internal Current Identity-derived subject id, for assertions. */
1717
+ _identitySubjectForTests() {
1718
+ return _identityUserId;
1719
+ },
1381
1720
  /** Test seam: stand in for react-native's `AppState`. */
1382
1721
  _setAppStateForTests(appState) {
1383
1722
  _appStateOverride = appState;