@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,185 @@
1
+ import Foundation
2
+
3
+ /// `GET /v1/sdk/config`, with the defaults used until a config is cached.
4
+ struct RemoteConfig: Equatable, Sendable {
5
+ var version: Int?
6
+ /// Kill switch: false → stop sending, keep collecting reserved events.
7
+ var enabled = true
8
+ /// Kerdly is off for this app version: record, collect and send nothing.
9
+ var off = false
10
+ var maxBatch = BatchBuilder.maxEvents
11
+ var queueFlushAt = 20
12
+ var flushInterval: TimeInterval = 15
13
+ var blockedEvents: Set<String> = []
14
+ var collectAdvertisingId = true
15
+ var collectAppTransaction = true
16
+ var collectAsaToken = true
17
+ var collectPurchases = true
18
+ var collectPublicIp = true
19
+ /// The public IPv6 echo. Only an `https` URL replaces the default.
20
+ var ipv6EchoUrl = RemoteConfig.defaultIpv6EchoUrl
21
+ /// nil = the SDK never writes SKAN values.
22
+ var skan: SkanSchema?
23
+ /// Deferred deep links; nil = off.
24
+ var ddl: DdlConfig?
25
+ var minSupportedSdk: String?
26
+ var debugDevices: Set<String> = []
27
+
28
+ static let defaults = RemoteConfig()
29
+ static let defaultIpv6EchoUrl = URL(string: "https://api6.ipify.org?format=json")!
30
+
31
+ /// Reads a config body. Unknown fields are ignored and out-of-range values clamped. An invalid
32
+ /// `skan` ladder falls back to `previousValidSkan` (the last valid one); `skan: null` turns SKAN off.
33
+ static func parse(_ json: JSONValue, previousValidSkan: SkanSchema?) -> RemoteConfig {
34
+ var config = RemoteConfig()
35
+ guard let object = json.objectValue else { return config }
36
+ config.version = object["version"]?.int64Value.map { Int($0) }
37
+ config.enabled = object["enabled"]?.boolValue ?? true
38
+ config.off = object["off"]?.boolValue ?? false
39
+ if let flush = object["flush"] {
40
+ if let v = flush["max_batch"]?.int64Value { config.maxBatch = Int(min(max(v, 1), Int64(BatchBuilder.maxEvents))) }
41
+ if let v = flush["queue_flush_at"]?.int64Value { config.queueFlushAt = Int(min(max(v, 1), 1_000)) }
42
+ if let v = flush["interval_s"]?.doubleValue, v.isFinite { config.flushInterval = min(max(v, 1), 3_600) }
43
+ }
44
+ config.blockedEvents = Set(object["events"]?["block"]?.arrayValue?.compactMap(\.stringValue) ?? [])
45
+ if let collect = object["collect"] {
46
+ config.collectAdvertisingId = collect["advertising_id"]?.boolValue ?? true
47
+ config.collectAppTransaction = collect["app_transaction"]?.boolValue ?? true
48
+ config.collectAsaToken = collect["asa_token"]?.boolValue ?? true
49
+ config.collectPurchases = collect["purchases"]?.boolValue ?? true
50
+ config.collectPublicIp = collect["public_ip"]?.boolValue ?? true
51
+ }
52
+ if let raw = object["ipv6_echo_url"]?.stringValue, let url = URL(string: raw),
53
+ url.scheme?.lowercased() == "https", !(url.host ?? "").isEmpty {
54
+ config.ipv6EchoUrl = url
55
+ }
56
+ switch object["skan"] {
57
+ case .none, .some(.null):
58
+ config.skan = nil
59
+ case .some(let raw):
60
+ config.skan = SkanSchema.parse(raw) ?? previousValidSkan
61
+ }
62
+ config.ddl = DdlConfig.parse(object["ddl"])
63
+ config.minSupportedSdk = object["min_supported_sdk"]?.stringValue
64
+ config.debugDevices = Set(object["debug_devices"]?.arrayValue?.compactMap(\.stringValue) ?? [])
65
+ return config
66
+ }
67
+
68
+ /// True when `sdkVersion` is below `min_supported_sdk`: the SDK then behaves as if the kill switch
69
+ /// were on.
70
+ func isBelowMinimum(sdkVersion: String) -> Bool {
71
+ guard let min = minSupportedSdk else { return false }
72
+ return SemanticVersion.compare(sdkVersion, min) < 0
73
+ }
74
+ }
75
+
76
+ /// The config's `ddl` block: which networks to ask for a deferred deep link. The hosts are the
77
+ /// SDK's own (DeferredLinks.swift), never the config's.
78
+ struct DdlConfig: Equatable, Sendable {
79
+ struct Meta: Equatable, Sendable {
80
+ /// nil = the bundle's `FacebookAppID` / `FacebookClientToken`.
81
+ var appId: String?
82
+ var clientToken: String?
83
+ }
84
+
85
+ struct TikTok: Equatable, Sendable {
86
+ var appId: String
87
+ var storeAppId: String?
88
+ }
89
+
90
+ var enabled: Bool
91
+ /// Asked only this long after the first launch.
92
+ var maxAge: TimeInterval
93
+ var meta: Meta?
94
+ var tiktok: TikTok?
95
+ /// `require_att`: ask only with tracking authorized. False: also ask once the user denied
96
+ /// tracking (or it is restricted), without the IDFA (Meta through `ep2`). Default true.
97
+ var requireAtt = true
98
+
99
+ static let defaultMaxAgeHours: Double = 47
100
+
101
+ /// nil when the block is absent or not an object; out-of-range ages are clamped to 1–168 h.
102
+ static func parse(_ json: JSONValue?) -> DdlConfig? {
103
+ guard let object = json?.objectValue else { return nil }
104
+ let hours = object["max_age_h"]?.doubleValue.flatMap { $0.isFinite ? $0 : nil } ?? defaultMaxAgeHours
105
+ let nonEmpty = { (value: JSONValue?) -> String? in
106
+ value?.stringValue.flatMap { $0.isEmpty ? nil : $0 }
107
+ }
108
+ let meta = object["meta"]?.objectValue.map {
109
+ Meta(appId: nonEmpty($0["app_id"]), clientToken: nonEmpty($0["client_token"]))
110
+ }
111
+ let tiktok = object["tiktok"]?.objectValue.flatMap { block in
112
+ nonEmpty(block["app_id"]).map { TikTok(appId: $0, storeAppId: nonEmpty(block["store_app_id"])) }
113
+ }
114
+ return DdlConfig(enabled: object["enabled"]?.boolValue ?? false,
115
+ maxAge: min(max(hours, 1), 168) * 3_600, meta: meta, tiktok: tiktok,
116
+ requireAtt: object["require_att"]?.boolValue ?? true)
117
+ }
118
+ }
119
+
120
+ /// The cached config document (`Application Support/kerdly/config.json`).
121
+ struct ConfigCache: Codable, Equatable, Sendable {
122
+ var etag: String?
123
+ /// ms since the epoch.
124
+ var fetchedAt: Int64
125
+ var body: JSONValue
126
+ /// The last ladder that passed validation, kept for when a later one does not.
127
+ var lastValidSkan: JSONValue?
128
+ /// The app version this config was fetched for (Kerdly resolves the config per
129
+ /// version). Nil in a cache written before the field existed.
130
+ var appVersion: String?
131
+
132
+ enum CodingKeys: String, CodingKey {
133
+ case etag, body
134
+ case fetchedAt = "fetched_at"
135
+ case lastValidSkan = "last_valid_skan"
136
+ case appVersion = "app_version"
137
+ }
138
+
139
+ static let maxAge: TimeInterval = 6 * 3_600
140
+
141
+ func isStale(now: Date) -> Bool {
142
+ now.timeIntervalSince(Clocks.date(ms: fetchedAt)) >= Self.maxAge
143
+ || Clocks.date(ms: fetchedAt) > now.addingTimeInterval(Self.maxAge)
144
+ }
145
+
146
+ var config: RemoteConfig {
147
+ RemoteConfig.parse(body, previousValidSkan: SkanSchema.parse(lastValidSkan))
148
+ }
149
+
150
+ /// Whether this config was fetched for `appVersion`; after an app update it was not.
151
+ func isFor(appVersion: String) -> Bool {
152
+ self.appVersion == appVersion
153
+ }
154
+
155
+ /// The cache after a 200: the new body, and the last valid ladder carried forward.
156
+ func replacing(body: JSONValue, etag: String?, fetchedAt: Int64, appVersion: String) -> ConfigCache {
157
+ let newSkan = body["skan"]
158
+ let valid = SkanSchema.parse(newSkan) != nil ? newSkan : lastValidSkan
159
+ return ConfigCache(etag: etag, fetchedAt: fetchedAt, body: body, lastValidSkan: valid, appVersion: appVersion)
160
+ }
161
+
162
+ static func first(body: JSONValue, etag: String?, fetchedAt: Int64, appVersion: String) -> ConfigCache {
163
+ let skan = body["skan"]
164
+ return ConfigCache(etag: etag, fetchedAt: fetchedAt, body: body,
165
+ lastValidSkan: SkanSchema.parse(skan) != nil ? skan : nil, appVersion: appVersion)
166
+ }
167
+ }
168
+
169
+ enum SemanticVersion {
170
+ /// Compares dotted numeric versions ("0.1.0" < "0.10.0"); non-numeric parts count as 0.
171
+ static func compare(_ a: String, _ b: String) -> Int {
172
+ let pa = parts(a), pb = parts(b)
173
+ for i in 0..<max(pa.count, pb.count) {
174
+ let x = i < pa.count ? pa[i] : 0
175
+ let y = i < pb.count ? pb[i] : 0
176
+ if x != y { return x < y ? -1 : 1 }
177
+ }
178
+ return 0
179
+ }
180
+
181
+ private static func parts(_ v: String) -> [Int] {
182
+ let core = v.split(whereSeparator: { $0 == "-" || $0 == "+" }).first.map(String.init) ?? v
183
+ return core.split(separator: ".").map { Int($0) ?? 0 }
184
+ }
185
+ }
@@ -0,0 +1,343 @@
1
+ import Foundation
2
+
3
+ enum SkanCoarse: String, Sendable, Equatable {
4
+ case low, medium, high
5
+
6
+ var rank: Int {
7
+ switch self {
8
+ case .low: return 0
9
+ case .medium: return 1
10
+ case .high: return 2
11
+ }
12
+ }
13
+ }
14
+
15
+ /// One rung of the conversion-value ladder (config `skan.rungs`).
16
+ struct SkanRung: Equatable, Sendable {
17
+ let event: String
18
+ let fine: Int
19
+ let coarse: SkanCoarse
20
+ /// `launch` | `event` | `purchase` | `sweep` (| `ledger`, server hints, not used in v0.1).
21
+ let on: Set<String>
22
+ }
23
+
24
+ /// The config's `skan` block. `parse` re-checks the ladder rules and returns nil for
25
+ /// an invalid ladder, so the caller keeps the last valid one.
26
+ struct SkanSchema: Equatable, Sendable {
27
+ let version: Int
28
+ let enabled: Bool
29
+ let rungs: [SkanRung]
30
+ let lockWindow: Bool
31
+ let aakMirror: Bool
32
+
33
+ static func parse(_ json: JSONValue?) -> SkanSchema? {
34
+ guard let object = json?.objectValue else { return nil }
35
+ guard let rawRungs = object["rungs"]?.arrayValue else { return nil }
36
+ var rungs: [SkanRung] = []
37
+ for raw in rawRungs {
38
+ guard let event = raw["event"]?.stringValue, !event.isEmpty,
39
+ let fine = raw["fine"]?.int64Value, (0...63).contains(fine),
40
+ let coarseName = raw["coarse"]?.stringValue, let coarse = SkanCoarse(rawValue: coarseName)
41
+ else { return nil }
42
+ let on = Set(raw["on"]?.arrayValue?.compactMap(\.stringValue) ?? [])
43
+ rungs.append(SkanRung(event: event, fine: Int(fine), coarse: coarse, on: on))
44
+ }
45
+ // Fine values strictly increase down the ladder, coarse values never go down, events are unique.
46
+ for (previous, next) in zip(rungs, rungs.dropFirst()) {
47
+ if next.fine <= previous.fine || next.coarse.rank < previous.coarse.rank { return nil }
48
+ }
49
+ if Set(rungs.map(\.event)).count != rungs.count { return nil }
50
+ return SkanSchema(
51
+ version: Int(object["version"]?.int64Value ?? 0),
52
+ enabled: object["enabled"]?.boolValue ?? false,
53
+ rungs: rungs,
54
+ lockWindow: object["lock_window"]?.boolValue ?? false,
55
+ aakMirror: object["aak_mirror"]?.boolValue ?? false
56
+ )
57
+ }
58
+ }
59
+
60
+ /// What a StoreKit transaction says, for the `purchase` / `sweep` triggers.
61
+ struct PurchaseFacts: Equatable, Sendable {
62
+ /// An introductory offer whose payment mode is free trial.
63
+ let isFreeTrial: Bool
64
+ let purchaseDate: Date
65
+ let originalPurchaseDate: Date
66
+ /// From `Transaction.reason`; nil when unknown.
67
+ let isRenewal: Bool?
68
+ let revoked: Bool
69
+ }
70
+
71
+ enum SkanTrigger: Equatable, Sendable {
72
+ /// The first launch's baseline.
73
+ case launch
74
+ /// A reserved or custom event of the rung's name was enqueued.
75
+ case event(String)
76
+ /// A StoreKit transaction seen on the device (paywall notify, `Transaction.updates`).
77
+ case purchase(PurchaseFacts)
78
+ /// The `Transaction.currentEntitlements` sweep.
79
+ case sweep(PurchaseFacts)
80
+ }
81
+
82
+ /// When this install's conversion clock started.
83
+ struct SkanTimeline: Equatable, Sendable {
84
+ /// The install moment: the earlier of `installed_at` (the Documents directory's creation) and
85
+ /// the SDK's first launch. The Documents directory is recreated on a reinstall, so a returning
86
+ /// subscriber's old entitlement still predates it; and when an app update brings the SDK to an
87
+ /// existing install, it keeps the install's real age instead of the update's.
88
+ let start: Date
89
+
90
+ init(firstLaunchAt: Date, installedAt: Date?) {
91
+ start = min(installedAt ?? firstLaunchAt, firstLaunchAt)
92
+ }
93
+ }
94
+
95
+ enum SkanPlanner {
96
+ /// SKAN 4's first conversion window. The baseline is written only inside it, and only while
97
+ /// nothing was written yet: an app update that adds the SDK to an old install must not lower a
98
+ /// value the app's previous writer set.
99
+ static let baselineWindow: TimeInterval = 48 * 3_600
100
+ /// Store dates come from Apple's clock, the timeline from the device's.
101
+ static let clockTolerance: TimeInterval = 600
102
+
103
+ /// The rung a trigger asks for, or nil.
104
+ static func rung(for trigger: SkanTrigger, schema: SkanSchema, timeline: SkanTimeline,
105
+ now: Date, floor: Int?) -> SkanRung? {
106
+ switch trigger {
107
+ case .launch:
108
+ guard floor == nil, now.timeIntervalSince(timeline.start) < baselineWindow else { return nil }
109
+ return schema.rungs.first { $0.on.contains("launch") }
110
+ case .event(let name):
111
+ return schema.rungs.first { $0.event == name && $0.on.contains("event") }
112
+ case .purchase(let facts):
113
+ guard let event = purchaseRungEvent(facts, sweep: false, timeline: timeline) else { return nil }
114
+ return schema.rungs.first { $0.event == event && $0.on.contains("purchase") }
115
+ case .sweep(let facts):
116
+ guard let event = purchaseRungEvent(facts, sweep: true, timeline: timeline) else { return nil }
117
+ return schema.rungs.first { $0.event == event && $0.on.contains("sweep") }
118
+ }
119
+ }
120
+
121
+ /// `trial_start` for a free-trial offer, `subscribe` for a paid transaction, nil when the
122
+ /// transaction is not this install's conversion:
123
+ /// - sweep: only an entitlement whose subscription began after this install started (the
124
+ /// reinstall fix: a returning subscriber's old entitlement must not write `subscribe`);
125
+ /// - purchase: only a transaction made after this install started, and for a paid one, either a
126
+ /// subscription that began after it (a trial converting) or a fresh purchase rather than the
127
+ /// renewal of an older subscription.
128
+ static func purchaseRungEvent(_ facts: PurchaseFacts, sweep: Bool, timeline: SkanTimeline) -> String? {
129
+ if facts.revoked { return nil }
130
+ let start = timeline.start.addingTimeInterval(-clockTolerance)
131
+ if sweep {
132
+ guard facts.originalPurchaseDate > start else { return nil }
133
+ return facts.isFreeTrial ? "trial_start" : "subscribe"
134
+ }
135
+ guard facts.purchaseDate >= start else { return nil }
136
+ if facts.isFreeTrial { return "trial_start" }
137
+ if facts.originalPurchaseDate >= start || facts.isRenewal == false { return "subscribe" }
138
+ return nil
139
+ }
140
+
141
+ /// Monotonic: never write a fine value at or below the floor.
142
+ static func shouldWrite(fine: Int, floor: Int?) -> Bool {
143
+ guard let floor else { return true }
144
+ return fine > floor
145
+ }
146
+
147
+ /// The SKAN 4 window the SDK believes it is in: 0 (0–48 h), 1 (to day 7), 2 (to day 35), nil after.
148
+ static func window(since start: Date, now: Date) -> Int? {
149
+ let hours = now.timeIntervalSince(start) / 3_600
150
+ if hours < 48 { return 0 }
151
+ if hours < 168 { return 1 }
152
+ if hours < 840 { return 2 }
153
+ return nil
154
+ }
155
+
156
+ /// `$skan` props.
157
+ static func auditProps(rung: SkanRung, coarse: SkanCoarse?, previous: Int?, schemaVersion: Int,
158
+ window: Int?, api: String, error: String?) -> [String: JSONValue] {
159
+ [
160
+ "fine": .int(Int64(rung.fine)),
161
+ "coarse": .string(coarse?.rawValue),
162
+ "rung": .string(rung.event),
163
+ "previous": .int(previous.map(Int64.init)),
164
+ "schema_version": .int(Int64(schemaVersion)),
165
+ "window": .int(window.map(Int64.init)),
166
+ "api": .string(api),
167
+ "error": .string(error),
168
+ ]
169
+ }
170
+ }
171
+
172
+ /// The outcome of one SKAdNetwork or AdAttributionKit write.
173
+ enum SkanWriteResult: Equatable, Sendable {
174
+ /// The API does not exist on this OS (SKAN below 15.4, AdAttributionKit below 17.4): nothing was
175
+ /// written, nothing is audited.
176
+ case unsupported
177
+ /// Apple's completion ran. `api` is `skan4` | `skan3` | `aak`; `error` is nil on success.
178
+ case completed(api: String, error: String?)
179
+ }
180
+
181
+ /// The system calls behind the writer.
182
+ protocol SkanWriting: Sendable {
183
+ /// The SKAdNetwork API this OS writes through: `skan4` (16.1+), `skan3` (15.4–16.0), nil below.
184
+ var skanApiName: String? { get }
185
+ func updateSkan(fine: Int, coarse: SkanCoarse, lockWindow: Bool,
186
+ completion: @escaping @Sendable (SkanWriteResult) -> Void)
187
+ func updateAak(fine: Int, lockPostback: Bool, completion: @escaping @Sendable (SkanWriteResult) -> Void)
188
+ }
189
+
190
+ /// Serialises conversion-value writes and owns the floor. Every method runs on `queue`; Apple's
191
+ /// completions hop back onto it. Reading and raising the floor from two concurrent writes would let
192
+ /// the lower value win, hence one write at a time.
193
+ final class SkanCoordinator: @unchecked Sendable {
194
+ struct Job: Sendable {
195
+ let trigger: SkanTrigger
196
+ let schema: SkanSchema
197
+ let timeline: SkanTimeline
198
+ }
199
+
200
+ /// One write in progress: what its `$skan` events carry.
201
+ private struct Write: Sendable {
202
+ let rung: SkanRung
203
+ let schema: SkanSchema
204
+ let previous: Int?
205
+ let window: Int?
206
+ }
207
+
208
+ private enum Phase: Sendable {
209
+ case skan, aak
210
+ }
211
+
212
+ static let writeTimeout: TimeInterval = 10
213
+
214
+ private let timeout: TimeInterval
215
+ private let writer: SkanWriting
216
+ private let queue: DispatchQueue
217
+ private let now: @Sendable () -> Date
218
+ private(set) var floor: Int?
219
+ private var jobs: [Job] = []
220
+ private var busy = false
221
+ /// Bumped at every phase start; a completion or timeout for an older phase is ignored.
222
+ private var phaseToken = 0
223
+ private var idleWaiters: [() -> Void] = []
224
+
225
+ /// A `$skan` event to enqueue.
226
+ var onAudit: ([String: JSONValue]) -> Void = { _ in }
227
+ /// The floor rose (persist it).
228
+ var onFloorChange: (Int) -> Void = { _ in }
229
+
230
+ init(writer: SkanWriting, queue: DispatchQueue, floor: Int?, timeout: TimeInterval = SkanCoordinator.writeTimeout,
231
+ now: @escaping @Sendable () -> Date) {
232
+ self.timeout = timeout
233
+ self.writer = writer
234
+ self.queue = queue
235
+ self.floor = floor
236
+ self.now = now
237
+ }
238
+
239
+ var isIdle: Bool { !busy && jobs.isEmpty }
240
+
241
+ func reset(floor: Int?) {
242
+ self.floor = floor
243
+ }
244
+
245
+ func submit(_ job: Job) {
246
+ jobs.append(job)
247
+ pump()
248
+ }
249
+
250
+ /// Runs `block` once no write is pending or in flight.
251
+ func whenIdle(_ block: @escaping () -> Void) {
252
+ if isIdle { block() } else { idleWaiters.append(block) }
253
+ }
254
+
255
+ private func pump() {
256
+ while !busy, !jobs.isEmpty {
257
+ let job = jobs.removeFirst()
258
+ let at = now()
259
+ guard let rung = SkanPlanner.rung(for: job.trigger, schema: job.schema, timeline: job.timeline,
260
+ now: at, floor: floor),
261
+ SkanPlanner.shouldWrite(fine: rung.fine, floor: floor)
262
+ else { continue }
263
+ busy = true
264
+ let write = Write(rung: rung, schema: job.schema, previous: floor,
265
+ window: SkanPlanner.window(since: job.timeline.start, now: at))
266
+ startSkan(write)
267
+ }
268
+ if isIdle, !idleWaiters.isEmpty {
269
+ let waiters = idleWaiters
270
+ idleWaiters = []
271
+ waiters.forEach { $0() }
272
+ }
273
+ }
274
+
275
+ private func beginPhase(_ phase: Phase, _ write: Write) -> Int {
276
+ phaseToken += 1
277
+ let token = phaseToken
278
+ queue.asyncAfter(deadline: .now() + timeout) { [self] in
279
+ timedOut(token: token, phase: phase, write)
280
+ }
281
+ return token
282
+ }
283
+
284
+ private func startSkan(_ write: Write) {
285
+ let token = beginPhase(.skan, write)
286
+ writer.updateSkan(fine: write.rung.fine, coarse: write.rung.coarse, lockWindow: write.schema.lockWindow) {
287
+ [self] result in
288
+ queue.async { self.skanCompleted(result, token: token, write) }
289
+ }
290
+ }
291
+
292
+ private func skanCompleted(_ result: SkanWriteResult, token: Int, _ write: Write) {
293
+ guard phaseToken == token, busy else { return }
294
+ audit(result, write)
295
+ // The floor rises only when Apple reported no error.
296
+ if case .completed(_, nil) = result {
297
+ let raised = max(floor ?? write.rung.fine, write.rung.fine)
298
+ floor = raised
299
+ onFloorChange(raised)
300
+ }
301
+ startMirror(write)
302
+ }
303
+
304
+ private func startMirror(_ write: Write) {
305
+ guard write.schema.aakMirror else { return finish() }
306
+ let token = beginPhase(.aak, write)
307
+ writer.updateAak(fine: write.rung.fine, lockPostback: write.schema.lockWindow) { [self] result in
308
+ queue.async { self.aakCompleted(result, token: token, write) }
309
+ }
310
+ }
311
+
312
+ private func aakCompleted(_ result: SkanWriteResult, token: Int, _ write: Write) {
313
+ guard phaseToken == token, busy else { return }
314
+ audit(result, write)
315
+ finish()
316
+ }
317
+
318
+ private func timedOut(token: Int, phase: Phase, _ write: Write) {
319
+ guard phaseToken == token, busy else { return }
320
+ switch phase {
321
+ case .skan:
322
+ phaseToken += 1
323
+ audit(.completed(api: writer.skanApiName ?? "skan4", error: "timeout"), write)
324
+ startMirror(write)
325
+ case .aak:
326
+ phaseToken += 1
327
+ audit(.completed(api: "aak", error: "timeout"), write)
328
+ finish()
329
+ }
330
+ }
331
+
332
+ private func finish() {
333
+ busy = false
334
+ pump()
335
+ }
336
+
337
+ private func audit(_ result: SkanWriteResult, _ write: Write) {
338
+ guard case .completed(let api, let error) = result else { return }
339
+ onAudit(SkanPlanner.auditProps(
340
+ rung: write.rung, coarse: api == "skan4" ? write.rung.coarse : nil, previous: write.previous,
341
+ schemaVersion: write.schema.version, window: write.window, api: api, error: error))
342
+ }
343
+ }
@@ -0,0 +1,126 @@
1
+ import Foundation
2
+
3
+ /// Standard events: ordinary event names whose typed props are checked the same way
4
+ /// whether they come from the typed methods or from `track`. The other props follow the custom rules
5
+ /// (`EventValidator`), and the typed ones count toward the 25. A bad typed prop drops only that prop.
6
+ enum StandardEvent {
7
+ static let registration = "registration"
8
+ static let startTrial = "start_trial"
9
+ static let subscribe = "subscribe"
10
+ static let purchase = "purchase"
11
+
12
+ static let maxIdLength = 128
13
+ static let maxMethodLength = 64
14
+
15
+ private static let money = ["product_id", "value", "currency", "transaction_id"]
16
+
17
+ /// Each standard event's typed keys.
18
+ static let typedKeys: [String: [String]] = [
19
+ registration: ["method"],
20
+ startTrial: money,
21
+ subscribe: money,
22
+ purchase: ["product_id", "value", "currency", "quantity", "transaction_id"],
23
+ ]
24
+
25
+ // MARK: The typed methods' arguments, as props (nil arguments are left out)
26
+
27
+ static func arguments(method: String?) -> [String: Any] {
28
+ var args: [String: Any] = [:]
29
+ if let method { args["method"] = method }
30
+ return args
31
+ }
32
+
33
+ static func arguments(productId: String?, value: Double?, currency: String?, quantity: Int? = nil,
34
+ transactionId: String?) -> [String: Any] {
35
+ var args: [String: Any] = [:]
36
+ if let productId { args["product_id"] = productId }
37
+ if let value { args["value"] = value }
38
+ if let currency { args["currency"] = currency }
39
+ if let quantity { args["quantity"] = quantity }
40
+ if let transactionId { args["transaction_id"] = transactionId }
41
+ return args
42
+ }
43
+
44
+ /// A typed method's props: its arguments, then `properties` for every key no argument set. The
45
+ /// keys an argument kept `properties` from setting come back as `ignored`.
46
+ static func merge(_ arguments: [String: Any], _ properties: [String: Any]) -> (props: [String: Any], ignored: [String]) {
47
+ var merged = arguments
48
+ var ignored: [String] = []
49
+ for (key, value) in properties {
50
+ if arguments[key] != nil { ignored.append(key) } else { merged[key] = value }
51
+ }
52
+ return (merged, ignored.sorted())
53
+ }
54
+
55
+ // MARK: Validation
56
+
57
+ /// The props of an event named `name`: the typed checks for a standard name, then the custom
58
+ /// rules for the rest (only the custom rules for any other name).
59
+ static func sanitize(_ name: String, _ properties: [String: Any]) -> EventValidator.Sanitized {
60
+ guard let keys = typedKeys[name] else { return EventValidator.sanitize(properties) }
61
+ var props: [String: JSONValue] = [:]
62
+ var issues: [String] = []
63
+ var custom = properties
64
+ for key in keys {
65
+ guard let raw = custom.removeValue(forKey: key) else { continue }
66
+ switch typed(key, raw) {
67
+ case .kept(let value):
68
+ props[key] = value
69
+ case .truncated(let value, let max):
70
+ props[key] = value
71
+ issues.append("prop '\(key)' truncated to \(max) characters")
72
+ case .dropped(let reason):
73
+ issues.append("prop '\(key)' dropped: \(reason)")
74
+ }
75
+ }
76
+ // A value without a currency means nothing to a network.
77
+ if props["value"] != nil && props["currency"] == nil {
78
+ props["value"] = nil
79
+ issues.append("prop 'value' dropped: no valid currency")
80
+ }
81
+ let rest = EventValidator.sanitize(custom, limit: EventValidator.maxProps - props.count)
82
+ props.merge(rest.props) { current, _ in current }
83
+ return EventValidator.Sanitized(props: props, issues: issues + rest.issues)
84
+ }
85
+
86
+ private enum Typed {
87
+ case kept(JSONValue)
88
+ /// The value cut to the length limit given.
89
+ case truncated(JSONValue, Int)
90
+ case dropped(String)
91
+ }
92
+
93
+ private static func typed(_ key: String, _ raw: Any) -> Typed {
94
+ let value = JSONValue(any: raw)
95
+ switch key {
96
+ case "product_id", "transaction_id", "method":
97
+ guard let s = value?.stringValue else { return .dropped("not a string") }
98
+ let max = key == "method" ? maxMethodLength : maxIdLength
99
+ if let cut = EventValidator.truncated(s, to: max) { return .truncated(.string(cut), max) }
100
+ return .kept(.string(s))
101
+ case "currency":
102
+ guard let code = value?.stringValue?.trimmingCharacters(in: .whitespacesAndNewlines).uppercased(),
103
+ isCurrencyCode(code)
104
+ else { return .dropped("not a three-letter ISO 4217 code") }
105
+ return .kept(.string(code))
106
+ case "value":
107
+ switch value {
108
+ case .int(let i) where i >= 0: return .kept(.int(i))
109
+ case .double(let d) where d.isFinite && d >= 0: return .kept(.number(d))
110
+ default: return .dropped("not a finite number ≥ 0")
111
+ }
112
+ case "quantity":
113
+ // `JSONValue` stores an integral double (2.0) as an integer, so 2.0 counts and 2.5 does not.
114
+ guard case .int(let q) = value, q >= 1 else { return .dropped("not an integer ≥ 1") }
115
+ return .kept(.int(q))
116
+ default:
117
+ return .dropped("not a typed prop")
118
+ }
119
+ }
120
+
121
+ /// `^[A-Z]{3}$`, byte by byte.
122
+ static func isCurrencyCode(_ code: String) -> Bool {
123
+ let bytes = Array(code.utf8)
124
+ return bytes.count == 3 && bytes.allSatisfy { $0 >= 0x41 && $0 <= 0x5A }
125
+ }
126
+ }
@@ -0,0 +1,19 @@
1
+ import Foundation
2
+ import AdServices
3
+ import AdSupport
4
+
5
+ /// `AAAttribution.attributionToken()` (iOS 14.3+). It can throw and may block: callers run it off
6
+ /// the main thread.
7
+ final class SystemAdServices: AdServicesTokenProviding {
8
+ func attributionToken() throws -> String {
9
+ try AAAttribution.attributionToken()
10
+ }
11
+ }
12
+
13
+ /// The IDFA. The core reads it only when ATT = authorized and `ads` consent is on.
14
+ final class SystemAdvertisingId: AdvertisingIdProviding {
15
+ func advertisingId() -> String? {
16
+ let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
17
+ return idfa == "00000000-0000-0000-0000-000000000000" ? nil : idfa
18
+ }
19
+ }