@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,323 @@
1
+ // packages/swiss-knife-ios/Sources/SwissKnifeiOS/Identity/Identity.swift
2
+ //
3
+ // Wave 1 of the SDK architectural audit — unified `SwissKnife.Identity`
4
+ // surface. Before this commit the identity primitives (anonymous_id, user_id,
5
+ // attribute-setter delegation) were scattered across `SwissKnife.swift`,
6
+ // `Analytics.swift`, `AttributesClient.swift`, and Android's
7
+ // `BillingClientGateway.kt` with three different anonymous-id prefixes in one
8
+ // project. The Identity namespace centralises that state so subscriptions,
9
+ // analytics, attributes, and future crash-reporting all consume from one
10
+ // place.
11
+ //
12
+ // User-locked decisions baked into this module:
13
+ //
14
+ // - **No auto `$identify` event on `logIn`** — identity changes are
15
+ // decoupled from analytics. Hosts that want retro-tagging call
16
+ // `Analytics.identify(...)` explicitly. This was the audit-call
17
+ // locked-in decision; doing it implicitly here would defeat the user's
18
+ // mental model.
19
+ //
20
+ // - **No migration of existing anon-id prefixes** — whatever lives in
21
+ // the on-device cache stays. Not production yet; backfilling adds
22
+ // risk for zero current benefit.
23
+ //
24
+ // - **Two reset variants**:
25
+ // - `reset()` rotates the in-memory state but keeps persistent
26
+ // storage (DeviceID stays). Matches what `SKAnalytics.reset()`
27
+ // does today — meant for "switch test user" UX.
28
+ // - `wipe()` clears Keychain DeviceID, drops entitlements cache,
29
+ // drops AttributesClient state. GDPR-delete / test-build cleanup.
30
+ //
31
+ // - **ATT prompt config (`autoPromptATT: Bool = true`) is parked for
32
+ // Wave 2.** Not in this module.
33
+ //
34
+ // Thread safety: all mutable state goes through a serial DispatchQueue.
35
+ // `current` is a cheap snapshot — observers are notified on a background
36
+ // queue but each observer's block is invoked serially.
37
+
38
+ import Foundation
39
+
40
+ public extension SwissKnife {
41
+
42
+ /// Universal user-identity surface. Subscriptions, analytics, attributes,
43
+ /// and future crash-reporting consume from here.
44
+ enum Identity {
45
+
46
+ // MARK: Types
47
+
48
+ /// Immutable snapshot of the current identity state.
49
+ public struct Snapshot: Equatable {
50
+ public let anonymousId: String
51
+ public let userId: String?
52
+ public var isAnonymous: Bool { userId == nil }
53
+
54
+ public init(anonymousId: String, userId: String?) {
55
+ self.anonymousId = anonymousId
56
+ self.userId = userId
57
+ }
58
+ }
59
+
60
+ /// Delivered to observers whenever identity transitions.
61
+ public struct Change: Equatable {
62
+ public let previous: Snapshot
63
+ public let current: Snapshot
64
+
65
+ public init(previous: Snapshot, current: Snapshot) {
66
+ self.previous = previous
67
+ self.current = current
68
+ }
69
+ }
70
+
71
+ /// Result of a successful `logIn`. `customerInfo` is the refreshed
72
+ /// CustomerInfo for the identified user; `created` is `true` when
73
+ /// the backend treated this as a brand-new user record.
74
+ public struct LogInResult: Equatable {
75
+ public let customerInfo: CustomerInfo
76
+ public let created: Bool
77
+
78
+ public init(customerInfo: CustomerInfo, created: Bool) {
79
+ self.customerInfo = customerInfo
80
+ self.created = created
81
+ }
82
+ }
83
+
84
+ // MARK: Storage (private to this namespace, mediated by the queue)
85
+
86
+ private static let queue = DispatchQueue(label: "com.swissknife.identity")
87
+ private static var _userId: String?
88
+ private static var observers: [UUID: (Change) -> Void] = [:]
89
+
90
+ /// Monotonically increasing generation counter, bumped on every
91
+ /// `logIn`/`logOut`/`reset`/`wipe`. Each in-flight `logIn` captures
92
+ /// the generation it was issued under and aborts if a newer mutation
93
+ /// has since bumped the counter — closes the TOCTOU race where a
94
+ /// fast `logIn → logOut` sequence let an in-flight identify
95
+ /// completion land AFTER the logOut and silently re-apply the user.
96
+ /// Mirror of Android's Round E fix in
97
+ /// `packages/swiss-knife-android/.../identity/Identity.kt`.
98
+ private static var identityGeneration: Int = 0
99
+
100
+ /// Production identity client routes through BackendHttpClient;
101
+ /// tests inject a fake
102
+ /// via `_setNetworkForTesting`.
103
+ internal static var network: IdentityNetwork = BackendHttpClientIdentityNetwork()
104
+
105
+ // MARK: Public surface
106
+
107
+ /// Single source of truth for "who is this device pretending to be?"
108
+ ///
109
+ /// The anonymous id is derived from the Keychain-backed DeviceID with
110
+ /// the `$SKAnonymousID:` prefix — unified across iOS, Android, and
111
+ /// the analytics flush path. Reads are synchronous and lock-free
112
+ /// after the DeviceID cache warms.
113
+ public static var current: Snapshot {
114
+ queue.sync {
115
+ Snapshot(
116
+ anonymousId: "$SKAnonymousID:" + DeviceID.get(),
117
+ userId: _userId
118
+ )
119
+ }
120
+ }
121
+
122
+ /// Identify this device as a known user. POSTs the
123
+ /// `(anonymous_id, user_id)` pair to `/api/sdk/users/identify` so
124
+ /// the backend can merge the anonymous → identified user record,
125
+ /// then updates the in-memory snapshot, invalidates the
126
+ /// entitlements cache (so userA's entitlements don't leak into
127
+ /// userB's session), and notifies observers.
128
+ ///
129
+ /// The backend call uses a bounded exponential-backoff retry
130
+ /// (1/2/4s with jitter, cap 3) so transient 5xx doesn't lose the
131
+ /// identify side effect.
132
+ @discardableResult
133
+ public static func logIn(_ userId: String) async throws -> LogInResult {
134
+ guard SwissKnife.isConfigured else { throw PurchasesError.notConfigured }
135
+ precondition(!userId.isEmpty, "logIn requires a non-empty userId")
136
+
137
+ let previous = current
138
+ let (apiKey, baseURL) = SwissKnife.identityConfigSnapshot()
139
+ // Bump and capture under the queue — any newer mutation
140
+ // (`logOut`/`reset`/`wipe`/concurrent `logIn`) will bump again
141
+ // and our completion below detects "raced past" by comparing.
142
+ let myGeneration: Int = queue.sync {
143
+ identityGeneration += 1
144
+ return identityGeneration
145
+ }
146
+
147
+ let result: (created: Bool, body: Data)
148
+ do {
149
+ result = try await network.identify(
150
+ anonymousId: previous.anonymousId,
151
+ userId: userId,
152
+ apiKey: apiKey,
153
+ baseURL: baseURL
154
+ )
155
+ } catch {
156
+ // If a newer mutation (logOut/reset/wipe/another logIn)
157
+ // has raced past while we were in flight, swallow the
158
+ // error — the caller has already moved on. Otherwise
159
+ // surface it. Mirrors Android's Round E behaviour.
160
+ let racedPast: Bool = queue.sync { identityGeneration != myGeneration }
161
+ if racedPast { throw CancellationError() }
162
+ throw error
163
+ }
164
+
165
+ // TOCTOU guard: between issuing the POST and arriving here,
166
+ // a `logOut`/`reset`/`wipe`/another `logIn` may have bumped
167
+ // the generation. If so, discard the result — the newer
168
+ // mutation's intent wins. Mirrors Android's Round E fix.
169
+ let generationAfterNetwork: Int = queue.sync { identityGeneration }
170
+ if generationAfterNetwork != myGeneration {
171
+ throw CancellationError()
172
+ }
173
+
174
+ let newSnapshot = Snapshot(
175
+ anonymousId: previous.anonymousId,
176
+ userId: userId
177
+ )
178
+ // Re-check inside the same queue.sync that mutates state —
179
+ // closes the last narrow window before commit.
180
+ let applied: Bool = queue.sync {
181
+ if identityGeneration != myGeneration { return false }
182
+ _userId = userId
183
+ return true
184
+ }
185
+ guard applied else {
186
+ throw CancellationError()
187
+ }
188
+ // Push the user-id into the rest of the SDK so subscriptions and
189
+ // attributes get the new identity.
190
+ SwissKnife.identityDidChangeToIdentifiedUser(userId)
191
+ EntitlementsService.shared.setCurrentUser(userId)
192
+ notifyChange(previous: previous, current: newSnapshot)
193
+
194
+ // Refresh entitlements under the new identity — cache was just
195
+ // invalidated, so this hits the backend.
196
+ let info = try await EntitlementsService.shared.refresh()
197
+ return LogInResult(customerInfo: info, created: result.created)
198
+ }
199
+
200
+ /// Revert to anonymous. The DeviceID is NOT regenerated — Phase 1
201
+ /// keeps it stable across logout (analytics continuity for the
202
+ /// same physical install). Use `wipe()` for a full identity reset.
203
+ public static func logOut() async throws {
204
+ guard SwissKnife.isConfigured else { throw PurchasesError.notConfigured }
205
+ let previous = current
206
+ let anonId = previous.anonymousId
207
+ let newSnapshot = Snapshot(anonymousId: anonId, userId: nil)
208
+ // Bump generation BEFORE clearing state so any in-flight `logIn`
209
+ // sees the bumped counter and discards its completion. Mirrors
210
+ // Android Identity.logOut Round E fix.
211
+ queue.sync { identityGeneration += 1 }
212
+ applyLocalLogOut(previous: previous, newSnapshot: newSnapshot, anonId: anonId)
213
+
214
+ // Best-effort entitlements refresh — logging out should not
215
+ // throw just because the backend is unreachable.
216
+ do {
217
+ _ = try await EntitlementsService.shared.refresh()
218
+ } catch {
219
+ // Swallow — caller treats logOut as fire-and-forget on errors.
220
+ }
221
+ }
222
+
223
+ /// Rotate in-memory state but keep persistent storage. Matches
224
+ /// `SKAnalytics.reset()` semantics — use for "switch test user"
225
+ /// UX where the host wants a fresh logical session without
226
+ /// destroying the DeviceID continuity.
227
+ public static func reset() {
228
+ let previous = current
229
+ queue.sync {
230
+ _userId = nil
231
+ identityGeneration += 1
232
+ }
233
+ EntitlementsService.shared.invalidate()
234
+ SwissKnife.identityResetLocalState()
235
+ notifyChange(previous: previous, current: current)
236
+ }
237
+
238
+ /// Hard wipe: clears Keychain DeviceID, drops the entitlements
239
+ /// cache, drops AttributesClient state. Use for GDPR delete or
240
+ /// test-build cleanup. The next access regenerates DeviceID.
241
+ public static func wipe() {
242
+ let previous = current
243
+ queue.sync {
244
+ _userId = nil
245
+ identityGeneration += 1
246
+ }
247
+ DeviceID.wipe()
248
+ EntitlementsService.shared.invalidate()
249
+ AttributesClient.shared.wipe()
250
+ SwissKnife.identityResetLocalState()
251
+ notifyChange(previous: previous, current: current)
252
+ }
253
+
254
+ /// Subscribe to identity changes. Returns an observation token; pass
255
+ /// to `removeObserver` to unsubscribe. Thread-safe; each observer's
256
+ /// block is invoked off the calling thread, serially.
257
+ @discardableResult
258
+ public static func addObserver(_ block: @escaping (Change) -> Void) -> UUID {
259
+ let token = UUID()
260
+ queue.sync {
261
+ observers[token] = block
262
+ }
263
+ return token
264
+ }
265
+
266
+ public static func removeObserver(_ token: UUID) {
267
+ queue.sync {
268
+ observers.removeValue(forKey: token)
269
+ }
270
+ }
271
+
272
+ // MARK: Internal — SwissKnife facade entry points
273
+
274
+ /// Used by `SwissKnife.configure(...)` to seed the identified
275
+ /// userId when the host passes `appUserID:`. Bypasses the
276
+ /// backend identify call — at configure time we don't yet have
277
+ /// a stable anonymous identity to merge.
278
+ internal static func _seedConfiguredUser(_ userId: String?) {
279
+ queue.sync {
280
+ _userId = userId?.isEmpty == false ? userId : nil
281
+ }
282
+ }
283
+
284
+ /// Test seam — drop all in-memory state and observers, restore
285
+ /// the production network. Production code MUST NOT call this.
286
+ internal static func _resetForTesting() {
287
+ queue.sync {
288
+ _userId = nil
289
+ observers.removeAll()
290
+ network = BackendHttpClientIdentityNetwork()
291
+ identityGeneration = 0
292
+ }
293
+ }
294
+
295
+ /// Test seam — inject a stub network so identify calls don't
296
+ /// hit the real backend.
297
+ internal static func _setNetworkForTesting(_ network: IdentityNetwork) {
298
+ queue.sync { self.network = network }
299
+ }
300
+
301
+ // MARK: Private
302
+
303
+ private static func applyLocalLogOut(
304
+ previous: Snapshot,
305
+ newSnapshot: Snapshot,
306
+ anonId: String
307
+ ) {
308
+ queue.sync { _userId = nil }
309
+ SwissKnife.identityDidChangeToAnonymousUser(anonId)
310
+ EntitlementsService.shared.setCurrentUser(anonId)
311
+ notifyChange(previous: previous, current: newSnapshot)
312
+ }
313
+
314
+ private static func notifyChange(previous: Snapshot, current: Snapshot) {
315
+ guard previous != current else { return }
316
+ let snapshot = queue.sync { observers.values.map { $0 } }
317
+ let change = Change(previous: previous, current: current)
318
+ for observer in snapshot {
319
+ observer(change)
320
+ }
321
+ }
322
+ }
323
+ }
@@ -0,0 +1,70 @@
1
+ // packages/swiss-knife-ios/Sources/SwissKnifeiOS/Identity/IdentityNetwork.swift
2
+ //
3
+ // Backend identify POST. Round B collapsed the per-feature transport into
4
+ // a thin wrapper around `BackendHttpClient` — retry / X-API-Key /
5
+ // 4xx-vs-5xx / Date-header Clock sync are now uniform across every
6
+ // backend call the SDK makes.
7
+ //
8
+ // The `IdentityNetwork` protocol is preserved as the injection seam tests
9
+ // already use (`SwissKnife.Identity._setNetworkForTesting(StubNetwork())`).
10
+ // Production wires the real backend client; tests inject a fake.
11
+ //
12
+ // Retry policy: 3 retries (4 HTTP calls total) — preserved from the
13
+ // pre-migration policy. Identify is one-shot and a 4-second cumulative
14
+ // ceiling is the right tradeoff between "don't lose the identify
15
+ // side-effect to a blip" and "don't keep an app login spinner up forever".
16
+
17
+ import Foundation
18
+
19
+ /// Network seam for the `/api/sdk/users/identify` POST. Production
20
+ /// implementation is `BackendHttpClientIdentityNetwork` (defined below);
21
+ /// tests inject a fake via `SwissKnife.Identity._setNetworkForTesting`.
22
+ internal protocol IdentityNetwork {
23
+ func identify(
24
+ anonymousId: String,
25
+ userId: String,
26
+ apiKey: String,
27
+ baseURL: String?
28
+ ) async throws -> (created: Bool, body: Data)
29
+ }
30
+
31
+ /// Production implementation — thin wrapper around `BackendHttpClient`.
32
+ /// We construct the JSON body with `[String: Any]` (rather than a typed
33
+ /// struct) so the wire shape stays explicit at the call site; the
34
+ /// underlying client handles everything else.
35
+ ///
36
+ /// The `apiKey` / `baseURL` arguments are ignored at runtime — those flow
37
+ /// through `BackendHttpClient`'s shared config resolver. They remain in
38
+ /// the protocol signature only because callers (and tests) already pass
39
+ /// them through; removing them would force a wider API churn for no
40
+ /// behavior gain.
41
+ internal final class BackendHttpClientIdentityNetwork: IdentityNetwork {
42
+ private let http: BackendHttpClient
43
+
44
+ init(http: BackendHttpClient = .shared) {
45
+ self.http = http
46
+ }
47
+
48
+ func identify(
49
+ anonymousId: String,
50
+ userId: String,
51
+ apiKey: String,
52
+ baseURL: String?
53
+ ) async throws -> (created: Bool, body: Data) {
54
+ let body: [String: Any] = [
55
+ "anonymous_id": anonymousId,
56
+ "user_id": userId,
57
+ ]
58
+ let data = try JSONSerialization.data(withJSONObject: body, options: [])
59
+ let respData = try await http.postRaw(
60
+ path: "/api/sdk/users/identify",
61
+ body: data
62
+ )
63
+ // The backend's identify route currently returns `{ user: {...} }`
64
+ // with no explicit `created` flag — expose `created=false` as the
65
+ // conservative default. Consumers branch on the more reliable
66
+ // `Identity.current` snapshot.
67
+ return (false, respData)
68
+ }
69
+ }
70
+