react-native-asleep 1.0.17 → 1.1.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.
@@ -5,17 +5,30 @@ import { Platform, PermissionsAndroid } from "react-native";
5
5
  import {
6
6
  AsleepConfig,
7
7
  AsleepSetupConfig,
8
+ AsleepErrorCategory,
9
+ AsleepErrorInfo,
8
10
  AsleepEventType,
9
11
  AsleepReport,
10
12
  AsleepSession,
11
13
  AsleepAverageReport,
12
14
  AsleepAnalysisResult,
15
+ AsleepAnalysisAck,
13
16
  TrackingConfig,
14
17
  } from "./Asleep.types";
15
18
  import AsleepModule from "./AsleepModule";
16
19
 
17
20
  const emitter = new EventEmitter(AsleepModule);
18
21
 
22
+ // All dev-only warnings below are gated with an inline
23
+ // `typeof __DEV__ !== "undefined" && __DEV__` check rather than a helper
24
+ // function. Metro's inline plugin substitutes the bare `__DEV__` identifier
25
+ // for the literal at build time, then constant-folds `typeof <literal>` and
26
+ // the `&&` so the entire branch is dead-code-eliminated in production
27
+ // bundles. Wrapping the check in a function (e.g. `if (isDev())`) defeats
28
+ // that DCE because Metro does not constant-fold through call expressions.
29
+ // The `typeof` guard also keeps the module importable from plain Node,
30
+ // custom bundlers, or unconfigured jest setups without a ReferenceError.
31
+
19
32
  // Error codes emitted on onTrackingFailed for which the native SDK has already
20
33
  // terminated the session and will not deliver onTrackingClosed. JS must clear
21
34
  // tracking state itself when one of these arrives. See AGENTS.md "Native Behavior
@@ -25,11 +38,56 @@ const TERMINAL_TRACKING_ERROR_CODES = new Set<string>([
25
38
  "INTERRUPTION_RECOVERY_FAILED", // iOS 3 failed auto-resume attempts (3.2.0+)
26
39
  ]);
27
40
 
41
+ // iOS SDK 3.2.0 stops the recorder without closing the native session when
42
+ // audio engine initialization fails. The session must be stopped and restarted.
43
+ const RECORDING_DEAD_ERROR_CODES = new Set<string>(["AUDIO_INITIALIZATION_FAILED"]);
44
+
45
+ // iOS SDK 3.2.0 reports this when the audio engine cannot restart in the
46
+ // background. The consumer must call resumeTracking() after returning foreground.
47
+ const RECOVERY_REQUIRED_ERROR_CODES = new Set<string>(["CANNOT_ACTIVATE_IN_BACKGROUND"]);
48
+
49
+ // Numeric-code twin of TERMINAL_TRACKING_ERROR_CODES, matched against the
50
+ // `sdkCode` payload field. Android SDK 3.2.x AsleepCore.onErrorCodeReceived
51
+ // tears the session down and dual-fires onFail + onFinish for exactly these
52
+ // codes (the native module suppresses the duplicate onFinish), so JS must
53
+ // clear tracking state here or isTracking stays stuck true.
54
+ // Must stay in sync with the Kotlin TERMINAL_TRACKING_ERROR_CODES companion
55
+ // set in android/src/main/java/ai/asleep/reactnative/AsleepModule.kt.
56
+ const TERMINAL_TRACKING_SDK_CODES = new Set<number>([
57
+ 11003, // ERR_AUDIO
58
+ 22000,
59
+ 22401,
60
+ 22409,
61
+ 22422,
62
+ 22500, // ERR_CREATE_*
63
+ 23499, // ERR_UPLOAD_TRACKING_TERMINATED
64
+ 24000,
65
+ 24400,
66
+ 24401,
67
+ 24403,
68
+ 24404,
69
+ 24500, // ERR_CLOSE_*
70
+ ]);
71
+
72
+ // Upload failures the native session survives: absent from the AsleepCore
73
+ // terminal set above, so the Android SDK 3.2.x keeps the session open and later
74
+ // uploads continue (UploadDataTask retries 5xx internally before reporting).
75
+ // Deliberately small — only codes verifiable in upstream sources.
76
+ const TRANSIENT_TRACKING_SDK_CODES = new Set<number>([
77
+ 23000, // ERR_UPLOAD_FAILED
78
+ 23500, // ERR_UPLOAD_SERVER_ERROR
79
+ ]);
80
+
28
81
  export interface AsleepState {
29
82
  didClose: boolean;
30
83
  isTracking: boolean;
31
84
  isTrackingPaused: boolean;
85
+ isRecoveryRequired: boolean;
32
86
  error: string | null;
87
+ // Structured view of the last onTrackingFailed event. Kept in lockstep with
88
+ // `error`: every write or clear of `error` pairs an errorInfo write — a
89
+ // stale category surviving a later unrelated error would misclassify it.
90
+ errorInfo: AsleepErrorInfo | null;
33
91
  userId: string | null;
34
92
  sessionId: string | null;
35
93
  showDebugLog: boolean;
@@ -56,6 +114,7 @@ export interface AsleepState {
56
114
  requestBatteryOptimizationExemption: () => Promise<boolean>;
57
115
  startTracking: (config?: TrackingConfig) => Promise<void>;
58
116
  stopTracking: () => Promise<void>;
117
+ resumeTracking: () => Promise<void>;
59
118
  getReport: (sessionId: string) => Promise<AsleepReport | null>;
60
119
  getReportList: (fromDate: string, toDate: string) => Promise<AsleepSession[]>;
61
120
  getAverageReport: (fromDate: string, toDate: string) => Promise<AsleepAverageReport | null>;
@@ -65,7 +124,7 @@ export interface AsleepState {
65
124
  setCustomNotification: (title: string, text: string) => Promise<void>;
66
125
  enableLog: (print: boolean) => void;
67
126
  clearError: () => void;
68
- requestAnalysis: () => Promise<AsleepAnalysisResult | null>;
127
+ requestAnalysis: () => Promise<AsleepAnalysisResult | AsleepAnalysisAck | null>;
69
128
  addEventListener: <K extends keyof AsleepEventType>(
70
129
  eventType: K,
71
130
  listener: (data: AsleepEventType[K]) => void,
@@ -109,7 +168,9 @@ export const useAsleepStore = create<AsleepState>()(
109
168
  didClose: false,
110
169
  isTracking: AsleepModule.isTracking ? AsleepModule.isTracking() : false,
111
170
  isTrackingPaused: false,
171
+ isRecoveryRequired: false,
112
172
  error: null,
173
+ errorInfo: null,
113
174
  userId: null,
114
175
  sessionId: null,
115
176
  showDebugLog: false,
@@ -146,21 +207,24 @@ export const useAsleepStore = create<AsleepState>()(
146
207
  }
147
208
 
148
209
  addLog("[setup] Start");
149
- set({ isSetupInProgress: true, error: null });
210
+ set({ isSetupInProgress: true, error: null, errorInfo: null });
150
211
 
151
212
  await AsleepModule.setup(config.apiKey, config.baseUrl, config.callbackUrl, config.service, config.enableODA);
152
213
 
153
- // Store ODA enabled state
214
+ // Store ODA enabled state. Clearing `error` on success keeps the
215
+ // reactive `useAsleep().error` field aligned with the actual SDK status
216
+ // (no stale failure messages after a successful retry).
154
217
  set({
155
218
  isODAEnabled: config.enableODA || false,
156
219
  isInitialized: true,
157
220
  isSetupInProgress: false,
158
221
  isSetupComplete: true,
222
+ error: null,
223
+ errorInfo: null,
159
224
  });
160
225
  addLog(`[setup] Success - ODA enabled: ${config.enableODA || false}`);
161
226
  } catch (error: any) {
162
- console.error("setup error:", error);
163
- set({ error: error.message, isSetupInProgress: false });
227
+ set({ error: error.message, errorInfo: null, isSetupInProgress: false });
164
228
  throw error;
165
229
  }
166
230
  },
@@ -177,12 +241,11 @@ export const useAsleepStore = create<AsleepState>()(
177
241
  config.callbackUrl,
178
242
  );
179
243
 
180
- set({ isInitialized: true });
244
+ set({ isInitialized: true, error: null, errorInfo: null });
181
245
  addLog("[initAsleepConfig] Success");
182
246
  return result;
183
247
  } catch (error: any) {
184
- console.error("initAsleepConfig error:", error);
185
- set({ error: error.message });
248
+ set({ error: error.message, errorInfo: null });
186
249
  throw error;
187
250
  }
188
251
  },
@@ -217,8 +280,7 @@ export const useAsleepStore = create<AsleepState>()(
217
280
  hasActiveSession: isAlive,
218
281
  };
219
282
  } catch (error: any) {
220
- console.error("checkAndRestoreTracking error:", error);
221
- set({ error: error.message });
283
+ set({ error: error.message, errorInfo: null });
222
284
  throw error;
223
285
  }
224
286
  },
@@ -296,6 +358,10 @@ export const useAsleepStore = create<AsleepState>()(
296
358
  * @throws Error if prerequisites are not met or tracking is already in progress
297
359
  */
298
360
  startTracking: async (config?: TrackingConfig) => {
361
+ // Snapshot so the catch can tell a verdict published DURING this call
362
+ // (Android fires classified onTrackingFailed before rejecting the same
363
+ // promise) apart from a stale one left by an earlier failure.
364
+ const errorInfoBefore = get().errorInfo;
299
365
  try {
300
366
  const { requestRequiredPermissions, addLog, isODAEnabled, isSetupInProgress, hasCheckedStatus } = get();
301
367
 
@@ -356,7 +422,10 @@ export const useAsleepStore = create<AsleepState>()(
356
422
  didClose: false,
357
423
  isTracking: true,
358
424
  isAnalyzing: false,
425
+ isRecoveryRequired: false,
359
426
  trackingStartTime: new Date(),
427
+ error: null,
428
+ errorInfo: null,
360
429
  });
361
430
  await AsleepModule.startTracking(config);
362
431
 
@@ -368,9 +437,14 @@ export const useAsleepStore = create<AsleepState>()(
368
437
 
369
438
  addLog("[startTracking] Success");
370
439
  } catch (error: any) {
371
- console.error("startTracking error:", error);
440
+ // Preserve only a verdict that arrived during this call — the raw
441
+ // rejection message carries strictly less information than the
442
+ // numeric-code verdict. Reference inequality against the snapshot
443
+ // excludes stale verdicts, so guard failures still write the new error.
444
+ const nowInfo = get().errorInfo;
445
+ const classified = nowInfo !== null && nowInfo !== errorInfoBefore;
372
446
  set({
373
- error: error.message,
447
+ ...(classified ? {} : { error: error.message, errorInfo: null }),
374
448
  isTracking: false,
375
449
  isAnalyzing: false,
376
450
  trackingStartTime: null,
@@ -380,6 +454,8 @@ export const useAsleepStore = create<AsleepState>()(
380
454
  },
381
455
 
382
456
  stopTracking: async () => {
457
+ // Same dual-signal race as startTracking; see the snapshot rationale there.
458
+ const errorInfoBefore = get().errorInfo;
383
459
  try {
384
460
  const { addLog } = get();
385
461
  addLog("[stopTracking] Start");
@@ -390,18 +466,36 @@ export const useAsleepStore = create<AsleepState>()(
390
466
  ...(result ? { sessionId: result } : {}),
391
467
  isTracking: false,
392
468
  isAnalyzing: false,
469
+ isRecoveryRequired: false,
393
470
  trackingStartTime: null,
471
+ error: null,
472
+ errorInfo: null,
394
473
  });
395
474
 
396
475
  addLog(`[stopTracking] Success - result: ${result}`);
397
476
  } catch (error: any) {
398
- console.error("stopTracking error:", error);
399
- set({ error: error.message });
477
+ const nowInfo = get().errorInfo;
478
+ if (nowInfo === null || nowInfo === errorInfoBefore) set({ error: error.message, errorInfo: null });
400
479
  throw error;
401
480
  }
402
481
  },
403
482
 
483
+ resumeTracking: async () => {
484
+ if (Platform.OS !== "ios") {
485
+ throw Object.assign(new Error("resumeTracking is only supported on iOS."), {
486
+ name: "AsleepPlatformError",
487
+ code: "UNSUPPORTED_PLATFORM",
488
+ });
489
+ }
490
+
491
+ await AsleepModule.resumeTracking();
492
+ },
493
+
404
494
  getReport: async (sessionId: string) => {
495
+ // Snapshot the error before the await so we only clear it on success
496
+ // if no concurrent failure (e.g. onTrackingFailed firing during the
497
+ // network round-trip) wrote a different error in the meantime.
498
+ const errorBefore = get().error;
405
499
  try {
406
500
  const { addLog } = get();
407
501
  addLog(`[getReport] sessionId: ${sessionId}`);
@@ -410,6 +504,10 @@ export const useAsleepStore = create<AsleepState>()(
410
504
  const convertedReport = convertKeysToCamelCase(report);
411
505
 
412
506
  addLog("[getReport] Success");
507
+ // Guard so a successful query after a clean run does not spam an empty
508
+ // notification, and so we never clobber an unrelated tracking error
509
+ // that arrived during the await.
510
+ if (get().error !== null && get().error === errorBefore) set({ error: null, errorInfo: null });
413
511
 
414
512
  // Ensure the report has the expected AsleepReport structure
415
513
  // Handle cases where native modules might return data in different formats
@@ -437,13 +535,18 @@ export const useAsleepStore = create<AsleepState>()(
437
535
 
438
536
  return convertedReport as AsleepReport;
439
537
  } catch (error: any) {
440
- console.error("getReport error:", error);
441
- set({ error: error.message });
538
+ // Silent return on failure is a public-API quirk preserved for v1.x
539
+ // compat (v2.0 throws). Surface a dev-only warn so the consumer's
540
+ // Metro log still shows the failure when they're debugging without
541
+ // observing `useAsleep().error` directly.
542
+ if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[Asleep] getReport failed:", error);
543
+ set({ error: error.message, errorInfo: null });
442
544
  return null;
443
545
  }
444
546
  },
445
547
 
446
548
  getReportList: async (fromDate: string, toDate: string) => {
549
+ const errorBefore = get().error;
447
550
  try {
448
551
  const { addLog } = get();
449
552
  addLog(`[getReportList] fromDate: ${fromDate}, toDate: ${toDate}`);
@@ -465,15 +568,17 @@ export const useAsleepStore = create<AsleepState>()(
465
568
  });
466
569
 
467
570
  addLog("[getReportList] Success");
571
+ if (get().error !== null && get().error === errorBefore) set({ error: null, errorInfo: null });
468
572
  return convertedList;
469
573
  } catch (error: any) {
470
- console.error("getReportList error:", error);
471
- set({ error: error.message });
574
+ if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[Asleep] getReportList failed:", error);
575
+ set({ error: error.message, errorInfo: null });
472
576
  return [];
473
577
  }
474
578
  },
475
579
 
476
580
  deleteSession: async (sessionId: string) => {
581
+ const errorBefore = get().error;
477
582
  try {
478
583
  const { addLog } = get();
479
584
  addLog(`[deleteSession] sessionId: ${sessionId}`);
@@ -481,14 +586,15 @@ export const useAsleepStore = create<AsleepState>()(
481
586
  await AsleepModule.deleteSession(sessionId);
482
587
 
483
588
  addLog("[deleteSession] Success");
589
+ if (get().error !== null && get().error === errorBefore) set({ error: null, errorInfo: null });
484
590
  } catch (error: any) {
485
- console.error("deleteSession error:", error);
486
- set({ error: error.message });
591
+ set({ error: error.message, errorInfo: null });
487
592
  throw error;
488
593
  }
489
594
  },
490
595
 
491
596
  getAverageReport: async (fromDate: string, toDate: string) => {
597
+ const errorBefore = get().error;
492
598
  try {
493
599
  const { addLog } = get();
494
600
  addLog(`[getAverageReport] fromDate: ${fromDate}, toDate: ${toDate}`);
@@ -497,10 +603,11 @@ export const useAsleepStore = create<AsleepState>()(
497
603
  const convertedReport = convertKeysToCamelCase(averageReport);
498
604
 
499
605
  addLog("[getAverageReport] Success");
606
+ if (get().error !== null && get().error === errorBefore) set({ error: null, errorInfo: null });
500
607
  return convertedReport;
501
608
  } catch (error: any) {
502
- console.error("getAverageReport error:", error);
503
- set({ error: error.message });
609
+ if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[Asleep] getAverageReport failed:", error);
610
+ set({ error: error.message, errorInfo: null });
504
611
  return null;
505
612
  }
506
613
  },
@@ -509,9 +616,11 @@ export const useAsleepStore = create<AsleepState>()(
509
616
  * @deprecated Use requestRequiredPermissions instead. This method will be removed in a future version.
510
617
  */
511
618
  requestMicrophonePermission: async () => {
512
- console.warn(
513
- "[AsleepSDK] requestMicrophonePermission is deprecated. Please use requestRequiredPermissions instead.",
514
- );
619
+ if (typeof __DEV__ !== "undefined" && __DEV__) {
620
+ console.warn(
621
+ "[Asleep] requestMicrophonePermission is deprecated. Please use requestRequiredPermissions instead.",
622
+ );
623
+ }
515
624
  return get().requestRequiredPermissions();
516
625
  },
517
626
 
@@ -541,7 +650,7 @@ export const useAsleepStore = create<AsleepState>()(
541
650
  // Both must be granted for tracking to work properly
542
651
  return audioGranted && notificationGranted;
543
652
  } catch (err) {
544
- console.warn("Permission request error:", err);
653
+ if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[Asleep] Permission request error:", err);
545
654
  return false;
546
655
  }
547
656
  }
@@ -549,43 +658,39 @@ export const useAsleepStore = create<AsleepState>()(
549
658
  return AsleepModule.requestRequiredPermissions();
550
659
  },
551
660
 
552
- setCustomNotification: async (title: string, text: string) => {
553
- if (Platform.OS === "android") {
554
- await AsleepModule.setCustomNotification(title, text);
555
- } else {
556
- console.warn("setCustomNotification is not supported on this platform");
557
- }
661
+ setCustomNotification: async (_title: string, _text: string) => {
662
+ // Native method removed; notification config now flows through startTracking options.
663
+ if (typeof __DEV__ !== "undefined" && __DEV__)
664
+ console.warn(
665
+ "[Asleep] setCustomNotification is deprecated and a no-op; pass `{ android: { notification: { title, text, icon } } }` to startTracking() instead",
666
+ );
558
667
  },
559
668
 
560
669
  enableLog: (print: boolean) => {
670
+ if (Platform.OS === "ios") AsleepModule.enableLog(print);
561
671
  set({ showDebugLog: print });
562
672
  },
563
673
 
564
674
  requestAnalysis: async () => {
565
675
  try {
566
- const { addLog } = get();
676
+ const { addLog, showDebugLog } = get();
567
677
  addLog("[requestAnalysis] Start");
568
678
 
569
- set({ isAnalyzing: true });
679
+ set({ isAnalyzing: true, error: null, errorInfo: null });
570
680
 
571
681
  const result = await AsleepModule.requestAnalysis();
572
682
  const convertedResult = convertKeysToCamelCase(result);
573
683
 
574
- // Platform differences:
575
- // Android: Returns the actual analysis result immediately and also sends onAnalysisResult event
576
- // iOS: Returns acknowledgment data only, actual result comes through onAnalysisResult event
577
- if (Platform.OS === "android" && convertedResult.sleepStages) {
578
- // Android returns the actual session data
579
- set({ analysisResult: convertedResult, isAnalyzing: false });
580
- }
581
- // For iOS, isAnalyzing will be set to false when onAnalysisResult event fires
684
+ // analysisResult and isAnalyzing are owned by the onAnalysisResult event handler on both
685
+ // platforms. Android resolves the promise with the full session AND fires the event;
686
+ // iOS resolves with an ack only. Writing state here would double-update on Android.
582
687
 
583
- addLog(`[requestAnalysis] Request sent - ${JSON.stringify(convertedResult)}`);
688
+ if (showDebugLog) addLog(`[requestAnalysis] Request sent - ${JSON.stringify(convertedResult)}`);
584
689
 
585
690
  return convertedResult;
586
691
  } catch (error: any) {
587
- console.error("requestAnalysis error:", error);
588
- set({ error: error.message, isAnalyzing: false });
692
+ if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[Asleep] requestAnalysis failed:", error);
693
+ set({ error: error.message, errorInfo: null, isAnalyzing: false });
589
694
  return null;
590
695
  }
591
696
  },
@@ -602,8 +707,10 @@ export const useAsleepStore = create<AsleepState>()(
602
707
  },
603
708
 
604
709
  // internal actions
605
- setError: (error) => set({ error }),
606
- clearError: () => set({ error: null }),
710
+ // setError takes a raw string, so any structured classification is stale;
711
+ // reset errorInfo rather than let a previous event's category linger.
712
+ setError: (error) => set({ error, errorInfo: null }),
713
+ clearError: () => set({ error: null, errorInfo: null }),
607
714
  setUserId: (userId) => set({ userId }),
608
715
  setSessionId: (sessionId) => set({ sessionId }),
609
716
  setIsTracking: (isTracking) => set({ isTracking }),
@@ -619,63 +726,48 @@ export const useAsleepStore = create<AsleepState>()(
619
726
  setHasCheckedBatteryOptimization: (checked) => set({ hasCheckedBatteryOptimization: checked }),
620
727
 
621
728
  addLog: (log: string) => {
729
+ // Zero-cost when the consumer has not opted into debug logging. Without
730
+ // this guard, every native event handler would cause a spurious
731
+ // subscriber notification on top of any actual data update.
622
732
  const { showDebugLog } = get();
733
+ if (!showDebugLog) return;
623
734
  const now = new Date();
624
735
  const dateString = `${now.getHours().toString().padStart(2, "0")}:${now
625
736
  .getMinutes()
626
737
  .toString()
627
738
  .padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}`;
628
-
629
739
  const formattedLog = `[${dateString}]${log}`;
630
-
631
- if (showDebugLog) {
632
- console.log(`[Asleep]${formattedLog}`);
633
- }
634
-
740
+ console.log(`[Asleep]${formattedLog}`);
635
741
  set({ log: formattedLog });
636
742
  },
637
743
  })),
638
744
  );
639
745
 
640
- // Global flag to prevent multiple listener registrations
641
- let listenersInitialized = false;
642
- let cleanupFunction: (() => void) | null = null;
643
-
644
- // initialize event listeners
645
- export const initializeAsleepListeners = () => {
646
- // If listeners are already initialized, return the existing cleanup function
647
- if (listenersInitialized && cleanupFunction) {
648
- return cleanupFunction;
746
+ // Ref-counted registration. Each caller (useAsleep effect, background context,
747
+ // etc.) increments on entry and decrements via the returned cleanup. Native
748
+ // listeners only attach on 0→1 and detach on the final 1→0, so concurrent
749
+ // consumers cannot tear each other's subscriptions down.
750
+ let refCount = 0;
751
+ let teardown: (() => void) | null = null;
752
+
753
+ export const initializeAsleepListeners = (): (() => void) => {
754
+ // Cold start when no teardown is installed. `teardown` is the single source
755
+ // of truth for "listeners are currently attached"; refCount is just an
756
+ // increment-only counter for cleanup balancing. Always incrementing
757
+ // (instead of assigning =1 on cold start) keeps the count correct even if
758
+ // a future change introduces an async seam between this check and the
759
+ // listener registration below.
760
+ if (teardown) {
761
+ refCount++;
762
+ return makeCleanup();
649
763
  }
650
764
 
651
765
  const store = useAsleepStore.getState();
652
- const {
653
- addLog,
654
- setUserId,
655
- setSessionId,
656
- setIsTracking,
657
- setIsTrackingPaused,
658
- setError,
659
- setAnalysisResult,
660
- setIsAnalyzing,
661
- setIsSetupInProgress,
662
- setIsSetupComplete,
663
- } = store;
664
-
665
- // Clears session tracking state. Called from both onTrackingClosed (clean
666
- // close) and the terminal branch of onTrackingFailed (native SDK tore down
667
- // the session without firing onTrackingClosed). Single setState so
668
- // subscribers are notified once instead of four times.
669
- const clearTrackingState = () => {
670
- useAsleepStore.setState({
671
- isTracking: false,
672
- isAnalyzing: false,
673
- didClose: true,
674
- trackingStartTime: null,
675
- });
676
- };
766
+ const { addLog, setUserId, setIsTrackingPaused, setIsSetupInProgress } = store;
677
767
 
678
- // event handlers
768
+ // event handlers — each native SDK event corresponds to one logical state
769
+ // transaction. Use a single useAsleepStore.setState per handler so consumers
770
+ // subscribed via useAsleep re-render once per event, not once per field.
679
771
  const handlers = {
680
772
  // Connected: iOS userDidJoin, Android onSuccess (AsleepConfigListener)
681
773
  onUserJoined: (data: any) => {
@@ -685,7 +777,9 @@ export const initializeAsleepListeners = () => {
685
777
  // Connected: iOS didFailUserJoin, Android onFail (AsleepConfigListener)
686
778
  onUserJoinFailed: (error: any) => {
687
779
  const errorString = JSON.stringify(error);
688
- setError(errorString);
780
+ // Not a tracking-runtime failure; errorInfo stays reserved for
781
+ // onTrackingFailed classification.
782
+ useAsleepStore.setState({ error: errorString, errorInfo: null });
689
783
  addLog(`[onUserJoinFailed] error: ${errorString}`);
690
784
  },
691
785
  // Connected: iOS userDidDelete, Android NOT IMPLEMENTED
@@ -695,10 +789,10 @@ export const initializeAsleepListeners = () => {
695
789
  },
696
790
  // Connected: iOS didCreate, Android onStart (AsleepTrackingListener)
697
791
  onTrackingCreated: (data: any) => {
698
- setIsTracking(true);
699
- if (data && data.sessionId) {
700
- setSessionId(data.sessionId);
701
- }
792
+ useAsleepStore.setState({
793
+ isTracking: true,
794
+ ...(data?.sessionId ? { sessionId: data.sessionId } : {}),
795
+ });
702
796
  addLog(`[onTrackingCreated]${data?.sessionId ? ` sessionId: ${data.sessionId}` : ""}`);
703
797
  },
704
798
  // Connected: iOS didUpload, Android onPerform (AsleepTrackingListener)
@@ -706,37 +800,117 @@ export const initializeAsleepListeners = () => {
706
800
  onTrackingUploaded: (data: any) => {
707
801
  addLog(`[onTrackingUploaded] sequence: ${data.sequence}`);
708
802
 
803
+ // requestAnalysis() flips isAnalyzing internally; no separate setter
804
+ // needed before invoking it (avoids a duplicate subscriber notification).
709
805
  const state = useAsleepStore.getState();
710
- if (state.isODAEnabled && state.isTracking) {
711
- state.setIsAnalyzing(true);
806
+ // A completed upload is the only positive proof that recording actually came
807
+ // back — didResume fires before the engine restart is even attempted, so it
808
+ // cannot be trusted to clear this.
809
+ if (state.isRecoveryRequired) useAsleepStore.setState({ isRecoveryRequired: false });
810
+ const triggerAnalysis = () =>
712
811
  state.requestAnalysis().catch((error) => {
713
812
  addLog(`[onTrackingUploaded] Auto analysis failed: ${error.message}`);
714
813
  state.setIsAnalyzing(false);
715
814
  });
815
+
816
+ if (state.isODAEnabled && state.isTracking) {
817
+ triggerAnalysis();
716
818
  } else if (!state.isODAEnabled && state.isTracking) {
717
819
  if (data.sequence >= 10 && data.sequence % 10 === 1) {
718
- state.setIsAnalyzing(true);
719
- state.requestAnalysis().catch((error) => {
720
- addLog(`[onTrackingUploaded] Auto analysis failed: ${error.message}`);
721
- state.setIsAnalyzing(false);
722
- });
820
+ triggerAnalysis();
723
821
  }
724
822
  }
725
823
  },
726
824
  // Connected: iOS didClose, Android onFinish (AsleepTrackingListener)
727
825
  onTrackingClosed: (data: { sessionId: string }) => {
728
- setSessionId(data.sessionId);
729
- clearTrackingState();
826
+ useAsleepStore.setState({
827
+ sessionId: data.sessionId,
828
+ isTracking: false,
829
+ isAnalyzing: false,
830
+ isRecoveryRequired: false,
831
+ didClose: true,
832
+ trackingStartTime: null,
833
+ });
730
834
  addLog(`[onTrackingClosed] sessionId: ${data.sessionId}`);
731
835
  },
732
836
  // Connected: iOS didFail, Android onFail (AsleepTrackingListener)
837
+ // Four state buckets, each writing tracking state in the same setState as the
838
+ // error so subscribers see one event: terminal (native session already gone),
839
+ // recording-dead (recorder torn down but session still open — clearing
840
+ // isTracking is what unblocks a restart), recovery-required (resumeTracking()
841
+ // in foreground can revive it), and everything else (error only).
842
+ // The two dead-session buckets must also clear isRecoveryRequired: iOS retries
843
+ // cannotActivateInBackground and then gives up with interruptionRecoveryFailed,
844
+ // and no upload will ever arrive to clear the flag on that path.
845
+ // The bucket verdict is also published as errorInfo.category (with the
846
+ // else-bucket split into "transient" vs "unknown") so consumers can gate
847
+ // log severity on data instead of re-deriving code lists themselves.
733
848
  onTrackingFailed: (error: any) => {
734
- const errorString = JSON.stringify(error);
735
- setError(errorString);
736
- addLog(`[onTrackingError] error: ${errorString}`);
737
- if (error && TERMINAL_TRACKING_ERROR_CODES.has(error.code)) {
738
- clearTrackingState();
849
+ // The explicit iOS string buckets must win before the numeric terminal
850
+ // fallback: the numeric set encodes Android teardown semantics, and iOS
851
+ // reuses 11003 (.audioInitializationFailed -> .audio) for a failure whose
852
+ // session is still open. The numeric fallback still matters on iOS for
853
+ // start/stop failures that arrive as UNKNOWN_ERROR + 22xxx/24xxx and must
854
+ // clear the optimistically-set isTracking.
855
+ const recordingDead = !!(error && RECORDING_DEAD_ERROR_CODES.has(error.code));
856
+ const recoveryRequired = !!(error && RECOVERY_REQUIRED_ERROR_CODES.has(error.code));
857
+ const terminal = !!(
858
+ error &&
859
+ !recordingDead &&
860
+ !recoveryRequired &&
861
+ (TERMINAL_TRACKING_ERROR_CODES.has(error.code) || TERMINAL_TRACKING_SDK_CODES.has(error.sdkCode))
862
+ );
863
+ const transient = !!(error && TRANSIENT_TRACKING_SDK_CODES.has(error.sdkCode));
864
+
865
+ let category: AsleepErrorCategory;
866
+ if (recordingDead) category = "recordingDead";
867
+ else if (recoveryRequired) category = "recoveryRequired";
868
+ else if (terminal) category = "terminal";
869
+ else if (transient) category = "transient";
870
+ else category = "unknown";
871
+
872
+ // Category rides along in the stringified error too, so consumers still
873
+ // parsing the legacy string see the same verdict as errorInfo readers.
874
+ const errorString = JSON.stringify(error ? { ...error, category } : error);
875
+ const errorInfo: AsleepErrorInfo | null = error
876
+ ? {
877
+ code: typeof error.code === "string" ? error.code : "UNKNOWN_ERROR",
878
+ category,
879
+ ...(typeof error.sdkCode === "number" ? { sdkCode: error.sdkCode } : {}),
880
+ ...(typeof error.message === "string" ? { message: error.message } : {}),
881
+ ...(typeof error.caseName === "string" ? { caseName: error.caseName } : {}),
882
+ }
883
+ : null;
884
+
885
+ let nextState: Partial<AsleepState>;
886
+ if (terminal) {
887
+ nextState = {
888
+ error: errorString,
889
+ errorInfo,
890
+ isTracking: false,
891
+ isAnalyzing: false,
892
+ isRecoveryRequired: false,
893
+ didClose: true,
894
+ trackingStartTime: null,
895
+ };
896
+ } else if (recordingDead) {
897
+ nextState = {
898
+ error: errorString,
899
+ errorInfo,
900
+ isTracking: false,
901
+ isAnalyzing: false,
902
+ isRecoveryRequired: false,
903
+ didClose: false,
904
+ trackingStartTime: null,
905
+ };
906
+ } else if (recoveryRequired) {
907
+ nextState = { error: errorString, errorInfo, isTracking: true, isRecoveryRequired: true };
908
+ } else {
909
+ nextState = { error: errorString, errorInfo };
739
910
  }
911
+
912
+ useAsleepStore.setState(nextState);
913
+ addLog(`[onTrackingError] error: ${errorString}`);
740
914
  },
741
915
  // Connected: iOS didInterrupt, Android NOT IMPLEMENTED
742
916
  onTrackingInterrupted: () => {
@@ -748,35 +922,37 @@ export const initializeAsleepListeners = () => {
748
922
  // retry) reach this handler without a preceding didInterrupt, and the stale error
749
923
  // should still be cleared. Only the paused-state mutation is gated, to dedup the
750
924
  // iOS 3.2.1+ double fire from handleRecovering -> handleResumed.
925
+ // isRecoveryRequired, not isTrackingPaused, is authoritative when recording is
926
+ // dead because didResume fires before the engine restart is attempted.
751
927
  onTrackingResumed: () => {
752
- setError(null);
753
- if (!useAsleepStore.getState().isTrackingPaused) {
754
- addLog(`[onTrackingResumed] (no prior pause; error cleared)`);
755
- return;
756
- }
757
- setIsTrackingPaused(false);
758
- addLog(`[onTrackingResumed]`);
928
+ const wasPaused = useAsleepStore.getState().isTrackingPaused;
929
+ useAsleepStore.setState(
930
+ wasPaused ? { error: null, errorInfo: null, isTrackingPaused: false } : { error: null, errorInfo: null },
931
+ );
932
+ addLog(wasPaused ? `[onTrackingResumed]` : `[onTrackingResumed] (no prior pause; error cleared)`);
759
933
  },
760
934
  // Connected: iOS micPermissionWasDenied, Android NOT IMPLEMENTED
761
935
  onMicPermissionDenied: () => {
762
936
  addLog(`[onMicPermissionDenied]`);
763
937
  },
764
- // Connected: iOS didPrint (AsleepDebugLoggerDelegate), Android sendEvent called directly
938
+ // Connected: iOS AsleepLogger callbacks, Android sendEvent called directly
765
939
  onDebugLog: (data: any) => {
766
940
  addLog(`[onDebugLog] message: ${data.message}`);
767
941
  },
768
942
  // Connected: iOS setupDidComplete, Android onComplete (AsleepSetupListener)
769
943
  onSetupDidComplete: () => {
770
- setIsSetupInProgress(false);
771
- setIsSetupComplete(true);
944
+ useAsleepStore.setState({ isSetupInProgress: false, isSetupComplete: true });
772
945
  addLog(`[onSetupDidComplete]`);
773
946
  },
774
947
  // Connected: iOS setupDidFail, Android onFail (AsleepSetupListener)
775
948
  onSetupDidFail: (data: any) => {
776
949
  const errorString = JSON.stringify(data);
777
- setError(errorString);
778
- setIsSetupInProgress(false);
779
- setIsSetupComplete(false);
950
+ useAsleepStore.setState({
951
+ error: errorString,
952
+ errorInfo: null,
953
+ isSetupInProgress: false,
954
+ isSetupComplete: false,
955
+ });
780
956
  addLog(`[onSetupDidFail] error: ${errorString}`);
781
957
  },
782
958
  // Connected: iOS setupInProgress, Android onProgress (AsleepSetupListener)
@@ -785,31 +961,41 @@ export const initializeAsleepListeners = () => {
785
961
  addLog(`[onSetupInProgress] progress: ${data.progress}%`);
786
962
  },
787
963
  // Connected: iOS analyzing (session), Android onSleepDataReceived (AsleepSleepDataListener)
964
+ // Android serializes snake_case; normalize so both platforms match AsleepAnalysisResult.
788
965
  onAnalysisResult: (data: any) => {
789
- setAnalysisResult(data);
790
- setIsAnalyzing(false); // Analysis is complete, so set to false
791
- addLog(`[onAnalysisResult] ${JSON.stringify(data)}`);
966
+ const normalized = convertKeysToCamelCase(data);
967
+ useAsleepStore.setState({ analysisResult: normalized, isAnalyzing: false });
968
+ if (useAsleepStore.getState().showDebugLog) {
969
+ addLog(`[onAnalysisResult] ${JSON.stringify(normalized)}`);
970
+ }
792
971
  },
793
972
  };
794
973
 
795
974
  // register all event listeners
796
975
  const subscriptions: (() => void)[] = [];
797
-
798
976
  Object.entries(handlers).forEach(([eventType, handler]) => {
799
977
  const subscription = emitter.addListener(eventType, handler);
800
978
  subscriptions.push(() => subscription.remove());
801
979
  });
802
980
 
803
- // Mark listeners as initialized
804
- listenersInitialized = true;
805
-
806
- // Create cleanup function
807
- cleanupFunction = () => {
981
+ refCount++;
982
+ teardown = () => {
808
983
  subscriptions.forEach((unsubscribe) => unsubscribe());
809
- listenersInitialized = false;
810
- cleanupFunction = null;
984
+ teardown = null;
811
985
  };
812
986
 
813
- // return cleanup function
814
- return cleanupFunction;
987
+ return makeCleanup();
988
+ };
989
+
990
+ const makeCleanup = (): (() => void) => {
991
+ // Idempotent per-caller cleanup. The `called` flag is closure-private so
992
+ // calling the returned function twice (e.g. Strict Mode double-effect)
993
+ // decrements the shared ref count only once.
994
+ let called = false;
995
+ return () => {
996
+ if (called) return;
997
+ called = true;
998
+ refCount--;
999
+ if (refCount === 0 && teardown) teardown();
1000
+ };
815
1001
  };