@app-swiss-knife/react-native-sdk 0.3.2 → 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 +465 -0
  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 +641 -208
  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 +69 -35
  24. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +756 -98
  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 +531 -100
  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 +353 -31
  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 +353 -31
  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 +3 -1
  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 +50 -12
  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 +3 -1
  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 +50 -12
  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 +13 -4
  162. package/src/attribution.ts +4 -3
  163. package/src/identity.ts +12 -11
  164. package/src/index.ts +18 -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 +476 -67
  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
@@ -0,0 +1,403 @@
1
+ // packages/swiss-knife-ios/Sources/SwissKnifeiOS/Notifications/SwissKnife+Notifications.swift
2
+ //
3
+ // Public push-notification API: `SwissKnife.Notifications`.
4
+ //
5
+ // Manual integration (default) — call these from your AppDelegate / delegate:
6
+ //
7
+ // func application(_:didRegisterForRemoteNotificationsWithDeviceToken token: Data) {
8
+ // SwissKnife.Notifications.registerDeviceToken(token)
9
+ // }
10
+ // func userNotificationCenter(_:willPresent n: UNNotification, withCompletionHandler h: ...) {
11
+ // h(SwissKnife.Notifications.handleWillPresent(n))
12
+ // }
13
+ // func userNotificationCenter(_:didReceive r: UNNotificationResponse, withCompletionHandler h: ...) {
14
+ // if let link = SwissKnife.Notifications.handleNotificationResponse(r) { /* route */ }
15
+ // h()
16
+ // }
17
+ //
18
+ // Opt-in: `SwissKnife.Notifications.enableAutoIntegration()` installs a
19
+ // `UNUserNotificationCenterDelegate` proxy that does the two delegate calls for
20
+ // you and forwards everything to the delegate that was set before it.
21
+
22
+ import Foundation
23
+ import ObjectiveC
24
+ import UserNotifications
25
+ #if canImport(UIKit)
26
+ import UIKit
27
+ #endif
28
+
29
+ // MARK: - Permission
30
+
31
+ internal enum PushPermission {
32
+ static func map(_ status: UNAuthorizationStatus) -> SwissKnife.Notifications.PermissionStatus {
33
+ switch status {
34
+ case .authorized: return .authorized
35
+ case .provisional: return .provisional
36
+ case .denied: return .denied
37
+ case .notDetermined: return .notDetermined
38
+ #if os(iOS)
39
+ case .ephemeral: return .ephemeral
40
+ #endif
41
+ @unknown default: return .notDetermined
42
+ }
43
+ }
44
+
45
+ static func current() async -> SwissKnife.Notifications.PermissionStatus {
46
+ let settings = await UNUserNotificationCenter.current().notificationSettings()
47
+ return map(settings.authorizationStatus)
48
+ }
49
+ }
50
+
51
+ // MARK: - Public API
52
+
53
+ public extension SwissKnife.Notifications {
54
+
55
+ /// Ask the user for notification permission, then register for remote
56
+ /// notifications when granted and upsert the device. Pass
57
+ /// `provisional: true` for quiet delivery with no prompt.
58
+ @discardableResult
59
+ static func requestPermission(
60
+ options: UNAuthorizationOptions = [.alert, .sound, .badge],
61
+ provisional: Bool = false
62
+ ) async -> PermissionStatus {
63
+ var opts = options
64
+ if provisional { opts.insert(.provisional) }
65
+ _ = try? await UNUserNotificationCenter.current().requestAuthorization(options: opts)
66
+ let status = await permissionStatus()
67
+ if status == .authorized || status == .provisional || status == .ephemeral {
68
+ registerForRemoteNotifications()
69
+ }
70
+ startObserving()
71
+ await PushRegistrar.shared.sync()
72
+ return status
73
+ }
74
+
75
+ /// Current OS permission state. Also re-upserts the device if it changed.
76
+ @discardableResult
77
+ static func permissionStatus() async -> PermissionStatus {
78
+ let status = await PushPermission.current()
79
+ if PushRegistrar.shared.isEngaged { await PushRegistrar.shared.sync() }
80
+ return status
81
+ }
82
+
83
+ /// Ask iOS for an APNs token. The token arrives in
84
+ /// `application(_:didRegisterForRemoteNotificationsWithDeviceToken:)`.
85
+ static func registerForRemoteNotifications() {
86
+ #if canImport(UIKit) && !os(watchOS)
87
+ DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() }
88
+ #endif
89
+ }
90
+
91
+ /// Call from `didRegisterForRemoteNotificationsWithDeviceToken`. Converts
92
+ /// the token to hex and upserts the device (skipped if nothing changed).
93
+ static func registerDeviceToken(_ data: Data) {
94
+ PushRegistrar.shared.token = PushTokenFormat.hex(data)
95
+ startObserving()
96
+ Task { await PushRegistrar.shared.sync() }
97
+ }
98
+
99
+ /// Mark this install as unregistered (token = null on the server) and stop
100
+ /// receiving remote notifications. Call on sign-out if you want no pushes.
101
+ static func unregister() {
102
+ PushRegistrar.shared.token = nil
103
+ #if canImport(UIKit) && !os(watchOS)
104
+ DispatchQueue.main.async { UIApplication.shared.unregisterForRemoteNotifications() }
105
+ #endif
106
+ Task { await PushRegistrar.shared.sync(force: true) }
107
+ }
108
+
109
+ /// Track `opened` (default tap) or `action` (custom action button) and
110
+ /// return the deep link from the payload, if any. Dismissals are ignored.
111
+ @discardableResult
112
+ static func handleNotificationResponse(_ response: UNNotificationResponse) -> URL? {
113
+ let userInfo = response.notification.request.content.userInfo
114
+ guard let payload = Payload.parse(userInfo: userInfo) else { return nil }
115
+ var actionId: String?
116
+ switch response.actionIdentifier {
117
+ case UNNotificationDismissActionIdentifier:
118
+ return nil
119
+ case UNNotificationDefaultActionIdentifier:
120
+ PushEventQueue.shared.track(payload, type: "opened")
121
+ default:
122
+ actionId = response.actionIdentifier
123
+ PushEventQueue.shared.track(payload, type: "action", actionId: actionId)
124
+ }
125
+ PushOpenHub.shared.publish(Opened(payload: payload, actionId: actionId, userInfo: userInfo))
126
+ return payload.link
127
+ }
128
+
129
+ /// Track `received` for a notification delivered while the app is in the
130
+ /// foreground and return the presentation options to hand to the system.
131
+ @discardableResult
132
+ static func handleWillPresent(_ notification: UNNotification) -> UNNotificationPresentationOptions {
133
+ if let payload = Payload.parse(userInfo: notification.request.content.userInfo) {
134
+ PushEventQueue.shared.track(payload, type: "received")
135
+ }
136
+ return [.banner, .list, .sound, .badge]
137
+ }
138
+
139
+ /// Track `received` for a background (content-available) push.
140
+ static func handleBackgroundNotification(userInfo: [AnyHashable: Any]) {
141
+ if let payload = Payload.parse(userInfo: userInfo) {
142
+ PushEventQueue.shared.track(payload, type: "received")
143
+ }
144
+ }
145
+
146
+ /// Called with the deep link when a notification is tapped and auto
147
+ /// integration is enabled. Defaults to `UIApplication.open`.
148
+ static var deepLinkHandler: ((URL) -> Void)? {
149
+ get { NotificationDelegateProxy.shared.deepLinkHandler }
150
+ set { NotificationDelegateProxy.shared.deepLinkHandler = newValue }
151
+ }
152
+
153
+ /// OPT-IN, off by default. Installs a `UNUserNotificationCenterDelegate`
154
+ /// proxy that tracks received/opened and forwards to the delegate that was
155
+ /// set at the time of this call. Call it AFTER your own delegate is set;
156
+ /// if you assign `center.delegate` later, the proxy is replaced. It does
157
+ /// not (and cannot, without swizzling) cover the APNs token callback —
158
+ /// keep calling `registerDeviceToken`.
159
+ ///
160
+ /// `captureDeviceToken: true` additionally hooks the app delegate's
161
+ /// `didRegisterForRemoteNotificationsWithDeviceToken` (method
162
+ /// replacement, original still called) so you do not have to call
163
+ /// `registerDeviceToken` yourself. Used by the React Native bridge.
164
+ static func enableAutoIntegration(captureDeviceToken: Bool = false) {
165
+ NotificationDelegateProxy.shared.install()
166
+ if captureDeviceToken { DeviceTokenCapture.install() }
167
+ persistAutoIntegration(captureDeviceToken: captureDeviceToken)
168
+ }
169
+
170
+ /// A tapped notification (or action button), as delivered to `onOpened`.
171
+ struct Opened: @unchecked Sendable {
172
+ public let payload: Payload
173
+ public let actionId: String?
174
+ public let userInfo: [AnyHashable: Any]
175
+ }
176
+
177
+ /// Fires on every tracked open while auto integration is enabled (or
178
+ /// whenever you call `handleNotificationResponse`). Opens that happen
179
+ /// before a handler is set are buffered — see `takeInitialOpen()`.
180
+ static var onOpened: ((Opened) -> Void)? {
181
+ get { PushOpenHub.shared.handler }
182
+ set { PushOpenHub.shared.handler = newValue }
183
+ }
184
+
185
+ /// The open that launched the app (or happened before `onOpened` was
186
+ /// set), once. nil when there was none.
187
+ static func takeInitialOpen() -> Opened? { PushOpenHub.shared.takePending() }
188
+
189
+ /// Re-upsert now, ignoring the dedupe fingerprint (e.g. after a
190
+ /// server-side reset). Normally unnecessary.
191
+ static func forceSync() async {
192
+ await PushRegistrar.shared.sync(force: true)
193
+ }
194
+
195
+ /// Facts a JS-only registration path cannot know itself: bundle id, app /
196
+ /// OS / SDK version and the derived APNs environment.
197
+ static func deviceInfo() -> [String: String] {
198
+ let ctx = DeviceContextProvider.current()
199
+ return [
200
+ "bundleId": ctx.bundleIdentifier ?? "",
201
+ "appVersion": ctx.appVersion,
202
+ "osVersion": ctx.osVersion,
203
+ "sdkVersion": ctx.sdkVersion,
204
+ "environment": PushEnvironment.detectFromBundle(),
205
+ ]
206
+ }
207
+
208
+ /// Flush queued `received`/`opened` events.
209
+ static func flushEvents() async {
210
+ await PushEventQueue.shared.flush()
211
+ }
212
+ }
213
+
214
+ // MARK: - Internal triggers
215
+
216
+ internal extension SwissKnife.Notifications {
217
+ /// Identity changed: refresh the user link. `loggedOut` is true ONLY for an
218
+ /// explicit logOut / reset / wipe — that is the one transition that sends
219
+ /// `user_id: null`. A login just sends the new user.
220
+ static func identityChanged(loggedOut: Bool = false) {
221
+ guard PushRegistrar.shared.isEngaged else { return }
222
+ PushRegistrar.shared.unlinkPending = loggedOut
223
+ Task { await PushRegistrar.shared.sync() }
224
+ }
225
+
226
+ /// Called at configure time: if the app has used push before, resume
227
+ /// foreground re-sync and drain any queued events.
228
+ static func resumeIfEngaged() {
229
+ guard PushRegistrar.shared.isEngaged else { return }
230
+ resumeAutoIntegration()
231
+ startObserving()
232
+ Task {
233
+ // A token stored by a previous launch must not wait for the next
234
+ // foreground to be upserted (identity / permission may have moved).
235
+ await PushRegistrar.shared.resume()
236
+ await PushEventQueue.shared.flush()
237
+ }
238
+ }
239
+
240
+ private static let autoKey = "com.swissknife.push.autoIntegration"
241
+ private static let captureKey = "com.swissknife.push.captureToken"
242
+
243
+ /// Re-install the delegate proxy early on launches after the app opted in,
244
+ /// so a notification tap that cold-starts the app is seen. Native callers
245
+ /// can call this from `didFinishLaunching` (before `configureCore`) too.
246
+ static func resumeAutoIntegration() {
247
+ let d = UserDefaults.standard
248
+ guard d.bool(forKey: autoKey) else { return }
249
+ NotificationDelegateProxy.shared.install()
250
+ if d.bool(forKey: captureKey) { DeviceTokenCapture.install() }
251
+ }
252
+
253
+ static func persistAutoIntegration(captureDeviceToken: Bool) {
254
+ let d = UserDefaults.standard
255
+ d.set(true, forKey: autoKey)
256
+ if captureDeviceToken { d.set(true, forKey: captureKey) }
257
+ }
258
+
259
+ private static let observerLock = NSLock()
260
+ private static var observing = false
261
+
262
+ static func startObserving() {
263
+ observerLock.lock()
264
+ let already = observing
265
+ observing = true
266
+ observerLock.unlock()
267
+ guard !already else { return }
268
+ Task { @MainActor in
269
+ AppLifecycle.subscribe { event in
270
+ guard event == .didBecomeActive else { return }
271
+ Task {
272
+ // Permission may have changed in Settings while away.
273
+ await PushRegistrar.shared.sync()
274
+ await PushEventQueue.shared.flush()
275
+ }
276
+ }
277
+ }
278
+ }
279
+ }
280
+
281
+ // MARK: - Delegate proxy (opt-in)
282
+
283
+ internal final class NotificationDelegateProxy: NSObject, UNUserNotificationCenterDelegate {
284
+
285
+ static let shared = NotificationDelegateProxy()
286
+
287
+ var deepLinkHandler: ((URL) -> Void)?
288
+ private weak var original: UNUserNotificationCenterDelegate?
289
+
290
+ func install() {
291
+ let center = UNUserNotificationCenter.current()
292
+ if center.delegate === self { return }
293
+ original = center.delegate
294
+ center.delegate = self
295
+ }
296
+
297
+ func userNotificationCenter(
298
+ _ center: UNUserNotificationCenter,
299
+ willPresent notification: UNNotification,
300
+ withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
301
+ ) {
302
+ let ours = SwissKnife.Notifications.handleWillPresent(notification)
303
+ if let original, original.responds(to: #selector(UNUserNotificationCenterDelegate.userNotificationCenter(_:willPresent:withCompletionHandler:))) {
304
+ original.userNotificationCenter?(center, willPresent: notification, withCompletionHandler: completionHandler)
305
+ } else {
306
+ completionHandler(ours)
307
+ }
308
+ }
309
+
310
+ func userNotificationCenter(
311
+ _ center: UNUserNotificationCenter,
312
+ didReceive response: UNNotificationResponse,
313
+ withCompletionHandler completionHandler: @escaping () -> Void
314
+ ) {
315
+ let link = SwissKnife.Notifications.handleNotificationResponse(response)
316
+ if let original, original.responds(to: #selector(UNUserNotificationCenterDelegate.userNotificationCenter(_:didReceive:withCompletionHandler:))) {
317
+ original.userNotificationCenter?(center, didReceive: response, withCompletionHandler: completionHandler)
318
+ return
319
+ }
320
+ if let link {
321
+ DispatchQueue.main.async {
322
+ if let handler = self.deepLinkHandler {
323
+ handler(link)
324
+ } else {
325
+ #if canImport(UIKit) && !os(watchOS)
326
+ UIApplication.shared.open(link)
327
+ #endif
328
+ }
329
+ }
330
+ }
331
+ completionHandler()
332
+ }
333
+ }
334
+
335
+ // MARK: - Open hub (buffers opens until someone listens)
336
+
337
+ internal final class PushOpenHub: @unchecked Sendable {
338
+ static let shared = PushOpenHub()
339
+ private let lock = NSLock()
340
+ private var _handler: ((SwissKnife.Notifications.Opened) -> Void)?
341
+ private var pending: SwissKnife.Notifications.Opened?
342
+
343
+ /// Setting a handler drains an open that arrived before anyone listened
344
+ /// (cold-start tap), exactly once — `takePending()` then returns nil.
345
+ var handler: ((SwissKnife.Notifications.Opened) -> Void)? {
346
+ get { lock.lock(); defer { lock.unlock() }; return _handler }
347
+ set {
348
+ lock.lock()
349
+ _handler = newValue
350
+ let drained = newValue != nil ? pending : nil
351
+ if drained != nil { pending = nil }
352
+ lock.unlock()
353
+ if let drained { newValue?(drained) }
354
+ }
355
+ }
356
+
357
+ func publish(_ open: SwissKnife.Notifications.Opened) {
358
+ lock.lock()
359
+ let h = _handler
360
+ if h == nil { pending = open }
361
+ lock.unlock()
362
+ h?(open)
363
+ }
364
+
365
+ func takePending() -> SwissKnife.Notifications.Opened? {
366
+ lock.lock(); defer { lock.unlock() }
367
+ let p = pending
368
+ pending = nil
369
+ return p
370
+ }
371
+ }
372
+
373
+ // MARK: - APNs token capture (opt-in, used by the RN bridge)
374
+
375
+ internal enum DeviceTokenCapture {
376
+ private static var installed = false
377
+
378
+ static func install() {
379
+ #if canImport(UIKit) && !os(watchOS)
380
+ DispatchQueue.main.async {
381
+ guard !installed, let delegate = UIApplication.shared.delegate else { return }
382
+ installed = true
383
+ let cls: AnyClass = type(of: delegate)
384
+ let sel = #selector(UIApplicationDelegate.application(_:didRegisterForRemoteNotificationsWithDeviceToken:))
385
+ typealias OrigFn = @convention(c) (AnyObject, Selector, UIApplication, Data) -> Void
386
+ var original: OrigFn?
387
+ if let m = class_getInstanceMethod(cls, sel) {
388
+ original = unsafeBitCast(method_getImplementation(m), to: OrigFn.self)
389
+ }
390
+ let block: @convention(block) (AnyObject, UIApplication, Data) -> Void = { obj, app, token in
391
+ SwissKnife.Notifications.registerDeviceToken(token)
392
+ original?(obj, sel, app, token)
393
+ }
394
+ let imp = imp_implementationWithBlock(block)
395
+ if let m = class_getInstanceMethod(cls, sel) {
396
+ method_setImplementation(m, imp)
397
+ } else {
398
+ class_addMethod(cls, sel, imp, "v@:@@")
399
+ }
400
+ }
401
+ #endif
402
+ }
403
+ }
@@ -186,6 +186,7 @@ public final class SKTransaction {
186
186
 
187
187
  var payload: [String: Any] = [
188
188
  "traceId": traceId,
189
+ "spanId": spanId,
189
190
  "name": name,
190
191
  "op": op,
191
192
  "startTimestamp": SKPerformance.iso8601String(from: startTime),
@@ -37,9 +37,9 @@
37
37
  // ---------------
38
38
  // `handleSilentPush(_:)` is a stub for the host app to call from its
39
39
  // `application(_:didReceiveRemoteNotification:fetchCompletionHandler:)`
40
- // when a silent-push entitlements update arrives. Today it invalidates the
41
- // cache and triggers an immediate refresh; the APNs cert / backend
42
- // push-send service are follow-up work (see PR description).
40
+ // when a silent-push entitlements update arrives. Today it triggers an
41
+ // immediate refresh, which replaces the cache only on success; the APNs
42
+ // cert / backend push-send service are follow-up work (see PR description).
43
43
  //
44
44
  // Thread safety
45
45
  // -------------
@@ -265,16 +265,20 @@ public final class EntitlementsService {
265
265
  /// Silent-push handler for entitlement invalidations sent from the
266
266
  /// backend. Host apps wire this into
267
267
  /// `application(_:didReceiveRemoteNotification:fetchCompletionHandler:)`.
268
- /// Today it invalidates the cache and triggers an immediate refresh; the
269
- /// APNs cert / backend push-send service are follow-up work tracked in
270
- /// the Phase 5 PR description.
268
+ /// Today it triggers an immediate refresh; the APNs cert / backend
269
+ /// push-send service are follow-up work tracked in the Phase 5 PR
270
+ /// description.
271
271
  public func handleSilentPush(_ userInfo: [AnyHashable: Any]) {
272
272
  // We don't currently inspect `userInfo` — the policy is "any push
273
273
  // means our cache is stale; refresh from the source of truth."
274
274
  // Future work: read a `version` token from the push payload to
275
275
  // skip refresh when it's not newer than what we already have.
276
+ //
277
+ // No invalidate() first: it deletes the disk cache and the snapshot,
278
+ // so a push that arrived on a bad connection used to leave the user
279
+ // with no entitlements at all. `refresh()` replaces the snapshot
280
+ // only when the backend answers.
276
281
  _ = userInfo
277
- invalidate()
278
282
  Task {
279
283
  do { _ = try await refresh() }
280
284
  catch {
@@ -57,6 +57,21 @@ public final class PurchaseService {
57
57
  /// X-API-Key, retry, and Date-header Clock sync uniformly.
58
58
  internal var http: BackendHttpClient = BackendHttpClient.shared
59
59
 
60
+ /// `AppStore.sync()` seam, called by the user-initiated `restorePurchases()`
61
+ /// only. Production asks the App Store to sync this Apple ID's transactions
62
+ /// (it may show a sign-in sheet, which is why nothing else calls it); tests
63
+ /// count calls without touching StoreKit.
64
+ internal var syncWithAppStore: () async -> Void = PurchaseService.defaultAppStoreSync
65
+
66
+ private static let defaultAppStoreSync: () async -> Void = {
67
+ if #available(iOS 15.0, macOS 12.0, *) {
68
+ // A failure (the user dismissed the sign-in sheet, offline) is not
69
+ // a failed restore: the transactions already on the device are
70
+ // still validated below.
71
+ try? await AppStore.sync()
72
+ }
73
+ }
74
+
60
75
  // MARK: Transaction.updates observer
61
76
 
62
77
  private var observerTask: Task<Void, Never>?
@@ -126,6 +141,7 @@ public final class PurchaseService {
126
141
  serverURL = nil
127
142
  apiKey = nil
128
143
  http = BackendHttpClient.shared
144
+ syncWithAppStore = PurchaseService.defaultAppStoreSync
129
145
  }
130
146
  }
131
147
 
@@ -173,12 +189,15 @@ public final class PurchaseService {
173
189
  }
174
190
  }
175
191
 
176
- /// Restore prior purchases. Iterates `Transaction.currentEntitlements`,
177
- /// POSTs each verified JWS to the backend, refreshes the cache, and
178
- /// returns the resulting CustomerInfo. Empty entitlements + no error is
179
- /// the "restore-on-fresh-install with nothing to restore" path.
192
+ /// Restore prior purchases. Asks the App Store to sync first (a new
193
+ /// device or a changed Apple ID may not have the transactions locally
194
+ /// yet), then iterates `Transaction.currentEntitlements`, POSTs each
195
+ /// verified JWS to the backend, refreshes the cache, and returns the
196
+ /// resulting CustomerInfo. Empty entitlements + no error is the
197
+ /// "restore-on-fresh-install with nothing to restore" path.
180
198
  @available(iOS 15.0, macOS 12.0, *)
181
199
  public func restorePurchases() async throws -> CustomerInfo {
200
+ await syncWithAppStore()
182
201
  var anyValidated = false
183
202
  for await result in StoreKit.Transaction.currentEntitlements {
184
203
  let jws = result.jwsRepresentation
@@ -211,7 +230,9 @@ public final class PurchaseService {
211
230
  // Always end with a refresh so the cache reflects whatever the
212
231
  // backend believes the user now owns — even when there was nothing
213
232
  // to validate, we want to surface the latest server-side state.
214
- EntitlementsService.shared.invalidate()
233
+ // No invalidate() first: refresh() replaces the snapshot only on
234
+ // success, so a restore on a bad connection keeps the entitlements
235
+ // the user already had instead of wiping them.
215
236
  if anyValidated {
216
237
  return try await EntitlementsService.shared.refresh()
217
238
  }
@@ -272,8 +293,7 @@ public final class PurchaseService {
272
293
  do {
273
294
  try await validateTransactionWithBackend(transaction, jws: jws)
274
295
  await transaction.finish()
275
- EntitlementsService.shared.invalidate()
276
- _ = try? await EntitlementsService.shared.refresh()
296
+ await refreshEntitlementsAfterTransactionUpdate()
277
297
  } catch {
278
298
  os_log(
279
299
  "PurchaseService: backend validation failed for incoming transaction productId=%{public}@: %{public}@",
@@ -294,6 +314,17 @@ public final class PurchaseService {
294
314
  }
295
315
  }
296
316
 
317
+ /// Re-read entitlements after the backend accepted a `Transaction.updates`
318
+ /// delivery (a renewal, a refund, a purchase from another device).
319
+ ///
320
+ /// Never invalidates first. It used to, and `invalidate()` deletes the disk
321
+ /// cache and the in-memory snapshot, so a renewal that landed on a bad
322
+ /// connection left a paying subscriber with no entitlements until a later
323
+ /// refresh succeeded. `refresh()` replaces the snapshot only on success.
324
+ internal func refreshEntitlementsAfterTransactionUpdate() async {
325
+ _ = try? await EntitlementsService.shared.refresh()
326
+ }
327
+
297
328
  /// POST the JWS to our backend for receipt validation via
298
329
  /// `BackendHttpClient`. The client handles X-API-Key injection,
299
330
  /// 4xx-vs-5xx classification (backendRejected vs backendUnavailable),
@@ -86,7 +86,7 @@ public final class SwissKnife: NSObject {
86
86
  logLevel: String? = nil,
87
87
  attribution: SwissKnife.Attribution.Configuration = .init()
88
88
  ) {
89
- precondition(!apiKey.isEmpty, "configure requires a non-empty apiKey")
89
+ if rejectsBlankApiKey(apiKey, entryPoint: "configure") { return }
90
90
  os_log(
91
91
  "SwissKnife.configure called (apiKey prefix %{public}@…, proxyURL %{public}@)",
92
92
  log: shared.log,
@@ -139,7 +139,7 @@ public final class SwissKnife: NSObject {
139
139
  logLevel: String? = nil,
140
140
  attribution: SwissKnife.Attribution.Configuration = .init()
141
141
  ) {
142
- precondition(!apiKey.isEmpty, "configureCore requires a non-empty apiKey")
142
+ if rejectsBlankApiKey(apiKey, entryPoint: "configureCore") { return }
143
143
 
144
144
  let level = logLevel.flatMap(parseLogLevel) ?? .warn
145
145
  let (resolvedAppUserID, isAnonymous) = resolveConfiguredIdentity(appUserID)
@@ -182,6 +182,9 @@ public final class SwissKnife: NSObject {
182
182
  // config seeding inside is a no-op here because `coreConfigured` is
183
183
  // already true by this point, so configureCore's apiKey/serverURL stand.
184
184
  ensureObservabilityBackend(apiKey: apiKey, serverURL: proxyURL)
185
+ // Push: if this install has used swiss-push before, resume
186
+ // foreground re-sync and drain queued events. No-op otherwise.
187
+ Notifications.resumeIfEngaged()
185
188
  }
186
189
 
187
190
  /// Configure the purchase engine: StoreKit 2 transaction observation,
@@ -207,7 +210,7 @@ public final class SwissKnife: NSObject {
207
210
  proxyURL: String? = nil,
208
211
  storeKitVersion: String = "DEFAULT"
209
212
  ) {
210
- precondition(!apiKey.isEmpty, "configurePurchases requires a non-empty apiKey")
213
+ if rejectsBlankApiKey(apiKey, entryPoint: "configurePurchases") { return }
211
214
  os_log(
212
215
  "SwissKnife.configurePurchases called (apiKey prefix %{public}@…, proxyURL %{public}@)",
213
216
  log: shared.log,
@@ -251,6 +254,25 @@ public final class SwissKnife: NSObject {
251
254
  SwissKnife.Attribution._sendInstallOnFirstLaunchIfEnabled()
252
255
  }
253
256
 
257
+ /// True (after logging an error) when `apiKey` is empty or whitespace.
258
+ ///
259
+ /// `configure`, `configureCore` and `configurePurchases` call this first
260
+ /// and return without changing any state when it is true. A blank key is
261
+ /// almost always a build-time value that was not set; the `precondition`
262
+ /// that used to sit here trapped in release builds and crashed the host
263
+ /// app at launch, and configuring with the key would mark the SDK
264
+ /// configured with a key the backend refuses. Left unconfigured, a later
265
+ /// call with the real key still configures everything. Android does the
266
+ /// same (`SwissKnife.rejectsBlankApiKey`).
267
+ private static func rejectsBlankApiKey(_ apiKey: String, entryPoint: String) -> Bool {
268
+ guard apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return false }
269
+ SKLog.error(
270
+ "SwissKnife.\(entryPoint) was called with an empty apiKey; nothing was configured. "
271
+ + "Pass the project's SDK key."
272
+ )
273
+ return true
274
+ }
275
+
254
276
  /// Resolve `(appUserID, isAnonymous)` the way both configure entry points
255
277
  /// need it. Anonymous flow uses the keychain-backed device id, prefixed to
256
278
  /// match the convention upstream consumers grep for (similar to RC's
@@ -299,7 +321,7 @@ public final class SwissKnife: NSObject {
299
321
  /// inside `makeRequest`, so a *late* configure retroactively unblocks
300
322
  /// everything already sitting in the durable ingest queue — nothing that
301
323
  /// was tracked before the SDK knew its apiKey is lost.
302
- /// - An empty `apiKey` is rejected (no-op): wiring the pipeline against a
324
+ /// - An empty or whitespace `apiKey` is rejected (no-op): wiring the pipeline against a
303
325
  /// key that can never authenticate would just re-create the silent
304
326
  /// failure this method exists to remove.
305
327
  ///
@@ -313,11 +335,11 @@ public final class SwissKnife: NSObject {
313
335
  /// background, plus the JS-side interval calling `flushEvents`.
314
336
  ///
315
337
  /// - Parameters:
316
- /// - apiKey: the project's SDK key. Empty ⇒ no-op.
338
+ /// - apiKey: the project's SDK key. Empty or whitespace ⇒ no-op.
317
339
  /// - serverURL: backend base URL. `nil` / empty ⇒ the default host
318
340
  /// (`https://api.swiss-knife.dev`), matching `configure(proxyURL:)`.
319
341
  public static func ensureObservabilityBackend(apiKey: String, serverURL: String?) {
320
- guard !apiKey.isEmpty else { return }
342
+ guard !apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
321
343
  let normalizedServerURL: String? = {
322
344
  guard var trimmed = serverURL?.trimmingCharacters(in: .whitespacesAndNewlines) else {
323
345
  return nil
@@ -568,6 +590,7 @@ public final class SwissKnife: NSObject {
568
590
  shared.currentAppUserID = userId
569
591
  shared.currentIsAnonymous = false
570
592
  }
593
+ Notifications.identityChanged()
571
594
  }
572
595
 
573
596
  /// Update legacy state after a transition to the anonymous identity.
@@ -576,6 +599,7 @@ public final class SwissKnife: NSObject {
576
599
  shared.currentAppUserID = anonymousId
577
600
  shared.currentIsAnonymous = true
578
601
  }
602
+ Notifications.identityChanged(loggedOut: true)
579
603
  }
580
604
 
581
605
  /// Test seam — drops the SDK's configured state. Used by tests that
@@ -606,6 +630,7 @@ public final class SwissKnife: NSObject {
606
630
  shared.currentAppUserID = anonId
607
631
  shared.currentIsAnonymous = true
608
632
  }
633
+ Notifications.identityChanged(loggedOut: true)
609
634
  }
610
635
 
611
636
  // MARK: Subscriber attributes (unchanged from Phase 3 — AttributesClient)
@@ -643,6 +668,9 @@ public final class SwissKnife: NSObject {
643
668
  userId: currentExternalUserIdForAttributes()
644
669
  )
645
670
  }
671
+ /// Legacy: stores the token as a `$pushToken` subscriber attribute only.
672
+ /// It does NOT register the device with swiss-push.
673
+ @available(*, deprecated, message: "Use SwissKnife.Notifications.registerDeviceToken(_:) — it registers the device for push sends and tracking.")
646
674
  public static func setPushToken(_ pushToken: String?) {
647
675
  AttributesClient.shared.set(
648
676
  reservedKey: "$pushToken",
@@ -7,7 +7,7 @@ exports.Attribution = void 0;
7
7
  var _module = require("./native/module.js");
8
8
  // packages/react-native-sdk/src/attribution.ts
9
9
  //
10
- // Wave 2 — unified Attribution JS surface. Mirror of
10
+ // The Attribution JS surface. Mirror of
11
11
  // `SwissKnife.Attribution` (iOS, Swift) and
12
12
  // `com.appswissknife.attribution.Attribution` (Android, Kotlin). All
13
13
  // logic lives natively — this module is a thin passthrough.
@@ -35,8 +35,9 @@ const Attribution = exports.Attribution = {
35
35
  return (0, _module.getNativeModule)().attributionResolved();
36
36
  },
37
37
  /**
38
- * Auto-collect (ATT prompt + IDFA on iOS; advertising_id +
39
- * install_referrer on Android) and POST `/api/sdk/attribution/install`.
38
+ * Collect what the platform allows (ATT prompt + IDFA on iOS; on Android
39
+ * only what native collectors supply, none by default) and POST
40
+ * `/api/sdk/attribution/install`.
40
41
  * Idempotent — second call returns the cached resolution WITHOUT
41
42
  * re-prompting or re-POSTing.
42
43
  */