@app-swiss-knife/react-native-sdk 0.4.0 → 0.5.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 (177) hide show
  1. package/CHANGELOG.md +385 -2
  2. package/LICENSE +21 -0
  3. package/README.md +229 -42
  4. package/SwissKnifePurchases.podspec +1 -1
  5. package/android/build.gradle +24 -2
  6. package/android/consumer-rules.pro +12 -0
  7. package/android/src/main/AndroidManifest.xml +15 -1
  8. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +5 -4
  9. package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +7 -2
  10. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +168 -6
  11. package/android/src/play/java/com/swissknife/purchases/StoreIntentHandler.kt +7 -0
  12. package/android/src/rustore/java/com/swissknife/purchases/StoreIntentHandler.kt +9 -0
  13. package/android/vendor/java/com/appswissknife/SwissKnife.kt +107 -38
  14. package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +180 -115
  15. package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +16 -18
  16. package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +13 -13
  17. package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +56 -25
  18. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  19. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +365 -206
  20. package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +195 -26
  21. package/android/vendor/java/com/appswissknife/identity/Identity.kt +31 -6
  22. package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +5 -0
  23. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +56 -31
  24. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +673 -87
  25. package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +214 -30
  26. package/android/vendor/java/com/appswissknife/notifications/NotificationRenderer.kt +195 -0
  27. package/android/vendor/java/com/appswissknife/notifications/PermissionRequestActivity.kt +60 -0
  28. package/android/vendor/java/com/appswissknife/notifications/PermissionStatus.kt +41 -0
  29. package/android/vendor/java/com/appswissknife/notifications/PushEventQueue.kt +143 -0
  30. package/android/vendor/java/com/appswissknife/notifications/PushPayload.kt +72 -0
  31. package/android/vendor/java/com/appswissknife/notifications/PushRegistration.kt +89 -0
  32. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeMessagingService.kt +57 -0
  33. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeNotifications.kt +438 -0
  34. package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +266 -64
  35. package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +1 -0
  36. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +545 -88
  37. package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +55 -24
  38. package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +21 -0
  39. package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +14 -0
  40. package/android/vendor-rustore/AndroidManifest.xml +59 -0
  41. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreGateway.kt +428 -0
  42. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreInitProvider.kt +43 -0
  43. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStorePriceEnrichmentProvider.kt +85 -0
  44. package/app.plugin.js +287 -0
  45. package/ios/SwissKnifePurchases.m +20 -0
  46. package/ios/SwissKnifePurchases.swift +97 -3
  47. package/ios/SwissKnifePushBootstrap.m +34 -0
  48. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +138 -89
  49. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  50. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +345 -44
  51. package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +43 -2
  52. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +495 -16
  53. package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +231 -23
  54. package/ios/vendor/SwissKnifeiOS/Notifications/PushPayload.swift +87 -0
  55. package/ios/vendor/SwissKnifeiOS/Notifications/PushRegistrar.swift +322 -0
  56. package/ios/vendor/SwissKnifeiOS/Notifications/SwissKnife+Notifications.swift +403 -0
  57. package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +1 -0
  58. package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +11 -7
  59. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +38 -7
  60. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +34 -6
  61. package/lib/commonjs/attribution.js +4 -3
  62. package/lib/commonjs/attribution.js.map +1 -1
  63. package/lib/commonjs/identity.js +12 -11
  64. package/lib/commonjs/identity.js.map +1 -1
  65. package/lib/commonjs/index.js +16 -5
  66. package/lib/commonjs/index.js.map +1 -1
  67. package/lib/commonjs/internal/config.js +105 -8
  68. package/lib/commonjs/internal/config.js.map +1 -1
  69. package/lib/commonjs/internal/telemetry-context.js +70 -0
  70. package/lib/commonjs/internal/telemetry-context.js.map +1 -0
  71. package/lib/commonjs/modules/analytics.js +18 -25
  72. package/lib/commonjs/modules/analytics.js.map +1 -1
  73. package/lib/commonjs/modules/crash-reporting.js +27 -6
  74. package/lib/commonjs/modules/crash-reporting.js.map +1 -1
  75. package/lib/commonjs/modules/log.js +1 -1
  76. package/lib/commonjs/modules/notifications.js +500 -0
  77. package/lib/commonjs/modules/notifications.js.map +1 -0
  78. package/lib/commonjs/modules/performance.js +57 -8
  79. package/lib/commonjs/modules/performance.js.map +1 -1
  80. package/lib/commonjs/native/module.js +6 -0
  81. package/lib/commonjs/native/module.js.map +1 -1
  82. package/lib/commonjs/native/spec.js +12 -5
  83. package/lib/commonjs/native/spec.js.map +1 -1
  84. package/lib/commonjs/purchases.js +4 -4
  85. package/lib/commonjs/types.js +12 -15
  86. package/lib/commonjs/types.js.map +1 -1
  87. package/lib/module/attribution.js +4 -3
  88. package/lib/module/attribution.js.map +1 -1
  89. package/lib/module/identity.js +12 -11
  90. package/lib/module/identity.js.map +1 -1
  91. package/lib/module/index.js +8 -4
  92. package/lib/module/index.js.map +1 -1
  93. package/lib/module/internal/config.js +103 -8
  94. package/lib/module/internal/config.js.map +1 -1
  95. package/lib/module/internal/telemetry-context.js +63 -0
  96. package/lib/module/internal/telemetry-context.js.map +1 -0
  97. package/lib/module/modules/analytics.js +18 -25
  98. package/lib/module/modules/analytics.js.map +1 -1
  99. package/lib/module/modules/crash-reporting.js +27 -6
  100. package/lib/module/modules/crash-reporting.js.map +1 -1
  101. package/lib/module/modules/log.js +1 -1
  102. package/lib/module/modules/notifications.js +491 -0
  103. package/lib/module/modules/notifications.js.map +1 -0
  104. package/lib/module/modules/performance.js +57 -8
  105. package/lib/module/modules/performance.js.map +1 -1
  106. package/lib/module/native/module.js +6 -1
  107. package/lib/module/native/module.js.map +1 -1
  108. package/lib/module/native/spec.js +11 -4
  109. package/lib/module/native/spec.js.map +1 -1
  110. package/lib/module/purchases.js +4 -4
  111. package/lib/module/types.js +12 -15
  112. package/lib/module/types.js.map +1 -1
  113. package/lib/typescript/commonjs/attribution.d.ts +3 -2
  114. package/lib/typescript/commonjs/attribution.d.ts.map +1 -1
  115. package/lib/typescript/commonjs/identity.d.ts.map +1 -1
  116. package/lib/typescript/commonjs/index.d.ts +2 -0
  117. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  118. package/lib/typescript/commonjs/internal/config.d.ts +16 -2
  119. package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
  120. package/lib/typescript/commonjs/internal/telemetry-context.d.ts +22 -0
  121. package/lib/typescript/commonjs/internal/telemetry-context.d.ts.map +1 -0
  122. package/lib/typescript/commonjs/modules/analytics.d.ts +8 -11
  123. package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -1
  124. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +18 -5
  125. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
  126. package/lib/typescript/commonjs/modules/notifications.d.ts +110 -0
  127. package/lib/typescript/commonjs/modules/notifications.d.ts.map +1 -0
  128. package/lib/typescript/commonjs/modules/performance.d.ts +13 -0
  129. package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -1
  130. package/lib/typescript/commonjs/native/module.d.ts +2 -0
  131. package/lib/typescript/commonjs/native/module.d.ts.map +1 -1
  132. package/lib/typescript/commonjs/native/spec.d.ts +33 -4
  133. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
  134. package/lib/typescript/commonjs/purchases.d.ts +4 -4
  135. package/lib/typescript/commonjs/types.d.ts +4 -5
  136. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  137. package/lib/typescript/module/attribution.d.ts +3 -2
  138. package/lib/typescript/module/attribution.d.ts.map +1 -1
  139. package/lib/typescript/module/identity.d.ts.map +1 -1
  140. package/lib/typescript/module/index.d.ts +2 -0
  141. package/lib/typescript/module/index.d.ts.map +1 -1
  142. package/lib/typescript/module/internal/config.d.ts +16 -2
  143. package/lib/typescript/module/internal/config.d.ts.map +1 -1
  144. package/lib/typescript/module/internal/telemetry-context.d.ts +22 -0
  145. package/lib/typescript/module/internal/telemetry-context.d.ts.map +1 -0
  146. package/lib/typescript/module/modules/analytics.d.ts +8 -11
  147. package/lib/typescript/module/modules/analytics.d.ts.map +1 -1
  148. package/lib/typescript/module/modules/crash-reporting.d.ts +18 -5
  149. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
  150. package/lib/typescript/module/modules/notifications.d.ts +110 -0
  151. package/lib/typescript/module/modules/notifications.d.ts.map +1 -0
  152. package/lib/typescript/module/modules/performance.d.ts +13 -0
  153. package/lib/typescript/module/modules/performance.d.ts.map +1 -1
  154. package/lib/typescript/module/native/module.d.ts +2 -0
  155. package/lib/typescript/module/native/module.d.ts.map +1 -1
  156. package/lib/typescript/module/native/spec.d.ts +33 -4
  157. package/lib/typescript/module/native/spec.d.ts.map +1 -1
  158. package/lib/typescript/module/purchases.d.ts +4 -4
  159. package/lib/typescript/module/types.d.ts +4 -5
  160. package/lib/typescript/module/types.d.ts.map +1 -1
  161. package/package.json +12 -4
  162. package/src/attribution.ts +4 -3
  163. package/src/identity.ts +12 -11
  164. package/src/index.ts +16 -4
  165. package/src/internal/config.ts +113 -8
  166. package/src/internal/telemetry-context.ts +76 -0
  167. package/src/modules/analytics.ts +24 -33
  168. package/src/modules/crash-reporting.ts +50 -9
  169. package/src/modules/log.ts +1 -1
  170. package/src/modules/notifications.ts +557 -0
  171. package/src/modules/performance.ts +94 -14
  172. package/src/native/module.ts +6 -0
  173. package/src/native/spec.ts +45 -10
  174. package/src/purchases.ts +4 -4
  175. package/src/types.ts +12 -15
  176. package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +0 -326
  177. package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +0 -296
@@ -12,11 +12,16 @@ import com.appswissknife.models.CustomerInfo
12
12
  import com.appswissknife.models.PurchasesError
13
13
  import com.appswissknife.models.PurchasesErrorCode
14
14
  import com.appswissknife.models.StoreProduct
15
+ import android.content.Intent
16
+ import com.appswissknife.notifications.NotificationOpen
17
+ import com.facebook.react.bridge.ActivityEventListener
18
+ import com.facebook.react.bridge.Arguments
15
19
  import com.facebook.react.bridge.Promise
16
20
  import com.facebook.react.bridge.ReactApplicationContext
17
21
  import com.facebook.react.bridge.ReactContextBaseJavaModule
18
22
  import com.facebook.react.bridge.ReactMethod
19
23
  import com.facebook.react.bridge.ReadableMap
24
+ import com.facebook.react.bridge.WritableMap
20
25
  import com.facebook.react.modules.core.DeviceEventManagerModule
21
26
 
22
27
  class SwissKnifePurchasesModule(
@@ -26,11 +31,41 @@ class SwissKnifePurchasesModule(
26
31
  // Must match src/native/module.ts MODULE_NAME exactly.
27
32
  override fun getName(): String = "SwissKnifePurchases"
28
33
 
34
+ companion object {
35
+ // Must match PUSH_OPENED_EVENT in src/native/spec.ts.
36
+ const val PUSH_OPENED_EVENT = "SwissKnife-PushOpened"
37
+ }
38
+
29
39
  // The single CustomerInfo bridge listener. Removed + re-added on every
30
40
  // configure() so re-configuring does not stack duplicate listeners
31
41
  // (which would emit duplicate CustomerInfo events to JS).
32
42
  private var customerInfoListener: ((CustomerInfo) -> Unit)? = null
33
43
 
44
+ // ----- Push (swiss-push) -----
45
+ //
46
+ // Depends on the Android native SDK's `SwissKnife.notifications` API
47
+ // (packages/swiss-knife-android, com.appswissknife.notifications.*).
48
+ private var pushListener: ((NotificationOpen) -> Unit)? = null
49
+
50
+ private val pushIntentListener = object : ActivityEventListener {
51
+ override fun onActivityResult(
52
+ activity: android.app.Activity, requestCode: Int, resultCode: Int, data: Intent?
53
+ ) { /* not used */ }
54
+
55
+ // A tap on a system-tray notification while the app is already running.
56
+ // handleIntent tracks `opened` and dispatches to the listener registered
57
+ // in ensurePushListener(), which emits to JS.
58
+ override fun onNewIntent(intent: Intent) {
59
+ StoreIntentHandler.handle(intent)
60
+ try { SwissKnife.notifications.handleIntent(intent) } catch (_: Throwable) {}
61
+ }
62
+ }
63
+
64
+ init {
65
+ reactContext.addActivityEventListener(pushIntentListener)
66
+ reactContext.currentActivity?.intent?.let(StoreIntentHandler::handle)
67
+ }
68
+
34
69
  // ----- Lifecycle -----
35
70
 
36
71
  @ReactMethod
@@ -205,11 +240,12 @@ class SwissKnifePurchasesModule(
205
240
  // Do NOT re-point JS at them. They bottom out in the deprecated
206
241
  // `SwissKnife.*` facades, which on THIS platform are not equivalent to the
207
242
  // iOS ones: `SwissKnife.logOut` goes straight to the purchases gateway
208
- // instead of `Identity.logOut`, and `SwissKnife.appUserID` /
209
- // `SwissKnife.isAnonymous()` read gateway state — whose anonymous id is a
210
- // fresh random UUID per process, not the DeviceID-derived
211
- // `$SKAnonymousID:` subject `Identity.current()` reports, and which
212
- // `Identity.reset()` / `Identity.wipe()` never clear. That split is what
243
+ // instead of `Identity.logOut` (so it skips the push-token unlink), and
244
+ // `SwissKnife.appUserID` / `SwissKnife.isAnonymous()` read the gateway
245
+ // rather than `Identity.current()`. The gateway follows Identity
246
+ // (`Identity.reset()` / `Identity.wipe()` take it back to the anonymous
247
+ // user through `PurchasesGateway.resetToAnonymous`), but `Identity` is the
248
+ // source of truth. That split is what
213
249
  // `packages/react-native-sdk/src/identity-parity.test.ts` exists to keep out
214
250
  // of the JS surface.
215
251
 
@@ -483,10 +519,136 @@ class SwissKnifePurchasesModule(
483
519
  }
484
520
  }
485
521
 
522
+ // ----- Push notifications (swiss-push) -----
523
+
524
+ @ReactMethod
525
+ fun pushRequestPermission(provisional: Boolean, promise: Promise) {
526
+ // Android has no provisional authorization; the flag is accepted for
527
+ // cross-platform parity and ignored.
528
+ // RN 0.80+: same access path as the purchase flow above.
529
+ val activity = reactApplicationContext.currentActivity
530
+ if (activity == null) {
531
+ promise.reject("NO_ACTIVITY", "requestPermission needs a foreground Activity")
532
+ return
533
+ }
534
+ try {
535
+ SwissKnife.notifications.requestPermission(activity) { status ->
536
+ promise.resolve(status.wire)
537
+ }
538
+ } catch (e: Throwable) {
539
+ promise.reject("PUSH_PERMISSION_ERROR", e.message ?: "unknown", e)
540
+ }
541
+ }
542
+
543
+ @ReactMethod
544
+ fun pushPermissionStatus(promise: Promise) {
545
+ try {
546
+ promise.resolve(SwissKnife.notifications.permissionStatus().wire)
547
+ } catch (e: Throwable) {
548
+ promise.reject("PUSH_PERMISSION_ERROR", e.message ?: "unknown", e)
549
+ }
550
+ }
551
+
552
+ /** Fetches the FCM token through the native SDK and registers the device. */
553
+ @ReactMethod
554
+ fun pushRegister(promise: Promise) {
555
+ try {
556
+ ensurePushListener()
557
+ SwissKnife.notifications.fetchAndRegisterToken()
558
+ promise.resolve(null)
559
+ } catch (e: Throwable) {
560
+ promise.reject("PUSH_REGISTER_ERROR", e.message ?: "unknown", e)
561
+ }
562
+ }
563
+
564
+ @ReactMethod
565
+ fun pushUnregister(promise: Promise) {
566
+ try {
567
+ SwissKnife.notifications.unregister()
568
+ promise.resolve(null)
569
+ } catch (e: Throwable) {
570
+ promise.reject("PUSH_UNREGISTER_ERROR", e.message ?: "unknown", e)
571
+ }
572
+ }
573
+
574
+ /**
575
+ * The tap that launched the app, once. The native SDK captures launch intents
576
+ * itself (ActivityLifecycleCallbacks) and buffers the open; it is replayed
577
+ * exactly once, either here or to the first opened-listener, never both.
578
+ */
579
+ @ReactMethod
580
+ fun pushGetInitialNotification(promise: Promise) {
581
+ try {
582
+ replayLaunchIntent()
583
+ promise.resolve(SwissKnife.notifications.consumeInitialOpen()?.let { encodeOpen(it) })
584
+ } catch (e: Throwable) {
585
+ promise.reject("PUSH_INITIAL_ERROR", e.message ?: "unknown", e)
586
+ }
587
+ }
588
+
589
+ /** Facts the JS-only registration path cannot know itself. */
590
+ @ReactMethod
591
+ fun pushDeviceInfo(promise: Promise) {
592
+ try {
593
+ val map = Arguments.createMap()
594
+ val pkg = reactContext.packageName
595
+ map.putString("bundleId", pkg)
596
+ val versionName = try {
597
+ reactContext.packageManager.getPackageInfo(pkg, 0).versionName
598
+ } catch (_: Throwable) {
599
+ null
600
+ }
601
+ if (versionName != null) map.putString("appVersion", versionName)
602
+ map.putString("osVersion", android.os.Build.VERSION.RELEASE ?: "")
603
+ promise.resolve(map)
604
+ } catch (e: Throwable) {
605
+ promise.reject("PUSH_DEVICE_INFO_ERROR", e.message ?: "unknown", e)
606
+ }
607
+ }
608
+
609
+ /**
610
+ * In React Native the native SDK is configured from JS, i.e. AFTER the launcher
611
+ * Activity was created and resumed, so its ActivityLifecycleCallbacks never saw
612
+ * the notification tap that cold-started the app. Feed the current Activity's
613
+ * intent through handleIntent once the bridge is up; the native SDK dedupes by
614
+ * delivery id, so a tap that was already seen is not tracked twice.
615
+ */
616
+ private fun replayLaunchIntent() {
617
+ try {
618
+ SwissKnife.notifications.handleIntent(reactApplicationContext.currentActivity?.intent)
619
+ } catch (_: Throwable) {}
620
+ }
621
+
622
+ private fun ensurePushListener() {
623
+ if (pushListener != null) return
624
+ val listener: (NotificationOpen) -> Unit = { open ->
625
+ reactContext
626
+ .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
627
+ .emit(PUSH_OPENED_EVENT, encodeOpen(open))
628
+ }
629
+ pushListener = listener
630
+ SwissKnife.notifications.addOpenedListener(listener)
631
+ replayLaunchIntent()
632
+ }
633
+
634
+ private fun encodeOpen(open: NotificationOpen): WritableMap {
635
+ val map = Arguments.createMap()
636
+ open.messageId?.let { map.putString("messageId", it) }
637
+ open.deliveryId?.let { map.putString("deliveryId", it) }
638
+ open.link?.let { map.putString("link", it) }
639
+ open.actionId?.let { map.putString("actionId", it) }
640
+ val data = Arguments.createMap()
641
+ for ((k, v) in open.data) data.putString(k, v)
642
+ map.putMap("data", data)
643
+ return map
644
+ }
645
+
486
646
  // ----- NativeEventEmitter book-keeping (no-op on Android; required by JS spec) -----
487
647
 
488
648
  @ReactMethod
489
- fun addListener(eventType: String) { /* RN built-in handles registration */ }
649
+ fun addListener(eventType: String) {
650
+ if (eventType == PUSH_OPENED_EVENT) ensurePushListener()
651
+ }
490
652
 
491
653
  @ReactMethod
492
654
  fun removeListeners(count: Double) { /* no-op */ }
@@ -0,0 +1,7 @@
1
+ package com.swissknife.purchases
2
+
3
+ import android.content.Intent
4
+
5
+ internal object StoreIntentHandler {
6
+ fun handle(intent: Intent) = Unit
7
+ }
@@ -0,0 +1,9 @@
1
+ package com.swissknife.purchases
2
+
3
+ import android.content.Intent
4
+
5
+ internal object StoreIntentHandler {
6
+ fun handle(intent: Intent) {
7
+ ru.rustore.sdk.pay.RuStorePayClient.instance.getIntentInteractor().proceedIntent(intent)
8
+ }
9
+ }
@@ -137,7 +137,7 @@ object SwissKnife {
137
137
  logLevel: String? = null,
138
138
  attribution: Attribution.Configuration = Attribution.Configuration(),
139
139
  ) {
140
- require(apiKey.isNotEmpty()) { "configure requires a non-empty apiKey" }
140
+ if (rejectsBlankApiKey(apiKey, "configure")) return
141
141
  configureCore(
142
142
  context = context,
143
143
  apiKey = apiKey,
@@ -189,7 +189,7 @@ object SwissKnife {
189
189
  logLevel: String? = null,
190
190
  attribution: Attribution.Configuration = Attribution.Configuration(),
191
191
  ) {
192
- require(apiKey.isNotEmpty()) { "configureCore requires a non-empty apiKey" }
192
+ if (rejectsBlankApiKey(apiKey, "configureCore")) return
193
193
  val serverUrl = proxyURL?.trimEnd('/').orEmpty()
194
194
  // Phase 3 of the RC rip-and-replace — wire AttributesClient so the
195
195
  // setEmail/setPhoneNumber/etc. methods below have somewhere to send to.
@@ -280,20 +280,23 @@ object SwissKnife {
280
280
  proxyURL: String? = null,
281
281
  useAmazon: Boolean = false,
282
282
  ) {
283
- require(apiKey.isNotEmpty()) { "configurePurchases requires a non-empty apiKey" }
283
+ if (rejectsBlankApiKey(apiKey, "configurePurchases")) return
284
284
  gateway.configure(context, apiKey, appUserID, proxyURL, useAmazon)
285
285
  // Wire OfferingsRepository for any store that supplies a price-enrichment
286
- // provider (Play via BillingClientGateway, RuStore via the add-on). Test
287
- // fakes return null → no repo, preserving the prior "production gateway
288
- // only" guard so a [FakePurchasesGateway] never hits a real store query.
286
+ // provider (Play via BillingClientGateway, RuStore via the add-on); it then
287
+ // answers getOfferings() and getOfferingsForPaywall(). A gateway without
288
+ // one (the test FakePurchasesGateway) answers getOfferings() itself and
289
+ // never reaches a real store query, so the repository is cleared for it:
290
+ // one wired by an earlier configure in this process must not shadow it.
291
+ // A blank proxyURL means the SDK's default host, as on iOS.
289
292
  val priceProvider = gateway.priceEnrichmentProvider()
290
- if (priceProvider != null && !proxyURL.isNullOrEmpty()) {
291
- offeringsRepository = com.appswissknife.offerings.OfferingsRepository(
293
+ offeringsRepository = priceProvider?.let {
294
+ com.appswissknife.offerings.OfferingsRepository(
292
295
  httpClient = com.appswissknife.net.BackendHttpClientAdapter(),
293
- serverUrl = proxyURL.trimEnd('/'),
296
+ serverUrl = proxyURL?.trimEnd('/').orEmpty(),
294
297
  apiKey = apiKey,
295
- platformTags = priceProvider.platformTags(),
296
- priceProvider = priceProvider,
298
+ platformTags = it.platformTags(),
299
+ priceProvider = it,
297
300
  )
298
301
  }
299
302
  // Same store-agnostic gate as the offerings wiring: real store gateways
@@ -321,6 +324,25 @@ object SwissKnife {
321
324
  @Volatile
322
325
  private var coreConfigured = false
323
326
 
327
+ /**
328
+ * True (after logging an error) when [apiKey] is empty or whitespace.
329
+ *
330
+ * Every entry point that takes the project's SDK key calls this first and
331
+ * returns without changing any state when it is true. A blank key is almost
332
+ * always a build-time value that was not set; throwing here used to crash the
333
+ * host app at launch, and wiring the SDK against it would mark it configured
334
+ * with a key the backend refuses. Left unconfigured, a later call with the
335
+ * real key still configures everything. iOS does the same.
336
+ */
337
+ private fun rejectsBlankApiKey(apiKey: String, entryPoint: String): Boolean {
338
+ if (apiKey.isNotBlank()) return false
339
+ com.appswissknife.diagnostics.SKLog.error("swissknife") {
340
+ "SwissKnife.$entryPoint was called with an empty apiKey; nothing was configured. " +
341
+ "Pass the project's SDK key."
342
+ }
343
+ return true
344
+ }
345
+
324
346
  /**
325
347
  * Wire the observability backend (analytics / crash / performance ingest)
326
348
  * WITHOUT requiring [configure] or the purchase engine. Idempotent — safe to
@@ -341,11 +363,18 @@ object SwissKnife {
341
363
  *
342
364
  * A blank [serverUrl] means "use the SDK default host", matching a null
343
365
  * `proxyURL` on [configure].
366
+ *
367
+ * A blank [apiKey] is a logged no-op that does NOT count as the first call:
368
+ * nothing is wired and the once-guard stays open, so a later call with the
369
+ * real key (from [configureCore], or the React Native crash or analytics
370
+ * init) wires everything. Before, an empty key from the React Native
371
+ * `CrashReporting.init` latched the guard and wired the pipeline against it.
344
372
  */
345
373
  @JvmStatic
346
374
  @Synchronized
347
375
  fun ensureObservabilityBackend(context: Context, apiKey: String, serverUrl: String) {
348
376
  if (observabilityWired) return
377
+ if (rejectsBlankApiKey(apiKey, "ensureObservabilityBackend")) return
349
378
  observabilityWired = true
350
379
  // Configure Identity if the purchase `configure()` path hasn't already.
351
380
  // Without this, the observability-only path (RuStore / analytics-without-
@@ -396,6 +425,7 @@ object SwissKnife {
396
425
  )
397
426
  }
398
427
  runCatching { com.appswissknife.context.DeviceContextProvider.install(context) }
428
+ runCatching { com.appswissknife.notifications.SwissKnifeNotifications.attach(context) }
399
429
  runCatching {
400
430
  com.appswissknife.context.Session.shared(context).apply {
401
431
  startObservingLifecycle()
@@ -411,13 +441,16 @@ object SwissKnife {
411
441
  com.appswissknife.net.IngestClient.install(ingestClient)
412
442
  com.appswissknife.context.Reachability.shared(context).installAsIngestObserver()
413
443
  }
414
- // Initialize SKAnalytics — this sets its appContext, WITHOUT which
415
- // trackPreBuiltEvent() early-returns and silently drops every event. This
416
- // is required for analytics to work at all on Android (SKAnalytics.initialize
417
- // had no caller before this), and routes events through IngestClient.shared
418
- // (installed above) → POST /ingest.
444
+ // SKAnalytics needs its appContext, WITHOUT which track() and
445
+ // trackPreBuiltEvent() early-return and silently drop every event (the
446
+ // React Native bridges never call SKAnalytics.initialize). A host that
447
+ // initialized analytics itself keeps its configuration: re-initializing
448
+ // with the defaults here used to drop its optOut, trackingSessionEvents
449
+ // and flush interval and track a second Session Start, so an opted-out
450
+ // user was tracked again. Either way the events held so far go to
451
+ // IngestClient.shared (installed above) → POST /ingest.
419
452
  runCatching {
420
- com.appswissknife.analytics.SKAnalytics.initialize(
453
+ com.appswissknife.analytics.SKAnalytics.initializeUnlessInitialized(
421
454
  context,
422
455
  com.appswissknife.analytics.SKAnalyticsConfiguration(
423
456
  apiKey = apiKey,
@@ -453,6 +486,17 @@ object SwissKnife {
453
486
  @JvmStatic
454
487
  fun isAnonymous(): Boolean = gateway.isAnonymous()
455
488
 
489
+ /**
490
+ * [Identity.reset] and [Identity.wipe] left no user. The purchases gateway
491
+ * keeps a user id of its own (set by logIn) and that user's cached
492
+ * entitlements; this drops both, so [appUserID] and [getCustomerInfo]
493
+ * answer for the anonymous user. Mirror of iOS
494
+ * `SwissKnife.identityResetLocalState()`.
495
+ */
496
+ internal fun identityResetLocalState() {
497
+ gateway.resetToAnonymous()
498
+ }
499
+
456
500
  // ----- Reads / offerings (typed) -----
457
501
 
458
502
  @JvmStatic
@@ -461,30 +505,32 @@ object SwissKnife {
461
505
  }
462
506
 
463
507
  /**
464
- * Fetch offerings via the [PurchasesGateway].
508
+ * The app's offerings: every active paywall as an [com.appswissknife.models.Offering],
509
+ * with [Offerings.current] the one the dashboard marks current (else the
510
+ * oldest active one). The same answer as iOS `SwissKnife.getOfferings()`, and
511
+ * what React Native's `Purchases.getOfferings()` returns on Android.
512
+ *
513
+ * Read from `/api/sdk/offerings` by [com.appswissknife.offerings.OfferingsRepository]
514
+ * and priced live by the store (Play, or RuStore with that add-on); a
515
+ * product the store cannot price keeps its dashboard price. Cached for an
516
+ * hour. Callbacks run on a background thread. Call it after [configure].
465
517
  *
466
- * Phase 6 note: the production [com.appswissknife.purchases.BillingClientGateway]
467
- * intentionally returns an error from this method because Google Play
468
- * Billing has no equivalent "offerings" concept - that belongs to
469
- * [com.appswissknife.offerings.OfferingsRepository], which is keyed by
470
- * paywall slug. Call [getOfferingsForPaywall] for production. This
471
- * no-arg variant stays on the surface for RC parity (tests that inject
472
- * a [FakePurchasesGateway] still drive it).
518
+ * A gateway that brings no store price provider (the test
519
+ * [com.appswissknife.purchases.FakePurchasesGateway]) answers it itself.
473
520
  */
474
521
  @JvmStatic
475
522
  fun getOfferings(onSuccess: (Offerings) -> Unit, onError: (PurchasesError) -> Unit) {
476
- gateway.getOfferings(onSuccess, onError)
523
+ val repo = offeringsRepository ?: run { gateway.getOfferings(onSuccess, onError); return }
524
+ fetchOfferingsInBackground(onSuccess, onError) { repo.current() }
477
525
  }
478
526
 
479
527
  /**
480
- * Fetch offerings for a specific paywall. Production path - uses
481
- * [com.appswissknife.offerings.OfferingsRepository] which calls
482
- * /api/sdk/paywalls/show and enriches product prices via the live Play
483
- * Billing client.
528
+ * The offering for one paywall, with the variant an experiment assigned this
529
+ * user, from `/api/sdk/paywalls/show`, priced like [getOfferings]. For a host
530
+ * that renders a specific paywall and runs paywall experiments; most apps
531
+ * call [getOfferings] and pick from [Offerings.all] or [Offerings.current].
484
532
  *
485
- * Must be called AFTER [configure]. The host app is responsible for
486
- * knowing which paywall slug to render (paywall selection is a product
487
- * decision the SDK does not auto-resolve).
533
+ * Must be called AFTER [configure].
488
534
  */
489
535
  @JvmStatic
490
536
  fun getOfferingsForPaywall(
@@ -494,8 +540,17 @@ object SwissKnife {
494
540
  ) {
495
541
  val repo = offeringsRepository
496
542
  ?: run { onError(PurchasesError.Unknown("SDK not configured")); return }
543
+ fetchOfferingsInBackground(onSuccess, onError) { repo.current(paywallSlug, appUserID) }
544
+ }
545
+
546
+ /** Run [fetch] (network and store queries) off the caller's thread. */
547
+ private fun fetchOfferingsInBackground(
548
+ onSuccess: (Offerings) -> Unit,
549
+ onError: (PurchasesError) -> Unit,
550
+ fetch: () -> Offerings,
551
+ ) {
497
552
  Thread({
498
- runCatching { repo.current(paywallSlug, appUserID) }
553
+ runCatching(fetch)
499
554
  .onSuccess(onSuccess)
500
555
  .onFailure { onError(PurchasesError.NetworkError(it.message ?: "Network error", it)) }
501
556
  }, "swissknife-offerings-fetch").apply { isDaemon = true }.start()
@@ -611,9 +666,22 @@ object SwissKnife {
611
666
  @JvmStatic fun setDisplayName(displayName: String?) =
612
667
  AttributesClient.instance.set("\$displayName", displayName)
613
668
 
669
+ /**
670
+ * Legacy attribute-only path (`$pushToken` user attribute). It does NOT
671
+ * register the device for delivery.
672
+ */
673
+ @Deprecated(
674
+ "Use SwissKnife.notifications.registerToken(token) / fetchAndRegisterToken() - the device registry powers delivery.",
675
+ ReplaceWith("SwissKnife.notifications.registerToken(pushToken)"),
676
+ )
614
677
  @JvmStatic fun setPushToken(pushToken: String?) =
615
678
  AttributesClient.instance.set("\$pushToken", pushToken)
616
679
 
680
+ /** Push notifications (permission, FCM token registration, open tracking). */
681
+ @JvmStatic
682
+ val notifications: com.appswissknife.notifications.SwissKnifeNotifications
683
+ get() = com.appswissknife.notifications.SwissKnifeNotifications
684
+
617
685
  // ----- Device identifier (RN bridge facade) -----
618
686
 
619
687
  /**
@@ -682,10 +750,11 @@ object SwissKnife {
682
750
  }
683
751
 
684
752
  /**
685
- * Kick off a flush of the disk-backed queue via WorkManager. Fire-and-
686
- * forget — the actual HTTP work runs on a [com.appswissknife.analytics.FlushEventsWorker]
687
- * with WorkManager-backed exponential back-off and dead-letter on permanent
688
- * failure.
753
+ * Kick off a flush of the telemetry queue. Fire-and-forget: it hands any
754
+ * events held since before configure to [com.appswissknife.net.IngestClient]
755
+ * and schedules its WorkManager drain (`IngestFlushWorker`), which POSTs the
756
+ * queue to `/ingest` with the client's backoff and 4xx policy. A no-op until
757
+ * [configureCore] (or [configure]) has wired the ingest pipeline.
689
758
  */
690
759
  @JvmStatic
691
760
  fun flushEvents() {