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