react-native-asleep 1.1.0 → 2.0.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.
@@ -0,0 +1,442 @@
1
+ # React Native Asleep Integration Guide
2
+
3
+ [English](./INTEGRATION.md) | [한국어](./INTEGRATION.ko.md)
4
+
5
+ This guide covers production integration of `react-native-asleep` in React Native and Expo apps. It expands on the [README](../README.md) with restoration, lifecycle ownership, platform differences, recovery, analysis, reports, and release verification.
6
+
7
+ The examples use service-based sleep tracking through `initAsleepConfig()`. ODA (On-Device Analysis) is outside this guide: `setup()` configures a new ODA session and cannot run while a restored session is tracking.
8
+
9
+ ## Integration flow
10
+
11
+ ```mermaid
12
+ flowchart LR
13
+ A["App starts"] --> B["Mount useAsleep or initialize listeners"]
14
+ B --> C["checkAndRestoreTracking()"]
15
+ C --> D["initAsleepConfig() and wait for iOS user event"]
16
+ D --> E["checkBatteryOptimization()"]
17
+ E --> F{"Android service restored?"}
18
+ F -- "Yes" --> G["Render restored SDK state"]
19
+ F -- "No" --> H["User starts tracking"]
20
+ H --> I["Check and request permission"]
21
+ I --> J["Recheck Android battery exemption"]
22
+ J --> K["startTracking()"]
23
+ G --> L["Observe state and events"]
24
+ K --> L
25
+ L --> M["stopTracking()"]
26
+ M --> N["Fetch report when ready"]
27
+ ```
28
+
29
+ Three rules prevent most integration failures:
30
+
31
+ 1. Complete the Android service-restoration check before configuration, and always configure afterward—even when it finds a live session.
32
+ 2. Request runtime permissions only from a user action. `startTracking()` checks permissions but does not request them.
33
+ 3. Treat the SDK state as native facts. Keep product workflow, persistence, timers, retries, UI, and analytics in the app.
34
+
35
+ ## 1. Installation and native configuration
36
+
37
+ Follow the [README installation instructions](../README.md#installation) and [native configuration](../README.md#native-configuration).
38
+
39
+ Because the package contains native modules:
40
+
41
+ - rebuild the development or store binary after installation or a version change;
42
+ - do not validate it with Expo Go;
43
+ - do not expect an OTA update alone to install a new native SDK.
44
+
45
+ The app must provide iOS microphone usage text and the audio background mode. Android permissions and the foreground service come from the library manifest.
46
+
47
+ ## 2. Own the listener lifecycle
48
+
49
+ ### React applications
50
+
51
+ Mount `useAsleep()` in the integration owner that coordinates app-wide sleep tracking. The hook attaches native listeners on mount and releases them on unmount.
52
+
53
+ The listener bridge is ref-counted, so additional components may also use the hook without creating competing SDK stores. Keeping one app-level integration hook is still useful because it gives product workflow a single owner.
54
+
55
+ Importing `react-native-asleep` is side-effect-free; it does not attach listeners.
56
+
57
+ ### Non-React code
58
+
59
+ Call `Asleep.initialize()` before relying on state or native events where no mounted hook owns the bridge. Always call the returned cleanup function.
60
+
61
+ ```ts
62
+ import { Asleep } from "react-native-asleep";
63
+
64
+ const releaseListeners = Asleep.initialize();
65
+
66
+ const unsubscribe = Asleep.subscribe((state) => {
67
+ console.log(state.status);
68
+ });
69
+
70
+ const removeAnalysisListener = Asleep.addEventListener(
71
+ "onAnalysisResult",
72
+ (result) => {
73
+ console.log(result);
74
+ },
75
+ );
76
+
77
+ // When the owner is disposed:
78
+ removeAnalysisListener();
79
+ unsubscribe();
80
+ releaseListeners();
81
+ ```
82
+
83
+ `Asleep.initialize()` is also ref-counted, so it can coexist with mounted `useAsleep()` hooks.
84
+
85
+ ## 3. Restore, then configure
86
+
87
+ Run this sequence once from the app-level integration owner:
88
+
89
+ ```tsx
90
+ import { Platform } from "react-native";
91
+ import { useCallback } from "react";
92
+ import { AsleepError, useAsleep } from "react-native-asleep";
93
+
94
+ export function useSleepTrackingBootstrap(stableUserId?: string) {
95
+ const asleep = useAsleep();
96
+
97
+ const initialize = useCallback(async () => {
98
+ const restoration = await asleep.checkAndRestoreTracking();
99
+
100
+ const config = {
101
+ apiKey: "YOUR_API_KEY",
102
+ userId: stableUserId,
103
+ };
104
+
105
+ if (Platform.OS === "ios") {
106
+ let removeJoined = () => {};
107
+ let removeFailed = () => {};
108
+ const configurationFinished = new Promise<void>((resolve, reject) => {
109
+ removeJoined = asleep.addEventListener("onUserJoined", () => resolve());
110
+ removeFailed = asleep.addEventListener(
111
+ "onUserJoinFailed",
112
+ (failure) => {
113
+ reject(
114
+ new AsleepError(
115
+ "USER_JOIN_FAILED",
116
+ failure.detail ?? failure.error ?? "User join failed.",
117
+ {
118
+ sdkCode: failure.sdkCode,
119
+ caseName: failure.caseName,
120
+ cause: failure,
121
+ },
122
+ ),
123
+ );
124
+ },
125
+ );
126
+ });
127
+
128
+ try {
129
+ await Promise.all([
130
+ asleep.initAsleepConfig(config),
131
+ configurationFinished,
132
+ ]);
133
+ } finally {
134
+ removeJoined();
135
+ removeFailed();
136
+ }
137
+ } else {
138
+ await asleep.initAsleepConfig(config);
139
+ }
140
+
141
+ const battery = await asleep.checkBatteryOptimization();
142
+
143
+ return {
144
+ hasActiveSession: restoration.hasActiveSession,
145
+ battery,
146
+ };
147
+ }, [
148
+ asleep.checkAndRestoreTracking,
149
+ asleep.initAsleepConfig,
150
+ asleep.addEventListener,
151
+ asleep.checkBatteryOptimization,
152
+ stableUserId,
153
+ ]);
154
+
155
+ return { ...asleep, initialize };
156
+ }
157
+ ```
158
+
159
+ ### Why this order is required
160
+
161
+ - `checkAndRestoreTracking()` asks Android native code whether tracking survived the JavaScript process and reconnects the service when needed. On iOS, the method is a required cross-platform prerequisite but returns `{ hasActiveSession: false }`; iOS has no persistent service to reconnect.
162
+ - `initAsleepConfig()` remains required after that check. A restored session does not mean the current JavaScript process has configured the SDK and report APIs.
163
+ - On iOS, the bridge call starts asynchronous user configuration and can return before the native tracking and report managers exist. Register `onUserJoined` and `onUserJoinFailed` before calling it, then wait for one of those events. On Android, await the action itself; the restored-service fast path resolves without emitting `onUserJoined`.
164
+ - Do not use `isSetupComplete` alone as the iOS readiness signal. The current bridge action can update it before the user-join delegate creates the native managers.
165
+ - `checkBatteryOptimization()` marks the required prerequisite as checked. On iOS it resolves with `{ exempted: true, platform: "ios" }`.
166
+ - `startTracking()` rejects with `MISSING_PREREQUISITE` if restoration or the battery check has not run.
167
+
168
+ Do not run restoration and configuration concurrently. Do not skip configuration when `hasActiveSession` is `true`.
169
+
170
+ If initialization fails, keep tracking controls disabled and offer an app-owned retry action. Do not convert the failure into an apparently ready state.
171
+
172
+ Do not commit the API key to source control. Load it through the secret or configuration mechanism used by the app's build environment.
173
+
174
+ Token authentication uses the same actions: pass `{ appId, appSecret }` instead of `{ apiKey }` to `setup()` or `initAsleepConfig()`. The two forms are mutually exclusive (`AsleepCredentials`); neither, both, an incomplete pair, or an empty value rejects with `INVALID_ARGUMENT` before the native call. On Android, the restored-service fast path recognizes the same `appId` and `userId` as the running session, so restore works in token mode as it does with an API key. Treat `appSecret` with the same secret handling as the API key.
175
+
176
+ ### Stable user identity
177
+
178
+ If the app supplies `userId`, persist the stable identifier in app storage and reuse it on later initialization. The SDK exposes the current native `userId`, but account mapping and guest-to-member policy belong to the app.
179
+
180
+ Do not reconfigure a live session with a different product identity. Define any identity migration policy outside the SDK.
181
+
182
+ ## 4. Check prerequisites and start
183
+
184
+ Permission prompts must originate from a user-driven interaction:
185
+
186
+ ```ts
187
+ async function startSleepTracking() {
188
+ if (!(await asleep.hasRequiredPermissions())) {
189
+ const granted = await asleep.requestRequiredPermissions();
190
+ if (!granted) return { status: "permissionDenied" as const };
191
+ }
192
+
193
+ const battery = await asleep.checkBatteryOptimization();
194
+ if (!battery.exempted) {
195
+ await asleep.requestBatteryOptimizationExemption();
196
+ return { status: "batterySettingsOpened" as const };
197
+ }
198
+
199
+ await asleep.startTracking({
200
+ android: {
201
+ notification: {
202
+ title: "Sleep tracking",
203
+ text: "Sleep analysis is running.",
204
+ },
205
+ },
206
+ });
207
+
208
+ return { status: "started" as const };
209
+ }
210
+
211
+ async function handleTrackingPress() {
212
+ const shouldStop =
213
+ asleep.isTracking || asleep.error?.category === "recordingDead";
214
+
215
+ if (shouldStop) {
216
+ await asleep.stopTracking();
217
+ return { status: "stopped" as const };
218
+ }
219
+
220
+ return startSleepTracking();
221
+ }
222
+ ```
223
+
224
+ When Android opens battery settings, the result only means the settings flow was requested. Recheck `checkBatteryOptimization()` after the app returns and let the user retry. `startTracking()` performs its own Android exemption check and throws `BATTERY_NOT_EXEMPTED` if the device is still not exempted.
225
+
226
+ Use the same `shouldStop` predicate for the primary button label and action. In the `recordingDead` state, `isTracking` is `false` but the native session is still open, so the app must stop that session instead of starting another one.
227
+
228
+ On Android 13 and later, `requestRequiredPermissions()` also requests notification permission for foreground-service visibility. Its boolean result reflects microphone-side permissions, matching `hasRequiredPermissions()`; notification denial alone does not prevent tracking.
229
+
230
+ The app owns permission-denied screens, settings guidance, retry buttons, and analytics. The library never renders UI.
231
+
232
+ ## 5. Separate SDK state from app state
233
+
234
+ | SDK-owned native facts | App-owned product state |
235
+ |---|---|
236
+ | `status`, `isTracking`, `isTrackingPaused` | Bootstrap or screen readiness |
237
+ | `isRecoveryRequired`, `error` | Permission education and retry UI |
238
+ | `sessionId`, `userId` | Persisted identity mapping |
239
+ | `analysisResult`, `isAnalyzing` | Wall-clock tracking start time and duration |
240
+ | `didClose`, `isSetupComplete`, `isODAEnabled` | Alarm, widget, Live Activity, cloud sync |
241
+ | Native event and action transitions | Business retry policy and observability severity |
242
+
243
+ `status` is the lifecycle source:
244
+
245
+ | `status` | Meaning |
246
+ |---|---|
247
+ | `idle` | No projected live tracking session |
248
+ | `tracking` | Tracking is active |
249
+ | `paused` | The live native session is interrupted |
250
+ | `recoveryRequired` | The live iOS session needs an explicit foreground resume |
251
+
252
+ `isTracking` is derived from `status` and is `true` for `tracking`, `paused`, and `recoveryRequired`. Do not store a competing app boolean for the same fact.
253
+
254
+ The SDK does not expose wall-clock tracking duration. Store a start timestamp in the app and compute `now - startedAt`; do not count timer ticks because background suspension makes them inaccurate.
255
+
256
+ ## 6. Platform behavior
257
+
258
+ | Concern | Android | iOS |
259
+ |---|---|---|
260
+ | Background operation | Foreground service with a persistent notification | Audio background mode |
261
+ | Cold restoration | `checkAndRestoreTracking()` reconnects the live service | No persistent service; the check returns `false` |
262
+ | Battery prerequisite | Exemption is required and checked again by `startTracking()` | Check resolves as exempted |
263
+ | Runtime permissions | Microphone; notification is also requested on API 33+ | Microphone |
264
+ | Interruption recovery | `resumeTracking()` is unsupported | `resumeTracking()` is available |
265
+ | `requestAnalysis()` promise | Full analysis payload | `{ status: "requested", timestamp }` acknowledgement |
266
+ | Reactive analysis | `onAnalysisResult`, normalized to camelCase | `onAnalysisResult` |
267
+
268
+ ### Android foreground behavior
269
+
270
+ Pass notification text to `startTracking()` rather than configuring a separate notification API. The notification is part of the long-running recording service.
271
+
272
+ Test cold restoration by starting tracking, terminating the app process without ending the native session, reopening the app, and verifying that `checkAndRestoreTracking()` reconnects before configuration continues.
273
+
274
+ ### iOS interruption recovery
275
+
276
+ A phone call, audio-session conflict, or failed background activation can interrupt recording. When `isRecoveryRequired` is `true`, call `resumeTracking()` after the app enters the foreground.
277
+
278
+ Use an app-owned in-flight guard so repeated foreground events do not issue concurrent resume calls:
279
+
280
+ ```tsx
281
+ import { useEffect, useRef } from "react";
282
+ import { AppState } from "react-native";
283
+ import { useAsleep } from "react-native-asleep";
284
+
285
+ export function useAsleepForegroundRecovery() {
286
+ const asleep = useAsleep();
287
+ const resumeInFlight = useRef(false);
288
+
289
+ useEffect(() => {
290
+ const resumeIfNeeded = (appState: string) => {
291
+ if (
292
+ appState !== "active" ||
293
+ !asleep.isRecoveryRequired ||
294
+ resumeInFlight.current
295
+ ) {
296
+ return;
297
+ }
298
+
299
+ resumeInFlight.current = true;
300
+ void asleep
301
+ .resumeTracking()
302
+ .catch(() => {
303
+ // The classified failure is available reactively as asleep.error.
304
+ })
305
+ .finally(() => {
306
+ resumeInFlight.current = false;
307
+ });
308
+ };
309
+
310
+ resumeIfNeeded(AppState.currentState);
311
+ const subscription = AppState.addEventListener("change", resumeIfNeeded);
312
+
313
+ return () => subscription.remove();
314
+ }, [asleep.isRecoveryRequired, asleep.resumeTracking]);
315
+ }
316
+ ```
317
+
318
+ A resolved `resumeTracking()` promise means the resume request was accepted; it does not prove audio upload has recovered. The SDK keeps `status === "recoveryRequired"` until a later successful upload changes it back to `"tracking"`.
319
+
320
+ `resumeTracking()` is iOS-only and throws `UNSUPPORTED_PLATFORM` on Android.
321
+
322
+ ## 7. Handle structured errors
323
+
324
+ All actions and queries reject with `AsleepError`. Do not use `null`, an empty array, or parsed message text as a generic error channel.
325
+
326
+ ```ts
327
+ import { AsleepError } from "react-native-asleep";
328
+
329
+ try {
330
+ await asleep.startTracking();
331
+ } catch (cause: unknown) {
332
+ if (!(cause instanceof AsleepError)) throw cause;
333
+
334
+ console.log({
335
+ code: cause.code,
336
+ category: cause.category,
337
+ sdkCode: cause.sdkCode,
338
+ caseName: cause.caseName,
339
+ });
340
+ }
341
+ ```
342
+
343
+ Tracking-runtime failures carry an objective recovery classification:
344
+
345
+ | `error.category` | Native state | Required integration behavior |
346
+ |---|---|---|
347
+ | `terminal` | The session is already gone and a separate close event may not follow | Clear app-owned live-session state and allow a new session |
348
+ | `recordingDead` | The recorder stopped, but the native session remains open | Call `stopTracking()` to close it, then start a new session |
349
+ | `recoveryRequired` | The iOS session remains live | Call `resumeTracking()` in the foreground and wait for a successful upload |
350
+ | `transient` | The session survived | Keep tracking and observe later state/events |
351
+ | `unknown` | Not safely classified | Record the error and do not assume tracking is healthy |
352
+
353
+ Only tracking-runtime failures are guaranteed to have `category`; precondition, setup, permission, report, and other action errors may leave it undefined. Use the stable `code` for action-specific behavior.
354
+
355
+ Do not call `stopTracking()` only because `isTracking` became `false`: terminal failures already closed their session. The demonstrated exception is `recordingDead`, where `isTracking` is false but `stopTracking()` is required because native recording stopped without closing the session.
356
+
357
+ Forward the `AsleepError` itself to observability so `cause`, `sdkCode`, and `caseName` remain available. The app decides log severity; the SDK only reports the recovery fact.
358
+
359
+ ## 8. Stop tracking and read reports
360
+
361
+ `stopTracking()` closes the active session and marks the public state closed. The final `sessionId` may also arrive through the native close event. Product cleanup—alarms, app timers, cloud state, and navigation—belongs to the app and should occur only after the SDK stop succeeds or a terminal event proves the session is gone.
362
+
363
+ Report generation may lag behind session close. The wrapper produces `REPORT_NOT_FOUND` when native code resolves without a report payload, but platform SDK failures can arrive under another `AsleepError.code` such as Android `REPORT_ERROR`. Do not blanket-retry every report failure. Until all native not-found codes are normalized by the wrapper, choose retry behavior only for error cases the app has explicitly verified; keep network, authentication, and other failures visible.
364
+
365
+ Report APIs:
366
+
367
+ | Action | Result |
368
+ |---|---|
369
+ | `getReport(sessionId)` | One `AsleepReport`; may throw `REPORT_NOT_FOUND` when native resolves no payload |
370
+ | `getReportList(fromDate, toDate)` | `AsleepSession[]`; an empty array is a valid result |
371
+ | `getAverageReport(fromDate, toDate)` | `AsleepAverageReport`; may throw `REPORT_NOT_FOUND` when native resolves no payload |
372
+ | `deleteSession(sessionId)` | Deletes a session or throws |
373
+
374
+ `getReportList()` currently returns at most 100 sessions and has no public pagination API. Pass dates as `YYYY-MM-DD`.
375
+
376
+ ## 9. Consume analysis consistently
377
+
378
+ `requestAnalysis()` has different promise results:
379
+
380
+ - Android resolves with the analysis payload and also emits `onAnalysisResult`.
381
+ - iOS resolves with `{ status: "requested", timestamp }`; the result arrives later through `onAnalysisResult`.
382
+
383
+ For cross-platform UI, read `analysisResult` and `isAnalyzing` from `useAsleep()` or subscribe to `onAnalysisResult`. The event transition is the only writer of reactive `analysisResult`, preventing an Android promise and event from updating state twice.
384
+
385
+ ```tsx
386
+ import { useAsleep } from "react-native-asleep";
387
+
388
+ export function useLiveSleepAnalysis() {
389
+ const { analysisResult, isAnalyzing, requestAnalysis } = useAsleep();
390
+
391
+ async function refresh() {
392
+ await requestAnalysis();
393
+ // Read `analysisResult`; the promise is not the cross-platform result.
394
+ }
395
+
396
+ return { analysisResult, isAnalyzing, refresh };
397
+ }
398
+ ```
399
+
400
+ Android snake_case event payloads are normalized to camelCase before they reach `analysisResult`.
401
+
402
+ ## 10. Keep optional product features outside the SDK
403
+
404
+ These concerns are intentionally app-owned:
405
+
406
+ - account authentication and cloud synchronization;
407
+ - alarms, widgets, Live Activities, and notifications unrelated to the Android tracking service;
408
+ - report-derived labels, timeline slots, and product metrics;
409
+ - persistent storage and wall-clock duration;
410
+ - permission-denied UI and retry policy;
411
+ - analytics and observability.
412
+
413
+ Integrate them around SDK state and events. Their failure should not silently skip or replace the SDK's required start, stop, restore, or recovery operations.
414
+
415
+ ## Production checklist
416
+
417
+ - [ ] Install an exact package version and create a new native build.
418
+ - [ ] Verify the API key and initialization-failure UI.
419
+ - [ ] Test a cold start with no granted permissions.
420
+ - [ ] Test microphone denial and a later successful request from a user action.
421
+ - [ ] On Android 13+, test both notification grant and denial.
422
+ - [ ] Verify the Android foreground-service notification.
423
+ - [ ] Verify battery exemption, settings return, and the second check.
424
+ - [ ] On Android, start tracking, kill the JavaScript app process, reopen it, and restore the live session.
425
+ - [ ] Verify `initAsleepConfig()` still runs after an Android session is restored.
426
+ - [ ] Keep tracking through background and foreground transitions.
427
+ - [ ] On iOS, trigger an audio interruption and verify foreground recovery through a later upload.
428
+ - [ ] Verify each handled error category against its documented action.
429
+ - [ ] Verify `recordingDead` closes the remaining native session before restart.
430
+ - [ ] Verify a terminal failure does not wait for or synthesize a second close event.
431
+ - [ ] Stop tracking and verify the app distinguishes a pending report from network, authentication, and other failures on both platforms.
432
+ - [ ] Verify analysis UI from `analysisResult` on both platforms.
433
+ - [ ] Run a full-night-length session on representative physical iOS and Android devices.
434
+
435
+ Simulator audio behavior and warm-path testing alone are not sufficient release evidence.
436
+
437
+ ## References
438
+
439
+ - [SDK README](../README.md)
440
+ - [Example app](https://github.com/asleep-ai/asleep-sdk-react-native/tree/main/example)
441
+ - [Asleep developer documentation](https://docs.asleep.ai)
442
+ - [GitHub issues](https://github.com/asleep-ai/asleep-sdk-react-native/issues)
@@ -10,7 +10,7 @@ Pod::Spec.new do |s|
10
10
  s.static_framework = true
11
11
 
12
12
  s.dependency 'ExpoModulesCore'
13
- s.dependency 'AsleepSDK', '3.2.0'
13
+ s.dependency 'AsleepSDK', '3.3.2'
14
14
 
15
15
 
16
16
  # Swift/Objective-C compatibility
@@ -27,23 +27,43 @@ public class AsleepModule: Module {
27
27
  Events("onSetupInProgress")
28
28
  Events("onAnalysisResult")
29
29
 
30
- Function("setup") { (apiKey: String, baseUrl: String?, callbackUrl: String?, service: String?, enableODA: Bool?) in
30
+ // JS validates that exactly one credential form is present: apiKey, or appId + appSecret.
31
+ Function("setup") { (apiKey: String?, appId: String?, appSecret: String?, baseUrl: String?, callbackUrl: String?, service: String?, enableODA: Bool?) in
31
32
  Asleep.setLogger(self)
32
- Asleep.setup(apiKey: apiKey,
33
- baseUrl: URL(string: baseUrl ?? ""),
34
- callbackUrl: URL(string: callbackUrl ?? ""),
35
- service: service,
36
- enableODA: enableODA ?? false,
37
- delegate: self)
33
+ if let appId = appId, let appSecret = appSecret {
34
+ Asleep.setup(appId: appId,
35
+ appSecret: appSecret,
36
+ baseUrl: URL(string: baseUrl ?? ""),
37
+ callbackUrl: URL(string: callbackUrl ?? ""),
38
+ service: service,
39
+ enableODA: enableODA ?? false,
40
+ delegate: self)
41
+ } else {
42
+ Asleep.setup(apiKey: apiKey ?? "",
43
+ baseUrl: URL(string: baseUrl ?? ""),
44
+ callbackUrl: URL(string: callbackUrl ?? ""),
45
+ service: service,
46
+ enableODA: enableODA ?? false,
47
+ delegate: self)
48
+ }
38
49
  }
39
50
 
40
- Function("initAsleepConfig") { (apiKey: String, userId: String?, baseUrl: String?, callbackUrl: String?) in
51
+ Function("initAsleepConfig") { (apiKey: String?, appId: String?, appSecret: String?, userId: String?, baseUrl: String?, callbackUrl: String?) in
41
52
  Asleep.setLogger(self)
42
- Asleep.initAsleepConfig(apiKey: apiKey,
43
- userId: userId,
44
- baseUrl: URL(string: baseUrl ?? ""),
45
- callbackUrl: URL(string: callbackUrl ?? ""),
46
- delegate: self)
53
+ if let appId = appId, let appSecret = appSecret {
54
+ Asleep.initAsleepConfig(appId: appId,
55
+ appSecret: appSecret,
56
+ userId: userId,
57
+ baseUrl: URL(string: baseUrl ?? ""),
58
+ callbackUrl: URL(string: callbackUrl ?? ""),
59
+ delegate: self)
60
+ } else {
61
+ Asleep.initAsleepConfig(apiKey: apiKey,
62
+ userId: userId,
63
+ baseUrl: URL(string: baseUrl ?? ""),
64
+ callbackUrl: URL(string: callbackUrl ?? ""),
65
+ delegate: self)
66
+ }
47
67
  }
48
68
 
49
69
  // Gates SDK log forwarding natively so disabled logs never cross the
@@ -167,6 +187,10 @@ public class AsleepModule: Module {
167
187
  return trackingManager?.getTrackingStatus().sessionId != nil
168
188
  }
169
189
 
190
+ AsyncFunction("hasRequiredPermissions") { () -> Bool in
191
+ return AVAudioSession.sharedInstance().recordPermission == .granted
192
+ }
193
+
170
194
  // Deprecated method for backward compatibility
171
195
  AsyncFunction("requestMicrophonePermission") { () -> Bool in
172
196
  let audioSession = AVAudioSession.sharedInstance()
@@ -294,13 +318,14 @@ extension AsleepModule: AsleepSleepTrackingManagerDelegate {
294
318
  errorInfo["message"] = "Audio recording could not be initialized and the recording engine has been torn down. resumeTracking() will not help; the session must be stopped and restarted."
295
319
  case .cannotActivateInBackground:
296
320
  errorInfo["code"] = "CANNOT_ACTIVATE_IN_BACKGROUND"
297
- errorInfo["message"] = "Recording could not resume in background. resumeTracking() must be called in foreground."
321
+ errorInfo["message"] = "Recording could not resume in background. The SDK retries when the app becomes active; call resumeTracking() in foreground if uploads do not resume."
298
322
  default:
299
323
  errorInfo["code"] = "UNKNOWN_ERROR"
300
324
  errorInfo["caseName"] = String(describing: error)
301
325
  }
302
326
  // (error as NSError).code is the Swift enum declaration ordinal, not the
303
327
  // documented Asleep error code; kept for backward compatibility only.
328
+ // It shifts when the SDK adds enum cases (3.3.x moved 38/39 to 59/60).
304
329
  errorInfo["errorCode"] = (error as NSError).code
305
330
  // Documented numeric code (10000-34999) via the SDK's errorCode computed
306
331
  // property — the v3.2.0+ recommended API (Asleep.Interface.swift). This is
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-asleep",
3
- "version": "1.1.0",
3
+ "version": "2.0.0",
4
4
  "description": "Asleep SDK for React Native",
5
5
  "main": "build/index.js",
6
6
  "types": "build/index.d.ts",
@@ -44,27 +44,27 @@
44
44
  "expo-module.config.json",
45
45
  "*.podspec",
46
46
  "LICENSE.md",
47
- "CHANGELOG.md"
47
+ "CHANGELOG.md",
48
+ "docs/INTEGRATION.md",
49
+ "docs/INTEGRATION.ko.md"
48
50
  ],
49
51
  "devDependencies": {
50
52
  "@types/react": "^19.0.0",
51
53
  "expo-module-scripts": "^5.0.8",
52
54
  "expo-modules-core": "^1.12.19",
53
55
  "oxfmt": "^0.51.0",
54
- "oxlint": "^1.66.0",
55
- "zustand": "^5.0.12"
56
+ "oxlint": "^1.66.0"
56
57
  },
57
58
  "peerDependencies": {
58
59
  "expo": "*",
59
60
  "expo-modules-core": ">=1.12.0",
60
61
  "react": ">=18.2.0",
61
- "react-native": ">=0.74.0",
62
- "zustand": ">=5.0.0"
62
+ "react-native": ">=0.74.0"
63
63
  },
64
64
  "peerDependenciesMeta": {
65
65
  "expo": {
66
66
  "optional": true
67
67
  }
68
68
  },
69
- "packageManager": "pnpm@10.30.3"
69
+ "packageManager": "pnpm@12.21.0"
70
70
  }