@kerdly/expo 0.0.0-stage → 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 (113) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +235 -2
  3. package/android/build.gradle +61 -0
  4. package/android/src/main/AndroidManifest.xml +19 -0
  5. package/android/src/main/java/com/kerdly/expo/KerdlySdkModule.kt +326 -0
  6. package/android/vendor/kerdly-sdk/.kerdly-sync.json +8 -0
  7. package/android/vendor/kerdly-sdk/consumer-rules.pro +15 -0
  8. package/android/vendor/kerdly-sdk/kerdly-sdk.properties +2 -0
  9. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/Kerdly.kt +343 -0
  10. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/KerdlyTypes.kt +89 -0
  11. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Attribution.kt +39 -0
  12. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Batch.kt +159 -0
  13. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Core.kt +991 -0
  14. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeepLinks.kt +114 -0
  15. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeferredLinks.kt +111 -0
  16. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeviceContext.kt +137 -0
  17. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/EventQueue.kt +135 -0
  18. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Events.kt +314 -0
  19. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Json.kt +116 -0
  20. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Logger.kt +49 -0
  21. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Options.kt +47 -0
  22. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Ports.kt +83 -0
  23. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/PublicIp.kt +120 -0
  24. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Referrers.kt +137 -0
  25. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/RemoteConfig.kt +100 -0
  26. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Storage.kt +271 -0
  27. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/AndroidPlatform.kt +274 -0
  28. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/AndroidRuntime.kt +187 -0
  29. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/PlayReferrerReader.kt +97 -0
  30. package/app.plugin.js +2 -0
  31. package/build/Kerdly.d.ts +106 -0
  32. package/build/Kerdly.d.ts.map +1 -0
  33. package/build/Kerdly.js +494 -0
  34. package/build/Kerdly.js.map +1 -0
  35. package/build/index.d.ts +4 -0
  36. package/build/index.d.ts.map +1 -0
  37. package/build/index.js +2 -0
  38. package/build/index.js.map +1 -0
  39. package/build/log.d.ts +13 -0
  40. package/build/log.d.ts.map +1 -0
  41. package/build/log.js +45 -0
  42. package/build/log.js.map +1 -0
  43. package/build/native.d.ts +74 -0
  44. package/build/native.d.ts.map +1 -0
  45. package/build/native.js +56 -0
  46. package/build/native.js.map +1 -0
  47. package/build/normalize.d.ts +8 -0
  48. package/build/normalize.d.ts.map +1 -0
  49. package/build/normalize.js +86 -0
  50. package/build/normalize.js.map +1 -0
  51. package/build/types.d.ts +134 -0
  52. package/build/types.d.ts.map +1 -0
  53. package/build/types.js +3 -0
  54. package/build/types.js.map +1 -0
  55. package/build/validation.d.ts +70 -0
  56. package/build/validation.d.ts.map +1 -0
  57. package/build/validation.js +349 -0
  58. package/build/validation.js.map +1 -0
  59. package/build/version.d.ts +4 -0
  60. package/build/version.d.ts.map +1 -0
  61. package/build/version.js +5 -0
  62. package/build/version.js.map +1 -0
  63. package/expo-module.config.json +9 -0
  64. package/ios/KerdlySDK/.kerdly-sync.json +7 -0
  65. package/ios/KerdlySDK/Core/Dependencies.swift +163 -0
  66. package/ios/KerdlySDK/Core/KerdlyCore+API.swift +117 -0
  67. package/ios/KerdlySDK/Core/KerdlyCore+Collectors.swift +410 -0
  68. package/ios/KerdlySDK/Core/KerdlyCore+DeferredLinks.swift +220 -0
  69. package/ios/KerdlySDK/Core/KerdlyCore+Delivery.swift +424 -0
  70. package/ios/KerdlySDK/Core/KerdlyCore.swift +557 -0
  71. package/ios/KerdlySDK/Core/Support.swift +95 -0
  72. package/ios/KerdlySDK/Logic/Backoff.swift +22 -0
  73. package/ios/KerdlySDK/Logic/Batch.swift +180 -0
  74. package/ios/KerdlySDK/Logic/Context.swift +85 -0
  75. package/ios/KerdlySDK/Logic/DeepLinks.swift +93 -0
  76. package/ios/KerdlySDK/Logic/DeferredLinks.swift +239 -0
  77. package/ios/KerdlySDK/Logic/Environment.swift +39 -0
  78. package/ios/KerdlySDK/Logic/EventQueue.swift +85 -0
  79. package/ios/KerdlySDK/Logic/EventValidator.swift +84 -0
  80. package/ios/KerdlySDK/Logic/Events.swift +102 -0
  81. package/ios/KerdlySDK/Logic/IPv6Address.swift +26 -0
  82. package/ios/KerdlySDK/Logic/InstallIdentity.swift +106 -0
  83. package/ios/KerdlySDK/Logic/JSONValue.swift +198 -0
  84. package/ios/KerdlySDK/Logic/Purchases.swift +84 -0
  85. package/ios/KerdlySDK/Logic/RemoteConfig.swift +185 -0
  86. package/ios/KerdlySDK/Logic/Skan.swift +343 -0
  87. package/ios/KerdlySDK/Logic/StandardEvents.swift +126 -0
  88. package/ios/KerdlySDK/Platform/AdSignals.swift +19 -0
  89. package/ios/KerdlySDK/Platform/DeferredLinkBundle.swift +25 -0
  90. package/ios/KerdlySDK/Platform/DeviceInfo.swift +82 -0
  91. package/ios/KerdlySDK/Platform/Lifecycle.swift +74 -0
  92. package/ios/KerdlySDK/Platform/PublicIp.swift +33 -0
  93. package/ios/KerdlySDK/Platform/SkanWriter.swift +70 -0
  94. package/ios/KerdlySDK/Platform/StoreKitAdapter.swift +185 -0
  95. package/ios/KerdlySDK/Platform/SystemStores.swift +200 -0
  96. package/ios/KerdlySDK/Platform/Tracking.swift +124 -0
  97. package/ios/KerdlySDK/Public/Kerdly.swift +202 -0
  98. package/ios/KerdlySDK/Public/KerdlyTypes.swift +130 -0
  99. package/ios/KerdlySDK/Resources/PrivacyInfo.xcprivacy +95 -0
  100. package/ios/KerdlySDK/Storage/PersistedState.swift +175 -0
  101. package/ios/KerdlySDK/Storage/StateStore.swift +36 -0
  102. package/ios/KerdlySdk.podspec +45 -0
  103. package/ios/KerdlySdkModule.swift +332 -0
  104. package/package.json +92 -4
  105. package/plugin/withKerdly.js +163 -0
  106. package/src/Kerdly.ts +524 -0
  107. package/src/index.ts +23 -0
  108. package/src/log.ts +49 -0
  109. package/src/native.ts +150 -0
  110. package/src/normalize.ts +82 -0
  111. package/src/types.ts +183 -0
  112. package/src/validation.ts +343 -0
  113. package/src/version.ts +5 -0
@@ -0,0 +1,557 @@
1
+ import Foundation
2
+
3
+ /// The SDK's engine. All mutable state is confined to `queue`, a private serial queue: the public
4
+ /// `Kerdly` facade validates on the caller's thread and hops onto it, and every completion from the
5
+ /// system hops back onto it. The few values public getters read from any thread live in `Locked`
6
+ /// boxes. Nothing here throws into the app.
7
+ final class KerdlyCore: @unchecked Sendable {
8
+ static let sdkName = "kerdly-ios"
9
+ static let sdkVersion = "0.1.0"
10
+ static let defaultsInstallIdKey = "com.kerdly.sdk.install_id"
11
+ static let defaultsKeychainFailedKey = "com.kerdly.sdk.keychain_write_failed"
12
+ /// The same two keys as builds before 0.1.0 named them; `migrateLegacyDefaults` moves them once.
13
+ static let legacyDefaultsInstallIdKey = "com.afr.sdk.install_id"
14
+ static let legacyDefaultsKeychainFailedKey = "com.afr.sdk.keychain_write_failed"
15
+ static let foregroundOpenThreshold: TimeInterval = 30 * 60
16
+ static let maxPreStartCalls = 200
17
+ static let maxEventBytes = 64 * 1_024
18
+ static let maxIdLength = 256
19
+
20
+ static let shared = KerdlyCore(dependencies: .system())
21
+
22
+ let queue: DispatchQueue
23
+ let deps: KerdlyDependencies
24
+ let log = KerdlyLogger()
25
+ let scheduler: Scheduling
26
+ let store: StateStore
27
+ let skan: SkanCoordinator
28
+
29
+ // MARK: Readable from any thread
30
+
31
+ let installIdBox = Locked<String?>(nil)
32
+ let attributionBox = Locked<[String: JSONValue]?>(nil)
33
+ let attributionHandlers = Locked<[UncheckedSendable<(KerdlyAttribution) -> Void>]>([])
34
+ let configureCalled = Locked(false)
35
+
36
+ // MARK: Confined to `queue`
37
+
38
+ var options: KerdlyOptions?
39
+ /// The install id is resolved and the persisted state loaded.
40
+ var started = false
41
+ /// The Keychain was locked at `configure`; start waits for protected data.
42
+ var waitingForProtectedData = false
43
+ /// Calls made before the SDK started, replayed in order once it has.
44
+ var preStartCalls: [@Sendable () -> Void] = []
45
+ /// `afterStart` replayed `preStartCalls`; later calls run directly.
46
+ var callsOpen = false
47
+ var state = PersistedState(installId: "")
48
+ var eventQueue = EventQueue()
49
+ var configCache: ConfigCache?
50
+ var config = RemoteConfig.defaults
51
+ var appInfo = AppInfo(bundle: "unknown", version: "", build: "")
52
+ var facts: DeviceFacts?
53
+ var snapshot: DeviceSnapshot?
54
+ var environment = KerdlyEnvironment.production.rawValue
55
+ var isForeground = true
56
+ var lastBackgroundAt: Date?
57
+ var configuredAt = Date()
58
+ var deepLinkSources = DeepLinkSourceTracker(configuredAt: Date())
59
+ var lifecycleObserved = false
60
+ /// This launch enqueued a `$install`.
61
+ var launchEnqueuedInstall = false
62
+
63
+ // Delivery
64
+ var launchFlushReleased = false
65
+ var inFlight = false
66
+ var flushScheduled = false
67
+ var flushAfterInFlight = false
68
+ /// 401/403: nothing is sent until the next launch.
69
+ var stoppedUntilRelaunch = false
70
+ /// After a 413: the halved batch size, growing back after successes.
71
+ var batchLimitOverride: Int?
72
+ var retryTimer: Cancellable?
73
+ var foregroundTimer: Cancellable?
74
+ var backgroundTaskToken: Int?
75
+ var loggedDropCodes: Set<String> = []
76
+
77
+ // Config and attribution
78
+ var configFetchInFlight = false
79
+ var configFetchWaiters: [() -> Void] = []
80
+ /// While no config for this app version is in: the next fetch, backing off.
81
+ var configRetryTimer: Cancellable?
82
+ var configRetryAttempt = 0
83
+ /// `afterStart` read the app's version: `configReady` can be decided.
84
+ var appInfoLoaded = false
85
+ var attributionPolls = 0
86
+
87
+ // Collectors
88
+ var launchPipelineStarted = false
89
+ var launchConfigResolved = false
90
+ var launchCollectorsStarted = false
91
+ var asaInFlight = false
92
+ var appTransactionInFlight = false
93
+ var advertisingIdInFlight = false
94
+ var ddlInFlight = false
95
+ var updatesObserved = false
96
+ var sweepInFlight = false
97
+ var skanReady = false
98
+ var pendingSkanTriggers: [SkanTrigger] = []
99
+ var notifyLookups: [Int: NotifiedPurchase] = [:]
100
+ var notifyLookupCounter = 0
101
+
102
+ init(dependencies: KerdlyDependencies,
103
+ queue: DispatchQueue = DispatchQueue(label: "com.kerdly.sdk", qos: .utility)) {
104
+ self.deps = dependencies
105
+ self.queue = queue
106
+ self.scheduler = dependencies.makeScheduler(queue)
107
+ self.store = StateStore(files: dependencies.files)
108
+ let clock = dependencies.clock
109
+ self.skan = SkanCoordinator(writer: dependencies.skanWriter, queue: queue, floor: nil,
110
+ now: { clock.now() })
111
+ skan.onAudit = { [unowned self] props in
112
+ enqueue(ReservedEvent.skan, props)
113
+ }
114
+ skan.onFloorChange = { [unowned self] floor in
115
+ state.skanFloor = floor
116
+ saveState()
117
+ }
118
+ }
119
+
120
+ var now: Date { deps.clock.now() }
121
+
122
+ /// Sending is on: the kill switch is off and this SDK version is still supported.
123
+ var sendingEnabled: Bool {
124
+ config.enabled && !config.isBelowMinimum(sdkVersion: Self.sdkVersion)
125
+ }
126
+
127
+ /// The config in use was fetched for this app version. Until it is, the config
128
+ /// request is the only request the SDK makes and no collector runs: Kerdly may have switched this
129
+ /// version off.
130
+ var configReady: Bool {
131
+ appInfoLoaded && configCache?.isFor(appVersion: appInfo.version) == true
132
+ }
133
+
134
+ /// Kerdly is off for this app version: nothing is recorded, collected or sent.
135
+ var kerdlyOff: Bool {
136
+ configReady && config.off
137
+ }
138
+
139
+ var skanEnabled: Bool {
140
+ (options?.skanWriter ?? false) && (config.skan?.enabled ?? false)
141
+ }
142
+
143
+ // MARK: - configure
144
+
145
+ /// Synchronous and cheap: resolves the install id, loads the state and queue, enqueues
146
+ /// `$install` (when due) and `$open`; everything else continues on `queue`.
147
+ func configure(_ options: KerdlyOptions) {
148
+ let already = configureCalled.update { called -> Bool in
149
+ defer { called = true }
150
+ return called
151
+ }
152
+ if already {
153
+ log.warn("configure was called more than once; ignoring the later call")
154
+ return
155
+ }
156
+ log.currentLevel = options.logLevel
157
+ guard Self.validate(options, log: log) else {
158
+ configureCalled.set(false)
159
+ return
160
+ }
161
+ var snapshot: DeviceSnapshot?
162
+ if Thread.isMainThread {
163
+ let device = deps.device
164
+ snapshot = MainActor.assumeIsolated { device.snapshot() }
165
+ }
166
+ queue.sync {
167
+ start(options: options, snapshot: snapshot)
168
+ }
169
+ if snapshot == nil {
170
+ let device = deps.device
171
+ DispatchQueue.main.async { [self] in
172
+ let fresh = MainActor.assumeIsolated { device.snapshot() }
173
+ queue.async { self.receive(snapshot: fresh) }
174
+ }
175
+ }
176
+ }
177
+
178
+ static func validate(_ options: KerdlyOptions, log: KerdlyLogger) -> Bool {
179
+ let key = options.key.trimmingCharacters(in: .whitespacesAndNewlines)
180
+ guard !key.isEmpty else {
181
+ log.error("configure: the key is empty; the SDK stays off")
182
+ return false
183
+ }
184
+ guard let scheme = options.endpoint.scheme?.lowercased(), scheme == "https" || scheme == "http",
185
+ options.endpoint.host != nil else {
186
+ log.error("configure: the endpoint must be an http(s) URL; the SDK stays off")
187
+ return false
188
+ }
189
+ if key.hasPrefix("sk_") {
190
+ log.error("configure: that is a server key (sk_…); apps take their public pk_ key. The SDK stays off")
191
+ return false
192
+ }
193
+ if !key.hasPrefix("pk_") {
194
+ log.warn("configure: the key does not look like a public SDK key (pk_…)")
195
+ }
196
+ return true
197
+ }
198
+
199
+ func start(options: KerdlyOptions, snapshot: DeviceSnapshot?) {
200
+ self.options = options
201
+ let at = now
202
+ configuredAt = at
203
+ deepLinkSources = DeepLinkSourceTracker(configuredAt: at)
204
+ if let snapshot {
205
+ self.snapshot = snapshot
206
+ isForeground = snapshot.isForeground
207
+ }
208
+ observeLifecycleOnce()
209
+ resolveInstall(at: at)
210
+ }
211
+
212
+ /// An app updating from a build before 0.1.0 keeps its install id: the UserDefaults copy (and
213
+ /// the Keychain failure flag) move to the current keys once; the current keys win.
214
+ func migrateLegacyDefaults() {
215
+ let defaults = deps.defaults
216
+ if let legacyId = defaults.string(forKey: Self.legacyDefaultsInstallIdKey) {
217
+ if defaults.string(forKey: Self.defaultsInstallIdKey) == nil {
218
+ defaults.set(legacyId, forKey: Self.defaultsInstallIdKey)
219
+ }
220
+ defaults.set(nil as String?, forKey: Self.legacyDefaultsInstallIdKey)
221
+ }
222
+ if defaults.bool(forKey: Self.legacyDefaultsKeychainFailedKey) {
223
+ defaults.set(true, forKey: Self.defaultsKeychainFailedKey)
224
+ defaults.set(nil as String?, forKey: Self.legacyDefaultsKeychainFailedKey)
225
+ }
226
+ }
227
+
228
+ /// Install identity and state, then the launch's reserved events.
229
+ func resolveInstall(at: Date) {
230
+ migrateLegacyDefaults()
231
+ let decision = InstallIdentityResolver.decide(
232
+ keychain: deps.keychain.readInstallId(),
233
+ defaults: deps.defaults.string(forKey: Self.defaultsInstallIdKey),
234
+ keychainWriteFailedBefore: deps.defaults.bool(forKey: Self.defaultsKeychainFailedKey),
235
+ newId: deps.newId)
236
+ guard let decision else {
237
+ waitingForProtectedData = true
238
+ log.info("the Keychain is locked (no unlock since boot); starting once protected data is available")
239
+ return
240
+ }
241
+ waitingForProtectedData = false
242
+ let id = decision.installId
243
+ if decision.writeKeychain {
244
+ let written = deps.keychain.writeInstallId(id)
245
+ if written == deps.defaults.bool(forKey: Self.defaultsKeychainFailedKey) {
246
+ deps.defaults.set(!written, forKey: Self.defaultsKeychainFailedKey)
247
+ }
248
+ if !written { log.warn("could not write the install id to the Keychain") }
249
+ }
250
+ if decision.writeDefaults {
251
+ deps.defaults.set(id, forKey: Self.defaultsInstallIdKey)
252
+ }
253
+
254
+ let loaded = store.loadState()
255
+ if let loaded, loaded.installId == id {
256
+ state = loaded
257
+ } else {
258
+ state = (loaded ?? PersistedState(installId: id)).reset(for: id)
259
+ }
260
+ if let file = store.loadQueue(), file.installId == id {
261
+ eventQueue = EventQueue(events: file.events)
262
+ } else {
263
+ eventQueue = EventQueue()
264
+ }
265
+ configCache = store.loadConfig()
266
+ config = configCache?.config ?? .defaults
267
+ installIdBox.set(id)
268
+ attributionBox.set(state.attribution?.objectValue)
269
+ started = true
270
+ applyLogLevel()
271
+
272
+ let atMs = Clocks.ms(at)
273
+ if let installState = decision.state {
274
+ let installedAt = deps.device.installedAt().map(Clocks.ms)
275
+ state.firstLaunchAt = atMs
276
+ state.installedAt = installedAt
277
+ state.asaDue = state.asaAttempts < 3
278
+ state.asaFailures = 0
279
+ state.ddlEligible = installState != .restore
280
+ state.ddl = [:]
281
+ launchEnqueuedInstall = true
282
+ // `device` is a snapshot taken now, so the app and device facts `afterStart` loads are
283
+ // read here already (both are cheap).
284
+ appInfo = deps.device.appInfo()
285
+ facts = deps.device.facts()
286
+ enqueue(ReservedEvent.install, [
287
+ "install_state": .string(installState.rawValue),
288
+ "restored_from": .string(decision.restoredFrom),
289
+ "installed_at": .int(installedAt),
290
+ "installed_at_source": .string("documents_dir"),
291
+ "first_launch_at": .int(atMs),
292
+ "installer": .null,
293
+ "initial_url": .null,
294
+ "device": currentDevice(),
295
+ ], at: at, persist: false)
296
+ log.info("$install (\(installState.rawValue)) for install \(id)")
297
+ } else if state.firstLaunchAt == nil {
298
+ // The state file was lost: date the install from what is known.
299
+ state.firstLaunchAt = atMs
300
+ state.installedAt = deps.device.installedAt().map(Clocks.ms)
301
+ }
302
+ skan.reset(floor: state.skanFloor)
303
+ enqueue(ReservedEvent.open, ["reason": .string("launch")], at: at, persist: false)
304
+ replayPendingDeepLinks()
305
+ checkAttStatus(persist: false)
306
+ saveQueue()
307
+ saveState()
308
+ queue.async { self.afterStart() }
309
+ }
310
+
311
+ /// Re-enqueues attribution-bearing deep links the server has not accepted yet (same event id).
312
+ func replayPendingDeepLinks() {
313
+ for event in state.pendingDeepLinks where !eventQueue.contains(id: event.id) {
314
+ eventQueue.append(event)
315
+ log.debug("re-enqueued pending $deeplink \(event.id)")
316
+ }
317
+ }
318
+
319
+ /// The rest of the launch, off the caller's thread.
320
+ func afterStart() {
321
+ guard let options else { return }
322
+ appInfo = deps.device.appInfo()
323
+ appInfoLoaded = true
324
+ facts = deps.device.facts()
325
+ environment = EnvironmentResolver.resolve(option: options.environment, inputs: deps.device.environmentInputs())
326
+ log.debug("environment \(environment), bundle \(appInfo.bundle) \(appInfo.version) (\(appInfo.build))")
327
+ let calls = preStartCalls
328
+ preStartCalls = []
329
+ calls.forEach { $0() }
330
+ callsOpen = true
331
+ if isForeground { startForegroundTimer() }
332
+ if snapshot != nil {
333
+ releaseLaunchFlush()
334
+ } else {
335
+ scheduler.schedule(after: 1.5) { [self] in releaseLaunchFlush() }
336
+ }
337
+ runLaunchPipeline()
338
+ }
339
+
340
+ func receive(snapshot: DeviceSnapshot) {
341
+ self.snapshot = snapshot
342
+ isForeground = snapshot.isForeground
343
+ if started { releaseLaunchFlush() }
344
+ }
345
+
346
+ /// The launch flush waits for the UIKit snapshot (idfv, screen) so the first batch carries a
347
+ /// complete context; a blocked main thread holds it back at most 1.5 s. It is sent before any
348
+ /// other request of the launch.
349
+ func releaseLaunchFlush() {
350
+ guard !launchFlushReleased else { return }
351
+ launchFlushReleased = true
352
+ flushNow(explicit: false)
353
+ }
354
+
355
+ /// Runs `call` on the queue once the SDK has started; earlier calls are kept (bounded) and
356
+ /// replayed in order.
357
+ func run(_ call: @escaping @Sendable () -> Void) {
358
+ queue.async { [self] in
359
+ if callsOpen {
360
+ call()
361
+ } else if preStartCalls.count < Self.maxPreStartCalls {
362
+ preStartCalls.append(call)
363
+ } else {
364
+ log.warn("dropped a call made before configure (too many pending)")
365
+ }
366
+ }
367
+ }
368
+
369
+ // MARK: - Enqueue
370
+
371
+ /// Gates, numbers, stores and (for reserved events) flushes an event. Returns nil when it was
372
+ /// dropped. Queue-confined.
373
+ @discardableResult
374
+ func enqueue(_ name: String, _ props: [String: JSONValue], at date: Date? = nil,
375
+ persist: Bool = true) -> QueuedEvent? {
376
+ guard started else { return nil }
377
+ if kerdlyOff {
378
+ log.debug("\(name) dropped: Kerdly is off for this app version")
379
+ return nil
380
+ }
381
+ let reserved = ReservedEvent.isReserved(name)
382
+ if !state.consentAnalytics && !ReservedEvent.allowedWithoutAnalyticsConsent.contains(name) {
383
+ log.debug("\(name) dropped: analytics consent is off")
384
+ return nil
385
+ }
386
+ if !reserved {
387
+ // Before this version's config is in, events are kept: that config decides.
388
+ if configReady && !sendingEnabled {
389
+ log.debug("\(name) dropped: the SDK is disabled by its remote config")
390
+ return nil
391
+ }
392
+ if config.blockedEvents.contains(name) {
393
+ log.debug("\(name) dropped: blocked by the remote config")
394
+ return nil
395
+ }
396
+ }
397
+ let event = QueuedEvent(id: deps.newId(), name: name, ts: Clocks.ms(date ?? now), seq: state.seq + 1,
398
+ userId: state.userId, props: props)
399
+ guard event.size <= Self.maxEventBytes else {
400
+ log.error("\(name) dropped: \(event.size) bytes is over the \(Self.maxEventBytes)-byte event limit")
401
+ return nil
402
+ }
403
+ state.seq = event.seq
404
+ for dropped in eventQueue.append(event) {
405
+ log.warn("queue full: dropped the oldest custom event (\(dropped.name))")
406
+ }
407
+ if persist {
408
+ saveQueue()
409
+ saveState()
410
+ }
411
+ log.debug("enqueued \(name) #\(event.seq)")
412
+ if name != ReservedEvent.skan {
413
+ skanTrigger(.event(name))
414
+ }
415
+ if reserved || eventQueue.count >= config.queueFlushAt {
416
+ scheduleFlush()
417
+ }
418
+ return event
419
+ }
420
+
421
+ func saveQueue() {
422
+ guard started else { return }
423
+ if !store.save(queue: eventQueue.events, installId: state.installId) {
424
+ log.warn("could not write the event queue")
425
+ }
426
+ }
427
+
428
+ func saveState() {
429
+ guard started else { return }
430
+ if !store.save(state) {
431
+ log.warn("could not write the SDK state")
432
+ }
433
+ }
434
+
435
+ func applyLogLevel() {
436
+ guard let options else { return }
437
+ let verbose = config.debugDevices.contains(state.installId)
438
+ log.currentLevel = verbose ? .debug : options.logLevel
439
+ }
440
+
441
+ // MARK: - Public operations (called through `run`)
442
+
443
+ func setUserId(_ userId: String?, at: Date) {
444
+ guard userId != state.userId else { return }
445
+ let previous = state.userId
446
+ state.userId = userId
447
+ saveState()
448
+ enqueue(ReservedEvent.identify, [
449
+ "user_id": .string(userId),
450
+ "previous_user_id": .string(previous),
451
+ ], at: at)
452
+ }
453
+
454
+ func setConsent(analytics: Bool?, ads: Bool?, at: Date) {
455
+ var changed = false
456
+ if let analytics, analytics != state.consentAnalytics {
457
+ state.consentAnalytics = analytics
458
+ changed = true
459
+ }
460
+ if let ads, ads != state.consentAds {
461
+ state.consentAds = ads
462
+ changed = true
463
+ }
464
+ guard changed else { return }
465
+ saveState()
466
+ enqueueConsent(at: at)
467
+ if state.consentAds { collectAdvertisingId() }
468
+ }
469
+
470
+ func enqueueConsent(at: Date? = nil) {
471
+ enqueue(ReservedEvent.consent, [
472
+ "att": .string(deps.tracking.status().rawValue),
473
+ "analytics": .bool(state.consentAnalytics),
474
+ "ads": .bool(state.consentAds),
475
+ ], at: at)
476
+ }
477
+
478
+ func setAppAccountToken(_ token: String?, at: Date) {
479
+ guard token != state.appAccountToken else { return }
480
+ state.appAccountToken = token
481
+ saveState()
482
+ enqueueIds(at: at)
483
+ }
484
+
485
+ /// Merges into the stored map; an empty value removes its key.
486
+ func setPartnerIds(_ ids: [String: String], at: Date) {
487
+ var merged = state.partnerIds
488
+ for (key, value) in ids {
489
+ if value.isEmpty { merged.removeValue(forKey: key) } else { merged[key] = value }
490
+ }
491
+ guard merged != state.partnerIds else { return }
492
+ state.partnerIds = merged
493
+ saveState()
494
+ enqueueIds(at: at)
495
+ }
496
+
497
+ func enqueueIds(at: Date) {
498
+ enqueue(ReservedEvent.ids, [
499
+ "app_account_token": .string(state.appAccountToken),
500
+ "partner": .object(state.partnerIds.mapValues { .string($0) }),
501
+ ], at: at)
502
+ }
503
+
504
+ func track(_ name: String, props: [String: JSONValue], at: Date) {
505
+ enqueue(name, props, at: at)
506
+ }
507
+
508
+ func handleDeepLink(_ link: ParsedDeepLink, source explicit: String?, at: Date) {
509
+ var props = link.props
510
+ props["source"] = .string(deepLinkSources.source(at: at, explicit: explicit))
511
+ guard let event = enqueue(ReservedEvent.deeplink, props, at: at) else { return }
512
+ if link.isAttributionBearing {
513
+ state.pendingDeepLinks.append(event)
514
+ if state.pendingDeepLinks.count > PersistedState.maxPendingDeepLinks {
515
+ state.pendingDeepLinks.removeFirst(state.pendingDeepLinks.count - PersistedState.maxPendingDeepLinks)
516
+ }
517
+ saveState()
518
+ }
519
+ }
520
+
521
+ func recordNetworkSend(_ send: KerdlyNetworkSend, at: Date) {
522
+ func clip(_ s: String?) -> JSONValue { .string(s.map { String($0.prefix(Self.maxIdLength)) }) }
523
+ enqueue(ReservedEvent.networkSend, [
524
+ "network": clip(send.network),
525
+ "event": clip(send.event),
526
+ "event_id": clip(send.eventId),
527
+ "value": send.value.flatMap { $0.isFinite ? JSONValue.number($0) : nil } ?? .null,
528
+ "currency": clip(send.currency),
529
+ "flag": clip(send.flag),
530
+ ], at: at)
531
+ }
532
+
533
+ // MARK: - Attribution
534
+
535
+ func updateAttribution(_ attribution: [String: JSONValue]) {
536
+ guard state.attribution?.objectValue != attribution else { return }
537
+ state.attribution = .object(attribution)
538
+ saveState()
539
+ attributionBox.set(attribution)
540
+ log.info("attribution: \(attribution["network"]?.stringValue ?? "?") (\(attribution["state"]?.stringValue ?? "?"))")
541
+ let handlers = attributionHandlers.get()
542
+ guard !handlers.isEmpty else { return }
543
+ DispatchQueue.main.async {
544
+ let value = KerdlyAttribution(json: attribution)
545
+ handlers.forEach { $0.value(value) }
546
+ }
547
+ }
548
+
549
+ func addAttributionHandler(_ handler: UncheckedSendable<(KerdlyAttribution) -> Void>) {
550
+ attributionHandlers.update { $0.append(handler) }
551
+ if let current = attributionBox.get() {
552
+ DispatchQueue.main.async {
553
+ handler.value(KerdlyAttribution(json: current))
554
+ }
555
+ }
556
+ }
557
+ }
@@ -0,0 +1,95 @@
1
+ import Foundation
2
+ import os
3
+ #if canImport(CryptoKit)
4
+ import CryptoKit
5
+ #endif
6
+
7
+ /// Moves a value the compiler cannot prove `Sendable` (an app's completion handler) to the thread
8
+ /// that will use it. Only used where the value is touched on one thread at a time.
9
+ struct UncheckedSendable<Value>: @unchecked Sendable {
10
+ let value: Value
11
+ init(_ value: Value) { self.value = value }
12
+ }
13
+
14
+ /// A value guarded by a lock, for the few things public getters read from any thread.
15
+ final class Locked<Value>: @unchecked Sendable {
16
+ private let lock = NSLock()
17
+ private var value: Value
18
+
19
+ init(_ value: Value) {
20
+ self.value = value
21
+ }
22
+
23
+ func get() -> Value {
24
+ lock.lock()
25
+ defer { lock.unlock() }
26
+ return value
27
+ }
28
+
29
+ func set(_ newValue: Value) {
30
+ lock.lock()
31
+ value = newValue
32
+ lock.unlock()
33
+ }
34
+
35
+ @discardableResult
36
+ func update<T>(_ body: (inout Value) -> T) -> T {
37
+ lock.lock()
38
+ defer { lock.unlock() }
39
+ return body(&value)
40
+ }
41
+ }
42
+
43
+ /// `[Kerdly]`-prefixed logging at the configured level. Callers never pass keys or a
44
+ /// full IDFA.
45
+ final class KerdlyLogger: @unchecked Sendable {
46
+ private let level = Locked(KerdlyLogLevel.warn)
47
+ private let osLog = os.Logger(subsystem: "com.kerdly.sdk", category: "Kerdly")
48
+
49
+ var currentLevel: KerdlyLogLevel {
50
+ get { level.get() }
51
+ set { level.set(newValue) }
52
+ }
53
+
54
+ func error(_ message: @autoclosure () -> String) { write(.error, message()) }
55
+ func warn(_ message: @autoclosure () -> String) { write(.warn, message()) }
56
+ func info(_ message: @autoclosure () -> String) { write(.info, message()) }
57
+ func debug(_ message: @autoclosure () -> String) { write(.debug, message()) }
58
+
59
+ func enabled(_ messageLevel: KerdlyLogLevel) -> Bool {
60
+ messageLevel != .none && messageLevel.rawValue <= level.get().rawValue
61
+ }
62
+
63
+ private func write(_ messageLevel: KerdlyLogLevel, _ message: @autoclosure () -> String) {
64
+ guard enabled(messageLevel) else { return }
65
+ let text = "[Kerdly] \(message())"
66
+ switch messageLevel {
67
+ case .error: osLog.error("\(text, privacy: .public)")
68
+ case .warn: osLog.warning("\(text, privacy: .public)")
69
+ case .info: osLog.info("\(text, privacy: .public)")
70
+ case .debug, .none: osLog.debug("\(text, privacy: .public)")
71
+ }
72
+ }
73
+ }
74
+
75
+ enum Hashing {
76
+ /// Lowercase hex SHA-256.
77
+ static func sha256(_ data: Data) -> String {
78
+ #if canImport(CryptoKit)
79
+ return SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
80
+ #else
81
+ return String(data.hashValue)
82
+ #endif
83
+ }
84
+
85
+ static func sha256(_ string: String) -> String {
86
+ sha256(Data(string.utf8))
87
+ }
88
+ }
89
+
90
+ enum Redact {
91
+ /// First 4 characters, for log lines about an IDFA or a token.
92
+ static func short(_ value: String) -> String {
93
+ value.count <= 4 ? "…" : "\(value.prefix(4))…"
94
+ }
95
+ }
@@ -0,0 +1,22 @@
1
+ import Foundation
2
+
3
+ /// Exponential back-off with full jitter, 1 s to 5 min. A server `Retry-After` wins
4
+ /// over it (see `DeliveryPolicy.retryAfter`).
5
+ struct BackoffPolicy: Equatable, Sendable {
6
+ var base: TimeInterval = 1
7
+ var cap: TimeInterval = 300
8
+
9
+ /// The ceiling for a 0-based attempt: `min(cap, base × 2^attempt)`.
10
+ func ceiling(attempt: Int) -> TimeInterval {
11
+ let exponent = Double(min(max(attempt, 0), 30))
12
+ return min(cap, base * pow(2, exponent))
13
+ }
14
+
15
+ /// A delay drawn uniformly from `[0, ceiling]`, floored at `base`, so it always lies in
16
+ /// `[base, cap]`.
17
+ /// - Parameter unitRandom: a value in `[0, 1]`.
18
+ func delay(attempt: Int, unitRandom: Double) -> TimeInterval {
19
+ let r = min(max(unitRandom, 0), 1)
20
+ return min(cap, max(base, ceiling(attempt: attempt) * r))
21
+ }
22
+ }