react-native-asleep 1.1.0 → 1.2.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.
@@ -1,420 +1,337 @@
1
- import { create } from "zustand";
2
- import { subscribeWithSelector } from "zustand/middleware";
3
1
  import { EventEmitter } from "expo-modules-core";
4
- import { Platform, PermissionsAndroid } from "react-native";
2
+ import { PermissionsAndroid, Platform } from "react-native";
3
+ import { AsleepError } from "./Asleep.types";
5
4
  import AsleepModule from "./AsleepModule";
5
+ import { createStore } from "./store/createStore";
6
6
  const emitter = new EventEmitter(AsleepModule);
7
- // All dev-only warnings below are gated with an inline
8
- // `typeof __DEV__ !== "undefined" && __DEV__` check rather than a helper
9
- // function. Metro's inline plugin substitutes the bare `__DEV__` identifier
10
- // for the literal at build time, then constant-folds `typeof <literal>` and
11
- // the `&&` so the entire branch is dead-code-eliminated in production
12
- // bundles. Wrapping the check in a function (e.g. `if (isDev())`) defeats
13
- // that DCE because Metro does not constant-fold through call expressions.
14
- // The `typeof` guard also keeps the module importable from plain Node,
15
- // custom bundlers, or unconfigured jest setups without a ReferenceError.
16
- // Error codes emitted on onTrackingFailed for which the native SDK has already
17
- // terminated the session and will not deliver onTrackingClosed. JS must clear
18
- // tracking state itself when one of these arrives. See AGENTS.md "Native Behavior
19
- // Compensations" for the upstream behavior these guard against.
20
- const TERMINAL_TRACKING_ERROR_CODES = new Set([
21
- "UPLOAD_TRACKING_TERMINATED", // iOS 403/429 closeSessionSilently; Android errorCode 23499
22
- "INTERRUPTION_RECOVERY_FAILED", // iOS 3 failed auto-resume attempts (3.2.0+)
23
- ]);
24
- // iOS SDK 3.2.0 stops the recorder without closing the native session when
25
- // audio engine initialization fails. The session must be stopped and restarted.
7
+ // Native sessions are already gone for these errors and no close event follows.
8
+ const TERMINAL_TRACKING_ERROR_CODES = new Set(["UPLOAD_TRACKING_TERMINATED", "INTERRUPTION_RECOVERY_FAILED"]);
9
+ // iOS 3.2.0 stops recording but leaves the native session open.
26
10
  const RECORDING_DEAD_ERROR_CODES = new Set(["AUDIO_INITIALIZATION_FAILED"]);
27
- // iOS SDK 3.2.0 reports this when the audio engine cannot restart in the
28
- // background. The consumer must call resumeTracking() after returning foreground.
11
+ // iOS 3.2.0 needs an explicit foreground resume after this failure.
29
12
  const RECOVERY_REQUIRED_ERROR_CODES = new Set(["CANNOT_ACTIVATE_IN_BACKGROUND"]);
30
- // Numeric-code twin of TERMINAL_TRACKING_ERROR_CODES, matched against the
31
- // `sdkCode` payload field. Android SDK 3.2.x AsleepCore.onErrorCodeReceived
32
- // tears the session down and dual-fires onFail + onFinish for exactly these
33
- // codes (the native module suppresses the duplicate onFinish), so JS must
34
- // clear tracking state here or isTracking stays stuck true.
35
- // Must stay in sync with the Kotlin TERMINAL_TRACKING_ERROR_CODES companion
36
- // set in android/src/main/java/ai/asleep/reactnative/AsleepModule.kt.
13
+ // Android SDK 3.2.x tears the session down for exactly these codes. Keep this
14
+ // synchronized with AsleepModule.kt's TERMINAL_TRACKING_ERROR_CODES.
37
15
  const TERMINAL_TRACKING_SDK_CODES = new Set([
38
- 11003, // ERR_AUDIO
39
- 22000,
40
- 22401,
41
- 22409,
42
- 22422,
43
- 22500, // ERR_CREATE_*
44
- 23499, // ERR_UPLOAD_TRACKING_TERMINATED
45
- 24000,
46
- 24400,
47
- 24401,
48
- 24403,
49
- 24404,
50
- 24500, // ERR_CLOSE_*
51
- ]);
52
- // Upload failures the native session survives: absent from the AsleepCore
53
- // terminal set above, so the Android SDK 3.2.x keeps the session open and later
54
- // uploads continue (UploadDataTask retries 5xx internally before reporting).
55
- // Deliberately small — only codes verifiable in upstream sources.
56
- const TRANSIENT_TRACKING_SDK_CODES = new Set([
57
- 23000, // ERR_UPLOAD_FAILED
58
- 23500, // ERR_UPLOAD_SERVER_ERROR
16
+ 11003, 22000, 22401, 22409, 22422, 22500, 23499, 24000, 24400, 24401, 24403, 24404, 24500,
59
17
  ]);
60
- const convertKeysToCamelCase = (obj) => {
61
- if (Array.isArray(obj)) {
62
- return obj.map(convertKeysToCamelCase);
63
- }
64
- else if (obj !== null && obj.constructor === Object) {
65
- return Object.keys(obj).reduce((acc, key) => {
66
- const camelKey = key.replace(/_([a-z])/g, (g) => g[1].toUpperCase());
67
- acc[camelKey] = convertKeysToCamelCase(obj[key]);
68
- return acc;
69
- }, {});
70
- }
71
- return obj;
72
- };
73
- export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
74
- // initial state
75
- didClose: false,
76
- isTracking: AsleepModule.isTracking ? AsleepModule.isTracking() : false,
77
- isTrackingPaused: false,
78
- isRecoveryRequired: false,
79
- error: null,
80
- errorInfo: null,
81
- userId: null,
18
+ // The native session survives these exhausted upload attempts.
19
+ const TRANSIENT_TRACKING_SDK_CODES = new Set([23000, 23500]);
20
+ const initialTrackingStatus = typeof AsleepModule.isTracking === "function" && AsleepModule.isTracking() ? "tracking" : "idle";
21
+ export const useAsleepStore = createStore(() => ({
22
+ setupStatus: "idle",
23
+ trackingStatus: initialTrackingStatus,
82
24
  sessionId: null,
83
- showDebugLog: false,
84
- log: "",
25
+ userId: null,
26
+ error: null,
85
27
  analysisResult: null,
86
- isODAEnabled: false,
87
28
  isAnalyzing: false,
29
+ didClose: false,
30
+ isODAEnabled: false,
88
31
  trackingStartTime: null,
89
32
  isInitialized: false,
90
- isSetupInProgress: false,
91
- isSetupComplete: false,
92
- // Service status state
93
33
  hasCheckedStatus: false,
94
- // Battery optimization state
95
34
  hasCheckedBatteryOptimization: false,
96
- // actions
35
+ showDebugLog: false,
36
+ log: "",
37
+ }));
38
+ const convertKeysToCamelCase = (value) => {
39
+ if (Array.isArray(value))
40
+ return value.map(convertKeysToCamelCase);
41
+ if (value !== null && value.constructor === Object) {
42
+ return Object.keys(value).reduce((result, key) => {
43
+ const camelKey = key.replace(/_([a-z])/g, (_match, letter) => letter.toUpperCase());
44
+ result[camelKey] = convertKeysToCamelCase(value[key]);
45
+ return result;
46
+ }, {});
47
+ }
48
+ return value;
49
+ };
50
+ export const normalizeError = (source, fallbackCode, options = {}) => {
51
+ if (source instanceof AsleepError && Object.keys(options).length === 0)
52
+ return source;
53
+ const payload = source && typeof source === "object"
54
+ ? source
55
+ : undefined;
56
+ const code = typeof payload?.code === "string" ? payload.code : fallbackCode;
57
+ const message = typeof payload?.message === "string"
58
+ ? payload.message
59
+ : typeof payload?.error === "string"
60
+ ? payload.error
61
+ : typeof payload?.detail === "string"
62
+ ? payload.detail
63
+ : source instanceof Error
64
+ ? source.message
65
+ : String(source ?? "Unknown error");
66
+ return new AsleepError(code, message, {
67
+ cause: source instanceof AsleepError ? (source.cause ?? source) : source,
68
+ category: options.category ?? (source instanceof AsleepError ? source.category : undefined),
69
+ sdkCode: options.sdkCode ??
70
+ (typeof payload?.sdkCode === "number"
71
+ ? payload.sdkCode
72
+ : source instanceof AsleepError
73
+ ? source.sdkCode
74
+ : undefined),
75
+ caseName: options.caseName ??
76
+ (typeof payload?.caseName === "string"
77
+ ? payload.caseName
78
+ : source instanceof AsleepError
79
+ ? source.caseName
80
+ : undefined),
81
+ });
82
+ };
83
+ const logPartial = (message, state = useAsleepStore.getState()) => {
84
+ if (!state.showDebugLog)
85
+ return {};
86
+ const now = new Date();
87
+ const time = `${now.getHours().toString().padStart(2, "0")}:${now
88
+ .getMinutes()
89
+ .toString()
90
+ .padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}`;
91
+ const log = `[${time}]${message}`;
92
+ console.log(`[Asleep]${log}`);
93
+ return { log };
94
+ };
95
+ const addLog = (message) => {
96
+ useAsleepStore.setState(logPartial(message));
97
+ };
98
+ const storeAndThrow = (error, partial = {}) => {
99
+ useAsleepStore.setState({ ...partial, error });
100
+ throw error;
101
+ };
102
+ const guardedFailure = (source, fallbackCode, errorBefore, partial = {}) => {
103
+ const current = useAsleepStore.getState().error;
104
+ if (current !== null && current !== errorBefore) {
105
+ useAsleepStore.setState(partial);
106
+ throw current;
107
+ }
108
+ return storeAndThrow(normalizeError(source, fallbackCode), partial);
109
+ };
110
+ const clearErrorIfUnchanged = (errorBefore) => {
111
+ const current = useAsleepStore.getState().error;
112
+ if (current !== null && current === errorBefore)
113
+ useAsleepStore.setState({ error: null });
114
+ };
115
+ const normalizeReport = (report, sessionId) => {
116
+ const converted = convertKeysToCamelCase(report);
117
+ if (converted && !converted.session && converted.sessionId) {
118
+ return {
119
+ timezone: converted.timezone || "",
120
+ session: {
121
+ id: converted.sessionId || converted.id || sessionId,
122
+ createdTimezone: converted.createdTimezone || "",
123
+ startTime: converted.sessionStartTime || converted.startTime || "",
124
+ endTime: converted.sessionEndTime || converted.endTime,
125
+ unexpectedEndTime: converted.unexpectedEndTime,
126
+ state: converted.state || "",
127
+ sleepStages: converted.sleepStages,
128
+ breathStages: converted.breathStages,
129
+ snoringStages: converted.snoringStages,
130
+ },
131
+ missingDataRatio: converted.missingDataRatio || 0,
132
+ peculiarities: converted.peculiarities || [],
133
+ stat: converted.stat,
134
+ };
135
+ }
136
+ return converted;
137
+ };
138
+ export const asleepActions = {
97
139
  setup: async (config) => {
140
+ const state = useAsleepStore.getState();
141
+ if (state.setupStatus === "inProgress") {
142
+ storeAndThrow(new AsleepError("OPERATION_IN_PROGRESS", "Setup is already in progress."));
143
+ }
144
+ if (state.trackingStatus !== "idle") {
145
+ storeAndThrow(new AsleepError("INVALID_STATE", "Cannot execute setup while tracking is in progress."));
146
+ }
147
+ const errorBefore = state.error;
148
+ addLog("[setup] Start");
149
+ useAsleepStore.setState({ setupStatus: "inProgress" });
98
150
  try {
99
- const { addLog, isSetupInProgress, isTracking } = get();
100
- // Prevent duplicate execution if setup is already in progress
101
- if (isSetupInProgress) {
102
- addLog("[setup] Setup is already in progress. Please try again later.");
103
- throw new Error("Setup is already in progress.");
104
- }
105
- // Block setup execution if tracking is in progress
106
- if (isTracking) {
107
- addLog("[setup] Cannot execute setup while tracking is in progress.");
108
- throw new Error("Cannot execute setup while tracking is in progress.");
109
- }
110
- addLog("[setup] Start");
111
- set({ isSetupInProgress: true, error: null, errorInfo: null });
112
151
  await AsleepModule.setup(config.apiKey, config.baseUrl, config.callbackUrl, config.service, config.enableODA);
113
- // Store ODA enabled state. Clearing `error` on success keeps the
114
- // reactive `useAsleep().error` field aligned with the actual SDK status
115
- // (no stale failure messages after a successful retry).
116
- set({
152
+ useAsleepStore.setState({
153
+ setupStatus: "complete",
117
154
  isODAEnabled: config.enableODA || false,
118
155
  isInitialized: true,
119
- isSetupInProgress: false,
120
- isSetupComplete: true,
121
- error: null,
122
- errorInfo: null,
123
156
  });
157
+ clearErrorIfUnchanged(errorBefore);
124
158
  addLog(`[setup] Success - ODA enabled: ${config.enableODA || false}`);
125
159
  }
126
160
  catch (error) {
127
- set({ error: error.message, errorInfo: null, isSetupInProgress: false });
128
- throw error;
161
+ return guardedFailure(error, "SETUP_FAILED", errorBefore, { setupStatus: "idle" });
129
162
  }
130
163
  },
131
164
  initAsleepConfig: async (config) => {
165
+ const state = useAsleepStore.getState();
166
+ if (state.setupStatus === "inProgress") {
167
+ return storeAndThrow(new AsleepError("OPERATION_IN_PROGRESS", "Setup is already in progress."));
168
+ }
169
+ // No tracking-state guard here: checkAndRestoreTracking() reconnects a live
170
+ // session before the app configures the SDK, so this must remain callable
171
+ // while trackingStatus is "tracking" (v1 behavior the restore flow relies on).
172
+ const errorBefore = state.error;
173
+ addLog("[initAsleepConfig] Start");
174
+ useAsleepStore.setState({ setupStatus: "inProgress" });
132
175
  try {
133
- const { addLog } = get();
134
- addLog("[initAsleepConfig] Start");
135
- const result = await AsleepModule.initAsleepConfig(config.apiKey, config.userId, config.baseUrl, config.callbackUrl);
136
- set({ isInitialized: true, error: null, errorInfo: null });
176
+ await AsleepModule.initAsleepConfig(config.apiKey, config.userId, config.baseUrl, config.callbackUrl);
177
+ useAsleepStore.setState({ setupStatus: "complete", isInitialized: true });
178
+ clearErrorIfUnchanged(errorBefore);
137
179
  addLog("[initAsleepConfig] Success");
138
- return result;
139
180
  }
140
181
  catch (error) {
141
- set({ error: error.message, errorInfo: null });
142
- throw error;
182
+ return guardedFailure(error, "INIT_CONFIG_FAILED", errorBefore, { setupStatus: "idle" });
143
183
  }
144
184
  },
145
185
  checkAndRestoreTracking: async () => {
186
+ const errorBefore = useAsleepStore.getState().error;
187
+ addLog("[checkAndRestoreTracking] Start");
146
188
  try {
147
- const { addLog } = get();
148
- addLog("[checkAndRestoreTracking] Start");
149
- // Check if sleep tracking service is alive
150
189
  const isAlive = await AsleepModule.isSleepTrackingAlive();
151
- set({
152
- hasCheckedStatus: true,
153
- });
154
- // If service is alive on Android, restore connection to it
190
+ let trackingStatus = useAsleepStore.getState().trackingStatus;
155
191
  if (isAlive && Platform.OS === "android") {
156
- addLog("[checkAndRestoreTracking] Service is alive, restoring connection...");
157
192
  const isConnected = await AsleepModule.connectSleepTracking();
158
- if (isConnected) {
159
- set({ isTracking: true });
160
- addLog("[checkAndRestoreTracking] Successfully restored connection to existing service");
161
- }
162
- else {
163
- addLog("[checkAndRestoreTracking] Failed to restore connection to existing service");
164
- }
193
+ if (isConnected)
194
+ trackingStatus = "tracking";
165
195
  }
196
+ useAsleepStore.setState({ hasCheckedStatus: true, trackingStatus });
197
+ clearErrorIfUnchanged(errorBefore);
166
198
  addLog(`[checkAndRestoreTracking] Complete - hasActiveSession: ${isAlive}`);
167
- return {
168
- hasActiveSession: isAlive,
169
- };
199
+ return { hasActiveSession: isAlive };
170
200
  }
171
201
  catch (error) {
172
- set({ error: error.message, errorInfo: null });
173
- throw error;
202
+ return guardedFailure(error, "CHECK_AND_RESTORE_FAILED", errorBefore);
174
203
  }
175
204
  },
176
- /**
177
- * Checks battery optimization status on the device.
178
- * REQUIRED: Must be called before startTracking() on both iOS and Android.
179
- *
180
- * This ensures cross-platform consistency - iOS developers must handle
181
- * battery optimization to prevent their Android users from experiencing issues.
182
- *
183
- * @returns Promise with exemption status and platform information
184
- * @returns {boolean} exempted - Whether battery optimization is disabled (always true on iOS)
185
- * @returns {string} platform - Current platform ('ios' or 'android')
186
- * @returns {string} message - Optional status message
187
- */
188
205
  checkBatteryOptimization: async () => {
189
- const { addLog } = get();
206
+ const errorBefore = useAsleepStore.getState().error;
190
207
  addLog("[checkBatteryOptimization] Checking battery optimization status...");
191
- // Mark that check was performed (required for startTracking)
192
- set({ hasCheckedBatteryOptimization: true });
193
- if (Platform.OS === "ios") {
194
- addLog("[checkBatteryOptimization] iOS - not applicable");
195
- return { exempted: true, platform: "ios" };
208
+ useAsleepStore.setState({ hasCheckedBatteryOptimization: true });
209
+ try {
210
+ if (Platform.OS === "ios") {
211
+ clearErrorIfUnchanged(errorBefore);
212
+ return { exempted: true, platform: "ios" };
213
+ }
214
+ const exempted = await AsleepModule.isBatteryOptimizationExempted();
215
+ clearErrorIfUnchanged(errorBefore);
216
+ return {
217
+ exempted,
218
+ platform: "android",
219
+ message: exempted
220
+ ? "Battery optimization disabled - ready for tracking"
221
+ : "Battery optimization must be disabled for reliable tracking",
222
+ };
223
+ }
224
+ catch (error) {
225
+ return guardedFailure(error, "CHECK_BATTERY_OPTIMIZATION_FAILED", errorBefore);
196
226
  }
197
- // Android: Check current status
198
- const exempted = await AsleepModule.isBatteryOptimizationExempted();
199
- addLog(`[checkBatteryOptimization] Exempted: ${exempted}`);
200
- return {
201
- exempted,
202
- platform: "android",
203
- message: exempted
204
- ? "Battery optimization disabled - ready for tracking"
205
- : "Battery optimization must be disabled for reliable tracking",
206
- };
207
227
  },
208
- /**
209
- * Requests battery optimization exemption from the user.
210
- * On Android: Opens system settings for battery optimization.
211
- * On iOS: No-op, returns true (not applicable).
212
- *
213
- * Use this when checkBatteryOptimization() returns exempted: false.
214
- *
215
- * @returns Promise<boolean> - true if already exempted or iOS, false if settings opened
216
- */
217
228
  requestBatteryOptimizationExemption: async () => {
218
- const { addLog } = get();
229
+ const errorBefore = useAsleepStore.getState().error;
219
230
  if (Platform.OS === "ios") {
220
- addLog("[requestBatteryOptimizationExemption] iOS - not applicable");
221
- return true; // Not applicable on iOS
231
+ clearErrorIfUnchanged(errorBefore);
232
+ return true;
233
+ }
234
+ try {
235
+ const result = await AsleepModule.requestBatteryOptimizationExemption();
236
+ clearErrorIfUnchanged(errorBefore);
237
+ return result;
238
+ }
239
+ catch (error) {
240
+ return guardedFailure(error, "REQUEST_BATTERY_EXEMPTION_FAILED", errorBefore);
222
241
  }
223
- addLog("[requestBatteryOptimizationExemption] Opening battery settings...");
224
- // This just opens settings, doesn't wait
225
- // Returns true if already exempted, false if settings opened
226
- return await AsleepModule.requestBatteryOptimizationExemption();
227
242
  },
228
- /**
229
- * Starts sleep tracking session.
230
- *
231
- * Prerequisites:
232
- * 1. checkAndRestoreTracking() must be called at app startup
233
- * 2. checkBatteryOptimization() must be called (required on both platforms)
234
- *
235
- * @param config Optional tracking configuration
236
- * @throws Error if prerequisites are not met or tracking is already in progress
237
- */
238
243
  startTracking: async (config) => {
239
- // Snapshot so the catch can tell a verdict published DURING this call
240
- // (Android fires classified onTrackingFailed before rejecting the same
241
- // promise) apart from a stale one left by an earlier failure.
242
- const errorInfoBefore = get().errorInfo;
244
+ const state = useAsleepStore.getState();
245
+ if (!state.hasCheckedStatus) {
246
+ storeAndThrow(new AsleepError("MISSING_PREREQUISITE", "Must call checkAndRestoreTracking() at app startup before starting tracking."));
247
+ }
248
+ if (!state.hasCheckedBatteryOptimization) {
249
+ storeAndThrow(new AsleepError("MISSING_PREREQUISITE", "Must call checkBatteryOptimization() before starting tracking."));
250
+ }
251
+ if (state.setupStatus === "inProgress") {
252
+ storeAndThrow(new AsleepError("INVALID_STATE", "Cannot start tracking while setup is in progress."));
253
+ }
254
+ if (state.trackingStatus !== "idle") {
255
+ storeAndThrow(new AsleepError("OPERATION_IN_PROGRESS", "Tracking is already in progress."));
256
+ }
257
+ const errorBefore = state.error;
243
258
  try {
244
- const { requestRequiredPermissions, addLog, isODAEnabled, isSetupInProgress, hasCheckedStatus } = get();
245
- // Enforce that checkAndRestoreTracking must be called first
246
- if (!hasCheckedStatus) {
247
- addLog("[startTracking] Must call checkAndRestoreTracking() at app startup");
248
- throw new Error("Must call checkAndRestoreTracking() at app startup before starting tracking");
249
- }
250
- // Enforce battery optimization check on BOTH platforms for consistency
251
- // This ensures iOS developers handle battery optimization for their Android users
252
- if (!get().hasCheckedBatteryOptimization) {
253
- addLog("[startTracking] ERROR: Must check battery optimization first");
254
- throw new Error("Must call checkBatteryOptimization() before starting tracking. " +
255
- "This check is required on both iOS and Android to ensure cross-platform consistency.");
259
+ if (!(await asleepActions.hasRequiredPermissions())) {
260
+ storeAndThrow(new AsleepError("PERMISSION_DENIED", "Microphone permission is required. Call requestRequiredPermissions() before startTracking()."));
256
261
  }
257
- // Block startTracking execution if setup is in progress
258
- if (isSetupInProgress) {
259
- addLog("[startTracking] Cannot start tracking while setup is in progress.");
260
- throw new Error("Cannot start tracking while setup is in progress.");
262
+ if (Platform.OS === "android" && !(await AsleepModule.isBatteryOptimizationExempted())) {
263
+ storeAndThrow(new AsleepError("BATTERY_NOT_EXEMPTED", "Battery optimization must be disabled before startTracking(). Call requestBatteryOptimizationExemption()."));
261
264
  }
262
- // Prevent duplicate execution if already tracking
263
- if (get().isTracking) {
264
- addLog("[startTracking] Tracking is already in progress.");
265
- throw new Error("Tracking is already in progress.");
266
- }
267
- addLog("[startTracking] Start");
268
- const permission = await requestRequiredPermissions();
269
- if (!permission) {
270
- // SDK shouldn't show UI directly - throw specific error message
271
- if (Platform.OS === "android" && Platform.Version >= 33) {
272
- throw new Error("Microphone and notification permissions are required for sleep tracking");
273
- }
274
- else {
275
- throw new Error("Microphone permission is required for sleep tracking");
276
- }
277
- }
278
- // Always verify CURRENT exemption status
279
- if (Platform.OS === "android") {
280
- const batteryExempted = await AsleepModule.isBatteryOptimizationExempted();
281
- if (!batteryExempted) {
282
- addLog("[startTracking] ERROR: Battery optimization not disabled");
283
- throw new Error("Battery optimization must be disabled for reliable sleep tracking. " +
284
- "Call requestBatteryOptimizationExemption() to guide user to settings.");
285
- }
286
- addLog("[startTracking] Battery optimization exempted - OK");
287
- }
288
- set({
265
+ useAsleepStore.setState({
289
266
  didClose: false,
290
- isTracking: true,
267
+ trackingStatus: "tracking",
291
268
  isAnalyzing: false,
292
- isRecoveryRequired: false,
293
269
  trackingStartTime: new Date(),
294
- error: null,
295
- errorInfo: null,
296
270
  });
297
271
  await AsleepModule.startTracking(config);
298
- if (isODAEnabled) {
299
- addLog("[startTracking] ODA enabled - real-time analysis will start automatically");
300
- }
301
- else {
302
- addLog("[startTracking] ODA not enabled");
303
- }
272
+ clearErrorIfUnchanged(errorBefore);
304
273
  addLog("[startTracking] Success");
305
274
  }
306
275
  catch (error) {
307
- // Preserve only a verdict that arrived during this call — the raw
308
- // rejection message carries strictly less information than the
309
- // numeric-code verdict. Reference inequality against the snapshot
310
- // excludes stale verdicts, so guard failures still write the new error.
311
- const nowInfo = get().errorInfo;
312
- const classified = nowInfo !== null && nowInfo !== errorInfoBefore;
313
- set({
314
- ...(classified ? {} : { error: error.message, errorInfo: null }),
315
- isTracking: false,
276
+ return guardedFailure(error, "START_TRACKING_FAILED", errorBefore, {
277
+ trackingStatus: "idle",
316
278
  isAnalyzing: false,
317
279
  trackingStartTime: null,
318
280
  });
319
- throw error;
320
281
  }
321
282
  },
322
283
  stopTracking: async () => {
323
- // Same dual-signal race as startTracking; see the snapshot rationale there.
324
- const errorInfoBefore = get().errorInfo;
284
+ const errorBefore = useAsleepStore.getState().error;
325
285
  try {
326
- const { addLog } = get();
327
- addLog("[stopTracking] Start");
328
286
  const result = await AsleepModule.stopTracking();
329
- set({
287
+ useAsleepStore.setState({
330
288
  didClose: true,
331
- ...(result ? { sessionId: result } : {}),
332
- isTracking: false,
289
+ ...(typeof result === "string" && result ? { sessionId: result } : {}),
290
+ trackingStatus: "idle",
333
291
  isAnalyzing: false,
334
- isRecoveryRequired: false,
335
292
  trackingStartTime: null,
336
- error: null,
337
- errorInfo: null,
338
293
  });
294
+ clearErrorIfUnchanged(errorBefore);
339
295
  addLog(`[stopTracking] Success - result: ${result}`);
340
296
  }
341
297
  catch (error) {
342
- const nowInfo = get().errorInfo;
343
- if (nowInfo === null || nowInfo === errorInfoBefore)
344
- set({ error: error.message, errorInfo: null });
345
- throw error;
298
+ return guardedFailure(error, "STOP_TRACKING_FAILED", errorBefore);
346
299
  }
347
300
  },
348
301
  resumeTracking: async () => {
349
302
  if (Platform.OS !== "ios") {
350
- throw Object.assign(new Error("resumeTracking is only supported on iOS."), {
351
- name: "AsleepPlatformError",
352
- code: "UNSUPPORTED_PLATFORM",
353
- });
303
+ storeAndThrow(new AsleepError("UNSUPPORTED_PLATFORM", "resumeTracking is only supported on iOS."));
304
+ }
305
+ const errorBefore = useAsleepStore.getState().error;
306
+ try {
307
+ await AsleepModule.resumeTracking();
308
+ clearErrorIfUnchanged(errorBefore);
309
+ }
310
+ catch (error) {
311
+ return guardedFailure(error, "RESUME_TRACKING_FAILED", errorBefore);
354
312
  }
355
- await AsleepModule.resumeTracking();
356
313
  },
357
314
  getReport: async (sessionId) => {
358
- // Snapshot the error before the await so we only clear it on success
359
- // if no concurrent failure (e.g. onTrackingFailed firing during the
360
- // network round-trip) wrote a different error in the meantime.
361
- const errorBefore = get().error;
315
+ const errorBefore = useAsleepStore.getState().error;
362
316
  try {
363
- const { addLog } = get();
364
- addLog(`[getReport] sessionId: ${sessionId}`);
365
- const report = await AsleepModule.getReport(sessionId);
366
- const convertedReport = convertKeysToCamelCase(report);
367
- addLog("[getReport] Success");
368
- // Guard so a successful query after a clean run does not spam an empty
369
- // notification, and so we never clobber an unrelated tracking error
370
- // that arrived during the await.
371
- if (get().error !== null && get().error === errorBefore)
372
- set({ error: null, errorInfo: null });
373
- // Ensure the report has the expected AsleepReport structure
374
- // Handle cases where native modules might return data in different formats
375
- if (convertedReport && !convertedReport.session && convertedReport.sessionId) {
376
- // If the data comes in a flat format (like AsleepSession), convert it to AsleepReport format
377
- const normalizedReport = {
378
- timezone: convertedReport.timezone || "",
379
- session: {
380
- id: convertedReport.sessionId || convertedReport.id || sessionId,
381
- createdTimezone: convertedReport.createdTimezone || "",
382
- startTime: convertedReport.sessionStartTime || convertedReport.startTime || "",
383
- endTime: convertedReport.sessionEndTime || convertedReport.endTime,
384
- unexpectedEndTime: convertedReport.unexpectedEndTime,
385
- state: convertedReport.state || "",
386
- sleepStages: convertedReport.sleepStages,
387
- breathStages: convertedReport.breathStages,
388
- snoringStages: convertedReport.snoringStages,
389
- },
390
- missingDataRatio: convertedReport.missingDataRatio || 0,
391
- peculiarities: convertedReport.peculiarities || [],
392
- stat: convertedReport.stat,
393
- };
394
- return normalizedReport;
317
+ const payload = await AsleepModule.getReport(sessionId);
318
+ if (payload == null) {
319
+ throw new AsleepError("REPORT_NOT_FOUND", `No report available for session "${sessionId}".`);
395
320
  }
396
- return convertedReport;
321
+ const report = normalizeReport(payload, sessionId);
322
+ clearErrorIfUnchanged(errorBefore);
323
+ return report;
397
324
  }
398
325
  catch (error) {
399
- // Silent return on failure is a public-API quirk preserved for v1.x
400
- // compat (v2.0 throws). Surface a dev-only warn so the consumer's
401
- // Metro log still shows the failure when they're debugging without
402
- // observing `useAsleep().error` directly.
403
- if (typeof __DEV__ !== "undefined" && __DEV__)
404
- console.warn("[Asleep] getReport failed:", error);
405
- set({ error: error.message, errorInfo: null });
406
- return null;
326
+ return guardedFailure(error, "GET_REPORT_FAILED", errorBefore);
407
327
  }
408
328
  },
409
329
  getReportList: async (fromDate, toDate) => {
410
- const errorBefore = get().error;
330
+ const errorBefore = useAsleepStore.getState().error;
411
331
  try {
412
- const { addLog } = get();
413
- addLog(`[getReportList] fromDate: ${fromDate}, toDate: ${toDate}`);
414
- const reportList = await AsleepModule.getReportList(fromDate, toDate);
415
- const convertedList = reportList.map((session) => {
332
+ const reportList = (await AsleepModule.getReportList(fromDate, toDate)) ?? [];
333
+ const result = reportList.map((session) => {
416
334
  const converted = convertKeysToCamelCase(session);
417
- // Normalize property names to match other session types
418
335
  return {
419
336
  id: converted.sessionId || converted.id,
420
337
  state: converted.state,
@@ -426,405 +343,325 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
426
343
  timeInBed: converted.timeInBed,
427
344
  };
428
345
  });
429
- addLog("[getReportList] Success");
430
- if (get().error !== null && get().error === errorBefore)
431
- set({ error: null, errorInfo: null });
432
- return convertedList;
346
+ clearErrorIfUnchanged(errorBefore);
347
+ return result;
433
348
  }
434
349
  catch (error) {
435
- if (typeof __DEV__ !== "undefined" && __DEV__)
436
- console.warn("[Asleep] getReportList failed:", error);
437
- set({ error: error.message, errorInfo: null });
438
- return [];
350
+ return guardedFailure(error, "GET_REPORT_LIST_FAILED", errorBefore);
351
+ }
352
+ },
353
+ getAverageReport: async (fromDate, toDate) => {
354
+ const errorBefore = useAsleepStore.getState().error;
355
+ try {
356
+ const payload = await AsleepModule.getAverageReport(fromDate, toDate);
357
+ if (payload == null) {
358
+ throw new AsleepError("REPORT_NOT_FOUND", `No average report available for ${fromDate} to ${toDate}.`);
359
+ }
360
+ const result = convertKeysToCamelCase(payload);
361
+ clearErrorIfUnchanged(errorBefore);
362
+ return result;
363
+ }
364
+ catch (error) {
365
+ return guardedFailure(error, "GET_AVERAGE_REPORT_FAILED", errorBefore);
439
366
  }
440
367
  },
441
368
  deleteSession: async (sessionId) => {
442
- const errorBefore = get().error;
369
+ const errorBefore = useAsleepStore.getState().error;
443
370
  try {
444
- const { addLog } = get();
445
- addLog(`[deleteSession] sessionId: ${sessionId}`);
446
371
  await AsleepModule.deleteSession(sessionId);
447
- addLog("[deleteSession] Success");
448
- if (get().error !== null && get().error === errorBefore)
449
- set({ error: null, errorInfo: null });
372
+ clearErrorIfUnchanged(errorBefore);
450
373
  }
451
374
  catch (error) {
452
- set({ error: error.message, errorInfo: null });
453
- throw error;
375
+ return guardedFailure(error, "DELETE_SESSION_FAILED", errorBefore);
454
376
  }
455
377
  },
456
- getAverageReport: async (fromDate, toDate) => {
457
- const errorBefore = get().error;
378
+ requestAnalysis: async () => {
379
+ const errorBefore = useAsleepStore.getState().error;
380
+ useAsleepStore.setState({ isAnalyzing: true });
458
381
  try {
459
- const { addLog } = get();
460
- addLog(`[getAverageReport] fromDate: ${fromDate}, toDate: ${toDate}`);
461
- const averageReport = await AsleepModule.getAverageReport(fromDate, toDate);
462
- const convertedReport = convertKeysToCamelCase(averageReport);
463
- addLog("[getAverageReport] Success");
464
- if (get().error !== null && get().error === errorBefore)
465
- set({ error: null, errorInfo: null });
466
- return convertedReport;
382
+ const result = convertKeysToCamelCase(await AsleepModule.requestAnalysis());
383
+ clearErrorIfUnchanged(errorBefore);
384
+ return result;
467
385
  }
468
386
  catch (error) {
469
- if (typeof __DEV__ !== "undefined" && __DEV__)
470
- console.warn("[Asleep] getAverageReport failed:", error);
471
- set({ error: error.message, errorInfo: null });
472
- return null;
387
+ return guardedFailure(error, "REQUEST_ANALYSIS_FAILED", errorBefore, { isAnalyzing: false });
473
388
  }
474
389
  },
475
- /**
476
- * @deprecated Use requestRequiredPermissions instead. This method will be removed in a future version.
477
- */
478
- requestMicrophonePermission: async () => {
479
- if (typeof __DEV__ !== "undefined" && __DEV__) {
480
- console.warn("[Asleep] requestMicrophonePermission is deprecated. Please use requestRequiredPermissions instead.");
390
+ hasRequiredPermissions: async () => {
391
+ const errorBefore = useAsleepStore.getState().error;
392
+ try {
393
+ const result = await AsleepModule.hasRequiredPermissions();
394
+ clearErrorIfUnchanged(errorBefore);
395
+ return result;
396
+ }
397
+ catch (error) {
398
+ return guardedFailure(error, "CHECK_PERMISSION_FAILED", errorBefore);
481
399
  }
482
- return get().requestRequiredPermissions();
483
400
  },
484
401
  requestRequiredPermissions: async () => {
485
- if (Platform.OS === "android") {
486
- try {
487
- // Prepare permissions array with RECORD_AUDIO
402
+ const errorBefore = useAsleepStore.getState().error;
403
+ try {
404
+ if (Platform.OS === "android") {
488
405
  const permissions = [PermissionsAndroid.PERMISSIONS.RECORD_AUDIO];
489
- // Add POST_NOTIFICATIONS for Android 13+ (API level 33)
490
- if (Platform.Version >= 33) {
406
+ if (Platform.Version >= 33)
491
407
  permissions.push(PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS);
492
- }
493
- // Request all permissions together for better UX (single dialog)
494
408
  const results = await PermissionsAndroid.requestMultiple(permissions);
495
- // Check if all required permissions are granted
409
+ // POST_NOTIFICATIONS is requested for foreground-service notification
410
+ // visibility but is not needed for tracking to run, so the returned
411
+ // boolean mirrors hasRequiredPermissions(): microphone-side grants only.
496
412
  const audioGranted = results[PermissionsAndroid.PERMISSIONS.RECORD_AUDIO] === PermissionsAndroid.RESULTS.GRANTED;
497
- const notificationGranted = Platform.Version >= 33
498
- ? results[PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS] === PermissionsAndroid.RESULTS.GRANTED
499
- : true;
500
- // Both must be granted for tracking to work properly
501
- return audioGranted && notificationGranted;
502
- }
503
- catch (err) {
504
- if (typeof __DEV__ !== "undefined" && __DEV__)
505
- console.warn("[Asleep] Permission request error:", err);
506
- return false;
413
+ clearErrorIfUnchanged(errorBefore);
414
+ return audioGranted;
507
415
  }
416
+ const result = await AsleepModule.requestRequiredPermissions();
417
+ clearErrorIfUnchanged(errorBefore);
418
+ return result;
419
+ }
420
+ catch (error) {
421
+ return guardedFailure(error, "REQUEST_PERMISSION_FAILED", errorBefore);
508
422
  }
509
- // iOS uses native implementation
510
- return AsleepModule.requestRequiredPermissions();
511
423
  },
512
424
  setCustomNotification: async (_title, _text) => {
513
- // Native method removed; notification config now flows through startTracking options.
514
- if (typeof __DEV__ !== "undefined" && __DEV__)
515
- console.warn("[Asleep] setCustomNotification is deprecated and a no-op; pass `{ android: { notification: { title, text, icon } } }` to startTracking() instead");
425
+ if (typeof __DEV__ !== "undefined" && __DEV__) {
426
+ console.warn("[Asleep] setCustomNotification is deprecated and a no-op; pass notification options to startTracking() instead.");
427
+ }
516
428
  },
517
429
  enableLog: (print) => {
518
430
  if (Platform.OS === "ios")
519
431
  AsleepModule.enableLog(print);
520
- set({ showDebugLog: print });
521
- },
522
- requestAnalysis: async () => {
523
- try {
524
- const { addLog, showDebugLog } = get();
525
- addLog("[requestAnalysis] Start");
526
- set({ isAnalyzing: true, error: null, errorInfo: null });
527
- const result = await AsleepModule.requestAnalysis();
528
- const convertedResult = convertKeysToCamelCase(result);
529
- // analysisResult and isAnalyzing are owned by the onAnalysisResult event handler on both
530
- // platforms. Android resolves the promise with the full session AND fires the event;
531
- // iOS resolves with an ack only. Writing state here would double-update on Android.
532
- if (showDebugLog)
533
- addLog(`[requestAnalysis] Request sent - ${JSON.stringify(convertedResult)}`);
534
- return convertedResult;
535
- }
536
- catch (error) {
537
- if (typeof __DEV__ !== "undefined" && __DEV__)
538
- console.warn("[Asleep] requestAnalysis failed:", error);
539
- set({ error: error.message, errorInfo: null, isAnalyzing: false });
540
- return null;
541
- }
432
+ useAsleepStore.setState({ showDebugLog: print });
542
433
  },
434
+ clearError: () => useAsleepStore.setState({ error: null }),
543
435
  addEventListener: (eventType, listener) => {
544
436
  const subscription = emitter.addListener(eventType, listener);
545
437
  return () => subscription.remove();
546
438
  },
547
- getTrackingDurationMinutes: () => {
548
- const { trackingStartTime } = get();
549
- if (!trackingStartTime)
550
- return 0;
551
- return Math.floor((Date.now() - trackingStartTime.getTime()) / (1000 * 60));
552
- },
553
- // internal actions
554
- // setError takes a raw string, so any structured classification is stale;
555
- // reset errorInfo rather than let a previous event's category linger.
556
- setError: (error) => set({ error, errorInfo: null }),
557
- clearError: () => set({ error: null, errorInfo: null }),
558
- setUserId: (userId) => set({ userId }),
559
- setSessionId: (sessionId) => set({ sessionId }),
560
- setIsTracking: (isTracking) => set({ isTracking }),
561
- setIsTrackingPaused: (isTrackingPaused) => set({ isTrackingPaused }),
562
- setDidClose: (didClose) => set({ didClose }),
563
- setAnalysisResult: (result) => set({ analysisResult: result }),
564
- setIsAnalyzing: (isAnalyzing) => set({ isAnalyzing }),
565
- setTrackingStartTime: (time) => set({ trackingStartTime: time }),
566
- setIsInitialized: (initialized) => set({ isInitialized: initialized }),
567
- setIsSetupInProgress: (inProgress) => set({ isSetupInProgress: inProgress }),
568
- setIsSetupComplete: (complete) => set({ isSetupComplete: complete }),
569
- setHasCheckedStatus: (checked) => set({ hasCheckedStatus: checked }),
570
- setHasCheckedBatteryOptimization: (checked) => set({ hasCheckedBatteryOptimization: checked }),
571
- addLog: (log) => {
572
- // Zero-cost when the consumer has not opted into debug logging. Without
573
- // this guard, every native event handler would cause a spurious
574
- // subscriber notification on top of any actual data update.
575
- const { showDebugLog } = get();
576
- if (!showDebugLog)
577
- return;
578
- const now = new Date();
579
- const dateString = `${now.getHours().toString().padStart(2, "0")}:${now
580
- .getMinutes()
581
- .toString()
582
- .padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}`;
583
- const formattedLog = `[${dateString}]${log}`;
584
- console.log(`[Asleep]${formattedLog}`);
585
- set({ log: formattedLog });
586
- },
587
- })));
588
- // Ref-counted registration. Each caller (useAsleep effect, background context,
589
- // etc.) increments on entry and decrements via the returned cleanup. Native
590
- // listeners only attach on 0→1 and detach on the final 1→0, so concurrent
591
- // consumers cannot tear each other's subscriptions down.
592
- let refCount = 0;
593
- let teardown = null;
594
- export const initializeAsleepListeners = () => {
595
- // Cold start when no teardown is installed. `teardown` is the single source
596
- // of truth for "listeners are currently attached"; refCount is just an
597
- // increment-only counter for cleanup balancing. Always incrementing
598
- // (instead of assigning =1 on cold start) keeps the count correct even if
599
- // a future change introduces an async seam between this check and the
600
- // listener registration below.
601
- if (teardown) {
602
- refCount++;
603
- return makeCleanup();
439
+ };
440
+ let lastInternal = null;
441
+ let lastPublic = null;
442
+ export const toPublicState = (internal) => {
443
+ if (internal === lastInternal && lastPublic)
444
+ return lastPublic;
445
+ // Recovery-required is still a live native session on main; preserve that
446
+ // contract while representing the recovery fact with one enum value.
447
+ const isTracking = internal.trackingStatus !== "idle";
448
+ const next = {
449
+ status: internal.trackingStatus,
450
+ isTracking,
451
+ isTrackingPaused: internal.trackingStatus === "paused",
452
+ isRecoveryRequired: internal.trackingStatus === "recoveryRequired",
453
+ isSetupInProgress: internal.setupStatus === "inProgress",
454
+ isSetupComplete: internal.setupStatus === "complete",
455
+ sessionId: internal.sessionId,
456
+ userId: internal.userId,
457
+ error: internal.error,
458
+ analysisResult: internal.analysisResult,
459
+ isAnalyzing: internal.isAnalyzing,
460
+ didClose: internal.didClose,
461
+ isODAEnabled: internal.isODAEnabled,
462
+ log: internal.log,
463
+ ...asleepActions,
464
+ };
465
+ lastInternal = internal;
466
+ if (lastPublic &&
467
+ lastPublic.status === next.status &&
468
+ lastPublic.sessionId === next.sessionId &&
469
+ lastPublic.userId === next.userId &&
470
+ lastPublic.error === next.error &&
471
+ lastPublic.analysisResult === next.analysisResult &&
472
+ lastPublic.isAnalyzing === next.isAnalyzing &&
473
+ lastPublic.didClose === next.didClose &&
474
+ lastPublic.isODAEnabled === next.isODAEnabled &&
475
+ lastPublic.log === next.log &&
476
+ lastPublic.isSetupInProgress === next.isSetupInProgress &&
477
+ lastPublic.isSetupComplete === next.isSetupComplete) {
478
+ return lastPublic;
604
479
  }
605
- const store = useAsleepStore.getState();
606
- const { addLog, setUserId, setIsTrackingPaused, setIsSetupInProgress } = store;
607
- // event handlers — each native SDK event corresponds to one logical state
608
- // transaction. Use a single useAsleepStore.setState per handler so consumers
609
- // subscribed via useAsleep re-render once per event, not once per field.
610
- const handlers = {
611
- // Connected: iOS userDidJoin, Android onSuccess (AsleepConfigListener)
612
- onUserJoined: (data) => {
613
- setUserId(data.userId);
614
- addLog(`[onUserJoined] userId: ${data.userId}`);
615
- },
616
- // Connected: iOS didFailUserJoin, Android onFail (AsleepConfigListener)
617
- onUserJoinFailed: (error) => {
618
- const errorString = JSON.stringify(error);
619
- // Not a tracking-runtime failure; errorInfo stays reserved for
620
- // onTrackingFailed classification.
621
- useAsleepStore.setState({ error: errorString, errorInfo: null });
622
- addLog(`[onUserJoinFailed] error: ${errorString}`);
623
- },
624
- // Connected: iOS userDidDelete, Android NOT IMPLEMENTED
625
- onUserDeleted: (data) => {
626
- setUserId(null);
627
- addLog(`[onUserDeleted] userId: ${data.userId}`);
628
- },
629
- // Connected: iOS didCreate, Android onStart (AsleepTrackingListener)
630
- onTrackingCreated: (data) => {
631
- useAsleepStore.setState({
632
- isTracking: true,
633
- ...(data?.sessionId ? { sessionId: data.sessionId } : {}),
634
- });
635
- addLog(`[onTrackingCreated]${data?.sessionId ? ` sessionId: ${data.sessionId}` : ""}`);
636
- },
637
- // Connected: iOS didUpload, Android onPerform (AsleepTrackingListener)
638
- // Triggers automatic analysis requests in both ODA and non-ODA modes
639
- onTrackingUploaded: (data) => {
640
- addLog(`[onTrackingUploaded] sequence: ${data.sequence}`);
641
- // requestAnalysis() flips isAnalyzing internally; no separate setter
642
- // needed before invoking it (avoids a duplicate subscriber notification).
643
- const state = useAsleepStore.getState();
644
- // A completed upload is the only positive proof that recording actually came
645
- // back — didResume fires before the engine restart is even attempted, so it
646
- // cannot be trusted to clear this.
647
- if (state.isRecoveryRequired)
648
- useAsleepStore.setState({ isRecoveryRequired: false });
649
- const triggerAnalysis = () => state.requestAnalysis().catch((error) => {
650
- addLog(`[onTrackingUploaded] Auto analysis failed: ${error.message}`);
651
- state.setIsAnalyzing(false);
652
- });
653
- if (state.isODAEnabled && state.isTracking) {
654
- triggerAnalysis();
655
- }
656
- else if (!state.isODAEnabled && state.isTracking) {
657
- if (data.sequence >= 10 && data.sequence % 10 === 1) {
658
- triggerAnalysis();
659
- }
660
- }
661
- },
662
- // Connected: iOS didClose, Android onFinish (AsleepTrackingListener)
663
- onTrackingClosed: (data) => {
664
- useAsleepStore.setState({
665
- sessionId: data.sessionId,
666
- isTracking: false,
667
- isAnalyzing: false,
668
- isRecoveryRequired: false,
669
- didClose: true,
670
- trackingStartTime: null,
671
- });
672
- addLog(`[onTrackingClosed] sessionId: ${data.sessionId}`);
673
- },
674
- // Connected: iOS didFail, Android onFail (AsleepTrackingListener)
675
- // Four state buckets, each writing tracking state in the same setState as the
676
- // error so subscribers see one event: terminal (native session already gone),
677
- // recording-dead (recorder torn down but session still open — clearing
678
- // isTracking is what unblocks a restart), recovery-required (resumeTracking()
679
- // in foreground can revive it), and everything else (error only).
680
- // The two dead-session buckets must also clear isRecoveryRequired: iOS retries
681
- // cannotActivateInBackground and then gives up with interruptionRecoveryFailed,
682
- // and no upload will ever arrive to clear the flag on that path.
683
- // The bucket verdict is also published as errorInfo.category (with the
684
- // else-bucket split into "transient" vs "unknown") so consumers can gate
685
- // log severity on data instead of re-deriving code lists themselves.
686
- onTrackingFailed: (error) => {
687
- // The explicit iOS string buckets must win before the numeric terminal
688
- // fallback: the numeric set encodes Android teardown semantics, and iOS
689
- // reuses 11003 (.audioInitializationFailed -> .audio) for a failure whose
690
- // session is still open. The numeric fallback still matters on iOS for
691
- // start/stop failures that arrive as UNKNOWN_ERROR + 22xxx/24xxx and must
692
- // clear the optimistically-set isTracking.
693
- const recordingDead = !!(error && RECORDING_DEAD_ERROR_CODES.has(error.code));
694
- const recoveryRequired = !!(error && RECOVERY_REQUIRED_ERROR_CODES.has(error.code));
695
- const terminal = !!(error &&
696
- !recordingDead &&
697
- !recoveryRequired &&
698
- (TERMINAL_TRACKING_ERROR_CODES.has(error.code) || TERMINAL_TRACKING_SDK_CODES.has(error.sdkCode)));
699
- const transient = !!(error && TRANSIENT_TRACKING_SDK_CODES.has(error.sdkCode));
700
- let category;
701
- if (recordingDead)
702
- category = "recordingDead";
703
- else if (recoveryRequired)
704
- category = "recoveryRequired";
705
- else if (terminal)
706
- category = "terminal";
707
- else if (transient)
708
- category = "transient";
709
- else
710
- category = "unknown";
711
- // Category rides along in the stringified error too, so consumers still
712
- // parsing the legacy string see the same verdict as errorInfo readers.
713
- const errorString = JSON.stringify(error ? { ...error, category } : error);
714
- const errorInfo = error
715
- ? {
716
- code: typeof error.code === "string" ? error.code : "UNKNOWN_ERROR",
717
- category,
718
- ...(typeof error.sdkCode === "number" ? { sdkCode: error.sdkCode } : {}),
719
- ...(typeof error.message === "string" ? { message: error.message } : {}),
720
- ...(typeof error.caseName === "string" ? { caseName: error.caseName } : {}),
721
- }
722
- : null;
723
- let nextState;
724
- if (terminal) {
725
- nextState = {
726
- error: errorString,
727
- errorInfo,
728
- isTracking: false,
480
+ lastPublic = next;
481
+ return lastPublic;
482
+ };
483
+ const transitionForEvent = (eventType, payload, state) => {
484
+ switch (eventType) {
485
+ case "onUserJoined":
486
+ return { partial: { userId: payload.userId }, log: `[onUserJoined] userId: ${payload.userId}` };
487
+ case "onUserJoinFailed":
488
+ return {
489
+ partial: { error: normalizeError(payload, "USER_JOIN_FAILED") },
490
+ log: `[onUserJoinFailed] error: ${payload?.message ?? payload?.detail ?? payload?.error ?? "Unknown error"}`,
491
+ };
492
+ case "onUserDeleted":
493
+ return { partial: { userId: null }, log: `[onUserDeleted] userId: ${payload.userId}` };
494
+ case "onTrackingCreated":
495
+ return {
496
+ partial: { trackingStatus: "tracking", ...(payload?.sessionId ? { sessionId: payload.sessionId } : {}) },
497
+ log: `[onTrackingCreated]${payload?.sessionId ? ` sessionId: ${payload.sessionId}` : ""}`,
498
+ };
499
+ case "onTrackingUploaded": {
500
+ const shouldAnalyze = state.trackingStatus !== "idle" &&
501
+ (state.isODAEnabled || (payload.sequence >= 10 && payload.sequence % 10 === 1));
502
+ return {
503
+ partial: {
504
+ // iOS 3.2.0 emits didResume before its engine restart is proven.
505
+ // Only a completed upload clears recovery; see AGENTS.md
506
+ // "Native Behavior Compensations".
507
+ ...(state.trackingStatus === "recoveryRequired" ? { trackingStatus: "tracking" } : {}),
508
+ ...(shouldAnalyze ? { isAnalyzing: true } : {}),
509
+ },
510
+ log: `[onTrackingUploaded] sequence: ${payload.sequence}`,
511
+ requestAnalysis: shouldAnalyze,
512
+ };
513
+ }
514
+ case "onTrackingClosed":
515
+ return {
516
+ partial: {
517
+ sessionId: payload.sessionId,
518
+ trackingStatus: "idle",
729
519
  isAnalyzing: false,
730
- isRecoveryRequired: false,
731
520
  didClose: true,
732
521
  trackingStartTime: null,
522
+ },
523
+ log: `[onTrackingClosed] sessionId: ${payload.sessionId}`,
524
+ };
525
+ case "onTrackingFailed": {
526
+ const recordingDead = !!payload && RECORDING_DEAD_ERROR_CODES.has(payload.code);
527
+ const recoveryRequired = !!payload && RECOVERY_REQUIRED_ERROR_CODES.has(payload.code);
528
+ const terminal = !!payload &&
529
+ !recordingDead &&
530
+ !recoveryRequired &&
531
+ (TERMINAL_TRACKING_ERROR_CODES.has(payload.code) || TERMINAL_TRACKING_SDK_CODES.has(payload.sdkCode));
532
+ const transient = !!payload && TRANSIENT_TRACKING_SDK_CODES.has(payload.sdkCode);
533
+ const category = recordingDead
534
+ ? "recordingDead"
535
+ : recoveryRequired
536
+ ? "recoveryRequired"
537
+ : terminal
538
+ ? "terminal"
539
+ : transient
540
+ ? "transient"
541
+ : "unknown";
542
+ const error = normalizeError(payload, "TRACKING_FAILED", {
543
+ category,
544
+ sdkCode: typeof payload?.sdkCode === "number" ? payload.sdkCode : undefined,
545
+ caseName: typeof payload?.caseName === "string" ? payload.caseName : undefined,
546
+ });
547
+ if (terminal) {
548
+ return {
549
+ partial: {
550
+ // iOS 3.2.1 closeSessionSilently does not emit didClose, so this
551
+ // branch must clear the projected session state itself.
552
+ error,
553
+ trackingStatus: "idle",
554
+ isAnalyzing: false,
555
+ didClose: true,
556
+ trackingStartTime: null,
557
+ },
558
+ log: `[onTrackingError] error: ${error.message}`,
733
559
  };
734
560
  }
735
- else if (recordingDead) {
736
- nextState = {
737
- error: errorString,
738
- errorInfo,
739
- isTracking: false,
740
- isAnalyzing: false,
741
- isRecoveryRequired: false,
742
- didClose: false,
743
- trackingStartTime: null,
561
+ if (recordingDead) {
562
+ return {
563
+ partial: {
564
+ // iOS 3.2.0 audioInitializationFailed stops its recorder but
565
+ // intentionally keeps the native session open (didClose=false).
566
+ error,
567
+ trackingStatus: "idle",
568
+ isAnalyzing: false,
569
+ didClose: false,
570
+ trackingStartTime: null,
571
+ },
572
+ log: `[onTrackingError] error: ${error.message}`,
744
573
  };
745
574
  }
746
- else if (recoveryRequired) {
747
- nextState = { error: errorString, errorInfo, isTracking: true, isRecoveryRequired: true };
748
- }
749
- else {
750
- nextState = { error: errorString, errorInfo };
751
- }
752
- useAsleepStore.setState(nextState);
753
- addLog(`[onTrackingError] error: ${errorString}`);
754
- },
755
- // Connected: iOS didInterrupt, Android NOT IMPLEMENTED
756
- onTrackingInterrupted: () => {
757
- setIsTrackingPaused(true);
758
- addLog(`[onTrackingInterrupted]`);
759
- },
760
- // Connected: iOS didResume, Android NOT IMPLEMENTED
761
- // Always clear the error: some iOS recovery paths (e.g. cannotActivateInBackground
762
- // retry) reach this handler without a preceding didInterrupt, and the stale error
763
- // should still be cleared. Only the paused-state mutation is gated, to dedup the
764
- // iOS 3.2.1+ double fire from handleRecovering -> handleResumed.
765
- // isRecoveryRequired, not isTrackingPaused, is authoritative when recording is
766
- // dead because didResume fires before the engine restart is attempted.
767
- onTrackingResumed: () => {
768
- const wasPaused = useAsleepStore.getState().isTrackingPaused;
769
- useAsleepStore.setState(wasPaused ? { error: null, errorInfo: null, isTrackingPaused: false } : { error: null, errorInfo: null });
770
- addLog(wasPaused ? `[onTrackingResumed]` : `[onTrackingResumed] (no prior pause; error cleared)`);
771
- },
772
- // Connected: iOS micPermissionWasDenied, Android NOT IMPLEMENTED
773
- onMicPermissionDenied: () => {
774
- addLog(`[onMicPermissionDenied]`);
775
- },
776
- // Connected: iOS AsleepLogger callbacks, Android sendEvent called directly
777
- onDebugLog: (data) => {
778
- addLog(`[onDebugLog] message: ${data.message}`);
779
- },
780
- // Connected: iOS setupDidComplete, Android onComplete (AsleepSetupListener)
781
- onSetupDidComplete: () => {
782
- useAsleepStore.setState({ isSetupInProgress: false, isSetupComplete: true });
783
- addLog(`[onSetupDidComplete]`);
784
- },
785
- // Connected: iOS setupDidFail, Android onFail (AsleepSetupListener)
786
- onSetupDidFail: (data) => {
787
- const errorString = JSON.stringify(data);
788
- useAsleepStore.setState({
789
- error: errorString,
790
- errorInfo: null,
791
- isSetupInProgress: false,
792
- isSetupComplete: false,
793
- });
794
- addLog(`[onSetupDidFail] error: ${errorString}`);
795
- },
796
- // Connected: iOS setupInProgress, Android onProgress (AsleepSetupListener)
797
- onSetupInProgress: (data) => {
798
- setIsSetupInProgress(true);
799
- addLog(`[onSetupInProgress] progress: ${data.progress}%`);
800
- },
801
- // Connected: iOS analyzing (session), Android onSleepDataReceived (AsleepSleepDataListener)
802
- // Android serializes snake_case; normalize so both platforms match AsleepAnalysisResult.
803
- onAnalysisResult: (data) => {
804
- const normalized = convertKeysToCamelCase(data);
805
- useAsleepStore.setState({ analysisResult: normalized, isAnalyzing: false });
806
- if (useAsleepStore.getState().showDebugLog) {
807
- addLog(`[onAnalysisResult] ${JSON.stringify(normalized)}`);
575
+ if (recoveryRequired) {
576
+ return {
577
+ // iOS 3.2.0 cannotActivateInBackground keeps the session alive and
578
+ // requires an explicit foreground resume.
579
+ partial: { error, trackingStatus: "recoveryRequired" },
580
+ log: `[onTrackingError] error: ${error.message}`,
581
+ };
808
582
  }
809
- },
810
- };
811
- // register all event listeners
812
- const subscriptions = [];
813
- Object.entries(handlers).forEach(([eventType, handler]) => {
814
- const subscription = emitter.addListener(eventType, handler);
815
- subscriptions.push(() => subscription.remove());
816
- });
583
+ return { partial: { error }, log: `[onTrackingError] error: ${error.message}` };
584
+ }
585
+ case "onTrackingInterrupted":
586
+ return { partial: { trackingStatus: "paused" }, log: "[onTrackingInterrupted]" };
587
+ case "onTrackingResumed":
588
+ return {
589
+ partial: {
590
+ error: null,
591
+ // iOS 3.2.1 can emit didResume twice. Always clear the error, but
592
+ // mutate the paused state only for the first event.
593
+ ...(state.trackingStatus === "paused" ? { trackingStatus: "tracking" } : {}),
594
+ },
595
+ log: state.trackingStatus === "paused"
596
+ ? "[onTrackingResumed]"
597
+ : "[onTrackingResumed] (no prior pause; error cleared)",
598
+ };
599
+ case "onMicPermissionDenied":
600
+ return { partial: {}, log: "[onMicPermissionDenied]" };
601
+ case "onDebugLog":
602
+ return { partial: {}, log: `[onDebugLog] message: ${payload.message}` };
603
+ case "onSetupDidComplete":
604
+ return { partial: { setupStatus: "complete" }, log: "[onSetupDidComplete]" };
605
+ case "onSetupDidFail":
606
+ return {
607
+ partial: { error: normalizeError(payload, "SETUP_FAILED"), setupStatus: "idle" },
608
+ log: `[onSetupDidFail] error: ${payload?.message ?? payload?.error ?? "Unknown error"}`,
609
+ };
610
+ case "onSetupInProgress":
611
+ return { partial: { setupStatus: "inProgress" }, log: `[onSetupInProgress] progress: ${payload.progress}%` };
612
+ case "onAnalysisResult": {
613
+ // Android SDK 3.2.x emits snake_case while iOS emits camelCase.
614
+ const analysisResult = convertKeysToCamelCase(payload);
615
+ return {
616
+ partial: { analysisResult, isAnalyzing: false },
617
+ log: `[onAnalysisResult] ${JSON.stringify(analysisResult)}`,
618
+ };
619
+ }
620
+ }
621
+ };
622
+ const applyEvent = (eventType, payload) => {
623
+ const state = useAsleepStore.getState();
624
+ const transition = transitionForEvent(eventType, payload, state);
625
+ useAsleepStore.setState({ ...transition.partial, ...logPartial(transition.log, state) });
626
+ if (transition.requestAnalysis) {
627
+ void asleepActions.requestAnalysis().catch((error) => {
628
+ addLog(`[onTrackingUploaded] Auto analysis failed: ${error.message}`);
629
+ });
630
+ }
631
+ };
632
+ let refCount = 0;
633
+ let teardown = null;
634
+ export const initializeAsleepListeners = () => {
635
+ if (teardown) {
636
+ refCount++;
637
+ return makeCleanup();
638
+ }
639
+ const eventTypes = [
640
+ "onUserJoined",
641
+ "onUserJoinFailed",
642
+ "onUserDeleted",
643
+ "onTrackingCreated",
644
+ "onTrackingUploaded",
645
+ "onTrackingClosed",
646
+ "onTrackingFailed",
647
+ "onTrackingInterrupted",
648
+ "onTrackingResumed",
649
+ "onMicPermissionDenied",
650
+ "onDebugLog",
651
+ "onSetupDidComplete",
652
+ "onSetupDidFail",
653
+ "onSetupInProgress",
654
+ "onAnalysisResult",
655
+ ];
656
+ const subscriptions = eventTypes.map((eventType) => emitter.addListener(eventType, (payload) => applyEvent(eventType, payload)));
817
657
  refCount++;
818
658
  teardown = () => {
819
- subscriptions.forEach((unsubscribe) => unsubscribe());
659
+ subscriptions.forEach((subscription) => subscription.remove());
820
660
  teardown = null;
821
661
  };
822
662
  return makeCleanup();
823
663
  };
824
664
  const makeCleanup = () => {
825
- // Idempotent per-caller cleanup. The `called` flag is closure-private so
826
- // calling the returned function twice (e.g. Strict Mode double-effect)
827
- // decrements the shared ref count only once.
828
665
  let called = false;
829
666
  return () => {
830
667
  if (called)