@doorstepai/dropoff-sdk 2.1.2 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.md +115 -3
  3. package/android/build.gradle +1 -1
  4. package/android/src/main/java/com/doorstepai/dropoffsdk/DoorstepAIModule.kt +332 -0
  5. package/ios/DoorstepAI.mm +5 -2
  6. package/ios/DoorstepAI.swift +170 -2
  7. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64/DoorstepDropoffSDK.framework/DoorstepDropoffSDK +0 -0
  8. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/arm64-apple-ios.abi.json +1374 -413
  9. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/arm64-apple-ios.private.swiftinterface +13 -4
  10. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/arm64-apple-ios.swiftdoc +0 -0
  11. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/arm64-apple-ios.swiftinterface +13 -4
  12. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64/DoorstepDropoffSDK.framework/_CodeSignature/CodeResources +10 -10
  13. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64/dSYMs/DoorstepDropoffSDK.framework.dSYM/Contents/Resources/DWARF/DoorstepDropoffSDK +0 -0
  14. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64/dSYMs/DoorstepDropoffSDK.framework.dSYM/Contents/Resources/Relocations/aarch64/DoorstepDropoffSDK.yml +3248 -2687
  15. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/DoorstepDropoffSDK.framework/DoorstepDropoffSDK +0 -0
  16. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/arm64-apple-ios-simulator.abi.json +1374 -413
  17. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/arm64-apple-ios-simulator.private.swiftinterface +13 -4
  18. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/arm64-apple-ios-simulator.swiftdoc +0 -0
  19. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/arm64-apple-ios-simulator.swiftinterface +13 -4
  20. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/x86_64-apple-ios-simulator.abi.json +1374 -413
  21. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/x86_64-apple-ios-simulator.private.swiftinterface +13 -4
  22. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/x86_64-apple-ios-simulator.swiftdoc +0 -0
  23. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/x86_64-apple-ios-simulator.swiftinterface +13 -4
  24. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/DoorstepDropoffSDK.framework/_CodeSignature/CodeResources +20 -20
  25. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/dSYMs/DoorstepDropoffSDK.framework.dSYM/Contents/Resources/DWARF/DoorstepDropoffSDK +0 -0
  26. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/dSYMs/DoorstepDropoffSDK.framework.dSYM/Contents/Resources/Relocations/aarch64/DoorstepDropoffSDK.yml +3248 -2687
  27. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/dSYMs/DoorstepDropoffSDK.framework.dSYM/Contents/Resources/Relocations/x86_64/DoorstepDropoffSDK.yml +3233 -2674
  28. package/lib/module/DoorstepAI.js +190 -12
  29. package/lib/module/DoorstepAI.js.map +1 -1
  30. package/lib/module/RootDoorstepAI.js +70 -26
  31. package/lib/module/RootDoorstepAI.js.map +1 -1
  32. package/lib/module/index.js.map +1 -1
  33. package/lib/typescript/src/DoorstepAI.d.ts +151 -7
  34. package/lib/typescript/src/DoorstepAI.d.ts.map +1 -1
  35. package/lib/typescript/src/RootDoorstepAI.d.ts +14 -3
  36. package/lib/typescript/src/RootDoorstepAI.d.ts.map +1 -1
  37. package/lib/typescript/src/index.d.ts +1 -1
  38. package/lib/typescript/src/index.d.ts.map +1 -1
  39. package/package.json +2 -1
  40. package/src/DoorstepAI.tsx +241 -23
  41. package/src/RootDoorstepAI.tsx +98 -45
  42. package/src/index.tsx +4 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,66 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ ### `checkPermissions` + `requestPermissions` are the permission surface again
6
+
7
+ The pair that shipped in `@doorstepai/dropoff-sdk-capacitor` 1.0.4 is restored as
8
+ the public permission API, with the published names and shapes, and is now
9
+ **identical across the React Native, Capacitor and Flutter wrappers**. It is
10
+ implemented over the native SDK — the wrapper owns no permission list, no alias
11
+ table for OS permissions, no request sequencing, and no `CLLocationManager` /
12
+ `CBCentralManager` of its own.
13
+
14
+ ```ts
15
+ type PermissionState = 'granted' | 'denied' | 'prompt';
16
+ type DoorstepPermissionType = 'location' | 'motion' | 'bluetooth';
17
+ interface PermissionStatus { permissions: Record<DoorstepPermissionType, PermissionState> }
18
+ interface PermissionRequestOptions { permissions?: Array<DoorstepPermissionType | 'activity'> }
19
+
20
+ checkPermissions(): Promise<PermissionStatus>;
21
+ requestPermissions(options?: PermissionRequestOptions): Promise<PermissionStatus>;
22
+ ```
23
+
24
+ - **Added `checkPermissions()`**, both platforms. Reads the platform's own
25
+ non-prompting status APIs — `CLLocationManager.authorizationStatus` (the instance
26
+ property), `CMMotionActivityManager.authorizationStatus()` and the static
27
+ `CBManager.authorization` on iOS; `ContextCompat.checkSelfPermission` on Android —
28
+ over the names `DoorstepAI.getRequiredPermissions()` returns. It never
29
+ instantiates a `CBCentralManager`, which would prompt and would crash a host
30
+ without `NSBluetoothAlwaysUsageDescription`.
31
+ - **`requestPermissions` now resolves a `PermissionStatus`, after the user answers.**
32
+ Previously it resolved as soon as the prompt was *issued*
33
+ (`{ requestedPermissions }` on Android, `{}` on iOS), which said nothing about the
34
+ outcome. A concurrent second call now **rejects** with
35
+ `E_PERMISSION_REQUEST_IN_FLIGHT` instead of interleaving prompt sequences. An
36
+ unanswered prompt resolves with the current state after 120 s rather than hanging.
37
+ - **Removed `RequestPermissionsOptions` and `PermissionRequestResult`.** The options
38
+ object is `PermissionRequestOptions` (`{ permissions? }`) and the result is
39
+ `PermissionStatus`. The `includeBluetooth`, `requestAlwaysLocation`,
40
+ `onlyIfNotDetermined` and `requestCode` options are gone; `requestAlwaysLocation`
41
+ and `onlyIfNotDetermined` are left at their native defaults (both `true`), which
42
+ is what keeps a launch-time call from re-escalating a "While Using the App"
43
+ choice.
44
+ - **`permissions` can only narrow Bluetooth**, and this is documented rather than
45
+ silently swallowed: both natives request their whole required set behind a single
46
+ `includeBluetooth` / `requestBluetooth` flag, so the array is read as
47
+ `includeBluetooth = permissions.includes('bluetooth')` (true when omitted) and
48
+ `location` + `motion` always ride the base set. Passing `['bluetooth']` alone
49
+ still requests the base set.
50
+ - **`'activity'` is still accepted** wherever a `DoorstepPermissionType` is passed,
51
+ as a deprecated alias for `'motion'`, because it was the published 1.0.4 type. It
52
+ is normalised in the JS layer, so neither bridge ever sees it, and it is never a
53
+ key of `PermissionStatus`.
54
+ - `<RootDoorstepAI />` now gates its second-phase background-location prompt on
55
+ `status.permissions.location === 'granted'` from the request itself, which is only
56
+ meaningful now that the promise resolves post-answer.
57
+
58
+ ### Unchanged
59
+
60
+ - `requestBackgroundLocationPermission()` stays a separate Android-only entry
61
+ point, because Android 11+ requires background location as a second prompt after
62
+ the foreground grant and refuses to bundle it into one call. The wrapper does not
63
+ sequence the two for you. The iOS expression of the same intent is native's
64
+ `requestAlwaysLocation`, which `requestPermissions` leaves at its default (`true`).
65
+ - The query helpers `getRequiredPermissions` / `hasRequiredPermissions` /
66
+ `hasBackgroundLocationPermission` keep their shape and stay Android-only.
package/README.md CHANGED
@@ -192,6 +192,11 @@ In your `Info.plist`, include the following usage descriptions:
192
192
  <key>NSMotionUsageDescription</key>
193
193
  <string>This app uses motion data to enhance delivery tracking accuracy.</string>
194
194
 
195
+ <!-- Required if you let Bluetooth default to on (see the permission API below).
196
+ Without this key the SDK skips the Bluetooth request with a warning. -->
197
+ <key>NSBluetoothAlwaysUsageDescription</key>
198
+ <string>This app uses Bluetooth to improve delivery location accuracy.</string>
199
+
195
200
  <!-- Background Location Mode -->
196
201
  <key>UIBackgroundModes</key>
197
202
  <array>
@@ -201,17 +206,21 @@ In your `Info.plist`, include the following usage descriptions:
201
206
 
202
207
  ### 🤖 Android
203
208
 
204
- In your `AndroidManifest.xml`, include the following permissions:
209
+ The SDK's own manifest already declares every permission it needs, so manifest
210
+ merging supplies them to your app. Declare these only if you want them visible in
211
+ your own `AndroidManifest.xml`:
205
212
 
206
213
  ```xml
207
214
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
208
215
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
209
216
  <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
210
217
  <uses-permission android:name="android.permission.HIGH_SAMPLING_RATE_SENSORS" />
211
- <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
212
218
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
213
219
  <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
220
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
214
221
  <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
222
+ <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
223
+ <uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES" />
215
224
  <uses-permission android:name="android.permission.WAKE_LOCK" />
216
225
 
217
226
  <uses-feature android:name="android.hardware.sensor.accelerometer" />
@@ -221,6 +230,109 @@ In your `AndroidManifest.xml`, include the following permissions:
221
230
  <uses-feature android:name="android.hardware.sensor.proximity" />
222
231
  ```
223
232
 
224
- These permissions enable accurate location and motion tracking during delivery sessions.
233
+ ### Requesting them at runtime
234
+
235
+ `<RootDoorstepAI />` does this for you. Use the API directly if you drive
236
+ permissions from your own onboarding flow — every method delegates to the native
237
+ SDK, so the list and the ordering stay whatever the SDK says they are.
238
+
239
+ `checkPermissions` and `requestPermissions` are the **permission surface, identical
240
+ on both platforms and identical to the Capacitor and Flutter wrappers**. Do not
241
+ branch on `Platform.OS` to ask for permissions: the branch is inside the wrapper,
242
+ dispatching to `DoorstepAI.requestPermissions(activity, requestCode,
243
+ includeBluetooth)` on Android and
244
+ `DoorstepAI.requestAllPermissions(requestAlwaysLocation:requestBluetooth:onlyIfNotDetermined:)`
245
+ on iOS.
246
+
247
+ ```ts
248
+ type PermissionState = 'granted' | 'denied' | 'prompt';
249
+ type DoorstepPermissionType = 'location' | 'motion' | 'bluetooth';
250
+
251
+ interface PermissionStatus {
252
+ permissions: Record<DoorstepPermissionType, PermissionState>;
253
+ }
254
+
255
+ interface PermissionRequestOptions {
256
+ permissions?: Array<DoorstepPermissionType | 'activity'>;
257
+ }
258
+
259
+ checkPermissions(): Promise<PermissionStatus>;
260
+ requestPermissions(options?: PermissionRequestOptions): Promise<PermissionStatus>;
261
+ ```
262
+
263
+ ```ts
264
+ // Read the current state. Never shows a dialog.
265
+ const { permissions } = await DoorstepAI.checkPermissions();
266
+ // -> { location: 'prompt', motion: 'granted', bluetooth: 'denied' }
267
+
268
+ // Ask. Resolves AFTER the user answers, with the resulting state.
269
+ const after = await DoorstepAI.requestPermissions();
270
+ if (after.permissions.location !== 'granted') { /* explain, offer Settings */ }
271
+ ```
272
+
273
+ `checkPermissions` is pure observation: it reads `CLLocationManager.authorizationStatus`,
274
+ `CMMotionActivityManager.authorizationStatus()` and `CBManager.authorization` on
275
+ iOS, and `ContextCompat.checkSelfPermission` on Android, against the permission
276
+ names the **native SDK** returns from `getRequiredPermissions()`. The wrapper keeps
277
+ no permission list of its own. A bucket the native SDK needs no runtime grant for
278
+ on this OS version reports `granted` — `motion` on Android (sensor collection needs
279
+ none) and `bluetooth` below Android 12.
280
+
281
+ `requestPermissions` **resolves only after the dialog has been answered**, because
282
+ it returns a `PermissionStatus` and a status captured while the prompt is still up
283
+ would be stale. A second call issued while one is still awaiting an answer
284
+ **rejects** (`E_PERMISSION_REQUEST_IN_FLIGHT`) rather than interleaving two prompt
285
+ sequences. If the user never answers, the wait gives up after 120 s and resolves
286
+ with the state as it stands — still `prompt` for anything unanswered.
287
+
288
+ #### `permissions` can only narrow Bluetooth
289
+
290
+ Neither native offers per-permission selection: each requests its **whole required
291
+ set** behind one `includeBluetooth` / `requestBluetooth` flag. So the array is read
292
+ as:
293
+
294
+ ```
295
+ includeBluetooth = permissions === undefined || permissions.includes('bluetooth')
296
+ ```
297
+
298
+ and **`location` and `motion` always ride the base set**. Passing `['bluetooth']`
299
+ alone still requests the base set as well; passing `['location']` still shows the
300
+ Motion & Fitness prompt on iOS. This is documented rather than silently swallowed —
301
+ an array the wrapper cannot honour would be a lie.
302
+
303
+ `'activity'` is still accepted in the array as a **deprecated alias for `'motion'`**
304
+ (it was the published type in `@doorstepai/dropoff-sdk-capacitor` 1.0.4). It is
305
+ normalised to `'motion'` before it reaches native and is never a key of
306
+ `PermissionStatus`.
307
+
308
+ **Background location is a second call on Android.** Android 11+ refuses to bundle
309
+ `ACCESS_BACKGROUND_LOCATION` into the foreground request; it must be prompted
310
+ separately, *after* foreground location is granted, or the OS spends it on an
311
+ automatic denial. The wrapper does not sequence this for you.
312
+
313
+ ```ts
314
+ // Android only. On iOS the same intent is native's requestAlwaysLocation, which
315
+ // requestPermissions leaves at its default (true) — this method has no iOS
316
+ // counterpart and rejects there rather than inventing an answer.
317
+ if (Platform.OS === 'android') {
318
+ const { permissions } = await DoorstepAI.requestPermissions();
319
+ if (permissions.location === 'granted') {
320
+ if (!(await DoorstepAI.hasBackgroundLocationPermission())) {
321
+ await DoorstepAI.requestBackgroundLocationPermission();
322
+ }
323
+ }
324
+ }
325
+ ```
326
+
327
+ The query helpers below are Android-only and reject on iOS rather than resolving
328
+ `true`/`[]`, which a cross-platform host would read as "granted" / "nothing needed".
329
+
330
+ ```ts
331
+ await DoorstepAI.hasRequiredPermissions(); // -> boolean
332
+
333
+ // Want the grant results in JS? Request the SDK's own list with RN's API.
334
+ const required = await DoorstepAI.getRequiredPermissions();
335
+ await PermissionsAndroid.requestMultiple(required);
336
+ ```
225
337
 
226
338
  ---
@@ -86,7 +86,7 @@ def kotlin_version = getExtOrDefault("kotlinVersion")
86
86
  dependencies {
87
87
  implementation "com.facebook.react:react-android"
88
88
  implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
89
- implementation("ai.doorstep.com:doorstepai-dropoff-sdk:2.1.3")
89
+ implementation("ai.doorstep.com:doorstepai-dropoff-sdk:2.2.0")
90
90
  api "org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.1"
91
91
  }
92
92
 
@@ -1,5 +1,13 @@
1
1
  package com.doorstepai.dropoffsdk
2
2
 
3
+ import android.Manifest
4
+ import android.app.Activity
5
+ import android.content.pm.PackageManager
6
+ import android.os.Handler
7
+ import android.os.Looper
8
+ import androidx.core.app.ActivityCompat
9
+ import androidx.core.content.ContextCompat
10
+ import com.facebook.react.bridge.LifecycleEventListener
3
11
  import com.facebook.react.bridge.NativeModule
4
12
  import com.facebook.react.bridge.ReactApplicationContext
5
13
  import com.facebook.react.bridge.ReactContext
@@ -10,10 +18,13 @@ import com.doorstepai.sdks.tracking.DoorstepAI
10
18
  import com.doorstepai.sdks.tracking.AddressType
11
19
  import com.doorstepai.sdks.tracking.DropoffType
12
20
  import com.doorstepai.sdks.tracking.LatLngObject
21
+ import com.facebook.react.bridge.Dynamic
13
22
  import com.facebook.react.bridge.ReadableMap
14
23
  import com.facebook.react.bridge.ReadableArray
24
+ import com.facebook.react.bridge.ReadableType
15
25
  import com.facebook.react.bridge.WritableMap
16
26
  import com.facebook.react.bridge.Arguments
27
+ import com.facebook.react.bridge.UiThreadUtil
17
28
  import com.facebook.react.modules.core.DeviceEventManagerModule
18
29
  import com.doorstepai.sdks.tracking.DeliveryStop
19
30
  import com.doorstepai.sdks.tracking.RouteGeofenceOptions
@@ -292,6 +303,319 @@ class DoorstepAIModule(private val reactContext: ReactApplicationContext) :
292
303
  }
293
304
  }
294
305
 
306
+ // ---- Runtime permissions ----
307
+ // Pass-through to the SDK's own permission API. The SDK owns the permission list
308
+ // and the request ordering; the JS layer this replaced kept its own list and
309
+ // asked for ACCESS_FINE_LOCATION with no ACCESS_COARSE_LOCATION, which Android
310
+ // 12+ ignores outright, and never asked for ACCESS_BACKGROUND_LOCATION at all.
311
+ //
312
+ // An absent `includeBluetooth` means "whatever native defaults to", so the
313
+ // branches below omit the argument rather than restating a literal — the default
314
+ // is not the same on every method (true when requesting, false when checking).
315
+
316
+ /**
317
+ * `Dynamic` rather than `Boolean?` because RN's boxed-Boolean argument extractor
318
+ * calls `ReadableArray.getBoolean`, which throws on a JS `null` — "unset" cannot
319
+ * be expressed as a nullable Boolean parameter. Read it before leaving the
320
+ * @ReactMethod body: Dynamic instances are pooled and recycled.
321
+ */
322
+ private fun Dynamic.optionalBoolean(): Boolean? =
323
+ if (isNull || type != ReadableType.Boolean) null else asBoolean()
324
+
325
+ @ReactMethod
326
+ fun getRequiredPermissions(includeBluetooth: Dynamic, promise: Promise) {
327
+ try {
328
+ val bluetooth = includeBluetooth.optionalBoolean()
329
+ val permissions =
330
+ if (bluetooth == null) DoorstepAI.getRequiredPermissions()
331
+ else DoorstepAI.getRequiredPermissions(bluetooth)
332
+ val arr = Arguments.createArray()
333
+ permissions.forEach { arr.pushString(it) }
334
+ promise.resolve(arr)
335
+ } catch (e: Exception) {
336
+ promise.reject("PERMISSION_ERROR", e.message ?: "Failed to read required permissions")
337
+ }
338
+ }
339
+
340
+ @ReactMethod
341
+ fun hasRequiredPermissions(includeBluetooth: Dynamic, promise: Promise) {
342
+ try {
343
+ val bluetooth = includeBluetooth.optionalBoolean()
344
+ promise.resolve(
345
+ if (bluetooth == null) DoorstepAI.hasRequiredPermissions(reactContext)
346
+ else DoorstepAI.hasRequiredPermissions(reactContext, bluetooth)
347
+ )
348
+ } catch (e: Exception) {
349
+ promise.reject("PERMISSION_ERROR", e.message ?: "Failed to check required permissions")
350
+ }
351
+ }
352
+
353
+ @ReactMethod
354
+ fun hasBackgroundLocationPermission(promise: Promise) {
355
+ try {
356
+ promise.resolve(DoorstepAI.hasBackgroundLocationPermission(reactContext))
357
+ } catch (e: Exception) {
358
+ promise.reject("PERMISSION_ERROR", e.message ?: "Failed to check background location permission")
359
+ }
360
+ }
361
+
362
+ // ---- checkPermissions / requestPermissions (the published public surface) ----
363
+ //
364
+ // Reading a permission's state and OWNING permission policy are two different
365
+ // things. Everything here does the first: ContextCompat.checkSelfPermission on
366
+ // the names NATIVE returns from getRequiredPermissions(). The wrapper keeps no
367
+ // permission list of its own, and the request itself is dispatched to
368
+ // DoorstepAI.requestPermissions(activity, requestCode, includeBluetooth).
369
+
370
+ /**
371
+ * Which public bucket a NATIVE-named permission is reported under. This is not a
372
+ * permission list — `DoorstepAI.getRequiredPermissions()` remains the only source
373
+ * of what the SDK needs; this only decides which of the three public keys each of
374
+ * those names lands in. Names outside the three buckets (POST_NOTIFICATIONS) are
375
+ * not part of the public surface and are not reported.
376
+ */
377
+ private fun bucketOf(permission: String): String? = when (permission) {
378
+ Manifest.permission.ACCESS_FINE_LOCATION,
379
+ Manifest.permission.ACCESS_COARSE_LOCATION,
380
+ Manifest.permission.ACCESS_BACKGROUND_LOCATION -> "location"
381
+ Manifest.permission.ACTIVITY_RECOGNITION -> "motion"
382
+ Manifest.permission.BLUETOOTH_SCAN,
383
+ Manifest.permission.BLUETOOTH_CONNECT,
384
+ Manifest.permission.NEARBY_WIFI_DEVICES -> "bluetooth"
385
+ else -> null
386
+ }
387
+
388
+ /**
389
+ * `granted` / `denied` / `prompt` for a single OS permission.
390
+ *
391
+ * [justRequested] carries the names this call itself put on screen. Android has
392
+ * no "permanently denied" query: after a second denial
393
+ * `shouldShowRequestPermissionRationale` goes back to false, indistinguishable
394
+ * from never-asked. Inside a request we do not have to guess — anything we just
395
+ * asked for that is still not granted was denied by the user.
396
+ */
397
+ private fun permissionState(
398
+ permission: String,
399
+ activity: Activity?,
400
+ justRequested: Set<String>
401
+ ): String {
402
+ if (ContextCompat.checkSelfPermission(reactContext, permission) ==
403
+ PackageManager.PERMISSION_GRANTED
404
+ ) {
405
+ return "granted"
406
+ }
407
+ if (permission in justRequested) return "denied"
408
+ if (activity != null &&
409
+ ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)
410
+ ) {
411
+ return "denied"
412
+ }
413
+ return "prompt"
414
+ }
415
+
416
+ /**
417
+ * `{ permissions: { location, motion, bluetooth } }`.
418
+ *
419
+ * A bucket that native names nothing for on this OS version resolves to
420
+ * `granted`, because nothing is withheld: `motion` always (the Android SDK's
421
+ * sensor collection needs no runtime grant — `getRequiredPermissions` never
422
+ * returns ACTIVITY_RECOGNITION), and `bluetooth` below API 31.
423
+ */
424
+ private fun permissionStatusPayload(justRequested: Set<String> = emptySet()): WritableMap {
425
+ val activity = currentActivity
426
+ val byBucket = mutableMapOf<String, MutableList<String>>()
427
+ DoorstepAI.getRequiredPermissions(includeBluetooth = true).forEach { name ->
428
+ bucketOf(name)?.let { byBucket.getOrPut(it) { mutableListOf() }.add(name) }
429
+ }
430
+
431
+ val permissions = Arguments.createMap()
432
+ for (bucket in PUBLIC_PERMISSION_BUCKETS) {
433
+ // Read each name ONCE: `shouldShowRequestPermissionRationale` is an OS call,
434
+ // and two reads of the same permission could disagree across a grant landing
435
+ // mid-aggregation. Worst state wins.
436
+ val states = byBucket[bucket].orEmpty().map { permissionState(it, activity, justRequested) }
437
+ val state = when {
438
+ states.isEmpty() -> "granted"
439
+ states.contains("denied") -> "denied"
440
+ states.contains("prompt") -> "prompt"
441
+ else -> "granted"
442
+ }
443
+ permissions.putString(bucket, state)
444
+ }
445
+
446
+ val out = Arguments.createMap()
447
+ out.putMap("permissions", permissions)
448
+ return out
449
+ }
450
+
451
+ @ReactMethod
452
+ fun checkPermissions(promise: Promise) {
453
+ try {
454
+ promise.resolve(permissionStatusPayload())
455
+ } catch (e: Exception) {
456
+ promise.reject("PERMISSION_ERROR", e.message ?: "Failed to read permission status")
457
+ }
458
+ }
459
+
460
+ // In-flight request state. Main-thread confined.
461
+ private var pendingPermissionPromise: Promise? = null
462
+ private var pendingPermissionRequested: Set<String> = emptySet()
463
+ private var permissionLifecycleListener: LifecycleEventListener? = null
464
+ private var permissionTimeoutRunnable: Runnable? = null
465
+ private var permissionPollRunnable: Runnable? = null
466
+ private val mainHandler = Handler(Looper.getMainLooper())
467
+
468
+ /**
469
+ * Android half of the cross-platform requester.
470
+ *
471
+ * `options.permissions` can only narrow Bluetooth: the native call requests its
472
+ * whole required set behind one `includeBluetooth` flag, so
473
+ * `includeBluetooth = permissions.contains("bluetooth")` (true when `permissions`
474
+ * is absent) and location + motion always ride the base set.
475
+ *
476
+ * Resolves a PermissionStatus **after the user has answered**. The grant result
477
+ * of `ActivityCompat.requestPermissions` lands in the Activity's
478
+ * `onRequestPermissionsResult`, which RN does not route to a module that issued
479
+ * the request itself, so the answer is observed instead: the dialog pauses the
480
+ * host activity, so the pause→resume pair marks it dismissed; a poll catches a
481
+ * grant that somehow arrives without that pair; and a timeout keeps the promise
482
+ * from hanging forever if the user simply never answers.
483
+ *
484
+ * ACCESS_BACKGROUND_LOCATION is deliberately not part of this: Android 11+ needs
485
+ * it as a SECOND prompt after the foreground grant and refuses to bundle it, so
486
+ * it keeps its own entry point ([requestBackgroundLocationPermission]).
487
+ */
488
+ @ReactMethod
489
+ fun requestPermissions(options: ReadableMap?, promise: Promise) {
490
+ val selected: Set<String>? =
491
+ if (options != null && options.hasKey("permissions") && !options.isNull("permissions")) {
492
+ val arr = options.getArray("permissions")
493
+ if (arr == null) null
494
+ else (0 until arr.size()).mapNotNull { arr.getString(it) }.toSet()
495
+ } else {
496
+ null
497
+ }
498
+ val includeBluetooth = selected == null || selected.contains("bluetooth")
499
+
500
+ val activity = currentActivity
501
+ if (activity == null) {
502
+ promise.reject("NO_ACTIVITY", "requestPermissions needs a resumed Activity to prompt from")
503
+ return
504
+ }
505
+ // ActivityCompat.requestPermissions must be issued from the main thread;
506
+ // @ReactMethod bodies run on the native-modules thread.
507
+ UiThreadUtil.runOnUiThread {
508
+ if (pendingPermissionPromise != null) {
509
+ promise.reject(
510
+ "E_PERMISSION_REQUEST_IN_FLIGHT",
511
+ "A permission request is already awaiting the user's answer."
512
+ )
513
+ return@runOnUiThread
514
+ }
515
+ try {
516
+ val requested = DoorstepAI.requestPermissions(
517
+ activity,
518
+ DoorstepAI.PERMISSION_REQUEST_CODE,
519
+ includeBluetooth
520
+ )
521
+ if (requested.isEmpty()) {
522
+ // Nothing left to ask: the state on file is already the final answer.
523
+ promise.resolve(permissionStatusPayload())
524
+ return@runOnUiThread
525
+ }
526
+
527
+ pendingPermissionPromise = promise
528
+ pendingPermissionRequested = requested.toSet()
529
+
530
+ // The permission dialog is an activity: it pauses the host, and the resume
531
+ // that follows means it is gone. `addLifecycleEventListener` fires
532
+ // onHostResume immediately when the host is already RESUMED, which is the
533
+ // case here, so a resume only counts after a pause has been seen.
534
+ val listener = object : LifecycleEventListener {
535
+ private var sawPause = false
536
+ override fun onHostResume() {
537
+ if (sawPause) settlePermissionRequest(answered = true)
538
+ }
539
+
540
+ override fun onHostPause() {
541
+ sawPause = true
542
+ }
543
+
544
+ override fun onHostDestroy() {
545
+ settlePermissionRequest(answered = false)
546
+ }
547
+ }
548
+ permissionLifecycleListener = listener
549
+ reactContext.addLifecycleEventListener(listener)
550
+
551
+ // Backstop 1: a grant is visible without waiting for the lifecycle pair.
552
+ val poll = object : Runnable {
553
+ override fun run() {
554
+ if (pendingPermissionPromise == null) return
555
+ val allGranted = pendingPermissionRequested.all {
556
+ ContextCompat.checkSelfPermission(reactContext, it) ==
557
+ PackageManager.PERMISSION_GRANTED
558
+ }
559
+ if (allGranted) settlePermissionRequest(answered = true)
560
+ else mainHandler.postDelayed(this, PERMISSION_POLL_MS)
561
+ }
562
+ }
563
+ permissionPollRunnable = poll
564
+ mainHandler.postDelayed(poll, PERMISSION_POLL_MS)
565
+
566
+ // Backstop 2: the user never answers. Resolve with the state as it stands
567
+ // rather than leaving the promise pending forever.
568
+ val timeout = Runnable { settlePermissionRequest(answered = false) }
569
+ permissionTimeoutRunnable = timeout
570
+ mainHandler.postDelayed(timeout, PERMISSION_ANSWER_TIMEOUT_MS)
571
+ } catch (e: Exception) {
572
+ pendingPermissionPromise = null
573
+ promise.reject("PERMISSION_ERROR", e.message ?: "Failed to request permissions")
574
+ }
575
+ }
576
+ }
577
+
578
+ /**
579
+ * @param answered true when the dialog is known to be gone, which is what makes
580
+ * "requested but still not granted" mean DENIED. On a timeout it is false: the
581
+ * prompt may still be up, and calling that a denial would be a guess.
582
+ */
583
+ private fun settlePermissionRequest(answered: Boolean) {
584
+ UiThreadUtil.runOnUiThread {
585
+ val promise = pendingPermissionPromise ?: return@runOnUiThread
586
+ val requested = pendingPermissionRequested
587
+ pendingPermissionPromise = null
588
+ pendingPermissionRequested = emptySet()
589
+ permissionLifecycleListener?.let { reactContext.removeLifecycleEventListener(it) }
590
+ permissionLifecycleListener = null
591
+ permissionTimeoutRunnable?.let { mainHandler.removeCallbacks(it) }
592
+ permissionTimeoutRunnable = null
593
+ permissionPollRunnable?.let { mainHandler.removeCallbacks(it) }
594
+ permissionPollRunnable = null
595
+ try {
596
+ promise.resolve(permissionStatusPayload(if (answered) requested else emptySet()))
597
+ } catch (e: Exception) {
598
+ promise.reject("PERMISSION_ERROR", e.message ?: "Failed to read permission status")
599
+ }
600
+ }
601
+ }
602
+
603
+ @ReactMethod
604
+ fun requestBackgroundLocationPermission(promise: Promise) {
605
+ val activity = currentActivity
606
+ if (activity == null) {
607
+ promise.reject("NO_ACTIVITY", "requestBackgroundLocationPermission needs a resumed Activity to prompt from")
608
+ return
609
+ }
610
+ UiThreadUtil.runOnUiThread {
611
+ try {
612
+ promise.resolve(DoorstepAI.requestBackgroundLocationPermission(activity))
613
+ } catch (e: Exception) {
614
+ promise.reject("PERMISSION_ERROR", e.message ?: "Failed to request background location permission")
615
+ }
616
+ }
617
+ }
618
+
295
619
  private fun parseCoordinates(map: ReadableMap?): LatLngObject? {
296
620
  if (map == null) return null
297
621
  val lat = if (map.hasKey("lat")) map.getDouble("lat") else return null
@@ -398,6 +722,9 @@ class DoorstepAIModule(private val reactContext: ReactApplicationContext) :
398
722
  override fun invalidate() {
399
723
  geofenceJob?.cancel()
400
724
  geofenceJob = null
725
+ // A permission request outliving the module would leave the JS promise pending
726
+ // forever; settle it with whatever the OS currently reports.
727
+ settlePermissionRequest(answered = false)
401
728
  super.invalidate()
402
729
  }
403
730
 
@@ -448,5 +775,10 @@ class DoorstepAIModule(private val reactContext: ReactApplicationContext) :
448
775
  companion object {
449
776
  const val NAME = "DoorstepAI"
450
777
  private const val GEOFENCE_EVENT = "DoorstepGeofenceSessionEvent"
778
+
779
+ /** The three public permission keys, in a fixed order. */
780
+ private val PUBLIC_PERMISSION_BUCKETS = listOf("location", "motion", "bluetooth")
781
+ private const val PERMISSION_POLL_MS = 250L
782
+ private const val PERMISSION_ANSWER_TIMEOUT_MS = 120_000L
451
783
  }
452
784
  }
package/ios/DoorstepAI.mm CHANGED
@@ -4,8 +4,11 @@
4
4
  @interface RCT_EXTERN_MODULE(DoorstepAI, RCTEventEmitter)
5
5
 
6
6
  RCT_EXTERN_METHOD(setApiKey:(nonnull NSString *)apiKey)
7
- RCT_EXTERN_METHOD(requestAllPermissions:(BOOL)requestAlwaysLocation
8
- requestBluetooth:(BOOL)requestBluetooth)
7
+ RCT_EXTERN_METHOD(checkPermissions:(RCTPromiseResolveBlock)resolve
8
+ rejecter:(RCTPromiseRejectBlock)reject)
9
+ RCT_EXTERN_METHOD(requestPermissions:(nullable NSDictionary *)options
10
+ resolver:(RCTPromiseResolveBlock)resolve
11
+ rejecter:(RCTPromiseRejectBlock)reject)
9
12
  RCT_EXTERN_METHOD(configureRemoteLogging:(BOOL)enabled
10
13
  minLevel:(id)minLevel
11
14
  flushIntervalSeconds:(id)flushIntervalSeconds