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.
package/README.md CHANGED
@@ -1,56 +1,85 @@
1
1
  # react-native-asleep
2
2
 
3
- Advanced sleep tracking SDK for React Native applications, powered by Asleep's AI technology.
3
+ [English](./README.md) | [한국어](./README.ko.md)
4
4
 
5
- ## Status
5
+ Sleep tracking for React Native and Expo apps, powered by Asleep's AI technology. The SDK uses the device microphone, requires no wearable, and exposes one React hook plus typed data models for iOS and Android.
6
6
 
7
- This SDK is under active development. v2 has a deliberately small public surface; pin to exact versions and review the [CHANGELOG](./CHANGELOG.md) before upgrading.
7
+ > This SDK is under active development. v2 has a deliberately small public surface. Pin exact versions and review the [changelog](./CHANGELOG.md) before upgrading.
8
8
 
9
- ## Overview
9
+ ## What is included
10
10
 
11
- Non-invasive sleep tracking via the device microphone — no wearables required. Detects sleep stages and produces detailed reports. Works on iOS and Android, exposes a single React hook plus typed data models.
11
+ - Microphone-based sleep tracking and Android service restoration
12
+ - Sleep reports, session lists, average reports, and in-progress analysis
13
+ - A shared state model across iOS and Android
14
+ - Structured `AsleepError` values with recovery categories
15
+ - `useAsleep()` for React and a small `Asleep` API for non-React code
16
+
17
+ ## Requirements
18
+
19
+ | Component | Minimum |
20
+ |---|---|
21
+ | React Native | 0.74 |
22
+ | React | 18.2 |
23
+ | iOS deployment target | 14.0 |
24
+ | Android `minSdkVersion` | 24 |
25
+
26
+ The example app is currently verified with React Native 0.79.2, Expo 53, React 19.0.0, and Android compile/target SDK 34.
27
+
28
+ Bundled native SDK versions. The React Native package follows its own semver; its version number does not mirror the native SDKs.
29
+
30
+ | react-native-asleep | iOS SDK | Android SDK |
31
+ |---|---|---|
32
+ | 2.1.0 | 3.3.3 | 3.3.1 |
33
+ | 2.0.0 | 3.3.2 | 3.3.1 |
34
+ | 1.0.17 – 1.2.0 | 3.2.0 | 3.2.1 |
35
+ | 1.0.15 | 3.2.0 | 3.2.0 |
36
+ | 1.0.14 | 3.1.8 | 3.1.5 |
37
+ | 1.0.13 | 3.1.6 | 3.1.4 |
38
+
39
+ 1.2.0 already contained the breaking v2 API; 2.0.0 is the semver-correct release of that API.
12
40
 
13
41
  ## Installation
14
42
 
15
- ### For Expo Managed Projects
43
+ ### Expo projects
16
44
 
17
45
  ```bash
18
46
  expo install react-native-asleep
19
47
  ```
20
48
 
21
- ### For Bare React Native Projects
22
-
23
- This library uses the Expo Modules API. Bare RN projects need Expo modules installed once; after that, autolinking handles the rest — no `react-native.config.js` or manual native linking.
49
+ This package contains native modules, so create a new development or store build after installing or upgrading it. It does not run in Expo Go and cannot be upgraded through an OTA update alone.
24
50
 
25
- 1. **Install Expo modules** (skip if already installed):
51
+ ### Bare React Native projects
26
52
 
27
- ```bash
28
- npx install-expo-modules@latest
29
- ```
53
+ This library uses the Expo Modules API. Install Expo modules once if the app does not already use them:
30
54
 
31
- It prompts `Install the Expo CLI integration? (Y/n)` — either answer wires the bare modules. See the [Expo bare guide](https://docs.expo.dev/bare/installing-expo-modules/) for details.
55
+ ```bash
56
+ npx install-expo-modules@latest
57
+ npm install react-native-asleep
58
+ ```
32
59
 
33
- 2. **Install the package** (`npm install` / `pnpm add` / `yarn add`):
60
+ Then install iOS pods:
34
61
 
35
- ```bash
36
- npm install react-native-asleep
37
- ```
62
+ ```bash
63
+ cd ios
64
+ bundle install
65
+ bundle exec pod install
66
+ ```
38
67
 
39
- 3. **iOS**: in `ios/`, run `bundle install` (once) then `bundle exec pod install`. The project's `Gemfile` avoids host Ruby/CocoaPods conflicts. **Android**: no extra step.
68
+ Android needs no additional linking step.
40
69
 
41
- #### Static framework note
70
+ #### Static frameworks
42
71
 
43
- The iOS podspec sets `s.static_framework = true`. **Do not add `use_frameworks!` to your `Podfile`.** If your project already requires it, pin to static linkage:
72
+ The iOS pod is a static framework. Do not add `use_frameworks!` only for this package. If the app already requires it, use static linkage:
44
73
 
45
74
  ```ruby
46
75
  use_frameworks! :linkage => :static
47
76
  ```
48
77
 
49
- `:linkage => :dynamic` is known to break Expo SDK 55 builds (see [expo/expo#44487](https://github.com/expo/expo/issues/44487), [#41556](https://github.com/expo/expo/issues/41556)).
78
+ Dynamic linkage is known to break Expo SDK 55 builds; see [expo/expo#44487](https://github.com/expo/expo/issues/44487) and [expo/expo#41556](https://github.com/expo/expo/issues/41556).
50
79
 
51
- #### Monorepo / workspace projects
80
+ #### Monorepos and workspaces
52
81
 
53
- If `react-native-asleep` is hoisted to a parent `node_modules`, configure autolinking in your app's `package.json`:
82
+ If `react-native-asleep` is hoisted to a parent `node_modules`, configure Expo autolinking in the app's `package.json`:
54
83
 
55
84
  ```json
56
85
  {
@@ -62,49 +91,22 @@ If `react-native-asleep` is hoisted to a parent `node_modules`, configure autoli
62
91
  }
63
92
  ```
64
93
 
65
- #### Reference configuration
66
-
67
- The [example app](./example) is the reference setup. Adjacent versions are expected to work but aren't verified.
94
+ ## Native configuration
68
95
 
69
- | Component | Version |
70
- | --------------------------- | -------- |
71
- | React Native | 0.79.2 |
72
- | Expo | 53 |
73
- | React | 19.0.0 |
74
- | iOS deployment target | 14.0 |
75
- | Android `minSdkVersion` | 24 |
76
- | Android `compileSdkVersion` | 34 |
77
- | Android `targetSdkVersion` | 34 |
78
-
79
- #### Bundled native SDK versions
80
-
81
- | Platform | Native SDK version |
82
- |---|---|
83
- | iOS | 3.2.0 |
84
- | Android | 3.2.1 |
96
+ Create an API key in the [Asleep Dashboard](https://dashboard.asleep.ai).
85
97
 
86
- ## Setup
98
+ ### iOS
87
99
 
88
- ### 1. Get API Key
100
+ Your app must declare microphone usage and background audio.
89
101
 
90
- 1. Visit [Asleep Dashboard](https://dashboard.asleep.ai)
91
- 2. Create an account and generate your API key
92
- 3. Note your API key for configuration
93
-
94
- ### 2. Permissions
95
-
96
- #### iOS — declared by your app
97
-
98
- Add the microphone usage description and audio background mode.
99
-
100
- **For Expo Managed Projects (app.json):**
102
+ For Expo projects:
101
103
 
102
104
  ```json
103
105
  {
104
106
  "expo": {
105
107
  "ios": {
106
108
  "infoPlist": {
107
- "NSMicrophoneUsageDescription": "This app needs microphone access for sleep tracking",
109
+ "NSMicrophoneUsageDescription": "This app uses the microphone for sleep tracking.",
108
110
  "UIBackgroundModes": ["audio"]
109
111
  }
110
112
  }
@@ -112,264 +114,336 @@ Add the microphone usage description and audio background mode.
112
114
  }
113
115
  ```
114
116
 
115
- **For Bare React Native Projects (ios/YourApp/Info.plist):**
117
+ For bare React Native projects, add the equivalent entries to the app's `Info.plist`:
116
118
 
117
119
  ```xml
118
120
  <key>NSMicrophoneUsageDescription</key>
119
- <string>This app needs microphone access for sleep tracking</string>
121
+ <string>This app uses the microphone for sleep tracking.</string>
120
122
  <key>UIBackgroundModes</key>
121
123
  <array>
122
124
  <string>audio</string>
123
125
  </array>
124
126
  ```
125
127
 
126
- #### Android — declared by the library
127
-
128
- The library declares its own permissions; the manifest merger combines them into your app. No `<uses-permission>` entries are needed in your `AndroidManifest.xml`. For reference, the library declares:
128
+ ### Android
129
129
 
130
- ```xml
131
- <uses-permission android:name="android.permission.INTERNET" />
132
- <uses-permission android:name="android.permission.RECORD_AUDIO" />
133
- <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
134
- <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
135
- <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
136
- <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
137
- <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
138
- <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
139
- ```
130
+ The library declares its required permissions and foreground service in its manifest. The manifest merger adds them to the app, so do not duplicate them only for this SDK.
140
131
 
141
- `RECORD_AUDIO` and `POST_NOTIFICATIONS` are runtime permissions — request them via `useAsleep().requestRequiredPermissions()` (or `PermissionsAndroid`) before starting tracking.
132
+ `RECORD_AUDIO` is required at runtime. On Android 13 and later, `requestRequiredPermissions()` also requests `POST_NOTIFICATIONS` so the foreground-service notification can remain visible, but notification denial does not make its return value `false`.
142
133
 
143
134
  ## Quick Start
144
135
 
136
+ The required startup order is:
137
+
138
+ ```text
139
+ check for an existing Android tracking service
140
+ → initialize the SDK configuration
141
+ → check battery optimization
142
+ → request permissions from a user action
143
+ → start tracking
144
+ ```
145
+
146
+ Always call `initAsleepConfig()` after `checkAndRestoreTracking()`, including when an Android service session was restored. On iOS, the restoration check is a required cross-platform prerequisite but reports no persistent service.
147
+
145
148
  ```tsx
146
- import { useEffect } from "react";
149
+ import { useEffect, useRef, useState } from "react";
147
150
  import { Button, Text, View } from "react-native";
148
151
  import { AsleepError, useAsleep } from "react-native-asleep";
149
152
 
150
- function SleepTracker() {
151
- const {
152
- status,
153
- isTracking,
154
- error,
155
- initAsleepConfig,
156
- checkAndRestoreTracking,
157
- checkBatteryOptimization,
158
- hasRequiredPermissions,
159
- requestRequiredPermissions,
160
- startTracking,
161
- stopTracking,
162
- } = useAsleep();
163
-
164
- // Required order before startTracking: configure -> restore any in-progress session -> battery check
153
+ export function SleepTracker() {
154
+ const asleep = useAsleep();
155
+ const hasBootstrapped = useRef(false);
156
+ const [isReady, setIsReady] = useState(false);
157
+ const [bootstrapMessage, setBootstrapMessage] = useState<string | null>(null);
158
+
165
159
  useEffect(() => {
166
- (async () => {
167
- await initAsleepConfig({ apiKey: "YOUR_API_KEY" });
168
- await checkAndRestoreTracking();
169
- await checkBatteryOptimization();
170
- })();
171
- }, []);
172
-
173
- const handleStart = async () => {
160
+ if (hasBootstrapped.current) return;
161
+ hasBootstrapped.current = true;
162
+
163
+ async function bootstrap() {
164
+ await asleep.checkAndRestoreTracking();
165
+
166
+ const config = { apiKey: "YOUR_API_KEY" };
167
+ await asleep.initAsleepConfig(config);
168
+
169
+ await asleep.checkBatteryOptimization();
170
+ setIsReady(true);
171
+ }
172
+
173
+ void bootstrap().catch((cause: unknown) => {
174
+ setBootstrapMessage(cause instanceof Error ? cause.message : String(cause));
175
+ });
176
+ }, [
177
+ asleep.checkAndRestoreTracking,
178
+ asleep.initAsleepConfig,
179
+ asleep.checkBatteryOptimization,
180
+ ]);
181
+
182
+ async function start() {
174
183
  try {
175
- if (!(await hasRequiredPermissions())) {
176
- const granted = await requestRequiredPermissions();
184
+ if (!(await asleep.hasRequiredPermissions())) {
185
+ const granted = await asleep.requestRequiredPermissions();
177
186
  if (!granted) return;
178
187
  }
179
188
 
180
- await startTracking({
181
- android: { notification: { title: "Sleep tracking", text: "Recording..." } },
189
+ const battery = await asleep.checkBatteryOptimization();
190
+ if (!battery.exempted) {
191
+ await asleep.requestBatteryOptimizationExemption();
192
+ return; // Check again after the user returns from Android settings.
193
+ }
194
+
195
+ await asleep.startTracking({
196
+ android: {
197
+ notification: {
198
+ title: "Sleep tracking",
199
+ text: "Sleep analysis is running.",
200
+ },
201
+ },
182
202
  });
183
- } catch (cause) {
203
+ } catch (cause: unknown) {
184
204
  if (!(cause instanceof AsleepError)) throw cause;
185
- // `error` is also updated reactively and rendered below.
205
+ // The same AsleepError is also available reactively as asleep.error.
186
206
  }
187
- };
207
+ }
208
+
209
+ async function stop() {
210
+ try {
211
+ await asleep.stopTracking();
212
+ } catch (cause: unknown) {
213
+ if (!(cause instanceof AsleepError)) throw cause;
214
+ }
215
+ }
216
+
217
+ const shouldStop =
218
+ asleep.isTracking || asleep.error?.category === "recordingDead";
188
219
 
189
220
  return (
190
221
  <View>
191
- <Text>Status: {status}</Text>
192
- {error ? <Text>{error.message}</Text> : null}
193
- <Button title={isTracking ? "Stop" : "Start"} onPress={isTracking ? stopTracking : handleStart} />
222
+ <Text>Status: {asleep.status}</Text>
223
+ {bootstrapMessage ? <Text>{bootstrapMessage}</Text> : null}
224
+ {asleep.error ? <Text>{asleep.error.message}</Text> : null}
225
+ <Button
226
+ title={shouldStop ? "Stop tracking" : "Start tracking"}
227
+ disabled={!isReady}
228
+ onPress={shouldStop ? stop : start}
229
+ />
194
230
  </View>
195
231
  );
196
232
  }
197
233
  ```
198
234
 
199
- For ODA (On-Device Analysis) mode, call `setup()` instead of `initAsleepConfig()`. See [`example/App.tsx`](./example/App.tsx) for the full flow including report fetch and event-driven state.
235
+ Call `requestRequiredPermissions()` from a user-driven interaction. `startTracking()` checks permission but never opens a permission dialog. On Android, return from the battery settings screen and call `checkBatteryOptimization()` again before retrying.
236
+
237
+ `await initAsleepConfig()` resolves after the native user join completes and rejects when it fails, on both platforms. Await the action rather than `onUserJoined`: the Android restored-service fast path resolves without emitting that event. A second call while one is still in progress rejects with `OPERATION_IN_PROGRESS`, so finish (or fail) one init before starting another, for example when switching users. The native SDKs ignore an init, with no callback, while tracking is starting or stopping or while a previous init is still waiting for its response; on iOS the call then rejects with `INITIALIZATION_FAILED` after 60 seconds (a late SDK answer to it is applied and emits `onUserJoined`/`onUserJoinFailed` only if no newer `initAsleepConfig()` has started; otherwise it is ignored and per-user calls stay blocked until the next successful init), and a new call made while the SDK is still busy with the previous one can time out the same way; on Android it stays pending. Avoid calling `initAsleepConfig()` during a start or stop.
238
+
239
+ The `recordingDead` category is another deliberate exception: `isTracking` is `false`, but the native session remains open, so the action must still call `stopTracking()` before starting a new session.
200
240
 
201
- ## API surface
241
+ For ODA (On-Device Analysis), `setup()` is the configuration entry point for a new ODA session. This Quick Start documents service mode; `setup()` cannot run while a restored session is tracking.
202
242
 
203
- The v2 API has one reactive hook, one thin imperative escape hatch, and named value/type exports:
243
+ ## Core API
204
244
 
205
245
  ```ts
206
246
  import {
207
247
  Asleep,
208
248
  AsleepError,
209
249
  useAsleep,
210
- type AsleepAverageReport,
211
250
  type AsleepReport,
212
251
  type AsleepSession,
213
252
  type TrackingStatus,
214
253
  } from "react-native-asleep";
215
254
  ```
216
255
 
217
- `useAsleep()` attaches the native listeners while mounted and returns the public state plus bound actions.
256
+ ### Credentials
257
+
258
+ `setup()` and `initAsleepConfig()` accept exactly one credential form, typed as `AsleepCredentials`:
259
+
260
+ ```ts
261
+ const asleep = useAsleep();
262
+
263
+ await asleep.initAsleepConfig({ apiKey: "YOUR_API_KEY", userId });
264
+ // or token authentication
265
+ await asleep.initAsleepConfig({ appId: "YOUR_APP_ID", appSecret: "YOUR_APP_SECRET", userId });
266
+ ```
267
+
268
+ Mixing `apiKey` with `appId`/`appSecret` is a type error. At runtime, passing neither form, both forms, an incomplete pair, or an empty string rejects with `AsleepError` code `INVALID_ARGUMENT` before any native call. Keep the secret out of source control like the API key.
269
+
270
+ ### Device registration
271
+
272
+ `setup()` can register the hardware product the app runs on with Asleep (`POST customer/v1/products`). Pass `productInfo` with either credential form:
273
+
274
+ ```ts
275
+ import type { AsleepProductInfo } from "react-native-asleep";
276
+
277
+ const productInfo: AsleepProductInfo = {
278
+ model: "YOUR_PRODUCT_MODEL",
279
+ identifierType: "serial", // or "mac_address"
280
+ identifierValue: deviceSerialNumber,
281
+ };
282
+ await asleep.setup({ apiKey: "YOUR_API_KEY", productInfo });
283
+ ```
284
+
285
+ Behavior as of iOS SDK 3.3.3 and Android SDK 3.3.1:
286
+
287
+ - Only `setup()` accepts `productInfo`; `initAsleepConfig()` does not. Sessions created after a successful registration are bound to the product, so register before `startTracking()`. Omitting `productInfo` skips registration and keeps the previous `setup()` behavior.
288
+ - `model` is 1-100 characters and `identifierValue` 1-255 characters; neither may be blank, and values are sent untrimmed. `identifierType` is `"serial"` or `"mac_address"`. Invalid or unknown fields reject with `INVALID_ARGUMENT` before any native call.
289
+ - Registration is idempotent per identifier: the same `identifierType` and `identifierValue` return the existing product credential, and a device that already holds a credential for the same credentials owner and the same `productInfo` makes no network call. The server keeps the first `model` registered for an identifier; it cannot be changed through the SDK.
290
+ - A different identifier creates a new product on the server, which may be billable. Use the device's real serial number or MAC address, and never send placeholder or test values with production credentials.
291
+ - Changing the `apiKey` or `appId` drops the stored credential, and the next `setup()` with `productInfo` registers again.
292
+ - Registration blocks `setup()`. A failure fails the whole setup with code `SETUP_FAILED` and `error.sdkCode` 13400 (rejected: a 4xx other than 429, or failed input checks; fix the input or the contract) or 13000 (network, 5xx, 429, or an unreadable response; retry later). The SDK retries network failures, 5xx and 429 after 2, 4 and 8 seconds before reporting 13000. Offline, the failure can take about 1.5-3 minutes to arrive. After a failure the native SDK is left unconfigured and `setup()` can be called again.
293
+ - On Android, `setup()` resolves after registration and setup complete. On iOS, `setup()` returns once the native call starts, and `isSetupComplete` can be `true` before registration finishes. Wait for `onSetupDidComplete` or `onSetupDidFail` through `addEventListener()` before starting tracking, and do not call `setup()` again until one arrives: the native SDK ignores a second `setup()` while one is running, without a callback.
294
+
295
+ ### `useAsleep()`
218
296
 
219
- ### Public state
297
+ The primary React API. It attaches the ref-counted native listeners while mounted and returns state plus actions from the shared SDK store.
220
298
 
221
- The store keeps native facts internally and derives the public booleans from `status`:
299
+ Important state:
222
300
 
223
301
  | Field | Meaning |
224
302
  |---|---|
225
303
  | `status` | `"idle"`, `"tracking"`, `"paused"`, or `"recoveryRequired"` |
226
- | `isTracking` | `true` for every status except `"idle"`; recovery-required sessions are still live |
227
- | `isTrackingPaused` | `true` only while `status` is `"paused"` |
228
- | `isRecoveryRequired` | `true` only while `status` is `"recoveryRequired"` |
229
- | `isSetupInProgress` / `isSetupComplete` | Derived setup lifecycle |
230
- | `sessionId` / `userId` | Current native identifiers |
231
- | `error` | Last `AsleepError`, or `null` |
232
- | `analysisResult` / `isAnalyzing` | Latest analysis event and request state |
233
- | `didClose` / `isODAEnabled` / `log` | Session history, mode, and opt-in debug log |
304
+ | `isTracking` | `true` for every status except `"idle"` |
305
+ | `isTrackingPaused` | The native session is temporarily interrupted |
306
+ | `isRecoveryRequired` | iOS needs an explicit foreground `resumeTracking()` |
307
+ | `isSetupComplete` | SDK configuration completed |
308
+ | `sessionId`, `userId` | Current native identifiers |
309
+ | `analysisResult`, `isAnalyzing` | Latest analysis event and request state |
310
+ | `error` | The latest `AsleepError`, or `null` |
234
311
 
235
- `trackingStartTime`, listener bookkeeping, and mutable setters are internal implementation details.
312
+ Important actions:
236
313
 
237
- ### Actions
314
+ | Area | Actions |
315
+ |---|---|
316
+ | Configuration and restore | `setup`, `initAsleepConfig`, `checkAndRestoreTracking` |
317
+ | Prerequisites | `checkBatteryOptimization`, `requestBatteryOptimizationExemption`, `hasRequiredPermissions`, `requestRequiredPermissions` |
318
+ | Tracking | `startTracking`, `stopTracking`, `resumeTracking` |
319
+ | Reports | `getReport`, `getReportList`, `getAverageReport`, `deleteSession`, `reanalyze` |
320
+ | Analysis | `requestAnalysis` |
321
+ | User metadata | `saveUserMetadata`, `fetchUserMetadata` |
322
+ | Utilities | `addEventListener`, `enableLog`, `clearError` |
323
+
324
+ ### Analysis range at stop
238
325
 
239
- The hook exposes:
326
+ `stopTracking()` accepts an optional window that the server analyzes instead of the whole recording:
240
327
 
241
- - Setup and restore: `setup`, `initAsleepConfig`, `checkAndRestoreTracking`
242
- - Tracking: `startTracking`, `stopTracking`, `resumeTracking`
243
- - Reports: `getReport`, `getReportList`, `getAverageReport`, `deleteSession`, `requestAnalysis`
244
- - Prerequisites: `checkBatteryOptimization`, `requestBatteryOptimizationExemption`, `hasRequiredPermissions`, `requestRequiredPermissions`
245
- - Utilities: `enableLog`, `clearError`, `addEventListener`, and the deprecated no-op `setCustomNotification`
328
+ ```ts
329
+ await asleep.stopTracking({
330
+ analysisRange: { start: bedtime, end: new Date() },
331
+ });
332
+ ```
246
333
 
247
- `requestAnalysis()` returns the Android analysis result or the iOS `{ status: "requested", timestamp }` acknowledgement. On both platforms, `onAnalysisResult` is the only writer of reactive `analysisResult`.
334
+ `start` must be at least one whole second before `end`, and both must be valid `Date` objects; otherwise the call rejects with `INVALID_ARGUMENT` before any native call. Without options, `stopTracking()` behaves exactly as before. The server may silently ignore a range it does not accept and analyze the full session; the session still closes normally and the app receives no signal that the range was dropped, so verify the result with `getReport()` when the window matters. Keep the range inside the measured session: a range that starts before the native session start was verified on devices to produce a session with no analyzed data (`missing_data_ratio` 1.0, `TOO_MANY_DEFECTS_IN_SLEEP_STAGES`), so derive `start` from a time you know is after tracking began rather than from an earlier app-side timestamp.
248
335
 
249
- ### Non-React contexts
336
+ ### Reanalysis
250
337
 
251
- Use `Asleep` for background callbacks and other code where hooks are unavailable:
338
+ `reanalyze(sessionId, options?)` asks the server to analyze a closed session again, optionally restricted to `options.analysisRange`:
252
339
 
253
340
  ```ts
254
- import { Asleep } from "react-native-asleep";
341
+ await asleep.reanalyze(sessionId, { analysisRange: { start, end } });
342
+ // Resolves when the server accepted the request, not when analysis finished.
343
+ // Poll getReport(sessionId) until report.session.state is "COMPLETE".
344
+ ```
255
345
 
256
- // Required when no mounted useAsleep() hook owns the native listener lifecycle.
257
- const teardown = Asleep.initialize();
346
+ > **Reanalyzing without a range replaces any earlier range on the server**, including one passed to `stopTracking({ analysisRange })`. Pass the range again to keep it.
258
347
 
259
- const unsubscribe = Asleep.subscribe(({ status, error }) => {
260
- console.log(status, error?.code);
261
- });
348
+ An empty `sessionId` or an invalid range rejects with `INVALID_ARGUMENT` before any native call, and calling before the most recent `initAsleepConfig()` has resolved, while a re-init is in progress, or after it failed rejects with `MISSING_PREREQUISITE`. Server failures reject with code `REANALYZE_FAILED` and keep the SDK code in `error.sdkCode`: 30000 (generic/network), 30400, 30401, 30403, 30404, 30409 (reanalysis already in progress: back off, do not retry unboundedly), 30410 (data retention expired), 30422 (the session is still tracking), 30500.
262
349
 
263
- const offAnalysis = Asleep.addEventListener("onAnalysisResult", (result) => {
264
- console.log(result);
265
- });
350
+ ### User metadata
266
351
 
267
- await Asleep.getState().stopTracking();
352
+ After `initAsleepConfig()` completes, the app can save optional profile data that the server uses for analysis:
268
353
 
269
- offAnalysis();
270
- unsubscribe();
271
- teardown();
272
- ```
354
+ ```ts
355
+ import type { AsleepUserMetadata } from "react-native-asleep";
273
356
 
274
- `initialize()` is ref-counted, so it is safe to use alongside mounted hooks. Importing the package alone does not attach native listeners.
357
+ const metadata: AsleepUserMetadata = { birthYear: 1990, gender: "female", height: 165.5 };
358
+ await asleep.saveUserMetadata(metadata);
275
359
 
276
- On iOS, `isRecoveryRequired` becomes `true` when recording cannot resume while the app is in the background. After the app returns to the foreground, call `resumeTracking()`. The flag clears only after the next successful audio upload. `resumeTracking()` is iOS-only and rejects with `UNSUPPORTED_PLATFORM` on Android.
360
+ const saved = await asleep.fetchUserMetadata(); // AsleepUserMetadata | null
361
+ ```
277
362
 
278
- ## Tracking lifecycle and platform compensations
363
+ Every field is optional and omitted fields are not sent. Out-of-range values reject with `INVALID_ARGUMENT` before any native call: `birthYear` 1900-2100, `birthMonth` 1-12, `birthDay` 1-31 (integers), `height` 1-500 cm, `weight` 1-1000 kg, and `gender` one of `"male"`, `"female"`, `"non_binary"`, `"other"`, `"prefer_not_to_say"`. Call them after the most recent `initAsleepConfig()` has resolved. Calling them before that, while a re-init is in progress, or after it failed rejects with `MISSING_PREREQUISITE`, so a failed re-init never reads or writes the previous user's profile. `setup()` also invalidates the user config: call `initAsleepConfig()` again after it. Native failures keep the SDK code in `error.sdkCode`: 27400 (server validation, code `INVALID_ARGUMENT`), 27000 (`SAVE_USER_METADATA_FAILED`), 27100 (`FETCH_USER_METADATA_FAILED`). `fetchUserMetadata()` resolves `null` when nothing has been saved.
279
364
 
280
- The library handles a number of platform quirks internally so JS sees a consistent event model:
365
+ ### `Asleep`
281
366
 
282
- - iOS 3.2.1 `closeSessionSilently()` on 403/429 tears down a session without firing `didClose` — the wrapper detects terminal error codes and resets `isTracking` / `isAnalyzing` itself.
283
- - Android SDK 3.2.x emits both `onFail` and `onFinish` for fatal codes — the wrapper suppresses the spurious `onTrackingClosed` so JS doesn't misread a fatal error as a clean close.
284
- - iOS interruption recovery may emit duplicate `didResume` events — the wrapper deduplicates while still clearing `error`.
285
- - iOS audio initialization failure stops recording without closing the native session — stop and restart the session; `resumeTracking()` cannot recover it.
367
+ Use the imperative escape hatch where React hooks are unavailable:
286
368
 
287
- See [AGENTS.md](./AGENTS.md#native-behavior-compensations) for the full table including upstream SDK versions and rationale.
369
+ ```ts
370
+ import { Asleep } from "react-native-asleep";
288
371
 
289
- ## Error classification
372
+ const releaseListeners = Asleep.initialize();
373
+ const unsubscribe = Asleep.subscribe((state) => {
374
+ console.log(state.status, state.error?.code);
375
+ });
290
376
 
291
- Every failed action and native failure event produces an `AsleepError`, which extends `Error`:
377
+ console.log(Asleep.getState().status);
292
378
 
293
- ```ts
294
- class AsleepError extends Error {
295
- readonly code: string;
296
- readonly category?: "terminal" | "recordingDead" | "recoveryRequired" | "transient" | "unknown";
297
- readonly sdkCode?: number;
298
- readonly caseName?: string;
299
- readonly cause?: unknown;
300
- }
379
+ unsubscribe();
380
+ releaseListeners();
301
381
  ```
302
382
 
303
- Branch on the stable `code`, render `message`, and forward the error itself to observability tooling. Tracking failures also carry the library's objective recovery classification in `category`; the app decides what severity to record:
383
+ `Asleep.initialize()` is ref-counted and must be paired with its returned cleanup function. Importing the package alone does not attach native listeners.
304
384
 
305
- | `category` | Meaning | Suggested app-side severity |
306
- |---|---|---|
307
- | `terminal` | Native session is gone; no `onTrackingClosed` will follow. Start a new session. | error |
308
- | `recordingDead` | Recorder torn down but the session is still open; `stopTracking()` then start again. | error |
309
- | `recoveryRequired` | Tracking is alive; call `resumeTracking()` in the foreground (`isRecoveryRequired` is also set). | warning |
310
- | `transient` | The native session survived (e.g. one upload window failed after internal retries); later uploads continue. | warning |
311
- | `unknown` | Unclassified code — do not assume it is benign. | error |
385
+ ### Errors
386
+
387
+ Every failed action throws `AsleepError`; the same error is stored in `useAsleep().error` when applicable.
312
388
 
313
389
  ```ts
314
- const { error } = useAsleep();
315
-
316
- useEffect(() => {
317
- if (!error) return;
318
- if (error.category === "recoveryRequired" || error.category === "transient") {
319
- analytics.track("asleep_recoverable_error", {
320
- code: error.code,
321
- sdkCode: error.sdkCode,
322
- category: error.category,
323
- });
324
- } else {
325
- Sentry.captureException(error);
390
+ try {
391
+ await asleep.startTracking();
392
+ } catch (cause: unknown) {
393
+ if (cause instanceof AsleepError) {
394
+ console.log(cause.code, cause.category, cause.sdkCode);
326
395
  }
327
- }, [error]);
396
+ }
328
397
  ```
329
398
 
330
- `sdkCode` is the numeric code documented by the native Asleep SDKs. The legacy `errorCode` event-payload field remains for wire compatibility but is deprecated: on iOS it is a Swift enum ordinal from NSError bridging, not the documented code.
399
+ Use `code` for stable machine branching and `message` for display. Runtime tracking failures can also have one of these recovery categories:
331
400
 
332
- All actions, including report queries, throw `AsleepError` on failure. Queries no longer return `null` or `[]` as failure sentinels. Successful actions clear only the error that was present when the native call began; a classified failure event arriving during the await is preserved.
401
+ | Category | Meaning |
402
+ |---|---|
403
+ | `terminal` | The native session is already gone |
404
+ | `recordingDead` | Recording stopped but the native session remains open |
405
+ | `recoveryRequired` | The live iOS session needs a foreground resume |
406
+ | `transient` | The native session survived the failure |
407
+ | `unknown` | The failure is not classified; do not assume it is recoverable |
333
408
 
334
- ## Best practices
409
+ See the integration guide for the required action for each category.
335
410
 
336
- - **Permission flow**: use `hasRequiredPermissions()` for a non-interactive check, then call `requestRequiredPermissions()` from a user-initiated flow. `startTracking()` never opens a permission dialog and throws `PERMISSION_DENIED` when permission is missing.
337
- - **Battery optimization (Android, required)**: long sessions get killed without an exemption. Call `checkBatteryOptimization()` before `startTracking()`; if not exempted, call `requestBatteryOptimizationExemption()` and follow the system prompt. iOS's no-op call keeps cross-platform code uniform.
338
- - **Error handling**: gate log severity on `useAsleep().error?.category` and switch on `error.code` for category-specific UI rather than parsing message text.
339
- - **Non-React lifecycle**: pair every `Asleep.initialize()` with its returned teardown function.
411
+ ## Production integration
340
412
 
341
- ## Migrating from 1.x
413
+ The README covers installation and the first successful tracking flow. Before shipping, read the [Integration Guide](./docs/INTEGRATION.md) for:
342
414
 
343
- v2 deliberately removes the parallel and mutable v1 surfaces:
415
+ - cold-start restoration and listener ownership
416
+ - app-owned versus SDK-owned state
417
+ - Android foreground-service and battery behavior
418
+ - iOS interruption recovery
419
+ - recovery-category handling
420
+ - analysis and report timing
421
+ - real-device release checks
344
422
 
345
- 1. `error: string | null` is now `AsleepError | null`. Render `error?.message` and branch on `error?.code`.
346
- 2. `errorInfo` is removed. Read `error.category`, `error.sdkCode`, and `error.caseName`.
347
- 3. Report and analysis queries throw `AsleepError` on failure instead of returning `null` or `[]`. A session that has no report surfaces as code `REPORT_NOT_FOUND`; an empty report list still resolves to `[]`.
348
- 4. Public state setters are removed. Native events and SDK actions are the sole state writers; `clearError()` remains public.
349
- 5. `getTrackingDurationMinutes()` is removed and `trackingStartTime` is internal. Apps own wall-clock duration.
350
- 6. `requestMicrophonePermission()` is removed. Use `requestRequiredPermissions()`.
351
- 7. `startTracking()` no longer requests permission. Check with `hasRequiredPermissions()`, explicitly request if needed, then start.
352
- 8. The default export, `Asleep` class, `AsleepSDK`, and raw `asleepStore` export are removed. Use `useAsleep()` or the named `Asleep` escape hatch.
353
- 9. `zustand` is no longer a dependency. Remove it from your app if nothing else uses it.
354
- 10. Use the additive `status: TrackingStatus` field when a single lifecycle value is clearer than multiple derived booleans.
355
- 11. Android 13+: `requestRequiredPermissions()` still requests `POST_NOTIFICATIONS` (so the foreground-service notification stays visible), but its return value now reflects only what tracking needs to run — microphone-side permissions, matching `hasRequiredPermissions()`. In 1.x a denied notification permission made it return `false` even though tracking could start.
423
+ ## Migrating from 1.x
356
424
 
357
- ## Troubleshooting
425
+ v2 removes the parallel and mutable v1 surfaces:
358
426
 
359
- - **`PERMISSION_DENIED` from `startTracking`**: check and request microphone permission from a user-initiated flow, then retry.
360
- - **`MISSING_PREREQUISITE` from `startTracking`**: call `checkAndRestoreTracking()` and `checkBatteryOptimization()` before `startTracking()`.
361
- - **Tracking ends unexpectedly on Android**: battery optimization is on; call `checkBatteryOptimization()` and follow the prompt.
362
- - **Network errors**: verify API key and connectivity.
427
+ | 1.x | v2 |
428
+ |---|---|
429
+ | `error: string \| null` and `errorInfo` | One `AsleepError`; use `message`, `code`, `category`, and `sdkCode` |
430
+ | Report failures returned `null` or `[]` | Report APIs throw `AsleepError`; an empty report list remains a valid result |
431
+ | Public state setters and raw store | Native events and SDK actions are the only writers |
432
+ | `getTrackingDurationMinutes()` | Store a wall-clock start time in the app |
433
+ | `requestMicrophonePermission()` | `requestRequiredPermissions()` |
434
+ | `startTracking()` requested permission | Check and request permission explicitly before starting |
435
+ | Default export, `AsleepSDK`, and `Asleep` class | `useAsleep()` and the named thin `Asleep` escape hatch |
436
+ | Required `zustand` dependency | No external state-library dependency |
363
437
 
364
- Enable debug logs with `useAsleep().enableLog(true)`.
438
+ Android 13 and later still request notification permission, but `requestRequiredPermissions()` now returns the microphone-side result that determines whether tracking can start. Pin the new version, update all imports and error branches, and test cold-start permissions before release.
365
439
 
366
440
  ## Example app
367
441
 
368
- See [`example/`](./example) for a full implementation.
442
+ See the [example app on GitHub](https://github.com/asleep-ai/asleep-sdk-react-native/tree/main/example) for a runnable implementation.
369
443
 
370
444
  ## License
371
445
 
372
- MIT.
446
+ See [LICENSE.md](./LICENSE.md).
373
447
 
374
448
  ## Support
375
449