react-native-asleep 1.2.0 → 2.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.
@@ -1,10 +1,11 @@
1
- import type { AsleepAnalysisAck, AsleepAnalysisResult, AsleepAverageReport, AsleepConfig, AsleepErrorCategory, AsleepEventType, AsleepReport, AsleepSession, AsleepSetupConfig, SetupStatus, TrackingConfig, TrackingStatus } from "./Asleep.types";
1
+ import type { AsleepAnalysisAck, AsleepAnalysisResult, AsleepAverageReport, AsleepConfig, AsleepErrorCategory, AsleepEventType, AsleepReport, AsleepSession, AsleepSetupConfig, AsleepUserMetadata, ReanalyzeOptions, SetupStatus, StopTrackingOptions, TrackingConfig, TrackingStatus } from "./Asleep.types";
2
2
  import { AsleepError } from "./Asleep.types";
3
3
  export interface InternalAsleepState {
4
4
  setupStatus: SetupStatus;
5
5
  trackingStatus: TrackingStatus;
6
6
  sessionId: string | null;
7
7
  userId: string | null;
8
+ isUserConfigReady: boolean;
8
9
  error: AsleepError | null;
9
10
  analysisResult: AsleepAnalysisResult | null;
10
11
  isAnalyzing: boolean;
@@ -30,12 +31,15 @@ export interface AsleepActions {
30
31
  }>;
31
32
  requestBatteryOptimizationExemption: () => Promise<boolean>;
32
33
  startTracking: (config?: TrackingConfig) => Promise<void>;
33
- stopTracking: () => Promise<void>;
34
+ stopTracking: (options?: StopTrackingOptions) => Promise<void>;
34
35
  resumeTracking: () => Promise<void>;
35
36
  getReport: (sessionId: string) => Promise<AsleepReport>;
36
37
  getReportList: (fromDate: string, toDate: string) => Promise<AsleepSession[]>;
37
38
  getAverageReport: (fromDate: string, toDate: string) => Promise<AsleepAverageReport>;
38
39
  deleteSession: (sessionId: string) => Promise<void>;
40
+ reanalyze: (sessionId: string, options?: ReanalyzeOptions) => Promise<void>;
41
+ saveUserMetadata: (metadata: AsleepUserMetadata) => Promise<void>;
42
+ fetchUserMetadata: () => Promise<AsleepUserMetadata | null>;
39
43
  requestAnalysis: () => Promise<AsleepAnalysisResult | AsleepAnalysisAck>;
40
44
  hasRequiredPermissions: () => Promise<boolean>;
41
45
  requestRequiredPermissions: () => Promise<boolean>;
@@ -1 +1 @@
1
- {"version":3,"file":"AsleepStore.d.ts","sourceRoot":"","sources":["../src/AsleepStore.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,iBAAiB,EACjB,oBAAoB,EACpB,mBAAmB,EACnB,YAAY,EACZ,mBAAmB,EACnB,eAAe,EACf,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,WAAW,EACX,cAAc,EACd,cAAc,EACf,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAwB7C,MAAM,WAAW,mBAAmB;IAClC,WAAW,EAAE,WAAW,CAAC;IACzB,cAAc,EAAE,cAAc,CAAC;IAC/B,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,KAAK,EAAE,WAAW,GAAG,IAAI,CAAC;IAC1B,cAAc,EAAE,oBAAoB,GAAG,IAAI,CAAC;IAC5C,WAAW,EAAE,OAAO,CAAC;IACrB,QAAQ,EAAE,OAAO,CAAC;IAClB,YAAY,EAAE,OAAO,CAAC;IACtB,iBAAiB,EAAE,IAAI,GAAG,IAAI,CAAC;IAC/B,aAAa,EAAE,OAAO,CAAC;IACvB,gBAAgB,EAAE,OAAO,CAAC;IAC1B,6BAA6B,EAAE,OAAO,CAAC;IACvC,YAAY,EAAE,OAAO,CAAC;IACtB,GAAG,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,CAAC,MAAM,EAAE,iBAAiB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACpD,gBAAgB,EAAE,CAAC,MAAM,EAAE,YAAY,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1D,uBAAuB,EAAE,MAAM,OAAO,CAAC;QAAE,g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,YAAiB,KAAG,WA+ClG,CAAC;AAgOF,eAAO,MAAM,aAAa,EAAE,aAkZ3B,CAAC;AAKF,eAAO,MAAM,aAAa,GAAI,UAAU,mBAAmB,KAAG,eAyC7D,CAAC;AAgLF,eAAO,MAAM,yBAAyB,QAAO,CAAC,MAAM,IAAI,CAiCvD,CAAC"}
@@ -5,15 +5,19 @@ import AsleepModule from "./AsleepModule";
5
5
  import { createStore } from "./store/createStore";
6
6
  const emitter = new EventEmitter(AsleepModule);
7
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.
10
- const RECORDING_DEAD_ERROR_CODES = new Set(["AUDIO_INITIALIZATION_FAILED"]);
8
+ const TERMINAL_TRACKING_ERROR_CODES = new Set(["UPLOAD_TRACKING_TERMINATED"]);
9
+ // iOS stops recording but leaves the native session open; stopTracking() closes it.
10
+ const RECORDING_DEAD_ERROR_CODES = new Set(["AUDIO_INITIALIZATION_FAILED", "INTERRUPTION_RECOVERY_FAILED"]);
11
11
  // iOS 3.2.0 needs an explicit foreground resume after this failure.
12
12
  const RECOVERY_REQUIRED_ERROR_CODES = new Set(["CANNOT_ACTIVATE_IN_BACKGROUND"]);
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.
13
+ // The first 13 codes are the Android SDK 3.3.x session-teardown set; keep them
14
+ // synchronized with AsleepModule.kt's TERMINAL_TRACKING_ERROR_CODES. The rest are
15
+ // start failures after which no native session exists: iOS 3.3.2 create HTTP
16
+ // 400/403/429/404 (22400, 11403, 11404) and insufficient storage (11008, both
17
+ // platforms). Android reports create failures as 22000. 11010 (alreadyTracking)
18
+ // is deliberately absent because the existing session survives it.
15
19
  const TERMINAL_TRACKING_SDK_CODES = new Set([
16
- 11003, 22000, 22401, 22409, 22422, 22500, 23499, 24000, 24400, 24401, 24403, 24404, 24500,
20
+ 11003, 22000, 22401, 22409, 22422, 22500, 23499, 24000, 24400, 24401, 24403, 24404, 24500, 11008, 11403, 11404, 22400,
17
21
  ]);
18
22
  // The native session survives these exhausted upload attempts.
19
23
  const TRANSIENT_TRACKING_SDK_CODES = new Set([23000, 23500]);
@@ -23,6 +27,7 @@ export const useAsleepStore = createStore(() => ({
23
27
  trackingStatus: initialTrackingStatus,
24
28
  sessionId: null,
25
29
  userId: null,
30
+ isUserConfigReady: false,
26
31
  error: null,
27
32
  analysisResult: null,
28
33
  isAnalyzing: false,
@@ -47,13 +52,17 @@ const convertKeysToCamelCase = (value) => {
47
52
  }
48
53
  return value;
49
54
  };
55
+ // Expo promise rejections carry only a code string and a message, so native
56
+ // rejections that know the documented SDK code encode it as "<CODE>:<sdkCode>".
57
+ const NATIVE_REJECTION_CODE = /^([A-Z][A-Z0-9_]*):(\d+)$/;
50
58
  export const normalizeError = (source, fallbackCode, options = {}) => {
51
59
  if (source instanceof AsleepError && Object.keys(options).length === 0)
52
60
  return source;
53
61
  const payload = source && typeof source === "object"
54
62
  ? source
55
63
  : undefined;
56
- const code = typeof payload?.code === "string" ? payload.code : fallbackCode;
64
+ const encoded = typeof payload?.code === "string" ? NATIVE_REJECTION_CODE.exec(payload.code) : null;
65
+ const code = encoded ? encoded[1] : typeof payload?.code === "string" ? payload.code : fallbackCode;
57
66
  const message = typeof payload?.message === "string"
58
67
  ? payload.message
59
68
  : typeof payload?.error === "string"
@@ -69,9 +78,11 @@ export const normalizeError = (source, fallbackCode, options = {}) => {
69
78
  sdkCode: options.sdkCode ??
70
79
  (typeof payload?.sdkCode === "number"
71
80
  ? payload.sdkCode
72
- : source instanceof AsleepError
73
- ? source.sdkCode
74
- : undefined),
81
+ : encoded
82
+ ? Number(encoded[2])
83
+ : source instanceof AsleepError
84
+ ? source.sdkCode
85
+ : undefined),
75
86
  caseName: options.caseName ??
76
87
  (typeof payload?.caseName === "string"
77
88
  ? payload.caseName
@@ -112,6 +123,129 @@ const clearErrorIfUnchanged = (errorBefore) => {
112
123
  if (current !== null && current === errorBefore)
113
124
  useAsleepStore.setState({ error: null });
114
125
  };
126
+ // Runtime guard for JS callers and casts that bypass the AsleepCredentials union.
127
+ const resolveCredentials = (config) => {
128
+ const { apiKey, appId, appSecret } = (config ?? {});
129
+ const hasApiKey = apiKey !== undefined;
130
+ const hasToken = appId !== undefined || appSecret !== undefined;
131
+ if (hasApiKey && hasToken) {
132
+ return storeAndThrow(new AsleepError("INVALID_ARGUMENT", "Pass either apiKey or appId/appSecret credentials, not both."));
133
+ }
134
+ if (!hasApiKey && !hasToken) {
135
+ return storeAndThrow(new AsleepError("INVALID_ARGUMENT", "Credentials are required: pass apiKey or appId/appSecret."));
136
+ }
137
+ const isNonEmpty = (value) => typeof value === "string" && value.length > 0;
138
+ if (hasApiKey) {
139
+ if (!isNonEmpty(apiKey))
140
+ return storeAndThrow(new AsleepError("INVALID_ARGUMENT", "apiKey must be a non-empty string."));
141
+ return { apiKey };
142
+ }
143
+ if (!isNonEmpty(appId) || !isNonEmpty(appSecret)) {
144
+ return storeAndThrow(new AsleepError("INVALID_ARGUMENT", "appId and appSecret must both be non-empty strings."));
145
+ }
146
+ return { appId, appSecret };
147
+ };
148
+ const PRODUCT_INFO_FIELDS = new Set(["model", "identifierType", "identifierValue"]);
149
+ const PRODUCT_INFO_LENGTH_LIMITS = { model: 100, identifierValue: 255 };
150
+ // Mirrors the native pre-checks (iOS ProductManager.validate, Android
151
+ // ProductRegistrar.validate), which otherwise fail the whole setup with 13400:
152
+ // not blank after trimming, and the untrimmed value within the length limit.
153
+ // Returns null when no productInfo was supplied.
154
+ const resolveProductInfo = (productInfo) => {
155
+ if (productInfo == null)
156
+ return null;
157
+ if (typeof productInfo !== "object" || Array.isArray(productInfo)) {
158
+ return storeAndThrow(new AsleepError("INVALID_ARGUMENT", "productInfo must be an object."));
159
+ }
160
+ const source = productInfo;
161
+ const unknownField = Object.keys(source).find((field) => !PRODUCT_INFO_FIELDS.has(field));
162
+ if (unknownField !== undefined) {
163
+ return storeAndThrow(new AsleepError("INVALID_ARGUMENT", `productInfo.${unknownField} is not a known field.`));
164
+ }
165
+ for (const [field, max] of Object.entries(PRODUCT_INFO_LENGTH_LIMITS)) {
166
+ const value = source[field];
167
+ if (typeof value !== "string" || value.trim().length === 0 || value.length > max) {
168
+ return storeAndThrow(new AsleepError("INVALID_ARGUMENT", `productInfo.${field} must be a non-blank string of at most ${max} characters.`));
169
+ }
170
+ }
171
+ if (source.identifierType !== "serial" && source.identifierType !== "mac_address") {
172
+ return storeAndThrow(new AsleepError("INVALID_ARGUMENT", 'productInfo.identifierType must be "serial" or "mac_address".'));
173
+ }
174
+ return {
175
+ model: source.model,
176
+ identifierType: source.identifierType,
177
+ identifierValue: source.identifierValue,
178
+ };
179
+ };
180
+ const isValidDate = (value) => value instanceof Date && Number.isFinite(value.getTime());
181
+ // Both native SDKs reject start >= end (iOS 11009 via didFail after stop has
182
+ // already resolved), and they compare at whole-second precision. Returns epoch
183
+ // milliseconds for the bridge, or null when no range was supplied.
184
+ const resolveAnalysisRange = (range) => {
185
+ if (range == null)
186
+ return null;
187
+ const { start, end } = range;
188
+ if (!isValidDate(start) || !isValidDate(end)) {
189
+ return storeAndThrow(new AsleepError("INVALID_ARGUMENT", "analysisRange.start and analysisRange.end must be valid Date objects."));
190
+ }
191
+ if (Math.floor(start.getTime() / 1000) >= Math.floor(end.getTime() / 1000)) {
192
+ return storeAndThrow(new AsleepError("INVALID_ARGUMENT", "analysisRange.start must be at least one second before analysisRange.end."));
193
+ }
194
+ return [start.getTime(), end.getTime()];
195
+ };
196
+ const USER_METADATA_INTEGER_RANGES = {
197
+ birthYear: [1900, 2100],
198
+ birthMonth: [1, 12],
199
+ birthDay: [1, 31],
200
+ };
201
+ const USER_METADATA_NUMBER_RANGES = {
202
+ height: [1, 500],
203
+ weight: [1, 1000],
204
+ };
205
+ const USER_METADATA_GENDERS = new Set(["male", "female", "non_binary", "other", "prefer_not_to_say"]);
206
+ // Mirrors the native range checks (iOS UserMetadata.validate(), Android
207
+ // UserMetadata init) so invalid input never reaches the bridge. Only known
208
+ // fields are forwarded; undefined and null mean "not provided".
209
+ const resolveUserMetadata = (metadata) => {
210
+ if (metadata === null || typeof metadata !== "object" || Array.isArray(metadata)) {
211
+ return storeAndThrow(new AsleepError("INVALID_ARGUMENT", "metadata must be an object."));
212
+ }
213
+ const source = metadata;
214
+ const resolved = {};
215
+ for (const [field, [min, max]] of Object.entries(USER_METADATA_INTEGER_RANGES)) {
216
+ const value = source[field];
217
+ if (value == null)
218
+ continue;
219
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {
220
+ return storeAndThrow(new AsleepError("INVALID_ARGUMENT", `${field} must be an integer between ${min} and ${max}.`));
221
+ }
222
+ resolved[field] = value;
223
+ }
224
+ for (const [field, [min, max]] of Object.entries(USER_METADATA_NUMBER_RANGES)) {
225
+ const value = source[field];
226
+ if (value == null)
227
+ continue;
228
+ if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) {
229
+ return storeAndThrow(new AsleepError("INVALID_ARGUMENT", `${field} must be a number between ${min} and ${max}.`));
230
+ }
231
+ resolved[field] = value;
232
+ }
233
+ if (source.gender != null) {
234
+ if (typeof source.gender !== "string" || !USER_METADATA_GENDERS.has(source.gender)) {
235
+ return storeAndThrow(new AsleepError("INVALID_ARGUMENT", 'gender must be one of "male", "female", "non_binary", "other", or "prefer_not_to_say".'));
236
+ }
237
+ resolved.gender = source.gender;
238
+ }
239
+ return resolved;
240
+ };
241
+ // The native user config exists only after the most recent initAsleepConfig()
242
+ // joined its user. A re-init in progress or a failed re-init invalidates it, so
243
+ // these calls never run against a previous user's config.
244
+ const requireUserConfig = (action) => {
245
+ if (!useAsleepStore.getState().isUserConfigReady) {
246
+ storeAndThrow(new AsleepError("MISSING_PREREQUISITE", `initAsleepConfig() must resolve (complete its user join) before ${action}().`));
247
+ }
248
+ };
115
249
  const normalizeReport = (report, sessionId) => {
116
250
  const converted = convertKeysToCamelCase(report);
117
251
  if (converted && !converted.session && converted.sessionId) {
@@ -137,6 +271,8 @@ const normalizeReport = (report, sessionId) => {
137
271
  };
138
272
  export const asleepActions = {
139
273
  setup: async (config) => {
274
+ const credentials = resolveCredentials(config);
275
+ const productInfo = resolveProductInfo(config.productInfo);
140
276
  const state = useAsleepStore.getState();
141
277
  if (state.setupStatus === "inProgress") {
142
278
  storeAndThrow(new AsleepError("OPERATION_IN_PROGRESS", "Setup is already in progress."));
@@ -146,9 +282,13 @@ export const asleepActions = {
146
282
  }
147
283
  const errorBefore = state.error;
148
284
  addLog("[setup] Start");
149
- useAsleepStore.setState({ setupStatus: "inProgress" });
285
+ // setup() reconfigures the SDK (possibly with other credentials), so the
286
+ // previous user config is no longer valid until initAsleepConfig() resolves.
287
+ useAsleepStore.setState({ setupStatus: "inProgress", isUserConfigReady: false });
150
288
  try {
151
- await AsleepModule.setup(config.apiKey, config.baseUrl, config.callbackUrl, config.service, config.enableODA);
289
+ // Credentials travel as one record: Expo's Kotlin AsyncFunction accepts at
290
+ // most eight parameters including the promise.
291
+ await AsleepModule.setup(credentials, config.baseUrl, config.callbackUrl, config.service, config.enableODA, productInfo);
152
292
  useAsleepStore.setState({
153
293
  setupStatus: "complete",
154
294
  isODAEnabled: config.enableODA || false,
@@ -162,6 +302,7 @@ export const asleepActions = {
162
302
  }
163
303
  },
164
304
  initAsleepConfig: async (config) => {
305
+ const credentials = resolveCredentials(config);
165
306
  const state = useAsleepStore.getState();
166
307
  if (state.setupStatus === "inProgress") {
167
308
  return storeAndThrow(new AsleepError("OPERATION_IN_PROGRESS", "Setup is already in progress."));
@@ -171,15 +312,25 @@ export const asleepActions = {
171
312
  // while trackingStatus is "tracking" (v1 behavior the restore flow relies on).
172
313
  const errorBefore = state.error;
173
314
  addLog("[initAsleepConfig] Start");
174
- useAsleepStore.setState({ setupStatus: "inProgress" });
315
+ useAsleepStore.setState({ setupStatus: "inProgress", isUserConfigReady: false });
175
316
  try {
176
- await AsleepModule.initAsleepConfig(config.apiKey, config.userId, config.baseUrl, config.callbackUrl);
177
- useAsleepStore.setState({ setupStatus: "complete", isInitialized: true });
317
+ const result = await AsleepModule.initAsleepConfig(credentials.apiKey, credentials.appId, credentials.appSecret, config.userId, config.baseUrl, config.callbackUrl);
318
+ // Both platforms resolve after the user join with { userId }. This
319
+ // resolution, not onUserJoined, enables readiness for this init.
320
+ const joined = typeof result?.userId === "string" && result.userId.length > 0;
321
+ useAsleepStore.setState({
322
+ setupStatus: "complete",
323
+ isInitialized: true,
324
+ ...(joined ? { isUserConfigReady: true } : {}),
325
+ });
178
326
  clearErrorIfUnchanged(errorBefore);
179
327
  addLog("[initAsleepConfig] Success");
180
328
  }
181
329
  catch (error) {
182
- return guardedFailure(error, "INIT_CONFIG_FAILED", errorBefore, { setupStatus: "idle" });
330
+ return guardedFailure(error, "INIT_CONFIG_FAILED", errorBefore, {
331
+ setupStatus: "idle",
332
+ isUserConfigReady: false,
333
+ });
183
334
  }
184
335
  },
185
336
  checkAndRestoreTracking: async () => {
@@ -280,10 +431,13 @@ export const asleepActions = {
280
431
  });
281
432
  }
282
433
  },
283
- stopTracking: async () => {
434
+ stopTracking: async (options) => {
435
+ const range = resolveAnalysisRange(options?.analysisRange);
284
436
  const errorBefore = useAsleepStore.getState().error;
285
437
  try {
286
- const result = await AsleepModule.stopTracking();
438
+ // Always pass both arguments: older expo-modules-core versions do not let
439
+ // trailing nullable arguments be omitted.
440
+ const result = await AsleepModule.stopTracking(range ? range[0] : null, range ? range[1] : null);
287
441
  useAsleepStore.setState({
288
442
  didClose: true,
289
443
  ...(typeof result === "string" && result ? { sessionId: result } : {}),
@@ -375,6 +529,49 @@ export const asleepActions = {
375
529
  return guardedFailure(error, "DELETE_SESSION_FAILED", errorBefore);
376
530
  }
377
531
  },
532
+ reanalyze: async (sessionId, options) => {
533
+ if (typeof sessionId !== "string" || sessionId.trim().length === 0) {
534
+ storeAndThrow(new AsleepError("INVALID_ARGUMENT", "sessionId must be a non-empty string."));
535
+ }
536
+ const range = resolveAnalysisRange(options?.analysisRange);
537
+ requireUserConfig("reanalyze");
538
+ const errorBefore = useAsleepStore.getState().error;
539
+ try {
540
+ // Resolves once the server accepts the request, not when analysis finishes.
541
+ // Nulls are explicit: iOS treats arguments before a Promise as required.
542
+ await AsleepModule.reanalyze(sessionId, range?.[0] ?? null, range?.[1] ?? null);
543
+ clearErrorIfUnchanged(errorBefore);
544
+ }
545
+ catch (error) {
546
+ return guardedFailure(error, "REANALYZE_FAILED", errorBefore);
547
+ }
548
+ },
549
+ saveUserMetadata: async (metadata) => {
550
+ const resolved = resolveUserMetadata(metadata);
551
+ requireUserConfig("saveUserMetadata");
552
+ const errorBefore = useAsleepStore.getState().error;
553
+ try {
554
+ await AsleepModule.saveUserMetadata(resolved);
555
+ clearErrorIfUnchanged(errorBefore);
556
+ }
557
+ catch (error) {
558
+ return guardedFailure(error, "SAVE_USER_METADATA_FAILED", errorBefore);
559
+ }
560
+ },
561
+ fetchUserMetadata: async () => {
562
+ requireUserConfig("fetchUserMetadata");
563
+ const errorBefore = useAsleepStore.getState().error;
564
+ try {
565
+ const payload = await AsleepModule.fetchUserMetadata();
566
+ // Android serializes the native model with snake_case keys.
567
+ const result = payload == null ? null : convertKeysToCamelCase(payload);
568
+ clearErrorIfUnchanged(errorBefore);
569
+ return result;
570
+ }
571
+ catch (error) {
572
+ return guardedFailure(error, "FETCH_USER_METADATA_FAILED", errorBefore);
573
+ }
574
+ },
378
575
  requestAnalysis: async () => {
379
576
  const errorBefore = useAsleepStore.getState().error;
380
577
  useAsleepStore.setState({ isAnalyzing: true });
@@ -483,14 +680,22 @@ export const toPublicState = (internal) => {
483
680
  const transitionForEvent = (eventType, payload, state) => {
484
681
  switch (eventType) {
485
682
  case "onUserJoined":
486
- return { partial: { userId: payload.userId }, log: `[onUserJoined] userId: ${payload.userId}` };
683
+ // During initAsleepConfig() the action's resolution owns readiness, so a
684
+ // stale join from an earlier init cannot enable the config for this one.
685
+ return {
686
+ partial: {
687
+ userId: payload.userId,
688
+ ...(state.setupStatus === "inProgress" ? {} : { isUserConfigReady: true }),
689
+ },
690
+ log: `[onUserJoined] userId: ${payload.userId}`,
691
+ };
487
692
  case "onUserJoinFailed":
488
693
  return {
489
- partial: { error: normalizeError(payload, "USER_JOIN_FAILED") },
694
+ partial: { error: normalizeError(payload, "USER_JOIN_FAILED"), isUserConfigReady: false },
490
695
  log: `[onUserJoinFailed] error: ${payload?.message ?? payload?.detail ?? payload?.error ?? "Unknown error"}`,
491
696
  };
492
697
  case "onUserDeleted":
493
- return { partial: { userId: null }, log: `[onUserDeleted] userId: ${payload.userId}` };
698
+ return { partial: { userId: null, isUserConfigReady: false }, log: `[onUserDeleted] userId: ${payload.userId}` };
494
699
  case "onTrackingCreated":
495
700
  return {
496
701
  partial: { trackingStatus: "tracking", ...(payload?.sessionId ? { sessionId: payload.sessionId } : {}) },
@@ -547,8 +752,9 @@ const transitionForEvent = (eventType, payload, state) => {
547
752
  if (terminal) {
548
753
  return {
549
754
  partial: {
550
- // iOS 3.2.1 closeSessionSilently does not emit didClose, so this
551
- // branch must clear the projected session state itself.
755
+ // iOS closeSessionSilently (upload 4xx) does not emit didClose, and
756
+ // start failures never create a session, so this branch must clear
757
+ // the projected session state itself.
552
758
  error,
553
759
  trackingStatus: "idle",
554
760
  isAnalyzing: false,
@@ -561,8 +767,8 @@ const transitionForEvent = (eventType, payload, state) => {
561
767
  if (recordingDead) {
562
768
  return {
563
769
  partial: {
564
- // iOS 3.2.0 audioInitializationFailed stops its recorder but
565
- // intentionally keeps the native session open (didClose=false).
770
+ // iOS audioInitializationFailed and interruptionRecoveryFailed stop
771
+ // the recorder but keep the native session open (didClose=false).
566
772
  error,
567
773
  trackingStatus: "idle",
568
774
  isAnalyzing: false,
@@ -574,8 +780,8 @@ const transitionForEvent = (eventType, payload, state) => {
574
780
  }
575
781
  if (recoveryRequired) {
576
782
  return {
577
- // iOS 3.2.0 cannotActivateInBackground keeps the session alive and
578
- // requires an explicit foreground resume.
783
+ // iOS cannotActivateInBackground keeps the session alive. 3.3.x also
784
+ // retries on foreground; only a later upload proves recovery.
579
785
  partial: { error, trackingStatus: "recoveryRequired" },
580
786
  log: `[onTrackingError] error: ${error.message}`,
581
787
  };
@@ -588,8 +794,9 @@ const transitionForEvent = (eventType, payload, state) => {
588
794
  return {
589
795
  partial: {
590
796
  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.
797
+ // iOS 3.2.1-3.3.0 can emit didResume twice, and recovery paths can
798
+ // resume without a prior pause. Always clear the error, but mutate
799
+ // the paused state only for the first event.
593
800
  ...(state.trackingStatus === "paused" ? { trackingStatus: "tracking" } : {}),
594
801
  },
595
802
  log: state.trackingStatus === "paused"