@doorstepai/dropoff-sdk 2.2.0 → 2.2.3

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/README.md +265 -112
  2. package/android/build.gradle +5 -1
  3. package/android/src/main/java/com/doorstepai/dropoffsdk/DoorstepAIModule.kt +368 -136
  4. package/ios/DoorstepAI.mm +8 -1
  5. package/ios/DoorstepAI.swift +120 -139
  6. package/ios/DoorstepDropoffSDK.xcframework/Info.plist +5 -5
  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 +10176 -6209
  9. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/arm64-apple-ios.private.swiftinterface +82 -0
  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 +82 -0
  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 +3867 -3248
  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 +10176 -6209
  17. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/arm64-apple-ios-simulator.private.swiftinterface +82 -0
  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 +82 -0
  20. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/x86_64-apple-ios-simulator.abi.json +10176 -6209
  21. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/x86_64-apple-ios-simulator.private.swiftinterface +82 -0
  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 +82 -0
  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 +3868 -3248
  27. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/dSYMs/DoorstepDropoffSDK.framework.dSYM/Contents/Resources/Relocations/x86_64/DoorstepDropoffSDK.yml +3836 -3233
  28. package/lib/module/DoorstepAI.js +306 -71
  29. package/lib/module/DoorstepAI.js.map +1 -1
  30. package/lib/module/RootDoorstepAI.js +50 -32
  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 +271 -73
  34. package/lib/typescript/src/DoorstepAI.d.ts.map +1 -1
  35. package/lib/typescript/src/RootDoorstepAI.d.ts +24 -7
  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 +1 -1
  40. package/src/DoorstepAI.tsx +425 -91
  41. package/src/RootDoorstepAI.tsx +75 -45
  42. package/src/index.tsx +6 -0
@@ -1,11 +1,8 @@
1
1
  package com.doorstepai.dropoffsdk
2
2
 
3
- import android.Manifest
4
- import android.app.Activity
5
3
  import android.content.pm.PackageManager
6
4
  import android.os.Handler
7
5
  import android.os.Looper
8
- import androidx.core.app.ActivityCompat
9
6
  import androidx.core.content.ContextCompat
10
7
  import com.facebook.react.bridge.LifecycleEventListener
11
8
  import com.facebook.react.bridge.NativeModule
@@ -28,6 +25,9 @@ import com.facebook.react.bridge.UiThreadUtil
28
25
  import com.facebook.react.modules.core.DeviceEventManagerModule
29
26
  import com.doorstepai.sdks.tracking.DeliveryStop
30
27
  import com.doorstepai.sdks.tracking.RouteGeofenceOptions
28
+ import com.doorstepai.sdks.tracking.DoorstepPermission
29
+ import com.doorstepai.sdks.tracking.DoorstepPermissionState
30
+ import com.doorstepai.sdks.tracking.DoorstepPermissionStatus
31
31
  import kotlinx.coroutines.Dispatchers
32
32
  import kotlinx.coroutines.CoroutineScope
33
33
  import kotlinx.coroutines.SupervisorJob
@@ -223,11 +223,21 @@ class DoorstepAIModule(private val reactContext: ReactApplicationContext) :
223
223
  }
224
224
  }
225
225
 
226
+ /**
227
+ * Resolves on the SDK's own callback rather than immediately. The previous
228
+ * version discarded the `Result` and always resolved, so a rejected event —
229
+ * unknown deliveryId, no session — reached JS as a success.
230
+ */
226
231
  @ReactMethod
227
232
  fun newEvent(eventName: String, deliveryId: String, timestamp: Double?, promise: Promise) {
228
233
  try {
229
- DoorstepAI.newEvent(eventName, deliveryId, timestamp) { /* Callback not needed here */ }
230
- promise.resolve("Event $eventName triggered for $deliveryId")
234
+ DoorstepAI.newEvent(eventName, deliveryId, timestamp) { result ->
235
+ result.onSuccess { message ->
236
+ promise.resolve(message)
237
+ }.onFailure { error ->
238
+ promise.reject("EVENT_CREATION_ERROR", error.message ?: "Failed to save event")
239
+ }
240
+ }
231
241
  } catch (e: Exception) {
232
242
  promise.reject("EVENT_CREATION_ERROR", e.message ?: "Failed to save event")
233
243
  }
@@ -269,6 +279,27 @@ class DoorstepAIModule(private val reactContext: ReactApplicationContext) :
269
279
  return true
270
280
  }
271
281
 
282
+ @ReactMethod(isBlockingSynchronousMethod = true)
283
+ fun setDoorstepGoApiKey(key: String): Boolean {
284
+ DoorstepAI.setDoorstepGoApiKey(key)
285
+ return true
286
+ }
287
+
288
+ /**
289
+ * Re-registers the raw-GNSS callbacks. Some devices (the S22U among them) stop
290
+ * delivering measurements without reporting an error; this is the SDK's recovery
291
+ * hook for that. Android-only by nature — iOS has no raw-GNSS API at all.
292
+ */
293
+ @ReactMethod
294
+ fun retryGnssCallbacks(promise: Promise) {
295
+ try {
296
+ DoorstepAI.retryGnssCallbacks()
297
+ promise.resolve(true)
298
+ } catch (e: Exception) {
299
+ promise.reject("GNSS_RETRY_ERROR", e.message ?: "Failed to retry GNSS callbacks")
300
+ }
301
+ }
302
+
272
303
  @ReactMethod
273
304
  fun enableDevMode(promise: Promise) {
274
305
  CoroutineScope(Dispatchers.IO).launch {
@@ -359,99 +390,129 @@ class DoorstepAIModule(private val reactContext: ReactApplicationContext) :
359
390
  }
360
391
  }
361
392
 
362
- // ---- checkPermissions / requestPermissions (the published public surface) ----
393
+ // ---- checkPermissions / requestPermissions (the whitelist surface) ----
394
+ //
395
+ // Pass-throughs to the SDK's whitelist permission API. The SDK owns the buckets,
396
+ // the eight-state vocabulary and the request plan — including the two rules a
397
+ // wrapper must never re-derive: LOCATION_ALWAYS is requested only alone and only
398
+ // after foreground location is granted, and a permanently-denied bucket is not
399
+ // asked at all (the OS would answer with an instant denial and no dialog).
363
400
  //
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).
401
+ // What used to live here was a hand-rolled `location`/`motion`/`bluetooth`
402
+ // bucketing over `getRequiredPermissions()` plus a three-value state machine.
403
+ // It could not express WHEN_IN_USE_ONLY (foreground held, background not — the
404
+ // state in which background collection and route geofencing silently do not
405
+ // work), nor NOT_DECLARED (a host-manifest omission, which is not a user
406
+ // refusal). Both are now reported verbatim from native.
407
+
408
+ /** The public bucket names, in native's own `wireName` spelling. */
409
+ private fun parseWhitelist(arr: ReadableArray?): Set<DoorstepPermission> {
410
+ // An ABSENT array means "no whitelist" — every bucket. An EMPTY array is a
411
+ // different statement: the caller narrowed it down to nothing, and answering
412
+ // that with "then I'll ask for everything" would invert their intent.
413
+ if (arr == null) return DoorstepPermission.ALL
414
+ val out = linkedSetOf<DoorstepPermission>()
415
+ for (i in 0 until arr.size()) {
416
+ val name = if (arr.getType(i) == ReadableType.String) arr.getString(i) else null
417
+ DoorstepPermission.fromWireName(name ?: continue)?.let { out.add(it) }
418
+ }
419
+ return out
420
+ }
369
421
 
370
422
  /**
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.
423
+ * Legacy three-key view of the eight-state buckets, kept so hosts written
424
+ * against the published 2.x wrapper API keep working. `location` is the
425
+ * foreground bucket — the Always-vs-When-In-Use distinction cannot survive three
426
+ * values, which is exactly what `statuses.locationAlways` is for.
376
427
  */
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
428
+ private fun legacyPermissionsView(
429
+ statuses: Map<DoorstepPermission, DoorstepPermissionStatus>
430
+ ): WritableMap {
431
+ fun collapse(permission: DoorstepPermission): String =
432
+ when (statuses[permission]?.state) {
433
+ DoorstepPermissionState.GRANTED,
434
+ DoorstepPermissionState.WHEN_IN_USE_ONLY,
435
+ DoorstepPermissionState.UNAVAILABLE -> "granted"
436
+ DoorstepPermissionState.NOT_DETERMINED -> "prompt"
437
+ null -> "prompt"
438
+ else -> "denied"
439
+ }
440
+ val m = Arguments.createMap()
441
+ m.putString("location", collapse(DoorstepPermission.LOCATION_WHEN_IN_USE))
442
+ // `motion` answers "can the SDK collect motion data", and on Android the answer
443
+ // is unconditionally yes: the IMU streams (accel, gyro, mag, rotation vectors,
444
+ // barometer) need NO runtime grant. ACTIVITY_RECOGNITION adds only the
445
+ // step-counter/step-detector streams, which is why the SDK leaves it out of
446
+ // `getRequiredPermissions()` and never blocks a session on it.
447
+ //
448
+ // So this is NOT collapsed from the ACTIVITY_RECOGNITION bucket, deliberately.
449
+ // Collapsing it would report `prompt`/`denied` for an optional stream and hand
450
+ // hosts a value that reads like "motion is unavailable" — and host code of the
451
+ // shape `if (permissions.motion === 'granted') startDelivery(...)` would then
452
+ // fail closed across a whole fleet on wrapper upgrade, silently, for a
453
+ // permission this wrapper could not even request before 2.2.0. Read
454
+ // `statuses.activityRecognition` for the real bucket state.
455
+ m.putString("motion", "granted")
456
+ m.putString("bluetooth", collapse(DoorstepPermission.BLUETOOTH_SCAN))
457
+ return m
386
458
  }
387
459
 
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"
460
+ private fun serializeStatuses(
461
+ statuses: Map<DoorstepPermission, DoorstepPermissionStatus>
462
+ ): WritableMap {
463
+ val out = Arguments.createMap()
464
+ statuses.forEach { (permission, status) ->
465
+ val m = Arguments.createMap()
466
+ m.putString("permission", permission.wireName)
467
+ m.putString("state", status.state.name.toWireState())
468
+ m.putString("osStatus", status.osStatus)
469
+ m.putBoolean("canRequest", status.canRequest)
470
+ out.putMap(permission.wireName, m)
412
471
  }
413
- return "prompt"
472
+ return out
414
473
  }
415
474
 
416
475
  /**
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.
476
+ * `WHEN_IN_USE_ONLY` -> `whenInUseOnly`. Android's enum is SCREAMING_SNAKE and
477
+ * iOS's is lowerCamel; the JS surface uses one spelling on both platforms so
478
+ * host code can branch once, and lowerCamel is the one iOS already ships.
423
479
  */
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
-
480
+ private fun String.toWireState(): String =
481
+ split('_').mapIndexed { i, part ->
482
+ if (i == 0) part.lowercase() else part.lowercase().replaceFirstChar { it.uppercase() }
483
+ }.joinToString("")
484
+
485
+ private fun statusPayload(
486
+ statuses: Map<DoorstepPermission, DoorstepPermissionStatus>
487
+ ): WritableMap {
446
488
  val out = Arguments.createMap()
447
- out.putMap("permissions", permissions)
489
+ out.putMap("statuses", serializeStatuses(statuses))
490
+ out.putMap("permissions", legacyPermissionsView(statuses))
491
+ out.putArray("unsupported", Arguments.createArray())
448
492
  return out
449
493
  }
450
494
 
495
+ /**
496
+ * Pass an Activity when there is one: it is the only way
497
+ * `shouldShowRequestPermissionRationale` can be consulted, and without that
498
+ * signal a refusal reports as the re-askable DENIED instead of
499
+ * PERMANENTLY_DENIED.
500
+ */
501
+ private fun permissionContext() = currentActivity ?: reactContext
502
+
503
+ @ReactMethod
504
+ fun checkPermissions(permissions: ReadableArray?, promise: Promise) {
505
+ try {
506
+ promise.resolve(statusPayload(DoorstepAI.checkPermissions(permissionContext(), parseWhitelist(permissions))))
507
+ } catch (e: Exception) {
508
+ promise.reject("PERMISSION_ERROR", e.message ?: "Failed to read permission status")
509
+ }
510
+ }
511
+
451
512
  @ReactMethod
452
- fun checkPermissions(promise: Promise) {
513
+ fun checkPermissionsJson(permissions: ReadableArray?, promise: Promise) {
453
514
  try {
454
- promise.resolve(permissionStatusPayload())
515
+ promise.resolve(DoorstepAI.checkPermissionsJson(permissionContext(), parseWhitelist(permissions)))
455
516
  } catch (e: Exception) {
456
517
  promise.reject("PERMISSION_ERROR", e.message ?: "Failed to read permission status")
457
518
  }
@@ -460,6 +521,9 @@ class DoorstepAIModule(private val reactContext: ReactApplicationContext) :
460
521
  // In-flight request state. Main-thread confined.
461
522
  private var pendingPermissionPromise: Promise? = null
462
523
  private var pendingPermissionRequested: Set<String> = emptySet()
524
+ private var pendingPermissionWhitelist: Set<DoorstepPermission> = emptySet()
525
+ private var pendingPermissionPlan: WritableMap? = null
526
+ private var pendingPermissionActivity: java.lang.ref.WeakReference<android.app.Activity>? = null
463
527
  private var permissionLifecycleListener: LifecycleEventListener? = null
464
528
  private var permissionTimeoutRunnable: Runnable? = null
465
529
  private var permissionPollRunnable: Runnable? = null
@@ -468,34 +532,40 @@ class DoorstepAIModule(private val reactContext: ReactApplicationContext) :
468
532
  /**
469
533
  * Android half of the cross-platform requester.
470
534
  *
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.
535
+ * `options.permissions` is the whitelist and it is honoured exactly: absent
536
+ * requests every bucket, an array requests only those buckets. Everything the
537
+ * native planner declines to ask comes back explained — `alreadyDetermined`,
538
+ * `unavailable`, `deferred` — rather than silently not happening.
475
539
  *
476
540
  * Resolves a PermissionStatus **after the user has answered**. The grant result
477
541
  * 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]).
542
+ * `onRequestPermissionsResult`, which RN does not route back to a module that
543
+ * did not issue the request itself, so the answer is observed three ways:
544
+ * - the host can forward the real result ([notePermissionRequestResult]) —
545
+ * the only path that also lets native tell DENIED from PERMANENTLY_DENIED;
546
+ * - otherwise the dialog pauses the host activity, so a pause→resume pair
547
+ * means it is gone;
548
+ * - a poll catches a grant that somehow arrives without that pair, and a
549
+ * timeout keeps the promise from hanging if the user never answers.
487
550
  */
488
551
  @ReactMethod
489
552
  fun requestPermissions(options: ReadableMap?, promise: Promise) {
490
- val selected: Set<String>? =
553
+ val whitelist =
491
554
  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()
555
+ parseWhitelist(options.getArray("permissions") ?: Arguments.createArray())
495
556
  } else {
496
- null
557
+ DoorstepPermission.ALL
558
+ }
559
+
560
+ // Same knob as iOS, where it is a native parameter: how long to wait for the
561
+ // user's answer before resolving with the state as it stands. Android's
562
+ // requester has no native timeout, so the wait lives here.
563
+ val answerTimeoutMs =
564
+ if (options != null && options.hasKey("timeoutSeconds") && !options.isNull("timeoutSeconds")) {
565
+ (options.getDouble("timeoutSeconds") * 1000).toLong().coerceAtLeast(1_000L)
566
+ } else {
567
+ PERMISSION_ANSWER_TIMEOUT_MS
497
568
  }
498
- val includeBluetooth = selected == null || selected.contains("bluetooth")
499
569
 
500
570
  val activity = currentActivity
501
571
  if (activity == null) {
@@ -513,61 +583,108 @@ class DoorstepAIModule(private val reactContext: ReactApplicationContext) :
513
583
  return@runOnUiThread
514
584
  }
515
585
  try {
516
- val requested = DoorstepAI.requestPermissions(
517
- activity,
518
- DoorstepAI.PERMISSION_REQUEST_CODE,
519
- includeBluetooth
586
+ val result = DoorstepAI.requestPermissions(activity, whitelist)
587
+ android.util.Log.i(
588
+ LOG_TAG,
589
+ "requestPermissions whitelist=${whitelist.map { it.wireName }} " +
590
+ "asked=${result.requested} didRequest=${result.didRequest} " +
591
+ "deferred=${result.deferred.keys.map { it.wireName }}"
520
592
  )
521
- if (requested.isEmpty()) {
522
- // Nothing left to ask: the state on file is already the final answer.
523
- promise.resolve(permissionStatusPayload())
593
+ val plan = Arguments.createMap()
594
+ plan.putArray("requested", wireNames(result.requestedBuckets))
595
+ plan.putArray("alreadyDetermined", wireNames(result.alreadyGranted))
596
+ plan.putArray("unavailable", wireNames(result.unavailable))
597
+ plan.putBoolean("didRequest", result.didRequest)
598
+ val deferred = Arguments.createMap()
599
+ result.deferred.forEach { (permission, reason) -> deferred.putString(permission.wireName, reason) }
600
+ plan.putMap("deferred", deferred)
601
+ val androidPermissions = Arguments.createArray()
602
+ result.requested.forEach { androidPermissions.pushString(it) }
603
+ plan.putArray("androidPermissions", androidPermissions)
604
+
605
+ if (!result.didRequest) {
606
+ // No dialog was shown and onRequestPermissionsResult will never fire, so
607
+ // the state on file is already the final answer — do not wait for one.
608
+ promise.resolve(mergePlan(statusPayload(DoorstepAI.checkPermissions(activity, whitelist)), plan))
524
609
  return@runOnUiThread
525
610
  }
526
611
 
527
612
  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.
613
+ pendingPermissionRequested = result.requested.toSet()
614
+ pendingPermissionWhitelist = whitelist
615
+ pendingPermissionPlan = plan
616
+ pendingPermissionActivity = java.lang.ref.WeakReference(activity)
617
+
618
+ // How the answer is observed, in order of how much it actually proves.
619
+ //
620
+ // NOT by the activity-lifecycle pause→resume pair, which is what this code
621
+ // used to do and which is WRONG: on this device the pair arrives ~19 ms
622
+ // after `ActivityCompat.requestPermissions` — RN's own startup lifecycle
623
+ // transitions land on the UI thread right behind the request — so the
624
+ // promise resolved with pre-answer state while the dialog was still on
625
+ // screen (measured, Moto G stylus 5G / API 34). "The host was paused and
626
+ // resumed" is not "the user answered".
627
+ //
628
+ // Window focus is the signal that tracks the dialog: the permission
629
+ // controller takes focus off the host activity for the whole sequence of
630
+ // prompts and hands it back only when the last one is gone. It is a local
631
+ // read, no IPC, and it does not care how many dialogs the OS decided to
632
+ // show.
534
633
  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
-
634
+ override fun onHostResume() = Unit
635
+ override fun onHostPause() = Unit
544
636
  override fun onHostDestroy() {
545
- settlePermissionRequest(answered = false)
637
+ settlePermissionRequest(answered = false, source = "destroy")
546
638
  }
547
639
  }
548
640
  permissionLifecycleListener = listener
549
641
  reactContext.addLifecycleEventListener(listener)
550
642
 
551
- // Backstop 1: a grant is visible without waiting for the lifecycle pair.
643
+ val requestedAt = android.os.SystemClock.elapsedRealtime()
552
644
  val poll = object : Runnable {
645
+ private var sawFocusLost = false
553
646
  override fun run() {
554
647
  if (pendingPermissionPromise == null) return
555
- val allGranted = pendingPermissionRequested.all {
556
- ContextCompat.checkSelfPermission(reactContext, it) ==
557
- PackageManager.PERMISSION_GRANTED
648
+ // A grant is visible: nothing left to wait for, whatever the window is
649
+ // doing. (Not sufficient on its own — a denial never shows up here.)
650
+ if (pendingPermissionRequested.isNotEmpty() &&
651
+ pendingPermissionRequested.all {
652
+ ContextCompat.checkSelfPermission(reactContext, it) ==
653
+ PackageManager.PERMISSION_GRANTED
654
+ }
655
+ ) {
656
+ settlePermissionRequest(answered = true, source = "granted")
657
+ return
658
+ }
659
+ val act = pendingPermissionActivity?.get()
660
+ val hasFocus = act?.hasWindowFocus() ?: true
661
+ if (!hasFocus) {
662
+ sawFocusLost = true
663
+ } else if (sawFocusLost) {
664
+ // Focus left for the dialog and has come back: the sequence is over
665
+ // and anything still not granted was refused.
666
+ settlePermissionRequest(answered = true, source = "focusReturned")
667
+ return
668
+ } else if (android.os.SystemClock.elapsedRealtime() - requestedAt >
669
+ minOf(PERMISSION_DIALOG_GRACE_MS, answerTimeoutMs)
670
+ ) {
671
+ // Focus never left. The OS decided not to show a dialog at all (it
672
+ // does that for an instantly-refused request), so there is no answer
673
+ // coming and waiting out the full timeout would just hang the host.
674
+ settlePermissionRequest(answered = false, source = "noDialog")
675
+ return
558
676
  }
559
- if (allGranted) settlePermissionRequest(answered = true)
560
- else mainHandler.postDelayed(this, PERMISSION_POLL_MS)
677
+ mainHandler.postDelayed(this, PERMISSION_POLL_MS)
561
678
  }
562
679
  }
563
680
  permissionPollRunnable = poll
564
681
  mainHandler.postDelayed(poll, PERMISSION_POLL_MS)
565
682
 
566
- // Backstop 2: the user never answers. Resolve with the state as it stands
683
+ // Last resort: the user never answers. Resolve with the state as it stands
567
684
  // rather than leaving the promise pending forever.
568
- val timeout = Runnable { settlePermissionRequest(answered = false) }
685
+ val timeout = Runnable { settlePermissionRequest(answered = false, source = "timeout") }
569
686
  permissionTimeoutRunnable = timeout
570
- mainHandler.postDelayed(timeout, PERMISSION_ANSWER_TIMEOUT_MS)
687
+ mainHandler.postDelayed(timeout, answerTimeoutMs)
571
688
  } catch (e: Exception) {
572
689
  pendingPermissionPromise = null
573
690
  promise.reject("PERMISSION_ERROR", e.message ?: "Failed to request permissions")
@@ -575,17 +692,66 @@ class DoorstepAIModule(private val reactContext: ReactApplicationContext) :
575
692
  }
576
693
  }
577
694
 
695
+ private fun wireNames(permissions: Collection<DoorstepPermission>) =
696
+ Arguments.createArray().also { arr -> permissions.forEach { arr.pushString(it.wireName) } }
697
+
698
+ private fun mergePlan(payload: WritableMap, plan: WritableMap): WritableMap {
699
+ payload.merge(plan)
700
+ return payload
701
+ }
702
+
703
+ /**
704
+ * Forwards a real `onRequestPermissionsResult` to the SDK, from either the host
705
+ * Activity or JS.
706
+ *
707
+ * This is the ONLY way native can tell a refusal it may re-ask (DENIED) from one
708
+ * only Settings can fix (PERMANENTLY_DENIED): after a permanent denial the OS
709
+ * reports exactly what "never asked" reports, and a CANCELLED dialog leaves the
710
+ * same trace as a denial. Native therefore refuses to guess, and neither does
711
+ * this bridge — an empty `grantResults` (which is what a cancelled interaction
712
+ * delivers) is passed through as empty and native records nothing from it.
713
+ *
714
+ * A forwarded result also settles an in-flight [requestPermissions] immediately,
715
+ * which is strictly better than the lifecycle backstop: it is the answer itself
716
+ * rather than the observation that a dialog went away.
717
+ */
718
+ @ReactMethod
719
+ fun notePermissionRequestResult(
720
+ permissions: ReadableArray,
721
+ grantResults: ReadableArray,
722
+ promise: Promise
723
+ ) {
724
+ try {
725
+ val names = (0 until permissions.size()).mapNotNull { permissions.getString(it) }.toTypedArray()
726
+ val results = IntArray(grantResults.size()) { grantResults.getInt(it) }
727
+ DoorstepAI.notePermissionRequestResult(reactContext, names, results)
728
+ promise.resolve(true)
729
+ if (results.isNotEmpty()) settlePermissionRequest(answered = true, source = "noteResult")
730
+ } catch (e: Exception) {
731
+ promise.reject("PERMISSION_ERROR", e.message ?: "Failed to record permission request result")
732
+ }
733
+ }
734
+
578
735
  /**
579
736
  * @param answered true when the dialog is known to be gone, which is what makes
580
737
  * "requested but still not granted" mean DENIED. On a timeout it is false: the
581
738
  * prompt may still be up, and calling that a denial would be a guess.
582
739
  */
583
- private fun settlePermissionRequest(answered: Boolean) {
740
+ private fun settlePermissionRequest(answered: Boolean, source: String = "?") {
584
741
  UiThreadUtil.runOnUiThread {
742
+ // Two lines per permission request, on purpose: "why did my promise resolve
743
+ // when it did" is the question hosts actually ask about this API, and the
744
+ // settle SOURCE is the answer. The SDK's own logger is silenced in release
745
+ // builds, so this is the only trace a host has.
746
+ android.util.Log.i(LOG_TAG, "requestPermissions settled: source=$source answered=$answered pending=${pendingPermissionPromise != null}")
585
747
  val promise = pendingPermissionPromise ?: return@runOnUiThread
586
- val requested = pendingPermissionRequested
748
+ val whitelist = pendingPermissionWhitelist
749
+ val plan = pendingPermissionPlan
587
750
  pendingPermissionPromise = null
588
751
  pendingPermissionRequested = emptySet()
752
+ pendingPermissionWhitelist = emptySet()
753
+ pendingPermissionPlan = null
754
+ pendingPermissionActivity = null
589
755
  permissionLifecycleListener?.let { reactContext.removeLifecycleEventListener(it) }
590
756
  permissionLifecycleListener = null
591
757
  permissionTimeoutRunnable?.let { mainHandler.removeCallbacks(it) }
@@ -593,7 +759,12 @@ class DoorstepAIModule(private val reactContext: ReactApplicationContext) :
593
759
  permissionPollRunnable?.let { mainHandler.removeCallbacks(it) }
594
760
  permissionPollRunnable = null
595
761
  try {
596
- promise.resolve(permissionStatusPayload(if (answered) requested else emptySet()))
762
+ // `answered` is not forwarded to native as a denial: only a real
763
+ // host-forwarded grantResults array may write that ledger. It only decides
764
+ // whether this promise waits any longer.
765
+ val statuses = DoorstepAI.checkPermissions(permissionContext(), whitelist)
766
+ val payload = statusPayload(statuses)
767
+ promise.resolve(if (plan != null) mergePlan(payload, plan) else payload)
597
768
  } catch (e: Exception) {
598
769
  promise.reject("PERMISSION_ERROR", e.message ?: "Failed to read permission status")
599
770
  }
@@ -719,12 +890,18 @@ class DoorstepAIModule(private val reactContext: ReactApplicationContext) :
719
890
  // is torn down in invalidate(); no per-listener teardown is needed.
720
891
  }
721
892
 
893
+ override fun initialize() {
894
+ super.initialize()
895
+ activeInstance = this
896
+ }
897
+
722
898
  override fun invalidate() {
899
+ if (activeInstance === this) activeInstance = null
723
900
  geofenceJob?.cancel()
724
901
  geofenceJob = null
725
902
  // A permission request outliving the module would leave the JS promise pending
726
903
  // forever; settle it with whatever the OS currently reports.
727
- settlePermissionRequest(answered = false)
904
+ settlePermissionRequest(answered = false, source = "invalidate")
728
905
  super.invalidate()
729
906
  }
730
907
 
@@ -774,11 +951,66 @@ class DoorstepAIModule(private val reactContext: ReactApplicationContext) :
774
951
 
775
952
  companion object {
776
953
  const val NAME = "DoorstepAI"
954
+ private const val LOG_TAG = "DoorstepAI-RN"
777
955
  private const val GEOFENCE_EVENT = "DoorstepGeofenceSessionEvent"
778
956
 
957
+ /**
958
+ * The live module, so the host-Activity hook below can reach it. Cleared in
959
+ * [invalidate]; null before the bridge is up, which is exactly when there is no
960
+ * in-flight request to settle.
961
+ */
962
+ @Volatile
963
+ private var activeInstance: DoorstepAIModule? = null
964
+
965
+ /**
966
+ * **The host wiring worth copying.** Call this from your Activity's
967
+ * `onRequestPermissionsResult` and it does both halves at once:
968
+ *
969
+ * 1. forwards the answer to `DoorstepAI.notePermissionRequestResult`, which is
970
+ * the only way the SDK can tell a refusal it may re-ask (`denied`) from one
971
+ * only Settings can fix (`permanentlyDenied`) — Android reports identical
972
+ * signals for "permanently denied" and "never asked", and a *cancelled*
973
+ * dialog leaves the same trace as a denial, so the SDK will not guess;
974
+ * 2. settles an in-flight JS `requestPermissions()` on the real answer instead
975
+ * of on the window-focus heuristic.
976
+ *
977
+ * ```kotlin
978
+ * override fun onRequestPermissionsResult(
979
+ * requestCode: Int, permissions: Array<out String>, grantResults: IntArray
980
+ * ) {
981
+ * super.onRequestPermissionsResult(requestCode, permissions, grantResults)
982
+ * DoorstepAIModule.notePermissionRequestResult(this, permissions, grantResults)
983
+ * }
984
+ * ```
985
+ *
986
+ * An EMPTY [grantResults] is a cancelled interaction, not a denial: it is
987
+ * forwarded (the SDK records nothing from it) and it does not settle the
988
+ * promise, because the OS may still be showing the rest of the sequence.
989
+ */
990
+ @JvmStatic
991
+ fun notePermissionRequestResult(
992
+ context: android.content.Context,
993
+ permissions: Array<out String>,
994
+ grantResults: IntArray
995
+ ) {
996
+ DoorstepAI.notePermissionRequestResult(context, permissions, grantResults)
997
+ if (grantResults.isNotEmpty()) {
998
+ activeInstance?.settlePermissionRequest(answered = true, source = "hostResult")
999
+ }
1000
+ }
1001
+
779
1002
  /** The three public permission keys, in a fixed order. */
780
1003
  private val PUBLIC_PERMISSION_BUCKETS = listOf("location", "motion", "bluetooth")
781
1004
  private const val PERMISSION_POLL_MS = 250L
782
1005
  private const val PERMISSION_ANSWER_TIMEOUT_MS = 120_000L
1006
+
1007
+ /**
1008
+ * How long a request waits for the permission dialog to take window focus
1009
+ * before concluding the OS is not going to show one. Generous because the
1010
+ * permission-controller process may have to cold-start; the cost of being
1011
+ * wrong in this direction is only a slower resolve, while being wrong in the
1012
+ * other direction resolves with pre-answer state.
1013
+ */
1014
+ private const val PERMISSION_DIALOG_GRACE_MS = 8_000L
783
1015
  }
784
1016
  }