@app-swiss-knife/react-native-sdk 0.1.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 (218) hide show
  1. package/README.md +182 -0
  2. package/SwissKnifePurchases.podspec +40 -0
  3. package/android/build.gradle +89 -0
  4. package/android/gradle.properties +3 -0
  5. package/android/src/main/AndroidManifest.xml +26 -0
  6. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +216 -0
  7. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingPackage.kt +17 -0
  8. package/android/src/main/java/com/swissknife/purchases/Conversions.kt +15 -0
  9. package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +371 -0
  10. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +497 -0
  11. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesPackage.kt +25 -0
  12. package/android/vendor/GENERATED.md +10 -0
  13. package/android/vendor/java/com/appswissknife/SwissKnife.kt +533 -0
  14. package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +326 -0
  15. package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +296 -0
  16. package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +503 -0
  17. package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +188 -0
  18. package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +204 -0
  19. package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +447 -0
  20. package/android/vendor/java/com/appswissknife/context/AppLifecycle.kt +120 -0
  21. package/android/vendor/java/com/appswissknife/context/Clock.kt +70 -0
  22. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +138 -0
  23. package/android/vendor/java/com/appswissknife/context/IDs.kt +55 -0
  24. package/android/vendor/java/com/appswissknife/context/Reachability.kt +145 -0
  25. package/android/vendor/java/com/appswissknife/context/Session.kt +192 -0
  26. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +945 -0
  27. package/android/vendor/java/com/appswissknife/crashreporting/SKScreenshot.kt +201 -0
  28. package/android/vendor/java/com/appswissknife/device/DeviceID.kt +172 -0
  29. package/android/vendor/java/com/appswissknife/diagnostics/SKLog.kt +97 -0
  30. package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +495 -0
  31. package/android/vendor/java/com/appswissknife/identity/Identity.kt +522 -0
  32. package/android/vendor/java/com/appswissknife/models/CustomerInfo.kt +67 -0
  33. package/android/vendor/java/com/appswissknife/models/Enums.kt +35 -0
  34. package/android/vendor/java/com/appswissknife/models/Offerings.kt +80 -0
  35. package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +89 -0
  36. package/android/vendor/java/com/appswissknife/models/StoreTransaction.kt +17 -0
  37. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +507 -0
  38. package/android/vendor/java/com/appswissknife/net/ExponentialBackoff.kt +69 -0
  39. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +582 -0
  40. package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +320 -0
  41. package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +219 -0
  42. package/android/vendor/java/com/appswissknife/performance/SKFrameTracker.kt +94 -0
  43. package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +428 -0
  44. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +560 -0
  45. package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +100 -0
  46. package/android/vendor/java/com/appswissknife/purchases/PriceEnrichmentProvider.kt +36 -0
  47. package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +120 -0
  48. package/android/vendor/res/xml/swissknife_data_extraction_rules.xml +20 -0
  49. package/ios/SwissKnifeCrashReporting.m +32 -0
  50. package/ios/SwissKnifeCrashReporting.swift +186 -0
  51. package/ios/SwissKnifeJSON.swift +347 -0
  52. package/ios/SwissKnifePurchases.m +124 -0
  53. package/ios/SwissKnifePurchases.swift +523 -0
  54. package/ios/vendor/GENERATED.md +10 -0
  55. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +488 -0
  56. package/ios/vendor/SwissKnifeiOS/AttributesClient.swift +460 -0
  57. package/ios/vendor/SwissKnifeiOS/Attribution/Attribution.swift +307 -0
  58. package/ios/vendor/SwissKnifeiOS/Attribution/AttributionNetwork.swift +92 -0
  59. package/ios/vendor/SwissKnifeiOS/Attribution/AttributionState.swift +141 -0
  60. package/ios/vendor/SwissKnifeiOS/Context/AppLifecycle.swift +130 -0
  61. package/ios/vendor/SwissKnifeiOS/Context/Clock.swift +100 -0
  62. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +190 -0
  63. package/ios/vendor/SwissKnifeiOS/Context/IDs.swift +64 -0
  64. package/ios/vendor/SwissKnifeiOS/Context/Reachability.swift +121 -0
  65. package/ios/vendor/SwissKnifeiOS/Context/Session.swift +223 -0
  66. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +1287 -0
  67. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKScreenshot.swift +175 -0
  68. package/ios/vendor/SwissKnifeiOS/DeviceID.swift +161 -0
  69. package/ios/vendor/SwissKnifeiOS/Diagnostics/SKLog.swift +128 -0
  70. package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +323 -0
  71. package/ios/vendor/SwissKnifeiOS/Identity/IdentityNetwork.swift +70 -0
  72. package/ios/vendor/SwissKnifeiOS/Net/BackendHttpClient.swift +329 -0
  73. package/ios/vendor/SwissKnifeiOS/Net/ExponentialBackoff.swift +87 -0
  74. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +681 -0
  75. package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +409 -0
  76. package/ios/vendor/SwissKnifeiOS/Performance/SKFrameTracker.swift +89 -0
  77. package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +440 -0
  78. package/ios/vendor/SwissKnifeiOS/Performance/SKURLSessionDelegate.swift +87 -0
  79. package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +646 -0
  80. package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +458 -0
  81. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +374 -0
  82. package/ios/vendor/SwissKnifeiOS/SwissKnife+Analytics.swift +46 -0
  83. package/ios/vendor/SwissKnifeiOS/SwissKnife+DeviceID.swift +30 -0
  84. package/ios/vendor/SwissKnifeiOS/SwissKnife+Session.swift +47 -0
  85. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +417 -0
  86. package/ios/vendor/SwissKnifeiOS/Types.swift +496 -0
  87. package/lib/commonjs/attribution.js +55 -0
  88. package/lib/commonjs/attribution.js.map +1 -0
  89. package/lib/commonjs/identity.js +126 -0
  90. package/lib/commonjs/identity.js.map +1 -0
  91. package/lib/commonjs/index.js +118 -0
  92. package/lib/commonjs/index.js.map +1 -0
  93. package/lib/commonjs/modules/analytics.js +646 -0
  94. package/lib/commonjs/modules/analytics.js.map +1 -0
  95. package/lib/commonjs/modules/attachments.js +169 -0
  96. package/lib/commonjs/modules/attachments.js.map +1 -0
  97. package/lib/commonjs/modules/crash-reporting.js +1327 -0
  98. package/lib/commonjs/modules/crash-reporting.js.map +1 -0
  99. package/lib/commonjs/modules/ids.js +50 -0
  100. package/lib/commonjs/modules/ids.js.map +1 -0
  101. package/lib/commonjs/modules/log.js +59 -0
  102. package/lib/commonjs/modules/log.js.map +1 -0
  103. package/lib/commonjs/modules/offline-store.js +44 -0
  104. package/lib/commonjs/modules/offline-store.js.map +1 -0
  105. package/lib/commonjs/modules/performance.js +494 -0
  106. package/lib/commonjs/modules/performance.js.map +1 -0
  107. package/lib/commonjs/native/module.js +41 -0
  108. package/lib/commonjs/native/module.js.map +1 -0
  109. package/lib/commonjs/native/spec.js +26 -0
  110. package/lib/commonjs/native/spec.js.map +1 -0
  111. package/lib/commonjs/package.json +1 -0
  112. package/lib/commonjs/purchases.js +194 -0
  113. package/lib/commonjs/purchases.js.map +1 -0
  114. package/lib/commonjs/types.js +236 -0
  115. package/lib/commonjs/types.js.map +1 -0
  116. package/lib/module/attribution.js +51 -0
  117. package/lib/module/attribution.js.map +1 -0
  118. package/lib/module/identity.js +122 -0
  119. package/lib/module/identity.js.map +1 -0
  120. package/lib/module/index.js +36 -0
  121. package/lib/module/index.js.map +1 -0
  122. package/lib/module/modules/analytics.js +642 -0
  123. package/lib/module/modules/analytics.js.map +1 -0
  124. package/lib/module/modules/attachments.js +162 -0
  125. package/lib/module/modules/attachments.js.map +1 -0
  126. package/lib/module/modules/crash-reporting.js +1320 -0
  127. package/lib/module/modules/crash-reporting.js.map +1 -0
  128. package/lib/module/modules/ids.js +44 -0
  129. package/lib/module/modules/ids.js.map +1 -0
  130. package/lib/module/modules/log.js +54 -0
  131. package/lib/module/modules/log.js.map +1 -0
  132. package/lib/module/modules/offline-store.js +39 -0
  133. package/lib/module/modules/offline-store.js.map +1 -0
  134. package/lib/module/modules/performance.js +491 -0
  135. package/lib/module/modules/performance.js.map +1 -0
  136. package/lib/module/native/module.js +34 -0
  137. package/lib/module/native/module.js.map +1 -0
  138. package/lib/module/native/spec.js +22 -0
  139. package/lib/module/native/spec.js.map +1 -0
  140. package/lib/module/package.json +1 -0
  141. package/lib/module/purchases.js +187 -0
  142. package/lib/module/purchases.js.map +1 -0
  143. package/lib/module/types.js +230 -0
  144. package/lib/module/types.js.map +1 -0
  145. package/lib/typescript/commonjs/attribution.d.ts +24 -0
  146. package/lib/typescript/commonjs/attribution.d.ts.map +1 -0
  147. package/lib/typescript/commonjs/identity.d.ts +37 -0
  148. package/lib/typescript/commonjs/identity.d.ts.map +1 -0
  149. package/lib/typescript/commonjs/index.d.ts +15 -0
  150. package/lib/typescript/commonjs/index.d.ts.map +1 -0
  151. package/lib/typescript/commonjs/modules/analytics.d.ts +127 -0
  152. package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -0
  153. package/lib/typescript/commonjs/modules/attachments.d.ts +50 -0
  154. package/lib/typescript/commonjs/modules/attachments.d.ts.map +1 -0
  155. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +175 -0
  156. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -0
  157. package/lib/typescript/commonjs/modules/ids.d.ts +17 -0
  158. package/lib/typescript/commonjs/modules/ids.d.ts.map +1 -0
  159. package/lib/typescript/commonjs/modules/log.d.ts +12 -0
  160. package/lib/typescript/commonjs/modules/log.d.ts.map +1 -0
  161. package/lib/typescript/commonjs/modules/offline-store.d.ts +9 -0
  162. package/lib/typescript/commonjs/modules/offline-store.d.ts.map +1 -0
  163. package/lib/typescript/commonjs/modules/performance.d.ts +75 -0
  164. package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -0
  165. package/lib/typescript/commonjs/native/module.d.ts +6 -0
  166. package/lib/typescript/commonjs/native/module.d.ts.map +1 -0
  167. package/lib/typescript/commonjs/native/spec.d.ts +119 -0
  168. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -0
  169. package/lib/typescript/commonjs/package.json +1 -0
  170. package/lib/typescript/commonjs/purchases.d.ts +68 -0
  171. package/lib/typescript/commonjs/purchases.d.ts.map +1 -0
  172. package/lib/typescript/commonjs/types.d.ts +384 -0
  173. package/lib/typescript/commonjs/types.d.ts.map +1 -0
  174. package/lib/typescript/module/attribution.d.ts +24 -0
  175. package/lib/typescript/module/attribution.d.ts.map +1 -0
  176. package/lib/typescript/module/identity.d.ts +37 -0
  177. package/lib/typescript/module/identity.d.ts.map +1 -0
  178. package/lib/typescript/module/index.d.ts +15 -0
  179. package/lib/typescript/module/index.d.ts.map +1 -0
  180. package/lib/typescript/module/modules/analytics.d.ts +127 -0
  181. package/lib/typescript/module/modules/analytics.d.ts.map +1 -0
  182. package/lib/typescript/module/modules/attachments.d.ts +50 -0
  183. package/lib/typescript/module/modules/attachments.d.ts.map +1 -0
  184. package/lib/typescript/module/modules/crash-reporting.d.ts +175 -0
  185. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -0
  186. package/lib/typescript/module/modules/ids.d.ts +17 -0
  187. package/lib/typescript/module/modules/ids.d.ts.map +1 -0
  188. package/lib/typescript/module/modules/log.d.ts +12 -0
  189. package/lib/typescript/module/modules/log.d.ts.map +1 -0
  190. package/lib/typescript/module/modules/offline-store.d.ts +9 -0
  191. package/lib/typescript/module/modules/offline-store.d.ts.map +1 -0
  192. package/lib/typescript/module/modules/performance.d.ts +75 -0
  193. package/lib/typescript/module/modules/performance.d.ts.map +1 -0
  194. package/lib/typescript/module/native/module.d.ts +6 -0
  195. package/lib/typescript/module/native/module.d.ts.map +1 -0
  196. package/lib/typescript/module/native/spec.d.ts +119 -0
  197. package/lib/typescript/module/native/spec.d.ts.map +1 -0
  198. package/lib/typescript/module/package.json +1 -0
  199. package/lib/typescript/module/purchases.d.ts +68 -0
  200. package/lib/typescript/module/purchases.d.ts.map +1 -0
  201. package/lib/typescript/module/types.d.ts +384 -0
  202. package/lib/typescript/module/types.d.ts.map +1 -0
  203. package/package.json +115 -0
  204. package/react-native.config.js +23 -0
  205. package/src/attribution.ts +56 -0
  206. package/src/identity.ts +133 -0
  207. package/src/index.ts +54 -0
  208. package/src/modules/analytics.ts +689 -0
  209. package/src/modules/attachments.ts +222 -0
  210. package/src/modules/crash-reporting.ts +1577 -0
  211. package/src/modules/ids.ts +41 -0
  212. package/src/modules/log.ts +56 -0
  213. package/src/modules/offline-store.ts +51 -0
  214. package/src/modules/performance.ts +589 -0
  215. package/src/native/module.ts +47 -0
  216. package/src/native/spec.ts +183 -0
  217. package/src/purchases.ts +214 -0
  218. package/src/types.ts +470 -0
@@ -0,0 +1,458 @@
1
+ // packages/swiss-knife-ios/Sources/SwissKnifeiOS/Services/OfferingsService.swift
2
+ //
3
+ // Phase 5 step 4 — own offerings service. Fetches the catalog of paywalls +
4
+ // packages from our backend (`GET /api/sdk/offerings?platform=ios`) and
5
+ // enriches each package with localized title / price from StoreKit 2's
6
+ // `Product.products(for:)`. Returns the SDK's public `Offerings` type.
7
+ //
8
+ // Two-stage fetch — by design
9
+ // ---------------------------
10
+ // 1) Backend tells us WHICH packages exist for this app (the curated
11
+ // paywall list, mapped via subscription_products).
12
+ // 2) StoreKit tells us WHAT THEY LOOK LIKE today (localized price string,
13
+ // localized title, subscription period, intro offer eligibility).
14
+ //
15
+ // We can't get (2) from the backend because price / title / intro-offer
16
+ // availability depend on the user's storefront, locale, and subscription
17
+ // history — all device-side concerns. We can't get (1) from StoreKit because
18
+ // it doesn't know about our paywall groupings. So both round-trips are
19
+ // load-bearing; we fan them out in parallel.
20
+ //
21
+ // Cache policy
22
+ // ------------
23
+ // In-memory 1h TTL. Offerings don't change often — typically when the
24
+ // dashboard publishes a new paywall — and the SDK consumer calls
25
+ // `getOfferings()` heavily on app foreground / paywall presentation. We
26
+ // refresh on first call after the TTL expires; consumers can force-refresh
27
+ // by calling `invalidate()` first.
28
+ //
29
+ // We deliberately do NOT persist offerings to disk: they're cheap to refetch,
30
+ // and a stale on-disk offerings list is more confusing than a one-shot
31
+ // network call on cold start. Disk persistence stays the domain of
32
+ // `EntitlementsService`, where offline-grace is the user-facing requirement.
33
+
34
+ import Foundation
35
+ import StoreKit
36
+ import os.log
37
+
38
+ /// Process-wide owner of the offerings fetch + cache.
39
+ public final class OfferingsService {
40
+
41
+ public static let shared = OfferingsService()
42
+
43
+ public static let cacheTTL: TimeInterval = 60 * 60 // 1h
44
+
45
+ private let log = OSLog(subsystem: "com.swissknife", category: "offerings")
46
+ private let queue = DispatchQueue(label: "com.swissknife.offerings")
47
+
48
+ // MARK: Configuration
49
+
50
+ private var serverURL: String?
51
+ private var apiKey: String?
52
+
53
+ // MARK: Cache
54
+
55
+ private var cachedOfferings: Offerings?
56
+ private var cachedAt: Date?
57
+
58
+ // MARK: Seams
59
+
60
+ internal var transport: OfferingsTransport = BackendHttpClientOfferingsTransport()
61
+ internal var productResolver: StoreProductResolver = StoreKit2ProductResolver()
62
+ internal var now: () -> Date = { Date() }
63
+
64
+ // MARK: Coalescing
65
+
66
+ private var inflightFetch: Task<Offerings, Error>?
67
+
68
+ private init() {}
69
+
70
+ // MARK: Configure
71
+
72
+ internal func configure(serverURL: String?, apiKey: String) {
73
+ queue.sync {
74
+ self.serverURL = (serverURL?.isEmpty == true) ? nil : serverURL
75
+ self.apiKey = apiKey
76
+ }
77
+ }
78
+
79
+ // MARK: Test seams
80
+
81
+ internal func _resetForTesting() {
82
+ queue.sync {
83
+ serverURL = nil
84
+ apiKey = nil
85
+ cachedOfferings = nil
86
+ cachedAt = nil
87
+ inflightFetch = nil
88
+ transport = BackendHttpClientOfferingsTransport()
89
+ productResolver = StoreKit2ProductResolver()
90
+ now = { Date() }
91
+ }
92
+ }
93
+
94
+ /// Test seam — pre-load a known cache entry so the read path can be
95
+ /// exercised without driving through the network.
96
+ internal func _seedCacheForTesting(_ offerings: Offerings, fetchedAt: Date) {
97
+ queue.sync {
98
+ cachedOfferings = offerings
99
+ cachedAt = fetchedAt
100
+ }
101
+ }
102
+
103
+ // MARK: Public API
104
+
105
+ /// Return the current offerings. Serves from the 1h in-memory cache when
106
+ /// fresh; otherwise issues a backend + StoreKit fetch. Coalesces
107
+ /// concurrent callers onto the same fetch task.
108
+ public func current() async throws -> Offerings {
109
+ // Fast path: cached and inside TTL → no network at all.
110
+ if let cached = queue.sync(execute: { () -> Offerings? in
111
+ guard let offerings = cachedOfferings, let at = cachedAt else { return nil }
112
+ if now().timeIntervalSince(at) > Self.cacheTTL { return nil }
113
+ return offerings
114
+ }) {
115
+ return cached
116
+ }
117
+ let task: Task<Offerings, Error> = queue.sync {
118
+ if let existing = inflightFetch { return existing }
119
+ let newTask = Task { [weak self] () throws -> Offerings in
120
+ guard let self else { throw PurchasesError.notConfigured }
121
+ do {
122
+ let offerings = try await self.performFetch()
123
+ self.queue.async { self.inflightFetch = nil }
124
+ return offerings
125
+ } catch {
126
+ self.queue.async { self.inflightFetch = nil }
127
+ throw error
128
+ }
129
+ }
130
+ inflightFetch = newTask
131
+ return newTask
132
+ }
133
+ return try await task.value
134
+ }
135
+
136
+ /// Drop the cached offerings; next `current()` will refetch.
137
+ public func invalidate() {
138
+ queue.sync {
139
+ cachedOfferings = nil
140
+ cachedAt = nil
141
+ }
142
+ }
143
+
144
+ // MARK: Internals
145
+
146
+ private func performFetch() async throws -> Offerings {
147
+ let (urlOpt, apiKeyOpt) = queue.sync { (self.serverURL, self.apiKey) }
148
+ guard let apiKey = apiKeyOpt, !apiKey.isEmpty else {
149
+ throw PurchasesError.notConfigured
150
+ }
151
+ let base = (urlOpt?.isEmpty == false ? urlOpt! : "https://api.swiss-knife.dev")
152
+ .trimmingTrailingSlash()
153
+ guard let url = URL(string: "\(base)/api/sdk/offerings?platform=ios") else {
154
+ throw PurchasesError.unknown(message: "Invalid offerings URL")
155
+ }
156
+
157
+ let response = try await transport.fetch(url: url, apiKey: apiKey)
158
+ guard (200...299).contains(response.statusCode) else {
159
+ if response.statusCode >= 500 {
160
+ throw PurchasesError.backendUnavailable(
161
+ statusCode: response.statusCode,
162
+ message: response.errorMessage
163
+ )
164
+ }
165
+ throw PurchasesError.backendRejected(
166
+ statusCode: response.statusCode,
167
+ message: response.errorMessage
168
+ )
169
+ }
170
+
171
+ // Decode the backend response.
172
+ guard let json = try? JSONSerialization.jsonObject(with: response.body, options: []) as? [String: Any] else {
173
+ throw PurchasesError.unknown(message: "Malformed offerings response")
174
+ }
175
+ let rawOfferings = (json["offerings"] as? [[String: Any]]) ?? []
176
+ let currentOfferingId = json["current_offering_id"] as? String
177
+
178
+ // Gather every product identifier we need to enrich and fetch them
179
+ // from StoreKit in a single call. Deduplicate to avoid asking
180
+ // StoreKit for the same product twice when multiple offerings share
181
+ // a package.
182
+ var allProductIds = Set<String>()
183
+ for offering in rawOfferings {
184
+ for pkg in (offering["packages"] as? [[String: Any]]) ?? [] {
185
+ if let pid = pkg["product_identifier"] as? String, !pid.isEmpty {
186
+ allProductIds.insert(pid)
187
+ }
188
+ }
189
+ }
190
+ let storeProducts = await productResolver.resolve(productIdentifiers: allProductIds)
191
+ let productById = Dictionary(uniqueKeysWithValues: storeProducts.map { ($0.productIdentifier, $0) })
192
+
193
+ // Build the Swiss Knife Offerings struct.
194
+ var allOfferings: [String: Offering] = [:]
195
+ var currentOffering: Offering?
196
+ for rawOffering in rawOfferings {
197
+ let identifier = (rawOffering["identifier"] as? String) ?? ""
198
+ if identifier.isEmpty { continue }
199
+ let description = (rawOffering["server_description"] as? String) ?? identifier
200
+ var metadata: [String: String] = [:]
201
+ if let m = rawOffering["metadata"] as? [String: Any] {
202
+ for (k, v) in m {
203
+ if let s = v as? String { metadata[k] = s }
204
+ else { metadata[k] = String(describing: v) }
205
+ }
206
+ }
207
+ var packages: [Package] = []
208
+ for rawPkg in (rawOffering["packages"] as? [[String: Any]]) ?? [] {
209
+ let pid = (rawPkg["product_identifier"] as? String) ?? ""
210
+ guard !pid.isEmpty else { continue }
211
+ // If StoreKit didn't resolve a localized product, fall back
212
+ // to a synthetic StoreProduct built from the backend's
213
+ // metadata. The user-visible price string is still useful
214
+ // ("$9.99 USD" rendered server-side), and the SDK doesn't
215
+ // crash on offerings whose StoreKit lookup failed (e.g.
216
+ // wrong bundle id during development).
217
+ let storeProduct = productById[pid] ?? fallbackStoreProduct(rawPkg: rawPkg, productId: pid)
218
+ let pkgType = parsePackageType(rawPkg["package_type"] as? String)
219
+ let package = Package(
220
+ identifier: (rawPkg["identifier"] as? String) ?? pid,
221
+ packageType: pkgType,
222
+ storeProduct: storeProduct,
223
+ offeringIdentifier: identifier
224
+ )
225
+ packages.append(package)
226
+ }
227
+ let offering = Offering(
228
+ identifier: identifier,
229
+ serverDescription: description,
230
+ metadata: metadata,
231
+ availablePackages: packages
232
+ )
233
+ allOfferings[identifier] = offering
234
+ if identifier == currentOfferingId {
235
+ currentOffering = offering
236
+ }
237
+ }
238
+ // Fallback: if backend didn't mark a current offering but only one
239
+ // exists, treat it as current (matches RC's default behavior).
240
+ if currentOffering == nil, allOfferings.count == 1 {
241
+ currentOffering = allOfferings.values.first
242
+ }
243
+
244
+ let offerings = Offerings(all: allOfferings, current: currentOffering)
245
+ queue.sync {
246
+ cachedOfferings = offerings
247
+ cachedAt = now()
248
+ }
249
+ return offerings
250
+ }
251
+
252
+ private func parsePackageType(_ raw: String?) -> PackageType {
253
+ switch raw {
254
+ case "monthly": return .monthly
255
+ case "annual": return .annual
256
+ case "weekly": return .weekly
257
+ case "lifetime": return .lifetime
258
+ case "six_month": return .sixMonth
259
+ case "three_month": return .threeMonth
260
+ case "two_month": return .twoMonth
261
+ case "custom": return .custom
262
+ default: return .unknown
263
+ }
264
+ }
265
+
266
+ /// Build a StoreProduct from backend metadata when StoreKit didn't return
267
+ /// one for the requested productId. The price / currency come from the
268
+ /// dashboard-configured value rather than a live storefront query — fine
269
+ /// for paywall rendering when StoreKit is unavailable (offline first
270
+ /// launch, sandbox config glitches).
271
+ private func fallbackStoreProduct(rawPkg: [String: Any], productId: String) -> StoreProduct {
272
+ let name = (rawPkg["name"] as? String) ?? productId
273
+ let priceVal = (rawPkg["price"] as? Double) ?? 0
274
+ let durationDays = (rawPkg["duration_days"] as? Int) ?? 30
275
+ let period = subscriptionPeriodFromDays(durationDays)
276
+ return StoreProduct(
277
+ productIdentifier: productId,
278
+ localizedTitle: name,
279
+ localizedDescription: name,
280
+ price: Decimal(priceVal),
281
+ currencyCode: "USD",
282
+ displayPrice: String(format: "$%.2f", priceVal),
283
+ subscriptionPeriod: period,
284
+ introductoryDiscount: nil,
285
+ discounts: []
286
+ )
287
+ }
288
+
289
+ private func subscriptionPeriodFromDays(_ days: Int) -> SubscriptionPeriod? {
290
+ switch days {
291
+ case 7: return SubscriptionPeriod(value: 1, unit: .week)
292
+ case 28...32: return SubscriptionPeriod(value: 1, unit: .month)
293
+ case 85...95: return SubscriptionPeriod(value: 3, unit: .month)
294
+ case 175...190: return SubscriptionPeriod(value: 6, unit: .month)
295
+ case 360...370: return SubscriptionPeriod(value: 1, unit: .year)
296
+ case 0: return nil // lifetime
297
+ default: return SubscriptionPeriod(value: days, unit: .day)
298
+ }
299
+ }
300
+ }
301
+
302
+ // MARK: - Backend transport seam
303
+
304
+ internal struct OfferingsTransportResponse {
305
+ let statusCode: Int
306
+ let body: Data
307
+ let errorMessage: String?
308
+ }
309
+
310
+ internal protocol OfferingsTransport {
311
+ func fetch(url: URL, apiKey: String) async throws -> OfferingsTransportResponse
312
+ }
313
+
314
+ /// Production transport — delegates to `BackendHttpClient`. Same pattern
315
+ /// as `BackendHttpClientEntitlementsTransport`: extract path + query
316
+ /// from the caller-built URL, let the shared client handle headers /
317
+ /// retry / Clock sync.
318
+ internal final class BackendHttpClientOfferingsTransport: OfferingsTransport {
319
+ private let http: BackendHttpClient
320
+
321
+ init(http: BackendHttpClient = .shared) {
322
+ self.http = http
323
+ }
324
+
325
+ func fetch(url: URL, apiKey: String) async throws -> OfferingsTransportResponse {
326
+ let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
327
+ let path = components?.path ?? url.path
328
+ let query: [(String, String)] = (components?.queryItems ?? []).compactMap { item in
329
+ guard let value = item.value else { return nil }
330
+ return (item.name, value)
331
+ }
332
+ do {
333
+ let data = try await http.getRaw(path: path, query: query)
334
+ return OfferingsTransportResponse(
335
+ statusCode: 200,
336
+ body: data,
337
+ errorMessage: nil
338
+ )
339
+ } catch let error as PurchasesError {
340
+ switch error {
341
+ case .backendRejected(let code, let msg):
342
+ return OfferingsTransportResponse(
343
+ statusCode: code,
344
+ body: Data(),
345
+ errorMessage: msg
346
+ )
347
+ case .backendUnavailable(let code, let msg):
348
+ return OfferingsTransportResponse(
349
+ statusCode: code ?? 503,
350
+ body: Data(),
351
+ errorMessage: msg
352
+ )
353
+ default:
354
+ throw error
355
+ }
356
+ }
357
+ }
358
+ }
359
+
360
+ // MARK: - StoreKit resolver seam
361
+
362
+ /// Abstraction over `Product.products(for:)` so tests can inject a stub
363
+ /// that returns synthetic StoreProducts without standing up an
364
+ /// `SKTestSession`.
365
+ internal protocol StoreProductResolver {
366
+ func resolve(productIdentifiers: Set<String>) async -> [StoreProduct]
367
+ }
368
+
369
+ internal final class StoreKit2ProductResolver: StoreProductResolver {
370
+ func resolve(productIdentifiers: Set<String>) async -> [StoreProduct] {
371
+ if productIdentifiers.isEmpty { return [] }
372
+ guard #available(iOS 15.0, macOS 12.0, *) else { return [] }
373
+ do {
374
+ let products = try await Product.products(for: productIdentifiers)
375
+ return products.map(Self.toStoreProduct)
376
+ } catch {
377
+ // Any StoreKit failure (network, configuration) → empty list.
378
+ // Callers fall back to the synthetic StoreProduct path so the
379
+ // SDK keeps surfacing offerings even when StoreKit is down.
380
+ return []
381
+ }
382
+ }
383
+
384
+ @available(iOS 15.0, macOS 12.0, *)
385
+ private static func toStoreProduct(_ p: Product) -> StoreProduct {
386
+ // Subscription period (only present on auto-renewable subscriptions).
387
+ var period: SubscriptionPeriod?
388
+ if let sub = p.subscription {
389
+ let unit: SubscriptionPeriod.Unit
390
+ switch sub.subscriptionPeriod.unit {
391
+ case .day: unit = .day
392
+ case .week: unit = .week
393
+ case .month: unit = .month
394
+ case .year: unit = .year
395
+ @unknown default: unit = .month
396
+ }
397
+ period = SubscriptionPeriod(value: sub.subscriptionPeriod.value, unit: unit)
398
+ }
399
+
400
+ // Intro discount.
401
+ var introDiscount: StoreProductDiscount?
402
+ if let intro = p.subscription?.introductoryOffer {
403
+ introDiscount = mapDiscount(intro)
404
+ }
405
+ let discounts: [StoreProductDiscount] = (p.subscription?.promotionalOffers ?? []).map(mapDiscount)
406
+
407
+ return StoreProduct(
408
+ productIdentifier: p.id,
409
+ localizedTitle: p.displayName,
410
+ localizedDescription: p.description,
411
+ price: p.price,
412
+ currencyCode: p.priceFormatStyle.currencyCode,
413
+ displayPrice: p.displayPrice,
414
+ subscriptionPeriod: period,
415
+ introductoryDiscount: introDiscount,
416
+ discounts: discounts
417
+ )
418
+ }
419
+
420
+ @available(iOS 15.0, macOS 12.0, *)
421
+ private static func mapDiscount(_ offer: Product.SubscriptionOffer) -> StoreProductDiscount {
422
+ let mode: StoreProductDiscount.PaymentMode
423
+ switch offer.paymentMode {
424
+ case .payAsYouGo: mode = .payAsYouGo
425
+ case .payUpFront: mode = .payUpFront
426
+ case .freeTrial: mode = .freeTrial
427
+ default: mode = .payAsYouGo
428
+ }
429
+ let type: StoreProductDiscount.DiscountType =
430
+ offer.type == .introductory ? .introductory : .promotional
431
+ let unit: SubscriptionPeriod.Unit
432
+ switch offer.period.unit {
433
+ case .day: unit = .day
434
+ case .week: unit = .week
435
+ case .month: unit = .month
436
+ case .year: unit = .year
437
+ @unknown default: unit = .month
438
+ }
439
+ return StoreProductDiscount(
440
+ offerIdentifier: offer.id,
441
+ price: offer.price,
442
+ paymentMode: mode,
443
+ subscriptionPeriod: SubscriptionPeriod(value: offer.period.value, unit: unit),
444
+ numberOfPeriods: offer.periodCount,
445
+ type: type
446
+ )
447
+ }
448
+ }
449
+
450
+ // MARK: - String helper
451
+
452
+ private extension String {
453
+ func trimmingTrailingSlash() -> String {
454
+ var s = self
455
+ while s.hasSuffix("/") { s.removeLast() }
456
+ return s
457
+ }
458
+ }