@app-swiss-knife/react-native-sdk 0.4.0 → 0.5.1

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 (185) hide show
  1. package/CHANGELOG.md +473 -2
  2. package/LICENSE +21 -0
  3. package/README.md +279 -47
  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 +20 -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/GENERATED.md +1 -0
  14. package/android/vendor/java/com/appswissknife/SwissKnife.kt +111 -38
  15. package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +180 -115
  16. package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +16 -18
  17. package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +13 -13
  18. package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +56 -25
  19. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  20. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +365 -206
  21. package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +195 -26
  22. package/android/vendor/java/com/appswissknife/identity/Identity.kt +31 -6
  23. package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +5 -0
  24. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +56 -31
  25. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +673 -87
  26. package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +214 -30
  27. package/android/vendor/java/com/appswissknife/notifications/NotificationRenderer.kt +195 -0
  28. package/android/vendor/java/com/appswissknife/notifications/PermissionRequestActivity.kt +60 -0
  29. package/android/vendor/java/com/appswissknife/notifications/PermissionStatus.kt +41 -0
  30. package/android/vendor/java/com/appswissknife/notifications/PushEventQueue.kt +143 -0
  31. package/android/vendor/java/com/appswissknife/notifications/PushPayload.kt +72 -0
  32. package/android/vendor/java/com/appswissknife/notifications/PushRegistration.kt +89 -0
  33. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeMessagingService.kt +57 -0
  34. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeNotifications.kt +438 -0
  35. package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +312 -65
  36. package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +1 -0
  37. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +705 -96
  38. package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +55 -24
  39. package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +29 -0
  40. package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +24 -0
  41. package/android/vendor-rustore/AndroidManifest.xml +59 -0
  42. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreGateway.kt +428 -0
  43. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreInitProvider.kt +43 -0
  44. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStorePriceEnrichmentProvider.kt +85 -0
  45. package/app.plugin.js +343 -0
  46. package/ios/SwissKnifeJSON.swift +24 -2
  47. package/ios/SwissKnifePurchases.m +20 -0
  48. package/ios/SwissKnifePurchases.swift +97 -3
  49. package/ios/SwissKnifePushBootstrap.m +34 -0
  50. package/ios/vendor/GENERATED.md +1 -0
  51. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +138 -89
  52. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  53. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +345 -44
  54. package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +43 -2
  55. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +495 -16
  56. package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +231 -23
  57. package/ios/vendor/SwissKnifeiOS/Notifications/PushPayload.swift +87 -0
  58. package/ios/vendor/SwissKnifeiOS/Notifications/PushRegistrar.swift +322 -0
  59. package/ios/vendor/SwissKnifeiOS/Notifications/SwissKnife+Notifications.swift +403 -0
  60. package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +1 -0
  61. package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +11 -7
  62. package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +37 -5
  63. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +38 -7
  64. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +34 -6
  65. package/ios/vendor/SwissKnifeiOS/Types.swift +31 -1
  66. package/ios-notification-service/SwissKnifeNotificationService.podspec +37 -0
  67. package/ios-notification-service/vendor/GENERATED.md +11 -0
  68. package/ios-notification-service/vendor/SwissKnifeNotificationService/SwissKnifeNotificationServiceExtension.swift +177 -0
  69. package/lib/commonjs/attribution.js +4 -3
  70. package/lib/commonjs/attribution.js.map +1 -1
  71. package/lib/commonjs/identity.js +12 -11
  72. package/lib/commonjs/identity.js.map +1 -1
  73. package/lib/commonjs/index.js +16 -5
  74. package/lib/commonjs/index.js.map +1 -1
  75. package/lib/commonjs/internal/config.js +105 -8
  76. package/lib/commonjs/internal/config.js.map +1 -1
  77. package/lib/commonjs/internal/telemetry-context.js +70 -0
  78. package/lib/commonjs/internal/telemetry-context.js.map +1 -0
  79. package/lib/commonjs/modules/analytics.js +18 -25
  80. package/lib/commonjs/modules/analytics.js.map +1 -1
  81. package/lib/commonjs/modules/crash-reporting.js +27 -6
  82. package/lib/commonjs/modules/crash-reporting.js.map +1 -1
  83. package/lib/commonjs/modules/log.js +1 -1
  84. package/lib/commonjs/modules/notifications.js +500 -0
  85. package/lib/commonjs/modules/notifications.js.map +1 -0
  86. package/lib/commonjs/modules/performance.js +57 -8
  87. package/lib/commonjs/modules/performance.js.map +1 -1
  88. package/lib/commonjs/native/module.js +6 -0
  89. package/lib/commonjs/native/module.js.map +1 -1
  90. package/lib/commonjs/native/spec.js +12 -5
  91. package/lib/commonjs/native/spec.js.map +1 -1
  92. package/lib/commonjs/purchases.js +4 -4
  93. package/lib/commonjs/types.js +12 -15
  94. package/lib/commonjs/types.js.map +1 -1
  95. package/lib/module/attribution.js +4 -3
  96. package/lib/module/attribution.js.map +1 -1
  97. package/lib/module/identity.js +12 -11
  98. package/lib/module/identity.js.map +1 -1
  99. package/lib/module/index.js +8 -4
  100. package/lib/module/index.js.map +1 -1
  101. package/lib/module/internal/config.js +103 -8
  102. package/lib/module/internal/config.js.map +1 -1
  103. package/lib/module/internal/telemetry-context.js +63 -0
  104. package/lib/module/internal/telemetry-context.js.map +1 -0
  105. package/lib/module/modules/analytics.js +18 -25
  106. package/lib/module/modules/analytics.js.map +1 -1
  107. package/lib/module/modules/crash-reporting.js +27 -6
  108. package/lib/module/modules/crash-reporting.js.map +1 -1
  109. package/lib/module/modules/log.js +1 -1
  110. package/lib/module/modules/notifications.js +491 -0
  111. package/lib/module/modules/notifications.js.map +1 -0
  112. package/lib/module/modules/performance.js +57 -8
  113. package/lib/module/modules/performance.js.map +1 -1
  114. package/lib/module/native/module.js +6 -1
  115. package/lib/module/native/module.js.map +1 -1
  116. package/lib/module/native/spec.js +11 -4
  117. package/lib/module/native/spec.js.map +1 -1
  118. package/lib/module/purchases.js +4 -4
  119. package/lib/module/types.js +12 -15
  120. package/lib/module/types.js.map +1 -1
  121. package/lib/typescript/commonjs/attribution.d.ts +3 -2
  122. package/lib/typescript/commonjs/attribution.d.ts.map +1 -1
  123. package/lib/typescript/commonjs/identity.d.ts.map +1 -1
  124. package/lib/typescript/commonjs/index.d.ts +2 -0
  125. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  126. package/lib/typescript/commonjs/internal/config.d.ts +16 -2
  127. package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
  128. package/lib/typescript/commonjs/internal/telemetry-context.d.ts +22 -0
  129. package/lib/typescript/commonjs/internal/telemetry-context.d.ts.map +1 -0
  130. package/lib/typescript/commonjs/modules/analytics.d.ts +8 -11
  131. package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -1
  132. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +18 -5
  133. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
  134. package/lib/typescript/commonjs/modules/notifications.d.ts +110 -0
  135. package/lib/typescript/commonjs/modules/notifications.d.ts.map +1 -0
  136. package/lib/typescript/commonjs/modules/performance.d.ts +13 -0
  137. package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -1
  138. package/lib/typescript/commonjs/native/module.d.ts +2 -0
  139. package/lib/typescript/commonjs/native/module.d.ts.map +1 -1
  140. package/lib/typescript/commonjs/native/spec.d.ts +33 -4
  141. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
  142. package/lib/typescript/commonjs/purchases.d.ts +4 -4
  143. package/lib/typescript/commonjs/types.d.ts +4 -5
  144. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  145. package/lib/typescript/module/attribution.d.ts +3 -2
  146. package/lib/typescript/module/attribution.d.ts.map +1 -1
  147. package/lib/typescript/module/identity.d.ts.map +1 -1
  148. package/lib/typescript/module/index.d.ts +2 -0
  149. package/lib/typescript/module/index.d.ts.map +1 -1
  150. package/lib/typescript/module/internal/config.d.ts +16 -2
  151. package/lib/typescript/module/internal/config.d.ts.map +1 -1
  152. package/lib/typescript/module/internal/telemetry-context.d.ts +22 -0
  153. package/lib/typescript/module/internal/telemetry-context.d.ts.map +1 -0
  154. package/lib/typescript/module/modules/analytics.d.ts +8 -11
  155. package/lib/typescript/module/modules/analytics.d.ts.map +1 -1
  156. package/lib/typescript/module/modules/crash-reporting.d.ts +18 -5
  157. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
  158. package/lib/typescript/module/modules/notifications.d.ts +110 -0
  159. package/lib/typescript/module/modules/notifications.d.ts.map +1 -0
  160. package/lib/typescript/module/modules/performance.d.ts +13 -0
  161. package/lib/typescript/module/modules/performance.d.ts.map +1 -1
  162. package/lib/typescript/module/native/module.d.ts +2 -0
  163. package/lib/typescript/module/native/module.d.ts.map +1 -1
  164. package/lib/typescript/module/native/spec.d.ts +33 -4
  165. package/lib/typescript/module/native/spec.d.ts.map +1 -1
  166. package/lib/typescript/module/purchases.d.ts +4 -4
  167. package/lib/typescript/module/types.d.ts +4 -5
  168. package/lib/typescript/module/types.d.ts.map +1 -1
  169. package/package.json +13 -4
  170. package/src/attribution.ts +4 -3
  171. package/src/identity.ts +12 -11
  172. package/src/index.ts +16 -4
  173. package/src/internal/config.ts +113 -8
  174. package/src/internal/telemetry-context.ts +76 -0
  175. package/src/modules/analytics.ts +24 -33
  176. package/src/modules/crash-reporting.ts +50 -9
  177. package/src/modules/log.ts +1 -1
  178. package/src/modules/notifications.ts +557 -0
  179. package/src/modules/performance.ts +94 -14
  180. package/src/native/module.ts +6 -0
  181. package/src/native/spec.ts +45 -10
  182. package/src/purchases.ts +4 -4
  183. package/src/types.ts +12 -15
  184. package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +0 -326
  185. 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 {
@@ -272,7 +272,10 @@ public final class OfferingsService {
272
272
  let name = (rawPkg["name"] as? String) ?? productId
273
273
  let priceVal = (rawPkg["price"] as? Double) ?? 0
274
274
  let durationDays = (rawPkg["duration_days"] as? Int) ?? 30
275
- let period = subscriptionPeriodFromDays(durationDays)
275
+ let type = Self.backendProductType(
276
+ rawProductType: rawPkg["product_type"] as? String,
277
+ durationDays: durationDays
278
+ )
276
279
  return StoreProduct(
277
280
  productIdentifier: productId,
278
281
  localizedTitle: name,
@@ -280,12 +283,25 @@ public final class OfferingsService {
280
283
  price: Decimal(priceVal),
281
284
  currencyCode: "USD",
282
285
  displayPrice: String(format: "$%.2f", priceVal),
283
- subscriptionPeriod: period,
286
+ subscriptionPeriod: type.isSubscription ? subscriptionPeriodFromDays(durationDays) : nil,
284
287
  introductoryDiscount: nil,
285
- discounts: []
288
+ discounts: [],
289
+ productType: type
286
290
  )
287
291
  }
288
292
 
293
+ /// The type of a product StoreKit did not return, from its backend
294
+ /// package: the server's `product_type` when it sends a known one;
295
+ /// otherwise a zero-day duration is a one-time product whose kind is not
296
+ /// known, and any other duration a subscription (the zero-day rule is
297
+ /// Android's `OfferingsRepository.BackendProduct.isOneTime`).
298
+ internal static func backendProductType(rawProductType: String?, durationDays: Int) -> StoreProductType {
299
+ if let raw = rawProductType, let known = StoreProductType(rawValue: raw), known != .unknown {
300
+ return known
301
+ }
302
+ return durationDays == 0 ? .unknown : .autoRenewableSubscription
303
+ }
304
+
289
305
  private func subscriptionPeriodFromDays(_ days: Int) -> SubscriptionPeriod? {
290
306
  switch days {
291
307
  case 7: return SubscriptionPeriod(value: 1, unit: .week)
@@ -381,9 +397,24 @@ internal final class StoreKit2ProductResolver: StoreProductResolver {
381
397
  }
382
398
  }
383
399
 
400
+ /// StoreKit's `Product.ProductType` as the SDK's `StoreProductType`. A
401
+ /// type StoreKit adds later is `.unknown`.
402
+ @available(iOS 15.0, macOS 12.0, *)
403
+ internal static func productType(_ type: Product.ProductType) -> StoreProductType {
404
+ switch type {
405
+ case .autoRenewable: return .autoRenewableSubscription
406
+ case .nonRenewable: return .nonRenewableSubscription
407
+ case .consumable: return .consumable
408
+ case .nonConsumable: return .nonConsumable
409
+ default: return .unknown
410
+ }
411
+ }
412
+
384
413
  @available(iOS 15.0, macOS 12.0, *)
385
414
  private static func toStoreProduct(_ p: Product) -> StoreProduct {
386
- // Subscription period (only present on auto-renewable subscriptions).
415
+ // Subscription period and offers: StoreKit sets `p.subscription` only
416
+ // on an auto-renewable subscription, so they stay nil for every other
417
+ // product type.
387
418
  var period: SubscriptionPeriod?
388
419
  if let sub = p.subscription {
389
420
  let unit: SubscriptionPeriod.Unit
@@ -413,7 +444,8 @@ internal final class StoreKit2ProductResolver: StoreProductResolver {
413
444
  displayPrice: p.displayPrice,
414
445
  subscriptionPeriod: period,
415
446
  introductoryDiscount: introDiscount,
416
- discounts: discounts
447
+ discounts: discounts,
448
+ productType: productType(p.type)
417
449
  )
418
450
  }
419
451
 
@@ -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),