react-native-asleep 0.0.7 → 0.0.9

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.
Files changed (40) hide show
  1. package/License.md +18 -0
  2. package/README.md +389 -18
  3. package/android/.gradle/8.9/checksums/checksums.lock +0 -0
  4. package/android/.gradle/8.9/fileHashes/fileHashes.lock +0 -0
  5. package/android/.gradle/buildOutputCleanup/buildOutputCleanup.lock +0 -0
  6. package/android/.gradle/buildOutputCleanup/cache.properties +2 -0
  7. package/android/build.gradle +1 -0
  8. package/android/src/main/java/ai/asleep/reactnative/AsleepModule.kt +98 -1
  9. package/build/Asleep.types.d.ts +27 -1
  10. package/build/Asleep.types.d.ts.map +1 -1
  11. package/build/Asleep.types.js.map +1 -1
  12. package/build/AsleepStore.d.ts +50 -0
  13. package/build/AsleepStore.d.ts.map +1 -0
  14. package/build/AsleepStore.js +314 -0
  15. package/build/AsleepStore.js.map +1 -0
  16. package/build/index.d.ts +38 -4
  17. package/build/index.d.ts.map +1 -1
  18. package/build/index.js +42 -167
  19. package/build/index.js.map +1 -1
  20. package/ios/AsleepModule.swift +67 -2
  21. package/package.json +5 -3
  22. package/src/Asleep.types.ts +23 -1
  23. package/src/AsleepStore.ts +436 -0
  24. package/src/index.ts +91 -219
  25. package/android/.gradle/8.5/checksums/checksums.lock +0 -0
  26. package/android/.gradle/8.5/dependencies-accessors/dependencies-accessors.lock +0 -0
  27. package/android/.gradle/8.5/fileHashes/fileHashes.lock +0 -0
  28. package/android/.gradle/config.properties +0 -2
  29. package/android/.idea/android.iml +0 -9
  30. package/android/.idea/appInsightsSettings.xml +0 -23
  31. package/android/.idea/caches/deviceStreaming.xml +0 -329
  32. package/android/.idea/gradle.xml +0 -13
  33. package/android/.idea/migrations.xml +0 -10
  34. package/android/.idea/misc.xml +0 -9
  35. package/android/.idea/modules.xml +0 -8
  36. package/android/.idea/vcs.xml +0 -7
  37. package/android/local.properties +0 -8
  38. /package/android/.gradle/{8.5 → 8.9}/dependencies-accessors/gc.properties +0 -0
  39. /package/android/.gradle/{8.5 → 8.9}/fileChanges/last-build.bin +0 -0
  40. /package/android/.gradle/{8.5 → 8.9}/gc.properties +0 -0
package/License.md CHANGED
@@ -115,3 +115,21 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
115
115
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
116
116
  THE SOFTWARE.
117
117
  =====
118
+ zustand (5.0.1) - MIT License
119
+ Copyright (c) 2019 Paul Henschel and contributors
120
+ Permission is hereby granted, free of charge, to any person obtaining a copy
121
+ of this software and associated documentation files (the "Software"), to deal
122
+ in the Software without restriction, including without limitation the rights
123
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
124
+ copies of the Software, and to permit persons to whom the Software is
125
+ furnished to do so, subject to the following conditions:
126
+ The above copyright notice and this permission notice shall be included in
127
+ all copies or substantial portions of the Software.
128
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
129
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
130
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
131
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
132
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
133
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
134
+ THE SOFTWARE.
135
+ =====
package/README.md CHANGED
@@ -1,36 +1,407 @@
1
- # ⚠️ Experimental Version - Not Recommended for Production Use
1
+ # react-native-asleep
2
2
 
3
- # This is an experimental version of the SDK and is not recommended for production use. Please be aware that it may contain bugs and breaking changes.
3
+ Advanced sleep tracking SDK for React Native applications, powered by Asleep's AI technology.
4
4
 
5
- # react-native-asleep
5
+ ## ⚠️ Important Notice
6
+
7
+ This is an experimental version of the SDK and is not recommended for production use. Please be aware that it may contain bugs and breaking changes.
8
+
9
+ ## Overview
10
+
11
+ The Asleep SDK for React Native provides comprehensive sleep tracking capabilities using advanced AI algorithms. It can detect sleep patterns, stages, and provide detailed analytics through audio analysis without requiring any wearable devices.
12
+
13
+ ### Key Features
14
+
15
+ - **Non-invasive Sleep Tracking**: Uses device microphone for sleep analysis
16
+ - **Real-time Monitoring**: Live tracking status and progress updates
17
+ - **Detailed Sleep Reports**: Comprehensive sleep analysis and metrics
18
+ - **Zustand State Management**: Singleton pattern for consistent state across your app
19
+ - **Cross-platform Support**: Works on both iOS and Android
20
+ - **Event-driven Architecture**: Real-time callbacks for tracking events
21
+
22
+ ## Installation
23
+
24
+ ### For Expo Managed Projects
25
+
26
+ ```bash
27
+ expo install react-native-asleep
28
+ ```
29
+
30
+ ### For Bare React Native Projects
31
+
32
+ 1. Install the package:
33
+
34
+ ```bash
35
+ npm install react-native-asleep zustand
36
+ ```
37
+
38
+ 2. For iOS, run:
39
+
40
+ ```bash
41
+ npx pod-install
42
+ ```
43
+
44
+ 3. Ensure you have [installed and configured the `expo` package](https://docs.expo.dev/bare/installing-expo-modules/).
45
+
46
+ ## Setup
47
+
48
+ ### 1. Get API Key
49
+
50
+ 1. Visit [Asleep Dashboard](https://dashboard.asleep.ai)
51
+ 2. Create an account and generate your API key
52
+ 3. Note your API key for configuration
53
+
54
+ ### 2. Permissions
55
+
56
+ Add the following permissions to your app:
57
+
58
+ #### iOS
59
+
60
+ **For Expo Managed Projects (app.json):**
61
+
62
+ ```json
63
+ {
64
+ "expo": {
65
+ "ios": {
66
+ "infoPlist": {
67
+ "NSMicrophoneUsageDescription": "This app needs microphone access for sleep tracking",
68
+ "UIBackgroundModes": ["audio"]
69
+ }
70
+ }
71
+ }
72
+ }
73
+ ```
74
+
75
+ **For Bare React Native Projects (ios/YourApp/Info.plist):**
76
+
77
+ ```xml
78
+ <key>NSMicrophoneUsageDescription</key>
79
+ <string>This app needs microphone access for sleep tracking</string>
80
+ <key>UIBackgroundModes</key>
81
+ <array>
82
+ <string>audio</string>
83
+ </array>
84
+ ```
85
+
86
+ #### Android (android/app/src/main/AndroidManifest.xml)
87
+
88
+ ```xml
89
+ <uses-permission android:name="android.permission.RECORD_AUDIO" />
90
+ <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
91
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
92
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE"/>
93
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
94
+ ```
95
+
96
+ ## Usage
97
+
98
+ ### Basic Implementation
99
+
100
+ ```typescript
101
+ import React, { useEffect } from "react";
102
+ import { useAsleep } from "react-native-asleep";
103
+ import { View, Text, Button } from "react-native";
104
+
105
+ const SleepTracker = () => {
106
+ const {
107
+ userId,
108
+ sessionId,
109
+ isTracking,
110
+ error,
111
+ initAsleepConfig,
112
+ startTracking,
113
+ stopTracking,
114
+ getReport,
115
+ enableLog,
116
+ } = useAsleep();
117
+
118
+ useEffect(() => {
119
+ const initSDK = async () => {
120
+ try {
121
+ // Enable debug logging (optional)
122
+ enableLog(true);
123
+
124
+ // Initialize SDK with your API key
125
+ await initAsleepConfig({
126
+ apiKey: "YOUR_API_KEY",
127
+ userId: "optional-user-id", // Optional: SDK generates one if not provided
128
+ });
129
+
130
+ console.log("SDK initialized successfully");
131
+ } catch (error) {
132
+ console.error("Failed to initialize SDK:", error);
133
+ }
134
+ };
135
+
136
+ initSDK();
137
+ }, []);
138
+
139
+ const handleStartTracking = async () => {
140
+ try {
141
+ await startTracking();
142
+ console.log("Sleep tracking started");
143
+ } catch (error) {
144
+ console.error("Failed to start tracking:", error);
145
+ }
146
+ };
147
+
148
+ const handleStopTracking = async () => {
149
+ try {
150
+ await stopTracking();
151
+ console.log("Sleep tracking stopped");
152
+ } catch (error) {
153
+ console.error("Failed to stop tracking:", error);
154
+ }
155
+ };
156
+
157
+ const handleGetReport = async () => {
158
+ if (!sessionId) return;
159
+
160
+ try {
161
+ const report = await getReport(sessionId);
162
+ console.log("Sleep report:", report);
163
+ } catch (error) {
164
+ console.error("Failed to get report:", error);
165
+ }
166
+ };
167
+
168
+ return (
169
+ <View>
170
+ <Text>User ID: {userId}</Text>
171
+ <Text>Session ID: {sessionId}</Text>
172
+ <Text>Status: {isTracking ? "Tracking" : "Not Tracking"}</Text>
173
+
174
+ <Button
175
+ title="Start Tracking"
176
+ onPress={handleStartTracking}
177
+ disabled={isTracking}
178
+ />
179
+ <Button
180
+ title="Stop Tracking"
181
+ onPress={handleStopTracking}
182
+ disabled={!isTracking}
183
+ />
184
+ <Button
185
+ title="Get Report"
186
+ onPress={handleGetReport}
187
+ disabled={!sessionId}
188
+ />
189
+ </View>
190
+ );
191
+ };
192
+ ```
193
+
194
+ ### Advanced Usage
6
195
 
7
- Asleep SDK for React Native
196
+ #### Using AsleepSDK for Non-React Components
8
197
 
9
- # API documentation
198
+ For use outside React components or for singleton access:
10
199
 
11
- - [Documentation for the main branch](https://github.com/expo/expo/blob/main/docs/pages/versions/unversioned/sdk/react-native-asleep.md)
12
- - [Documentation for the latest stable release](https://docs.expo.dev/versions/latest/sdk/react-native-asleep/)
200
+ ```typescript
201
+ import { AsleepSDK } from "react-native-asleep";
13
202
 
14
- # Installation in managed Expo projects
203
+ class SleepManager {
204
+ async initializeSDK() {
205
+ try {
206
+ await AsleepSDK.initAsleepConfig({
207
+ apiKey: "YOUR_API_KEY",
208
+ });
15
209
 
16
- For [managed](https://docs.expo.dev/archive/managed-vs-bare/) Expo projects, please follow the installation instructions in the [API documentation for the latest stable release](#api-documentation). If you follow the link and there is no documentation available then this library is not yet usable within managed projects &mdash; it is likely to be included in an upcoming Expo SDK release.
210
+ // Initialize event listeners
211
+ AsleepSDK.initialize();
17
212
 
18
- # Installation in bare React Native projects
213
+ console.log("SDK initialized");
214
+ } catch (error) {
215
+ console.error("SDK initialization failed:", error);
216
+ }
217
+ }
19
218
 
20
- For bare React Native projects, you must ensure that you have [installed and configured the `expo` package](https://docs.expo.dev/bare/installing-expo-modules/) before continuing.
219
+ async startSleepTracking() {
220
+ await AsleepSDK.startTracking();
221
+ }
21
222
 
22
- ### Add the package to your npm dependencies
223
+ async stopSleepTracking() {
224
+ return await AsleepSDK.stopTracking();
225
+ }
23
226
 
227
+ getCurrentStatus() {
228
+ return {
229
+ isTracking: AsleepSDK.isTracking(),
230
+ userId: AsleepSDK.getUserId(),
231
+ sessionId: AsleepSDK.getSessionId(),
232
+ };
233
+ }
234
+ }
24
235
  ```
25
- npm install react-native-asleep
236
+
237
+ #### Direct Store Access
238
+
239
+ ```typescript
240
+ import { useAsleepStore } from "react-native-asleep";
241
+
242
+ // Get current state
243
+ const currentState = useAsleepStore.getState();
244
+
245
+ // Subscribe to specific state changes
246
+ const unsubscribe = useAsleepStore.subscribe(
247
+ (state) => state.isTracking,
248
+ (isTracking) => {
249
+ console.log("Tracking status changed:", isTracking);
250
+ }
251
+ );
252
+ ```
253
+
254
+ ## API Reference
255
+
256
+ ### useAsleep Hook
257
+
258
+ Returns an object with the following properties and methods:
259
+
260
+ #### State Properties
261
+
262
+ - `userId: string | null` - Current user ID
263
+ - `sessionId: string | null` - Current session ID
264
+ - `isTracking: boolean` - Whether tracking is active
265
+ - `error: string | null` - Last error message
266
+ - `didClose: boolean` - Whether the last session was closed
267
+ - `log: string` - Latest log message
268
+
269
+ #### Methods
270
+
271
+ - `initAsleepConfig(config: AsleepConfig): Promise<void>` - Initialize SDK
272
+ - `startTracking(): Promise<void>` - Start sleep tracking
273
+ - `stopTracking(): Promise<void>` - Stop sleep tracking
274
+ - `getReport(sessionId: string): Promise<AsleepReport | null>` - Get sleep report
275
+ - `getReportList(fromDate: string, toDate: string): Promise<AsleepSession[]>` - Get list of reports
276
+ - `enableLog(enabled: boolean): void` - Enable/disable debug logging
277
+ - `setCustomNotification(title: string, text: string): Promise<void>` - Set custom notification (Android only)
278
+
279
+ ### AsleepConfig
280
+
281
+ Configuration object for SDK initialization:
282
+
283
+ ```typescript
284
+ interface AsleepConfig {
285
+ apiKey: string; // Required: Your API key
286
+ userId?: string; // Optional: User identifier
287
+ baseUrl?: string; // Optional: Custom API base URL
288
+ callbackUrl?: string; // Optional: Webhook callback URL
289
+ }
290
+ ```
291
+
292
+ ### AsleepReport
293
+
294
+ Sleep analysis report structure:
295
+
296
+ ```typescript
297
+ interface AsleepReport {
298
+ sessionId: string;
299
+ sleepEfficiency: number;
300
+ sleepLatency: number;
301
+ sleepTime: number;
302
+ wakeTime: number;
303
+ lightSleepTime: number;
304
+ deepSleepTime: number;
305
+ remSleepTime: number;
306
+ // ... additional metrics
307
+ }
308
+ ```
309
+
310
+ ### AsleepSession
311
+
312
+ Session information structure:
313
+
314
+ ```typescript
315
+ interface AsleepSession {
316
+ sessionId: string;
317
+ startTime: string;
318
+ endTime: string;
319
+ state: string;
320
+ // ... additional session data
321
+ }
322
+ ```
323
+
324
+ ## Event Handling
325
+
326
+ The SDK automatically handles events through the zustand store. Events are processed internally and state is updated accordingly. You can monitor state changes using useEffect:
327
+
328
+ ```typescript
329
+ const { userId, sessionId, isTracking, error } = useAsleep();
330
+
331
+ useEffect(() => {
332
+ if (error) {
333
+ console.error("SDK Error:", error);
334
+ }
335
+ }, [error]);
336
+
337
+ useEffect(() => {
338
+ if (sessionId) {
339
+ console.log("New session created:", sessionId);
340
+ }
341
+ }, [sessionId]);
342
+ ```
343
+
344
+ ## Best Practices
345
+
346
+ ### 1. SDK Initialization
347
+
348
+ - Initialize the SDK early in your app lifecycle
349
+ - Handle initialization errors gracefully
350
+ - Store API key securely (use environment variables)
351
+
352
+ ### 2. Permission Handling
353
+
354
+ - Request microphone permission before starting tracking
355
+ - Provide clear explanation to users about why permission is needed
356
+ - Handle permission denial gracefully
357
+
358
+ ### 3. Battery Optimization
359
+
360
+ - For Android, consider requesting battery optimization exemption
361
+ - Implement proper foreground service for long-running tracking
362
+
363
+ ### 4. Error Handling
364
+
365
+ - Always wrap SDK calls in try-catch blocks
366
+ - Monitor the error state for real-time error updates
367
+ - Provide user-friendly error messages
368
+
369
+ ### 5. State Management
370
+
371
+ - Use the built-in zustand store for consistent state
372
+ - Subscribe to specific state changes when needed
373
+ - Avoid unnecessary re-renders by selecting specific state slices
374
+
375
+ ## Example App
376
+
377
+ See the `/example` directory for a complete implementation example.
378
+
379
+ ## Troubleshooting
380
+
381
+ ### Common Issues
382
+
383
+ 1. **Permission Denied**: Ensure microphone permission is granted
384
+ 2. **SDK Not Initialized**: Call `initAsleepConfig` before other methods
385
+ 3. **Network Errors**: Check internet connection and API key validity
386
+ 4. **Battery Optimization**: On Android, exempt app from battery optimization
387
+
388
+ ### Debug Mode
389
+
390
+ Enable debug logging to see detailed SDK operations:
391
+
392
+ ```typescript
393
+ const { enableLog } = useAsleep();
394
+ enableLog(true);
26
395
  ```
27
396
 
28
- ### Configure for iOS
397
+ ## License
29
398
 
30
- Run `npx pod-install` after installing the npm package.
399
+ This project is licensed under the MIT License.
31
400
 
32
- ### Configure for Android
401
+ ## Support
33
402
 
34
- # Contributing
403
+ For issues and support:
35
404
 
36
- Contributions are very welcome! Please refer to guidelines described in the [contributing guide](https://github.com/expo/expo#contributing).
405
+ - [GitHub Issues](https://github.com/asleep-ai/asleep-sdk-react-native/issues)
406
+ - [Asleep Documentation](https://docs.asleep.ai)
407
+ - [Asleep Dashboard](https://dashboard.asleep.ai)
@@ -0,0 +1,2 @@
1
+ #Wed Jun 04 16:17:46 KST 2025
2
+ gradle.version=8.9
@@ -87,4 +87,5 @@ dependencies {
87
87
  implementation "androidx.lifecycle:lifecycle-service:2.8.7"
88
88
  implementation "androidx.lifecycle:lifecycle-common-java8:2.8.7"
89
89
  implementation "com.squareup.okhttp3:okhttp:4.11.0"
90
+ implementation 'com.google.android.play:integrity:1.3.0'
90
91
  }
@@ -34,6 +34,7 @@ import androidx.lifecycle.ViewModel
34
34
  import androidx.lifecycle.viewModelScope
35
35
  import android.app.Application
36
36
  import kotlinx.coroutines.*
37
+ import kotlinx.coroutines.delay
37
38
  import kotlin.coroutines.resume
38
39
  import kotlin.coroutines.resumeWithException
39
40
  import android.os.DeadObjectException
@@ -71,7 +72,43 @@ class AsleepModule : Module() {
71
72
 
72
73
  Events("onTrackingCreated", "onTrackingUploaded", "onTrackingClosed", "onTrackingFailed",
73
74
  "onTrackingInterrupted", "onTrackingResumed", "onMicPermissionDenied",
74
- "onUserJoined", "onUserJoinFailed", "onUserDeleted", "onDebugLog")
75
+ "onUserJoined", "onUserJoinFailed", "onUserDeleted", "onDebugLog",
76
+ "onSetupDidComplete", "onSetupDidFail", "onSetupInProgress", "onAnalysisResult")
77
+
78
+ AsyncFunction("setup") { apiKey: String, baseUrl: String?, callbackUrl: String?, service: String?, enableODA: Boolean?, promise: Promise ->
79
+ try {
80
+ val context = appContext.reactContext!!.applicationContext as Application
81
+
82
+ Asleep.setup(
83
+ context = context,
84
+ apiKey = apiKey,
85
+ baseUrl = baseUrl,
86
+ callbackUrl = callbackUrl,
87
+ service = service ?: "SleepTracking",
88
+ enableODA = enableODA,
89
+ asleepSetupListener = object : Asleep.AsleepSetupListener {
90
+ override fun onComplete() {
91
+ sendEvent("onSetupDidComplete", emptyMap<String, Any>())
92
+ promise.resolve("Setup completed")
93
+ }
94
+
95
+ override fun onProgress(progress: Int) {
96
+ sendEvent("onSetupInProgress", mapOf("progress" to progress))
97
+ sendEvent("onDebugLog", mapOf("message" to "Setup progress: $progress%"))
98
+ }
99
+
100
+ override fun onFail(errorCode: Int, detail: String) {
101
+ sendEvent("onSetupDidFail", mapOf("error" to detail))
102
+ sendEvent("onDebugLog", mapOf("message" to "Setup failed: $errorCode - $detail"))
103
+ promise.reject("SETUP_FAILED", "Setup failed: $errorCode - $detail", null)
104
+ }
105
+ }
106
+ )
107
+ } catch (e: Exception) {
108
+ sendEvent("onDebugLog", mapOf("message" to "Setup failed: ${e.message}"))
109
+ promise.reject("UNEXPECTED_ERROR", "Setup failed: ${e.message}", e)
110
+ }
111
+ }
75
112
 
76
113
  AsyncFunction("initAsleepConfig") { apiKey: String, userId: String?, baseUrl: String?, callbackUrl: String?, promise: Promise ->
77
114
  try {
@@ -302,6 +339,66 @@ class AsleepModule : Module() {
302
339
  }
303
340
  }
304
341
  }
342
+
343
+ AsyncFunction("requestAnalysis") { promise: Promise ->
344
+ CoroutineScope(Dispatchers.Main).launch {
345
+ try {
346
+ if (_asleepConfig == null) {
347
+ promise.reject("UNINITIALIZED_CONFIG", "AsleepConfig is not initialized", null)
348
+ return@launch
349
+ }
350
+
351
+ var retryCount = 0
352
+ val maxRetries = 3
353
+ val delayMs = 5000L // 5 seconds
354
+
355
+ while (retryCount < maxRetries) {
356
+ if (isTracking) {
357
+ // If tracking is active, request analysis
358
+ try {
359
+ Asleep.getCurrentSleepData(object : Asleep.AsleepSleepDataListener {
360
+ override fun onSleepDataReceived(session: ai.asleep.asleepsdk.data.Session) {
361
+ val sessionData = session.serializeToMap()
362
+ sendEvent("onAnalysisResult", sessionData)
363
+ sendEvent("onDebugLog", mapOf("message" to "Request analysis result: $sessionData"))
364
+ promise.resolve(sessionData)
365
+ }
366
+
367
+ override fun onFail(errorCode: Int, detail: String) {
368
+ val errorMessage = "Get current sleep data failed: errorCode=$errorCode, detail=$detail"
369
+ sendEvent("onDebugLog", mapOf("message" to errorMessage))
370
+ promise.reject("ANALYSIS_ERROR", errorMessage, null)
371
+ }
372
+ })
373
+ return@launch
374
+ } catch (e: Exception) {
375
+ val errorMessage = "Analysis request failed during getCurrentSleepData: ${e.message}"
376
+ sendEvent("onDebugLog", mapOf("message" to errorMessage))
377
+ promise.reject("ANALYSIS_ERROR", errorMessage, e)
378
+ return@launch
379
+ }
380
+ } else {
381
+ retryCount++
382
+ sendEvent("onDebugLog", mapOf("message" to "Sleep tracking not active, retry $retryCount/$maxRetries"))
383
+
384
+ if (retryCount < maxRetries) {
385
+ delay(delayMs)
386
+ }
387
+ }
388
+ }
389
+
390
+ // All retries failed
391
+ val errorMessage = "Sleep tracking is not active after $maxRetries retries"
392
+ sendEvent("onDebugLog", mapOf("message" to errorMessage))
393
+ promise.reject("NOT_TRACKING", errorMessage, null)
394
+
395
+ } catch (e: Exception) {
396
+ val errorMessage = "Analysis request failed: ${e.message}"
397
+ sendEvent("onDebugLog", mapOf("message" to errorMessage))
398
+ promise.reject("UNEXPECTED_ERROR", errorMessage, e)
399
+ }
400
+ }
401
+ }
305
402
  }
306
403
 
307
404
  private fun <T> T.serializeToMap(): Map<String, Any> {
@@ -4,6 +4,13 @@ export type AsleepConfig = {
4
4
  baseUrl?: string;
5
5
  callbackUrl?: string;
6
6
  };
7
+ export type AsleepSetupConfig = {
8
+ apiKey: string;
9
+ baseUrl?: string;
10
+ callbackUrl?: string;
11
+ service?: string;
12
+ enableODA?: boolean;
13
+ };
7
14
  export type AsleepReport = {
8
15
  timezone: string;
9
16
  session: {
@@ -68,8 +75,19 @@ export type AsleepSession = {
68
75
  sessionEndTime?: string;
69
76
  timeInBed?: number;
70
77
  };
78
+ export type AsleepAnalysisResult = {
79
+ id?: string;
80
+ state?: string;
81
+ startTime?: string;
82
+ endTime?: string;
83
+ sleepStages?: number[];
84
+ breathStages?: number[];
85
+ snoringStages?: number[];
86
+ };
71
87
  export type AsleepEventType = {
72
- onTrackingCreated: undefined;
88
+ onTrackingCreated: {
89
+ sessionId?: string;
90
+ };
73
91
  onTrackingUploaded: {
74
92
  sequence: number;
75
93
  };
@@ -86,5 +104,13 @@ export type AsleepEventType = {
86
104
  onDebugLog: {
87
105
  message: string;
88
106
  };
107
+ onSetupDidComplete: undefined;
108
+ onSetupDidFail: {
109
+ error: string;
110
+ };
111
+ onSetupInProgress: {
112
+ progress: number;
113
+ };
114
+ onAnalysisResult: AsleepAnalysisResult;
89
115
  };
90
116
  //# sourceMappingURL=Asleep.types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Asleep.types.d.ts","sourceRo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IACjC,iBAAiB,EAAE,SAAS,CAAC;IAC7B,qBAAqB,EAAE,SAAS,CAAC;IACjC,YAAY,EAAE,SAAS,CAAC;IACxB,gBAAgB,EAAE,SAAS,CAAC;IAC5B,aAAa,EAAE,SAAS,CAAC;IACzB,UAAU,EAAE;QAAE,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC;IAChC,kBAAkB,EAAE,SAAS,CAAC;IAC9B,cAAc,EAAE;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;IAClC,iBAAiB,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC;IACxC,gBAAgB,EAAE,oBAAoB,CAAC;CACxC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"Asleep.types.js","sourceRoot":"","sources":["../src/Asleep.types.ts"],"names":[],"mappings":"","sourcesContent":["export type AsleepConfig = {\n apiKey: string;\n userId?: string;\n baseUrl?: string;\n callbackUrl?: string;\n};\n\nexport type AsleepReport = {\n timezone: string;\n session: {\n id: string;\n createdTimezone: string;\n startTime: string;\n endTime?: string;\n unexpectedEndTime?: string;\n state: string;\n sleepStages?: number[];\n breathStages?: number[];\n snoringStages?: number[];\n };\n missingDataRatio: number;\n peculiarities: string[];\n stat?: AsleepStat;\n};\n\nexport type AsleepStat = {\n sleepCycleTime?: number[];\n timeInStableBreath?: number;\n timeInBed?: number;\n unstableBreathRatio?: number;\n sleepCycle?: number;\n timeInSleep?: number;\n breathingIndex?: number;\n deepLatency?: number;\n remLatency?: number;\n timeInSnoring?: number;\n wakeTime?: string;\n longestWaso?: number;\n lightRatio?: number;\n noSnoringRatio?: number;\n snoringCount?: number;\n unstableBreathCount?: number;\n timeInDeep?: number;\n sleepTime?: string;\n sleepCycleCount?: number;\n wakeupLatency?: number;\n breathingPattern?: string;\n timeInRem?: number;\n snoringRatio?: number;\n stableBreathRatio?: number;\n timeInSleepPeriod?: number;\n lightLatency?: number;\n remRatio?: number;\n sleepEfficiency?: number;\n timeInNoSnoring?: number;\n sleepLatency?: number;\n timeInLight?: number;\n sleepIndex?: number;\n sleepRatio?: number;\n timeInUnstableBreath?: number;\n wasoCount?: number;\n wakeRatio?: number;\n deepRatio?: number;\n timeInWake?: number;\n};\n\nexport type AsleepSession = {\n sessionId: string;\n state: string;\n sessionStartTime: string;\n sessionEndTime?: string;\n timeInBed?: number;\n};\n\nexport type AsleepEventType = {\n onTrackingCreated: undefined;\n onTrackingUploaded: { sequence: number };\n onTrackingClosed: { sessionId: string };\n onTrackingFailed: undefined;\n onTrackingInterrupted: undefined;\n onTrackingResumed: undefined;\n onMicPermissionDenied: undefined;\n onUserJoined: undefined;\n onUserJoinFailed: undefined;\n onUserDeleted: undefined;\n onDebugLog: { message: string };\n};\n"]}
1
+ {"version":3,"file":"Asleep.types.js","sourceRoot":"","sources":["../src/Asleep.types.ts"],"names":[],"mappings":"","sourcesContent":["export type AsleepConfig = {\n apiKey: string;\n userId?: string;\n baseUrl?: string;\n callbackUrl?: string;\n};\n\nexport type AsleepSetupConfig = {\n apiKey: string;\n baseUrl?: string;\n callbackUrl?: string;\n service?: string;\n enableODA?: boolean;\n};\n\nexport type AsleepReport = {\n timezone: string;\n session: {\n id: string;\n createdTimezone: string;\n startTime: string;\n endTime?: string;\n unexpectedEndTime?: string;\n state: string;\n sleepStages?: number[];\n breathStages?: number[];\n snoringStages?: number[];\n };\n missingDataRatio: number;\n peculiarities: string[];\n stat?: AsleepStat;\n};\n\nexport type AsleepStat = {\n sleepCycleTime?: number[];\n timeInStableBreath?: number;\n timeInBed?: number;\n unstableBreathRatio?: number;\n sleepCycle?: number;\n timeInSleep?: number;\n breathingIndex?: number;\n deepLatency?: number;\n remLatency?: number;\n timeInSnoring?: number;\n wakeTime?: string;\n longestWaso?: number;\n lightRatio?: number;\n noSnoringRatio?: number;\n snoringCount?: number;\n unstableBreathCount?: number;\n timeInDeep?: number;\n sleepTime?: string;\n sleepCycleCount?: number;\n wakeupLatency?: number;\n breathingPattern?: string;\n timeInRem?: number;\n snoringRatio?: number;\n stableBreathRatio?: number;\n timeInSleepPeriod?: number;\n lightLatency?: number;\n remRatio?: number;\n sleepEfficiency?: number;\n timeInNoSnoring?: number;\n sleepLatency?: number;\n timeInLight?: number;\n sleepIndex?: number;\n sleepRatio?: number;\n timeInUnstableBreath?: number;\n wasoCount?: number;\n wakeRatio?: number;\n deepRatio?: number;\n timeInWake?: number;\n};\n\nexport type AsleepSession = {\n sessionId: string;\n state: string;\n sessionStartTime: string;\n sessionEndTime?: string;\n timeInBed?: number;\n};\n\nexport type AsleepAnalysisResult = {\n id?: string;\n state?: string;\n startTime?: string;\n endTime?: string;\n sleepStages?: number[];\n breathStages?: number[];\n snoringStages?: number[];\n};\n\nexport type AsleepEventType = {\n onTrackingCreated: { sessionId?: string };\n onTrackingUploaded: { sequence: number };\n onTrackingClosed: { sessionId: string };\n onTrackingFailed: undefined;\n onTrackingInterrupted: undefined;\n onTrackingResumed: undefined;\n onMicPermissionDenied: undefined;\n onUserJoined: undefined;\n onUserJoinFailed: undefined;\n onUserDeleted: undefined;\n onDebugLog: { message: string };\n onSetupDidComplete: undefined;\n onSetupDidFail: { error: string };\n onSetupInProgress: { progress: number };\n onAnalysisResult: AsleepAnalysisResult;\n};\n"]}