react-native-asleep 1.0.15 → 1.0.18

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.
@@ -16,6 +16,25 @@ import AsleepModule from "./AsleepModule";
16
16
 
17
17
  const emitter = new EventEmitter(AsleepModule);
18
18
 
19
+ // All dev-only warnings below are gated with an inline
20
+ // `typeof __DEV__ !== "undefined" && __DEV__` check rather than a helper
21
+ // function. Metro's inline plugin substitutes the bare `__DEV__` identifier
22
+ // for the literal at build time, then constant-folds `typeof <literal>` and
23
+ // the `&&` so the entire branch is dead-code-eliminated in production
24
+ // bundles. Wrapping the check in a function (e.g. `if (isDev())`) defeats
25
+ // that DCE because Metro does not constant-fold through call expressions.
26
+ // The `typeof` guard also keeps the module importable from plain Node,
27
+ // custom bundlers, or unconfigured jest setups without a ReferenceError.
28
+
29
+ // Error codes emitted on onTrackingFailed for which the native SDK has already
30
+ // terminated the session and will not deliver onTrackingClosed. JS must clear
31
+ // tracking state itself when one of these arrives. See AGENTS.md "Native Behavior
32
+ // Compensations" for the upstream behavior these guard against.
33
+ const TERMINAL_TRACKING_ERROR_CODES = new Set<string>([
34
+ "UPLOAD_TRACKING_TERMINATED", // iOS 403/429 closeSessionSilently; Android errorCode 23499
35
+ "INTERRUPTION_RECOVERY_FAILED", // iOS 3 failed auto-resume attempts (3.2.0+)
36
+ ]);
37
+
19
38
  export interface AsleepState {
20
39
  didClose: boolean;
21
40
  isTracking: boolean;
@@ -59,7 +78,7 @@ export interface AsleepState {
59
78
  requestAnalysis: () => Promise<AsleepAnalysisResult | null>;
60
79
  addEventListener: <K extends keyof AsleepEventType>(
61
80
  eventType: K,
62
- listener: (data: AsleepEventType[K]) => void
81
+ listener: (data: AsleepEventType[K]) => void,
63
82
  ) => () => void;
64
83
  getTrackingDurationMinutes: () => number;
65
84
 
@@ -126,41 +145,33 @@ export const useAsleepStore = create<AsleepState>()(
126
145
 
127
146
  // Prevent duplicate execution if setup is already in progress
128
147
  if (isSetupInProgress) {
129
- addLog(
130
- "[setup] Setup is already in progress. Please try again later."
131
- );
148
+ addLog("[setup] Setup is already in progress. Please try again later.");
132
149
  throw new Error("Setup is already in progress.");
133
150
  }
134
151
 
135
152
  // Block setup execution if tracking is in progress
136
153
  if (isTracking) {
137
154
  addLog("[setup] Cannot execute setup while tracking is in progress.");
138
- throw new Error(
139
- "Cannot execute setup while tracking is in progress."
140
- );
155
+ throw new Error("Cannot execute setup while tracking is in progress.");
141
156
  }
142
157
 
143
158
  addLog("[setup] Start");
144
159
  set({ isSetupInProgress: true, error: null });
145
160
 
146
- await AsleepModule.setup(
147
- config.apiKey,
148
- config.baseUrl,
149
- config.callbackUrl,
150
- config.service,
151
- config.enableODA
152
- );
161
+ await AsleepModule.setup(config.apiKey, config.baseUrl, config.callbackUrl, config.service, config.enableODA);
153
162
 
154
- // Store ODA enabled state
163
+ // Store ODA enabled state. Clearing `error` on success keeps the
164
+ // reactive `useAsleep().error` field aligned with the actual SDK status
165
+ // (no stale failure messages after a successful retry).
155
166
  set({
156
167
  isODAEnabled: config.enableODA || false,
157
168
  isInitialized: true,
158
169
  isSetupInProgress: false,
159
170
  isSetupComplete: true,
171
+ error: null,
160
172
  });
161
173
  addLog(`[setup] Success - ODA enabled: ${config.enableODA || false}`);
162
174
  } catch (error: any) {
163
- console.error("setup error:", error);
164
175
  set({ error: error.message, isSetupInProgress: false });
165
176
  throw error;
166
177
  }
@@ -175,14 +186,13 @@ export const useAsleepStore = create<AsleepState>()(
175
186
  config.apiKey,
176
187
  config.userId,
177
188
  config.baseUrl,
178
- config.callbackUrl
189
+ config.callbackUrl,
179
190
  );
180
191
 
181
- set({ isInitialized: true });
192
+ set({ isInitialized: true, error: null });
182
193
  addLog("[initAsleepConfig] Success");
183
194
  return result;
184
195
  } catch (error: any) {
185
- console.error("initAsleepConfig error:", error);
186
196
  set({ error: error.message });
187
197
  throw error;
188
198
  }
@@ -197,7 +207,7 @@ export const useAsleepStore = create<AsleepState>()(
197
207
  const isAlive = await AsleepModule.isSleepTrackingAlive();
198
208
 
199
209
  set({
200
- hasCheckedStatus: true
210
+ hasCheckedStatus: true,
201
211
  });
202
212
 
203
213
  // If service is alive on Android, restore connection to it
@@ -215,10 +225,9 @@ export const useAsleepStore = create<AsleepState>()(
215
225
 
216
226
  addLog(`[checkAndRestoreTracking] Complete - hasActiveSession: ${isAlive}`);
217
227
  return {
218
- hasActiveSession: isAlive
228
+ hasActiveSession: isAlive,
219
229
  };
220
230
  } catch (error: any) {
221
- console.error("checkAndRestoreTracking error:", error);
222
231
  set({ error: error.message });
223
232
  throw error;
224
233
  }
@@ -244,9 +253,9 @@ export const useAsleepStore = create<AsleepState>()(
244
253
  // Mark that check was performed (required for startTracking)
245
254
  set({ hasCheckedBatteryOptimization: true });
246
255
 
247
- if (Platform.OS === 'ios') {
256
+ if (Platform.OS === "ios") {
248
257
  addLog("[checkBatteryOptimization] iOS - not applicable");
249
- return { exempted: true, platform: 'ios' };
258
+ return { exempted: true, platform: "ios" };
250
259
  }
251
260
 
252
261
  // Android: Check current status
@@ -255,10 +264,10 @@ export const useAsleepStore = create<AsleepState>()(
255
264
 
256
265
  return {
257
266
  exempted,
258
- platform: 'android',
259
- message: exempted ?
260
- "Battery optimization disabled - ready for tracking" :
261
- "Battery optimization must be disabled for reliable tracking"
267
+ platform: "android",
268
+ message: exempted
269
+ ? "Battery optimization disabled - ready for tracking"
270
+ : "Battery optimization must be disabled for reliable tracking",
262
271
  };
263
272
  },
264
273
 
@@ -274,9 +283,9 @@ export const useAsleepStore = create<AsleepState>()(
274
283
  requestBatteryOptimizationExemption: async () => {
275
284
  const { addLog } = get();
276
285
 
277
- if (Platform.OS === 'ios') {
286
+ if (Platform.OS === "ios") {
278
287
  addLog("[requestBatteryOptimizationExemption] iOS - not applicable");
279
- return true; // Not applicable on iOS
288
+ return true; // Not applicable on iOS
280
289
  }
281
290
 
282
291
  addLog("[requestBatteryOptimizationExemption] Opening battery settings...");
@@ -298,13 +307,7 @@ export const useAsleepStore = create<AsleepState>()(
298
307
  */
299
308
  startTracking: async (config?: TrackingConfig) => {
300
309
  try {
301
- const {
302
- requestRequiredPermissions,
303
- addLog,
304
- isODAEnabled,
305
- isSetupInProgress,
306
- hasCheckedStatus,
307
- } = get();
310
+ const { requestRequiredPermissions, addLog, isODAEnabled, isSetupInProgress, hasCheckedStatus } = get();
308
311
 
309
312
  // Enforce that checkAndRestoreTracking must be called first
310
313
  if (!hasCheckedStatus) {
@@ -318,15 +321,13 @@ export const useAsleepStore = create<AsleepState>()(
318
321
  addLog("[startTracking] ERROR: Must check battery optimization first");
319
322
  throw new Error(
320
323
  "Must call checkBatteryOptimization() before starting tracking. " +
321
- "This check is required on both iOS and Android to ensure cross-platform consistency."
324
+ "This check is required on both iOS and Android to ensure cross-platform consistency.",
322
325
  );
323
326
  }
324
327
 
325
328
  // Block startTracking execution if setup is in progress
326
329
  if (isSetupInProgress) {
327
- addLog(
328
- "[startTracking] Cannot start tracking while setup is in progress."
329
- );
330
+ addLog("[startTracking] Cannot start tracking while setup is in progress.");
330
331
  throw new Error("Cannot start tracking while setup is in progress.");
331
332
  }
332
333
 
@@ -341,7 +342,7 @@ export const useAsleepStore = create<AsleepState>()(
341
342
  const permission = await requestRequiredPermissions();
342
343
  if (!permission) {
343
344
  // SDK shouldn't show UI directly - throw specific error message
344
- if (Platform.OS === 'android' && Platform.Version >= 33) {
345
+ if (Platform.OS === "android" && Platform.Version >= 33) {
345
346
  throw new Error("Microphone and notification permissions are required for sleep tracking");
346
347
  } else {
347
348
  throw new Error("Microphone permission is required for sleep tracking");
@@ -349,13 +350,13 @@ export const useAsleepStore = create<AsleepState>()(
349
350
  }
350
351
 
351
352
  // Always verify CURRENT exemption status
352
- if (Platform.OS === 'android') {
353
+ if (Platform.OS === "android") {
353
354
  const batteryExempted = await AsleepModule.isBatteryOptimizationExempted();
354
355
  if (!batteryExempted) {
355
356
  addLog("[startTracking] ERROR: Battery optimization not disabled");
356
357
  throw new Error(
357
358
  "Battery optimization must be disabled for reliable sleep tracking. " +
358
- "Call requestBatteryOptimizationExemption() to guide user to settings."
359
+ "Call requestBatteryOptimizationExemption() to guide user to settings.",
359
360
  );
360
361
  }
361
362
  addLog("[startTracking] Battery optimization exempted - OK");
@@ -366,20 +367,18 @@ export const useAsleepStore = create<AsleepState>()(
366
367
  isTracking: true,
367
368
  isAnalyzing: false,
368
369
  trackingStartTime: new Date(),
370
+ error: null,
369
371
  });
370
372
  await AsleepModule.startTracking(config);
371
373
 
372
374
  if (isODAEnabled) {
373
- addLog(
374
- "[startTracking] ODA enabled - real-time analysis will start automatically"
375
- );
375
+ addLog("[startTracking] ODA enabled - real-time analysis will start automatically");
376
376
  } else {
377
377
  addLog("[startTracking] ODA not enabled");
378
378
  }
379
379
 
380
380
  addLog("[startTracking] Success");
381
381
  } catch (error: any) {
382
- console.error("startTracking error:", error);
383
382
  set({
384
383
  error: error.message,
385
384
  isTracking: false,
@@ -402,17 +401,21 @@ export const useAsleepStore = create<AsleepState>()(
402
401
  isTracking: false,
403
402
  isAnalyzing: false,
404
403
  trackingStartTime: null,
404
+ error: null,
405
405
  });
406
406
 
407
407
  addLog(`[stopTracking] Success - result: ${result}`);
408
408
  } catch (error: any) {
409
- console.error("stopTracking error:", error);
410
409
  set({ error: error.message });
411
410
  throw error;
412
411
  }
413
412
  },
414
413
 
415
414
  getReport: async (sessionId: string) => {
415
+ // Snapshot the error before the await so we only clear it on success
416
+ // if no concurrent failure (e.g. onTrackingFailed firing during the
417
+ // network round-trip) wrote a different error in the meantime.
418
+ const errorBefore = get().error;
416
419
  try {
417
420
  const { addLog } = get();
418
421
  addLog(`[getReport] sessionId: ${sessionId}`);
@@ -421,6 +424,10 @@ export const useAsleepStore = create<AsleepState>()(
421
424
  const convertedReport = convertKeysToCamelCase(report);
422
425
 
423
426
  addLog("[getReport] Success");
427
+ // Guard so a successful query after a clean run does not spam an empty
428
+ // notification, and so we never clobber an unrelated tracking error
429
+ // that arrived during the await.
430
+ if (get().error !== null && get().error === errorBefore) set({ error: null });
424
431
 
425
432
  // Ensure the report has the expected AsleepReport structure
426
433
  // Handle cases where native modules might return data in different formats
@@ -448,13 +455,18 @@ export const useAsleepStore = create<AsleepState>()(
448
455
 
449
456
  return convertedReport as AsleepReport;
450
457
  } catch (error: any) {
451
- console.error("getReport error:", error);
458
+ // Silent return on failure is a public-API quirk preserved for v1.x
459
+ // compat (v2.0 throws). Surface a dev-only warn so the consumer's
460
+ // Metro log still shows the failure when they're debugging without
461
+ // observing `useAsleep().error` directly.
462
+ if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[Asleep] getReport failed:", error);
452
463
  set({ error: error.message });
453
464
  return null;
454
465
  }
455
466
  },
456
467
 
457
468
  getReportList: async (fromDate: string, toDate: string) => {
469
+ const errorBefore = get().error;
458
470
  try {
459
471
  const { addLog } = get();
460
472
  addLog(`[getReportList] fromDate: ${fromDate}, toDate: ${toDate}`);
@@ -476,15 +488,17 @@ export const useAsleepStore = create<AsleepState>()(
476
488
  });
477
489
 
478
490
  addLog("[getReportList] Success");
491
+ if (get().error !== null && get().error === errorBefore) set({ error: null });
479
492
  return convertedList;
480
493
  } catch (error: any) {
481
- console.error("getReportList error:", error);
494
+ if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[Asleep] getReportList failed:", error);
482
495
  set({ error: error.message });
483
496
  return [];
484
497
  }
485
498
  },
486
499
 
487
500
  deleteSession: async (sessionId: string) => {
501
+ const errorBefore = get().error;
488
502
  try {
489
503
  const { addLog } = get();
490
504
  addLog(`[deleteSession] sessionId: ${sessionId}`);
@@ -492,14 +506,15 @@ export const useAsleepStore = create<AsleepState>()(
492
506
  await AsleepModule.deleteSession(sessionId);
493
507
 
494
508
  addLog("[deleteSession] Success");
509
+ if (get().error !== null && get().error === errorBefore) set({ error: null });
495
510
  } catch (error: any) {
496
- console.error("deleteSession error:", error);
497
511
  set({ error: error.message });
498
512
  throw error;
499
513
  }
500
514
  },
501
515
 
502
516
  getAverageReport: async (fromDate: string, toDate: string) => {
517
+ const errorBefore = get().error;
503
518
  try {
504
519
  const { addLog } = get();
505
520
  addLog(`[getAverageReport] fromDate: ${fromDate}, toDate: ${toDate}`);
@@ -508,9 +523,10 @@ export const useAsleepStore = create<AsleepState>()(
508
523
  const convertedReport = convertKeysToCamelCase(averageReport);
509
524
 
510
525
  addLog("[getAverageReport] Success");
526
+ if (get().error !== null && get().error === errorBefore) set({ error: null });
511
527
  return convertedReport;
512
528
  } catch (error: any) {
513
- console.error("getAverageReport error:", error);
529
+ if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[Asleep] getAverageReport failed:", error);
514
530
  set({ error: error.message });
515
531
  return null;
516
532
  }
@@ -520,14 +536,16 @@ export const useAsleepStore = create<AsleepState>()(
520
536
  * @deprecated Use requestRequiredPermissions instead. This method will be removed in a future version.
521
537
  */
522
538
  requestMicrophonePermission: async () => {
523
- console.warn(
524
- '[AsleepSDK] requestMicrophonePermission is deprecated. Please use requestRequiredPermissions instead.'
525
- );
539
+ if (typeof __DEV__ !== "undefined" && __DEV__) {
540
+ console.warn(
541
+ "[Asleep] requestMicrophonePermission is deprecated. Please use requestRequiredPermissions instead.",
542
+ );
543
+ }
526
544
  return get().requestRequiredPermissions();
527
545
  },
528
546
 
529
547
  requestRequiredPermissions: async () => {
530
- if (Platform.OS === 'android') {
548
+ if (Platform.OS === "android") {
531
549
  try {
532
550
  // Prepare permissions array with RECORD_AUDIO
533
551
  const permissions = [PermissionsAndroid.PERMISSIONS.RECORD_AUDIO];
@@ -541,17 +559,18 @@ export const useAsleepStore = create<AsleepState>()(
541
559
  const results = await PermissionsAndroid.requestMultiple(permissions);
542
560
 
543
561
  // Check if all required permissions are granted
544
- const audioGranted = results[PermissionsAndroid.PERMISSIONS.RECORD_AUDIO] ===
545
- PermissionsAndroid.RESULTS.GRANTED;
562
+ const audioGranted =
563
+ results[PermissionsAndroid.PERMISSIONS.RECORD_AUDIO] === PermissionsAndroid.RESULTS.GRANTED;
546
564
 
547
- const notificationGranted = Platform.Version >= 33 ?
548
- results[PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS] ===
549
- PermissionsAndroid.RESULTS.GRANTED : true;
565
+ const notificationGranted =
566
+ Platform.Version >= 33
567
+ ? results[PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS] === PermissionsAndroid.RESULTS.GRANTED
568
+ : true;
550
569
 
551
570
  // Both must be granted for tracking to work properly
552
571
  return audioGranted && notificationGranted;
553
572
  } catch (err) {
554
- console.warn('Permission request error:', err);
573
+ if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[Asleep] Permission request error:", err);
555
574
  return false;
556
575
  }
557
576
  }
@@ -563,7 +582,8 @@ export const useAsleepStore = create<AsleepState>()(
563
582
  if (Platform.OS === "android") {
564
583
  await AsleepModule.setCustomNotification(title, text);
565
584
  } else {
566
- console.warn("setCustomNotification is not supported on this platform");
585
+ if (typeof __DEV__ !== "undefined" && __DEV__)
586
+ console.warn("[Asleep] setCustomNotification is not supported on this platform");
567
587
  }
568
588
  },
569
589
 
@@ -576,7 +596,7 @@ export const useAsleepStore = create<AsleepState>()(
576
596
  const { addLog } = get();
577
597
  addLog("[requestAnalysis] Start");
578
598
 
579
- set({ isAnalyzing: true });
599
+ set({ isAnalyzing: true, error: null });
580
600
 
581
601
  const result = await AsleepModule.requestAnalysis();
582
602
  const convertedResult = convertKeysToCamelCase(result);
@@ -590,22 +610,17 @@ export const useAsleepStore = create<AsleepState>()(
590
610
  }
591
611
  // For iOS, isAnalyzing will be set to false when onAnalysisResult event fires
592
612
 
593
- addLog(
594
- `[requestAnalysis] Request sent - ${JSON.stringify(convertedResult)}`
595
- );
613
+ addLog(`[requestAnalysis] Request sent - ${JSON.stringify(convertedResult)}`);
596
614
 
597
615
  return convertedResult;
598
616
  } catch (error: any) {
599
- console.error("requestAnalysis error:", error);
617
+ if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[Asleep] requestAnalysis failed:", error);
600
618
  set({ error: error.message, isAnalyzing: false });
601
619
  return null;
602
620
  }
603
621
  },
604
622
 
605
- addEventListener: <K extends keyof AsleepEventType>(
606
- eventType: K,
607
- listener: (data: AsleepEventType[K]) => void
608
- ) => {
623
+ addEventListener: <K extends keyof AsleepEventType>(eventType: K, listener: (data: AsleepEventType[K]) => void) => {
609
624
  const subscription = emitter.addListener(eventType, listener);
610
625
  return () => subscription.remove();
611
626
  },
@@ -613,9 +628,7 @@ export const useAsleepStore = create<AsleepState>()(
613
628
  getTrackingDurationMinutes: () => {
614
629
  const { trackingStartTime } = get();
615
630
  if (!trackingStartTime) return 0;
616
- return Math.floor(
617
- (Date.now() - trackingStartTime.getTime()) / (1000 * 60)
618
- );
631
+ return Math.floor((Date.now() - trackingStartTime.getTime()) / (1000 * 60));
619
632
  },
620
633
 
621
634
  // internal actions
@@ -630,58 +643,54 @@ export const useAsleepStore = create<AsleepState>()(
630
643
  setIsAnalyzing: (isAnalyzing) => set({ isAnalyzing }),
631
644
  setTrackingStartTime: (time) => set({ trackingStartTime: time }),
632
645
  setIsInitialized: (initialized) => set({ isInitialized: initialized }),
633
- setIsSetupInProgress: (inProgress) =>
634
- set({ isSetupInProgress: inProgress }),
646
+ setIsSetupInProgress: (inProgress) => set({ isSetupInProgress: inProgress }),
635
647
  setIsSetupComplete: (complete) => set({ isSetupComplete: complete }),
636
648
  setHasCheckedStatus: (checked) => set({ hasCheckedStatus: checked }),
637
649
  setHasCheckedBatteryOptimization: (checked) => set({ hasCheckedBatteryOptimization: checked }),
638
650
 
639
651
  addLog: (log: string) => {
652
+ // Zero-cost when the consumer has not opted into debug logging. Without
653
+ // this guard, every native event handler would cause a spurious
654
+ // subscriber notification on top of any actual data update.
640
655
  const { showDebugLog } = get();
656
+ if (!showDebugLog) return;
641
657
  const now = new Date();
642
658
  const dateString = `${now.getHours().toString().padStart(2, "0")}:${now
643
659
  .getMinutes()
644
660
  .toString()
645
661
  .padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}`;
646
-
647
662
  const formattedLog = `[${dateString}]${log}`;
648
-
649
- if (showDebugLog) {
650
- console.log(`[Asleep]${formattedLog}`);
651
- }
652
-
663
+ console.log(`[Asleep]${formattedLog}`);
653
664
  set({ log: formattedLog });
654
665
  },
655
- }))
666
+ })),
656
667
  );
657
668
 
658
- // Global flag to prevent multiple listener registrations
659
- let listenersInitialized = false;
660
- let cleanupFunction: (() => void) | null = null;
661
-
662
- // initialize event listeners
663
- export const initializeAsleepListeners = () => {
664
- // If listeners are already initialized, return the existing cleanup function
665
- if (listenersInitialized && cleanupFunction) {
666
- return cleanupFunction;
669
+ // Ref-counted registration. Each caller (useAsleep effect, background context,
670
+ // etc.) increments on entry and decrements via the returned cleanup. Native
671
+ // listeners only attach on 0→1 and detach on the final 1→0, so concurrent
672
+ // consumers cannot tear each other's subscriptions down.
673
+ let refCount = 0;
674
+ let teardown: (() => void) | null = null;
675
+
676
+ export const initializeAsleepListeners = (): (() => void) => {
677
+ // Cold start when no teardown is installed. `teardown` is the single source
678
+ // of truth for "listeners are currently attached"; refCount is just an
679
+ // increment-only counter for cleanup balancing. Always incrementing
680
+ // (instead of assigning =1 on cold start) keeps the count correct even if
681
+ // a future change introduces an async seam between this check and the
682
+ // listener registration below.
683
+ if (teardown) {
684
+ refCount++;
685
+ return makeCleanup();
667
686
  }
668
687
 
669
688
  const store = useAsleepStore.getState();
670
- const {
671
- addLog,
672
- setUserId,
673
- setSessionId,
674
- setIsTracking,
675
- setIsTrackingPaused,
676
- setError,
677
- setDidClose,
678
- setAnalysisResult,
679
- setIsAnalyzing,
680
- setIsSetupInProgress,
681
- setIsSetupComplete,
682
- } = store;
683
-
684
- // event handlers
689
+ const { addLog, setUserId, setIsTrackingPaused, setIsSetupInProgress } = store;
690
+
691
+ // event handlers — each native SDK event corresponds to one logical state
692
+ // transaction. Use a single useAsleepStore.setState per handler so consumers
693
+ // subscribed via useAsleep re-render once per event, not once per field.
685
694
  const handlers = {
686
695
  // Connected: iOS userDidJoin, Android onSuccess (AsleepConfigListener)
687
696
  onUserJoined: (data: any) => {
@@ -691,7 +700,7 @@ export const initializeAsleepListeners = () => {
691
700
  // Connected: iOS didFailUserJoin, Android onFail (AsleepConfigListener)
692
701
  onUserJoinFailed: (error: any) => {
693
702
  const errorString = JSON.stringify(error);
694
- setError(errorString);
703
+ useAsleepStore.setState({ error: errorString });
695
704
  addLog(`[onUserJoinFailed] error: ${errorString}`);
696
705
  },
697
706
  // Connected: iOS userDidDelete, Android NOT IMPLEMENTED
@@ -701,52 +710,57 @@ export const initializeAsleepListeners = () => {
701
710
  },
702
711
  // Connected: iOS didCreate, Android onStart (AsleepTrackingListener)
703
712
  onTrackingCreated: (data: any) => {
704
- setIsTracking(true);
705
- if (data && data.sessionId) {
706
- setSessionId(data.sessionId);
707
- }
708
- addLog(
709
- `[onTrackingCreated]${data?.sessionId ? ` sessionId: ${data.sessionId}` : ""
710
- }`
711
- );
713
+ useAsleepStore.setState({
714
+ isTracking: true,
715
+ ...(data?.sessionId ? { sessionId: data.sessionId } : {}),
716
+ });
717
+ addLog(`[onTrackingCreated]${data?.sessionId ? ` sessionId: ${data.sessionId}` : ""}`);
712
718
  },
713
719
  // Connected: iOS didUpload, Android onPerform (AsleepTrackingListener)
714
720
  // Triggers automatic analysis requests in both ODA and non-ODA modes
715
721
  onTrackingUploaded: (data: any) => {
716
722
  addLog(`[onTrackingUploaded] sequence: ${data.sequence}`);
717
723
 
724
+ // requestAnalysis() flips isAnalyzing internally; no separate setter
725
+ // needed before invoking it (avoids a duplicate subscriber notification).
718
726
  const state = useAsleepStore.getState();
719
- if (state.isODAEnabled && state.isTracking) {
720
- state.setIsAnalyzing(true);
727
+ const triggerAnalysis = () =>
721
728
  state.requestAnalysis().catch((error) => {
722
729
  addLog(`[onTrackingUploaded] Auto analysis failed: ${error.message}`);
723
730
  state.setIsAnalyzing(false);
724
731
  });
725
- }
726
- else if (!state.isODAEnabled && state.isTracking) {
732
+
733
+ if (state.isODAEnabled && state.isTracking) {
734
+ triggerAnalysis();
735
+ } else if (!state.isODAEnabled && state.isTracking) {
727
736
  if (data.sequence >= 10 && data.sequence % 10 === 1) {
728
- state.setIsAnalyzing(true);
729
- state.requestAnalysis().catch((error) => {
730
- addLog(`[onTrackingUploaded] Auto analysis failed: ${error.message}`);
731
- state.setIsAnalyzing(false);
732
- });
737
+ triggerAnalysis();
733
738
  }
734
739
  }
735
740
  },
736
741
  // Connected: iOS didClose, Android onFinish (AsleepTrackingListener)
737
742
  onTrackingClosed: (data: { sessionId: string }) => {
738
- setSessionId(data.sessionId);
739
- setDidClose(true);
740
- setIsTracking(false);
741
- setIsAnalyzing(false);
742
- store.setTrackingStartTime(null);
743
+ useAsleepStore.setState({
744
+ sessionId: data.sessionId,
745
+ isTracking: false,
746
+ isAnalyzing: false,
747
+ didClose: true,
748
+ trackingStartTime: null,
749
+ });
743
750
  addLog(`[onTrackingClosed] sessionId: ${data.sessionId}`);
744
751
  },
745
752
  // Connected: iOS didFail, Android onFail (AsleepTrackingListener)
746
- // Note: This is a transient error event - tracking continues, only logs the error
753
+ // Terminal codes (UPLOAD_TRACKING_TERMINATED / INTERRUPTION_RECOVERY_FAILED)
754
+ // mean the native SDK already tore the session down — clear tracking state
755
+ // in the same setState as the error write so subscribers see one event.
747
756
  onTrackingFailed: (error: any) => {
748
757
  const errorString = JSON.stringify(error);
749
- setError(errorString);
758
+ const terminal = !!(error && TERMINAL_TRACKING_ERROR_CODES.has(error.code));
759
+ useAsleepStore.setState(
760
+ terminal
761
+ ? { error: errorString, isTracking: false, isAnalyzing: false, didClose: true, trackingStartTime: null }
762
+ : { error: errorString },
763
+ );
750
764
  addLog(`[onTrackingError] error: ${errorString}`);
751
765
  },
752
766
  // Connected: iOS didInterrupt, Android NOT IMPLEMENTED
@@ -755,10 +769,14 @@ export const initializeAsleepListeners = () => {
755
769
  addLog(`[onTrackingInterrupted]`);
756
770
  },
757
771
  // Connected: iOS didResume, Android NOT IMPLEMENTED
772
+ // Always clear the error: some iOS recovery paths (e.g. cannotActivateInBackground
773
+ // retry) reach this handler without a preceding didInterrupt, and the stale error
774
+ // should still be cleared. Only the paused-state mutation is gated, to dedup the
775
+ // iOS 3.2.1+ double fire from handleRecovering -> handleResumed.
758
776
  onTrackingResumed: () => {
759
- setIsTrackingPaused(false);
760
- setError(null);
761
- addLog(`[onTrackingResumed]`);
777
+ const wasPaused = useAsleepStore.getState().isTrackingPaused;
778
+ useAsleepStore.setState(wasPaused ? { error: null, isTrackingPaused: false } : { error: null });
779
+ addLog(wasPaused ? `[onTrackingResumed]` : `[onTrackingResumed] (no prior pause; error cleared)`);
762
780
  },
763
781
  // Connected: iOS micPermissionWasDenied, Android NOT IMPLEMENTED
764
782
  onMicPermissionDenied: () => {
@@ -770,16 +788,13 @@ export const initializeAsleepListeners = () => {
770
788
  },
771
789
  // Connected: iOS setupDidComplete, Android onComplete (AsleepSetupListener)
772
790
  onSetupDidComplete: () => {
773
- setIsSetupInProgress(false);
774
- setIsSetupComplete(true);
791
+ useAsleepStore.setState({ isSetupInProgress: false, isSetupComplete: true });
775
792
  addLog(`[onSetupDidComplete]`);
776
793
  },
777
794
  // Connected: iOS setupDidFail, Android onFail (AsleepSetupListener)
778
795
  onSetupDidFail: (data: any) => {
779
796
  const errorString = JSON.stringify(data);
780
- setError(errorString);
781
- setIsSetupInProgress(false);
782
- setIsSetupComplete(false);
797
+ useAsleepStore.setState({ error: errorString, isSetupInProgress: false, isSetupComplete: false });
783
798
  addLog(`[onSetupDidFail] error: ${errorString}`);
784
799
  },
785
800
  // Connected: iOS setupInProgress, Android onProgress (AsleepSetupListener)
@@ -789,30 +804,36 @@ export const initializeAsleepListeners = () => {
789
804
  },
790
805
  // Connected: iOS analyzing (session), Android onSleepDataReceived (AsleepSleepDataListener)
791
806
  onAnalysisResult: (data: any) => {
792
- setAnalysisResult(data);
793
- setIsAnalyzing(false); // Analysis is complete, so set to false
807
+ useAsleepStore.setState({ analysisResult: data, isAnalyzing: false });
794
808
  addLog(`[onAnalysisResult] ${JSON.stringify(data)}`);
795
809
  },
796
810
  };
797
811
 
798
812
  // register all event listeners
799
813
  const subscriptions: (() => void)[] = [];
800
-
801
814
  Object.entries(handlers).forEach(([eventType, handler]) => {
802
815
  const subscription = emitter.addListener(eventType, handler);
803
816
  subscriptions.push(() => subscription.remove());
804
817
  });
805
818
 
806
- // Mark listeners as initialized
807
- listenersInitialized = true;
808
-
809
- // Create cleanup function
810
- cleanupFunction = () => {
819
+ refCount++;
820
+ teardown = () => {
811
821
  subscriptions.forEach((unsubscribe) => unsubscribe());
812
- listenersInitialized = false;
813
- cleanupFunction = null;
822
+ teardown = null;
814
823
  };
815
824
 
816
- // return cleanup function
817
- return cleanupFunction;
825
+ return makeCleanup();
826
+ };
827
+
828
+ const makeCleanup = (): (() => void) => {
829
+ // Idempotent per-caller cleanup. The `called` flag is closure-private so
830
+ // calling the returned function twice (e.g. Strict Mode double-effect)
831
+ // decrements the shared ref count only once.
832
+ let called = false;
833
+ return () => {
834
+ if (called) return;
835
+ called = true;
836
+ refCount--;
837
+ if (refCount === 0 && teardown) teardown();
838
+ };
818
839
  };