@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.
- package/LICENSE +21 -0
- package/README.md +235 -2
- package/android/build.gradle +61 -0
- package/android/src/main/AndroidManifest.xml +19 -0
- package/android/src/main/java/com/kerdly/expo/KerdlySdkModule.kt +326 -0
- package/android/vendor/kerdly-sdk/.kerdly-sync.json +8 -0
- package/android/vendor/kerdly-sdk/consumer-rules.pro +15 -0
- package/android/vendor/kerdly-sdk/kerdly-sdk.properties +2 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/Kerdly.kt +343 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/KerdlyTypes.kt +89 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Attribution.kt +39 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Batch.kt +159 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Core.kt +991 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeepLinks.kt +114 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeferredLinks.kt +111 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeviceContext.kt +137 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/EventQueue.kt +135 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Events.kt +314 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Json.kt +116 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Logger.kt +49 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Options.kt +47 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Ports.kt +83 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/PublicIp.kt +120 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Referrers.kt +137 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/RemoteConfig.kt +100 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Storage.kt +271 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/AndroidPlatform.kt +274 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/AndroidRuntime.kt +187 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/PlayReferrerReader.kt +97 -0
- package/app.plugin.js +2 -0
- package/build/Kerdly.d.ts +106 -0
- package/build/Kerdly.d.ts.map +1 -0
- package/build/Kerdly.js +494 -0
- package/build/Kerdly.js.map +1 -0
- package/build/index.d.ts +4 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +2 -0
- package/build/index.js.map +1 -0
- package/build/log.d.ts +13 -0
- package/build/log.d.ts.map +1 -0
- package/build/log.js +45 -0
- package/build/log.js.map +1 -0
- package/build/native.d.ts +74 -0
- package/build/native.d.ts.map +1 -0
- package/build/native.js +56 -0
- package/build/native.js.map +1 -0
- package/build/normalize.d.ts +8 -0
- package/build/normalize.d.ts.map +1 -0
- package/build/normalize.js +86 -0
- package/build/normalize.js.map +1 -0
- package/build/types.d.ts +134 -0
- package/build/types.d.ts.map +1 -0
- package/build/types.js +3 -0
- package/build/types.js.map +1 -0
- package/build/validation.d.ts +70 -0
- package/build/validation.d.ts.map +1 -0
- package/build/validation.js +349 -0
- package/build/validation.js.map +1 -0
- package/build/version.d.ts +4 -0
- package/build/version.d.ts.map +1 -0
- package/build/version.js +5 -0
- package/build/version.js.map +1 -0
- package/expo-module.config.json +9 -0
- package/ios/KerdlySDK/.kerdly-sync.json +7 -0
- package/ios/KerdlySDK/Core/Dependencies.swift +163 -0
- package/ios/KerdlySDK/Core/KerdlyCore+API.swift +117 -0
- package/ios/KerdlySDK/Core/KerdlyCore+Collectors.swift +410 -0
- package/ios/KerdlySDK/Core/KerdlyCore+DeferredLinks.swift +220 -0
- package/ios/KerdlySDK/Core/KerdlyCore+Delivery.swift +424 -0
- package/ios/KerdlySDK/Core/KerdlyCore.swift +557 -0
- package/ios/KerdlySDK/Core/Support.swift +95 -0
- package/ios/KerdlySDK/Logic/Backoff.swift +22 -0
- package/ios/KerdlySDK/Logic/Batch.swift +180 -0
- package/ios/KerdlySDK/Logic/Context.swift +85 -0
- package/ios/KerdlySDK/Logic/DeepLinks.swift +93 -0
- package/ios/KerdlySDK/Logic/DeferredLinks.swift +239 -0
- package/ios/KerdlySDK/Logic/Environment.swift +39 -0
- package/ios/KerdlySDK/Logic/EventQueue.swift +85 -0
- package/ios/KerdlySDK/Logic/EventValidator.swift +84 -0
- package/ios/KerdlySDK/Logic/Events.swift +102 -0
- package/ios/KerdlySDK/Logic/IPv6Address.swift +26 -0
- package/ios/KerdlySDK/Logic/InstallIdentity.swift +106 -0
- package/ios/KerdlySDK/Logic/JSONValue.swift +198 -0
- package/ios/KerdlySDK/Logic/Purchases.swift +84 -0
- package/ios/KerdlySDK/Logic/RemoteConfig.swift +185 -0
- package/ios/KerdlySDK/Logic/Skan.swift +343 -0
- package/ios/KerdlySDK/Logic/StandardEvents.swift +126 -0
- package/ios/KerdlySDK/Platform/AdSignals.swift +19 -0
- package/ios/KerdlySDK/Platform/DeferredLinkBundle.swift +25 -0
- package/ios/KerdlySDK/Platform/DeviceInfo.swift +82 -0
- package/ios/KerdlySDK/Platform/Lifecycle.swift +74 -0
- package/ios/KerdlySDK/Platform/PublicIp.swift +33 -0
- package/ios/KerdlySDK/Platform/SkanWriter.swift +70 -0
- package/ios/KerdlySDK/Platform/StoreKitAdapter.swift +185 -0
- package/ios/KerdlySDK/Platform/SystemStores.swift +200 -0
- package/ios/KerdlySDK/Platform/Tracking.swift +124 -0
- package/ios/KerdlySDK/Public/Kerdly.swift +202 -0
- package/ios/KerdlySDK/Public/KerdlyTypes.swift +130 -0
- package/ios/KerdlySDK/Resources/PrivacyInfo.xcprivacy +95 -0
- package/ios/KerdlySDK/Storage/PersistedState.swift +175 -0
- package/ios/KerdlySDK/Storage/StateStore.swift +36 -0
- package/ios/KerdlySdk.podspec +45 -0
- package/ios/KerdlySdkModule.swift +332 -0
- package/package.json +92 -4
- package/plugin/withKerdly.js +163 -0
- package/src/Kerdly.ts +524 -0
- package/src/index.ts +23 -0
- package/src/log.ts +49 -0
- package/src/native.ts +150 -0
- package/src/normalize.ts +82 -0
- package/src/types.ts +183 -0
- package/src/validation.ts +343 -0
- package/src/version.ts +5 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// What the deferred-link requests read from the app bundle: the Facebook SDK's own config
|
|
4
|
+
/// (`FacebookAppID`, `FacebookClientToken`, both public) and the app's URL schemes.
|
|
5
|
+
struct DeferredLinkBundle: Sendable {
|
|
6
|
+
var metaAppId: String?
|
|
7
|
+
var metaClientToken: String?
|
|
8
|
+
var urlSchemes: [String]
|
|
9
|
+
var appName: String
|
|
10
|
+
var regionCode: String
|
|
11
|
+
|
|
12
|
+
static func read(_ bundle: Bundle = .main) -> DeferredLinkBundle {
|
|
13
|
+
let info = bundle.infoDictionary ?? [:]
|
|
14
|
+
let nonEmpty = { (key: String) -> String? in
|
|
15
|
+
(info[key] as? String).flatMap { $0.isEmpty ? nil : $0 }
|
|
16
|
+
}
|
|
17
|
+
let types = info["CFBundleURLTypes"] as? [[String: Any]] ?? []
|
|
18
|
+
return DeferredLinkBundle(
|
|
19
|
+
metaAppId: nonEmpty("FacebookAppID"),
|
|
20
|
+
metaClientToken: nonEmpty("FacebookClientToken"),
|
|
21
|
+
urlSchemes: types.flatMap { $0["CFBundleURLSchemes"] as? [String] ?? [] },
|
|
22
|
+
appName: nonEmpty("CFBundleDisplayName") ?? nonEmpty("CFBundleName") ?? "",
|
|
23
|
+
regionCode: (Locale.current as NSLocale).countryCode ?? "")
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import UIKit
|
|
3
|
+
|
|
4
|
+
/// Bundle, file-system and UIKit facts. Never collects disk space or boot time.
|
|
5
|
+
final class SystemDeviceInfo: DeviceInfoProviding {
|
|
6
|
+
func appInfo() -> AppInfo {
|
|
7
|
+
let info = Bundle.main.infoDictionary ?? [:]
|
|
8
|
+
return AppInfo(
|
|
9
|
+
bundle: Bundle.main.bundleIdentifier ?? "unknown",
|
|
10
|
+
version: info["CFBundleShortVersionString"] as? String ?? "",
|
|
11
|
+
build: info["CFBundleVersion"] as? String ?? "")
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
func facts() -> DeviceFacts {
|
|
15
|
+
DeviceFacts(
|
|
16
|
+
os: ContextBuilder.osVersion(ProcessInfo.processInfo.operatingSystemVersion),
|
|
17
|
+
model: Self.modelIdentifier(),
|
|
18
|
+
locale: ContextBuilder.localeIdentifier(Locale.current.identifier),
|
|
19
|
+
languages: Array(Locale.preferredLanguages.prefix(5)),
|
|
20
|
+
timeZone: TimeZone.current.identifier)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/// `utsname.machine`, e.g. `iPhone17,1`; the simulated model in the simulator.
|
|
24
|
+
static func modelIdentifier() -> String {
|
|
25
|
+
#if targetEnvironment(simulator)
|
|
26
|
+
if let simulated = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"], !simulated.isEmpty {
|
|
27
|
+
return simulated
|
|
28
|
+
}
|
|
29
|
+
#endif
|
|
30
|
+
var info = utsname()
|
|
31
|
+
uname(&info)
|
|
32
|
+
return withUnsafeBytes(of: &info.machine) { buffer in
|
|
33
|
+
String(decoding: buffer.prefix { $0 != 0 }, as: UTF8.self)
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
@MainActor
|
|
38
|
+
func snapshot() -> DeviceSnapshot {
|
|
39
|
+
let screen = UIScreen.main
|
|
40
|
+
let bounds = screen.nativeBounds
|
|
41
|
+
return DeviceSnapshot(
|
|
42
|
+
idfv: UIDevice.current.identifierForVendor?.uuidString,
|
|
43
|
+
screenWidth: Int(bounds.width.rounded()),
|
|
44
|
+
screenHeight: Int(bounds.height.rounded()),
|
|
45
|
+
screenScale: Double(screen.nativeScale),
|
|
46
|
+
isForeground: UIApplication.shared.applicationState != .background)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/// The Documents directory's creation date (FileTimestamp, reason C617.1): the moment the app's
|
|
50
|
+
/// container was created by this install.
|
|
51
|
+
func installedAt() -> Date? {
|
|
52
|
+
guard let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first,
|
|
53
|
+
let attributes = try? FileManager.default.attributesOfItem(atPath: documents.path),
|
|
54
|
+
let created = attributes[.creationDate] as? Date
|
|
55
|
+
else { return nil }
|
|
56
|
+
return created
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
func deferredLinkBundle() -> DeferredLinkBundle {
|
|
60
|
+
DeferredLinkBundle.read()
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
func environmentInputs() -> EnvironmentInputs {
|
|
64
|
+
#if targetEnvironment(simulator)
|
|
65
|
+
let simulator = true
|
|
66
|
+
#else
|
|
67
|
+
let simulator = false
|
|
68
|
+
#endif
|
|
69
|
+
#if DEBUG
|
|
70
|
+
let debug = true
|
|
71
|
+
#else
|
|
72
|
+
let debug = false
|
|
73
|
+
#endif
|
|
74
|
+
let profile = Bundle.main.url(forResource: "embedded", withExtension: "mobileprovision")
|
|
75
|
+
.flatMap { try? Data(contentsOf: $0) }
|
|
76
|
+
return EnvironmentInputs(
|
|
77
|
+
isSimulator: simulator,
|
|
78
|
+
isDebugBuild: debug,
|
|
79
|
+
isDevelopmentSigned: profile.map(EnvironmentResolver.profileAllowsDebugging) ?? false,
|
|
80
|
+
receiptName: Bundle.main.appStoreReceiptURL?.lastPathComponent)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import UIKit
|
|
3
|
+
|
|
4
|
+
/// UIApplication notifications, plus background time to finish a flush.
|
|
5
|
+
final class SystemLifecycle: LifecycleObserving, @unchecked Sendable {
|
|
6
|
+
private let observers = Locked<[NSObjectProtocol]>([])
|
|
7
|
+
private let tasks = Locked<[Int: UIBackgroundTaskIdentifier]>([:])
|
|
8
|
+
private let counter = Locked(0)
|
|
9
|
+
|
|
10
|
+
func observe(_ handler: @escaping @Sendable (LifecycleEvent) -> Void) {
|
|
11
|
+
let center = NotificationCenter.default
|
|
12
|
+
let pairs: [(Notification.Name, LifecycleEvent)] = [
|
|
13
|
+
(UIApplication.willEnterForegroundNotification, .willEnterForeground),
|
|
14
|
+
(UIApplication.didBecomeActiveNotification, .didBecomeActive),
|
|
15
|
+
(UIApplication.didEnterBackgroundNotification, .didEnterBackground),
|
|
16
|
+
(UIApplication.protectedDataDidBecomeAvailableNotification, .protectedDataAvailable),
|
|
17
|
+
]
|
|
18
|
+
let added = pairs.map { name, event in
|
|
19
|
+
center.addObserver(forName: name, object: nil, queue: nil) { _ in handler(event) }
|
|
20
|
+
}
|
|
21
|
+
observers.update { $0.append(contentsOf: added) }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
func beginBackgroundTask() -> Int? {
|
|
25
|
+
guard Thread.isMainThread else { return nil }
|
|
26
|
+
let token = counter.update { value -> Int in
|
|
27
|
+
value += 1
|
|
28
|
+
return value
|
|
29
|
+
}
|
|
30
|
+
let identifier = MainActor.assumeIsolated {
|
|
31
|
+
UIApplication.shared.beginBackgroundTask(withName: "com.kerdly.sdk.flush") { [weak self] in
|
|
32
|
+
self?.endBackgroundTask(token)
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
guard identifier != .invalid else { return nil }
|
|
36
|
+
tasks.update { $0[token] = identifier }
|
|
37
|
+
return token
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
func endBackgroundTask(_ token: Int) {
|
|
41
|
+
guard let identifier = tasks.update({ $0.removeValue(forKey: token) }) else { return }
|
|
42
|
+
if Thread.isMainThread {
|
|
43
|
+
MainActor.assumeIsolated { UIApplication.shared.endBackgroundTask(identifier) }
|
|
44
|
+
} else {
|
|
45
|
+
DispatchQueue.main.async {
|
|
46
|
+
MainActor.assumeIsolated { UIApplication.shared.endBackgroundTask(identifier) }
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
extension KerdlyDependencies {
|
|
53
|
+
/// The real system.
|
|
54
|
+
static func system() -> KerdlyDependencies {
|
|
55
|
+
KerdlyDependencies(
|
|
56
|
+
keychain: SystemKeychain(),
|
|
57
|
+
defaults: SystemDefaults(),
|
|
58
|
+
files: SystemFileStore(),
|
|
59
|
+
transport: URLSessionTransport(),
|
|
60
|
+
clock: SystemClock(),
|
|
61
|
+
device: SystemDeviceInfo(),
|
|
62
|
+
tracking: SystemTracking(),
|
|
63
|
+
adServices: SystemAdServices(),
|
|
64
|
+
advertisingId: SystemAdvertisingId(),
|
|
65
|
+
publicIp: SystemPublicIp(),
|
|
66
|
+
storeKit: SystemStoreKit(),
|
|
67
|
+
skanWriter: SystemSkanWriter(),
|
|
68
|
+
lifecycle: SystemLifecycle(),
|
|
69
|
+
makeScheduler: { DispatchScheduler(queue: $0) },
|
|
70
|
+
workQueue: DispatchQueue(label: "com.kerdly.sdk.work", qos: .utility, attributes: .concurrent),
|
|
71
|
+
newId: { InstallIdentityResolver.makeId() },
|
|
72
|
+
unitRandom: { Double.random(in: 0...1) })
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// The device's public IPv6 from the config's echo URL. The echo host has AAAA
|
|
4
|
+
/// records only, so it answers only over IPv6. One `GET` on an ephemeral session (no cookies, no URL
|
|
5
|
+
/// cache), 3 s in all, no retry; any failure completes with nil.
|
|
6
|
+
final class SystemPublicIp: PublicIpProviding {
|
|
7
|
+
static let timeout: TimeInterval = 3
|
|
8
|
+
|
|
9
|
+
func lookup(_ url: URL, completion: @escaping @Sendable (String?) -> Void) {
|
|
10
|
+
guard url.scheme?.lowercased() == "https" else { return completion(nil) }
|
|
11
|
+
let configuration = URLSessionConfiguration.ephemeral
|
|
12
|
+
configuration.timeoutIntervalForRequest = Self.timeout
|
|
13
|
+
configuration.timeoutIntervalForResource = Self.timeout
|
|
14
|
+
configuration.httpCookieAcceptPolicy = .never
|
|
15
|
+
configuration.httpShouldSetCookies = false
|
|
16
|
+
configuration.httpCookieStorage = nil
|
|
17
|
+
configuration.urlCache = nil
|
|
18
|
+
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
|
|
19
|
+
configuration.waitsForConnectivity = false
|
|
20
|
+
let session = URLSession(configuration: configuration)
|
|
21
|
+
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: Self.timeout)
|
|
22
|
+
request.httpMethod = "GET"
|
|
23
|
+
request.setValue("application/json", forHTTPHeaderField: "Accept")
|
|
24
|
+
session.dataTask(with: request) { data, response, _ in
|
|
25
|
+
guard let status = (response as? HTTPURLResponse)?.statusCode, (200..<300).contains(status) else {
|
|
26
|
+
return completion(nil)
|
|
27
|
+
}
|
|
28
|
+
completion(data.flatMap(JSONValue.parse)?["ip"]?.stringValue)
|
|
29
|
+
}.resume()
|
|
30
|
+
// Ends the session once the task is done.
|
|
31
|
+
session.finishTasksAndInvalidate()
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import StoreKit
|
|
3
|
+
#if canImport(AdAttributionKit)
|
|
4
|
+
import AdAttributionKit
|
|
5
|
+
#endif
|
|
6
|
+
|
|
7
|
+
/// SKAdNetwork and the AdAttributionKit mirror. Only `SkanCoordinator` calls these, and only when
|
|
8
|
+
/// both `skanWriter` and the config's `skan.enabled` are on.
|
|
9
|
+
final class SystemSkanWriter: SkanWriting {
|
|
10
|
+
var skanApiName: String? {
|
|
11
|
+
if #available(iOS 16.1, *) { return "skan4" }
|
|
12
|
+
if #available(iOS 15.4, *) { return "skan3" }
|
|
13
|
+
return nil
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/// iOS 16.1+: fine + coarse + lockWindow; 15.4–16.0: fine only. Below 15.4 there is no API that
|
|
17
|
+
/// reports an outcome, so nothing is written. (Sequential checks, not `else if #available`: the
|
|
18
|
+
/// chained form warns "unnecessary check" when an app compiles this at a 16.1+ deployment target.)
|
|
19
|
+
func updateSkan(fine: Int, coarse: SkanCoarse, lockWindow: Bool,
|
|
20
|
+
completion: @escaping @Sendable (SkanWriteResult) -> Void) {
|
|
21
|
+
if #available(iOS 16.1, *) {
|
|
22
|
+
SKAdNetwork.updatePostbackConversionValue(fine, coarseValue: Self.coarseValue(coarse),
|
|
23
|
+
lockWindow: lockWindow) { error in
|
|
24
|
+
completion(.completed(api: "skan4", error: Self.describe(error)))
|
|
25
|
+
}
|
|
26
|
+
return
|
|
27
|
+
}
|
|
28
|
+
if #available(iOS 15.4, *) {
|
|
29
|
+
SKAdNetwork.updatePostbackConversionValue(fine) { error in
|
|
30
|
+
completion(.completed(api: "skan3", error: Self.describe(error)))
|
|
31
|
+
}
|
|
32
|
+
return
|
|
33
|
+
}
|
|
34
|
+
completion(.unsupported)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/// iOS 17.4+: `Postback.updateConversionValue(_:lockPostback:)`.
|
|
38
|
+
func updateAak(fine: Int, lockPostback: Bool, completion: @escaping @Sendable (SkanWriteResult) -> Void) {
|
|
39
|
+
#if canImport(AdAttributionKit)
|
|
40
|
+
if #available(iOS 17.4, *) {
|
|
41
|
+
Task.detached(priority: .utility) {
|
|
42
|
+
do {
|
|
43
|
+
try await Postback.updateConversionValue(fine, lockPostback: lockPostback)
|
|
44
|
+
completion(.completed(api: "aak", error: nil))
|
|
45
|
+
} catch {
|
|
46
|
+
completion(.completed(api: "aak", error: Self.describe(error)))
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return
|
|
50
|
+
}
|
|
51
|
+
#endif
|
|
52
|
+
completion(.unsupported)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
@available(iOS 16.1, *)
|
|
56
|
+
static func coarseValue(_ coarse: SkanCoarse) -> SKAdNetwork.CoarseConversionValue {
|
|
57
|
+
switch coarse {
|
|
58
|
+
case .low: return .low
|
|
59
|
+
case .medium: return .medium
|
|
60
|
+
case .high: return .high
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/// `"<domain> <code>"`, short and stable for the `$skan.error` prop.
|
|
65
|
+
static func describe(_ error: Error?) -> String? {
|
|
66
|
+
guard let error else { return nil }
|
|
67
|
+
let ns = error as NSError
|
|
68
|
+
return "\(ns.domain) \(ns.code)"
|
|
69
|
+
}
|
|
70
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import StoreKit
|
|
3
|
+
|
|
4
|
+
/// StoreKit 2. Reads only: the SDK never purchases, never finishes a transaction (the paywall SDK
|
|
5
|
+
/// does) and never calls `AppTransaction.refresh()` (it can show a sign-in prompt).
|
|
6
|
+
final class SystemStoreKit: StoreKitProviding {
|
|
7
|
+
static let maxHistoryScan = 200
|
|
8
|
+
|
|
9
|
+
func appTransaction(_ completion: @escaping @Sendable (Result<AppTransactionInfo, KerdlyAdapterError>) -> Void) {
|
|
10
|
+
guard #available(iOS 16.0, *) else {
|
|
11
|
+
completion(.failure(KerdlyAdapterError("AppTransaction needs iOS 16")))
|
|
12
|
+
return
|
|
13
|
+
}
|
|
14
|
+
Task.detached(priority: .utility) {
|
|
15
|
+
do {
|
|
16
|
+
let result = try await AppTransaction.shared
|
|
17
|
+
// Verified or not, the server re-derives every field it trusts from the JWS.
|
|
18
|
+
let transaction = result.unsafePayloadValue
|
|
19
|
+
completion(.success(AppTransactionInfo(
|
|
20
|
+
jws: result.jwsRepresentation,
|
|
21
|
+
appTransactionId: Self.appTransactionId(transaction),
|
|
22
|
+
originalPurchaseDate: transaction.originalPurchaseDate,
|
|
23
|
+
originalAppVersion: transaction.originalAppVersion,
|
|
24
|
+
environment: transaction.environment.rawValue,
|
|
25
|
+
deviceVerificationNonce: transaction.deviceVerificationNonce.uuidString.lowercased(),
|
|
26
|
+
deviceVerification: transaction.deviceVerification.base64EncodedString())))
|
|
27
|
+
} catch {
|
|
28
|
+
completion(.failure(KerdlyAdapterError(String(describing: error))))
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
func currentEntitlements(_ completion: @escaping @Sendable ([PurchaseInfo]) -> Void) {
|
|
34
|
+
Task.detached(priority: .utility) {
|
|
35
|
+
var infos: [PurchaseInfo] = []
|
|
36
|
+
for await result in Transaction.currentEntitlements {
|
|
37
|
+
if case .verified(let transaction) = result {
|
|
38
|
+
infos.append(Self.info(transaction))
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
completion(infos)
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
func findTransaction(transactionId: String?, originalTransactionId: String?, productId: String?,
|
|
46
|
+
_ completion: @escaping @Sendable (PurchaseInfo?) -> Void) {
|
|
47
|
+
Task.detached(priority: .utility) {
|
|
48
|
+
// The exact transaction wins; a transaction of the same subscription is the fallback.
|
|
49
|
+
func exact(_ transaction: Transaction) -> Bool {
|
|
50
|
+
transactionId.map { String(transaction.id) == $0 } ?? false
|
|
51
|
+
}
|
|
52
|
+
func sameOriginal(_ transaction: Transaction) -> Bool {
|
|
53
|
+
originalTransactionId.map { String(transaction.originalID) == $0 } ?? false
|
|
54
|
+
}
|
|
55
|
+
var fallback: PurchaseInfo?
|
|
56
|
+
for await result in Transaction.currentEntitlements {
|
|
57
|
+
guard case .verified(let transaction) = result else { continue }
|
|
58
|
+
if exact(transaction) { return completion(Self.info(transaction)) }
|
|
59
|
+
if fallback == nil && sameOriginal(transaction) { fallback = Self.info(transaction) }
|
|
60
|
+
}
|
|
61
|
+
if let productId, let result = await Transaction.latest(for: productId),
|
|
62
|
+
case .verified(let transaction) = result {
|
|
63
|
+
if exact(transaction) { return completion(Self.info(transaction)) }
|
|
64
|
+
if fallback == nil && sameOriginal(transaction) { fallback = Self.info(transaction) }
|
|
65
|
+
}
|
|
66
|
+
if transactionId != nil {
|
|
67
|
+
var scanned = 0
|
|
68
|
+
for await result in Transaction.all {
|
|
69
|
+
scanned += 1
|
|
70
|
+
if scanned > Self.maxHistoryScan { break }
|
|
71
|
+
if case .verified(let transaction) = result, exact(transaction) {
|
|
72
|
+
return completion(Self.info(transaction))
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
completion(fallback)
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
func observeUpdates(_ handler: @escaping @Sendable (PurchaseInfo) -> Void) {
|
|
81
|
+
Task.detached(priority: .utility) {
|
|
82
|
+
for await result in Transaction.updates {
|
|
83
|
+
if case .verified(let transaction) = result {
|
|
84
|
+
handler(Self.info(transaction))
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// MARK: - Mapping
|
|
91
|
+
|
|
92
|
+
static func info(_ transaction: Transaction) -> PurchaseInfo {
|
|
93
|
+
PurchaseInfo(
|
|
94
|
+
originalTransactionId: String(transaction.originalID),
|
|
95
|
+
transactionId: String(transaction.id),
|
|
96
|
+
productId: transaction.productID,
|
|
97
|
+
appAccountToken: transaction.appAccountToken?.uuidString.lowercased(),
|
|
98
|
+
appTransactionId: appTransactionId(transaction),
|
|
99
|
+
purchaseDate: transaction.purchaseDate,
|
|
100
|
+
originalPurchaseDate: transaction.originalPurchaseDate,
|
|
101
|
+
offerType: offerTypeName(transaction),
|
|
102
|
+
isFreeTrial: isFreeTrial(transaction),
|
|
103
|
+
environment: environment(transaction),
|
|
104
|
+
isRenewal: isRenewal(transaction),
|
|
105
|
+
revoked: transaction.revocationDate != nil)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/// `Transaction.offer` from iOS 17.2, the deprecated `offerType` before.
|
|
109
|
+
static func offerType(_ transaction: Transaction) -> Transaction.OfferType? {
|
|
110
|
+
if #available(iOS 17.2, *) {
|
|
111
|
+
return transaction.offer?.type
|
|
112
|
+
}
|
|
113
|
+
return transaction.offerType
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
static func offerTypeName(_ transaction: Transaction) -> String? {
|
|
117
|
+
guard let type = offerType(transaction) else { return nil }
|
|
118
|
+
switch type {
|
|
119
|
+
case .introductory: return "introductory"
|
|
120
|
+
case .promotional: return "promotional"
|
|
121
|
+
case .code: return "offer_code"
|
|
122
|
+
case .winBack: return "win_back"
|
|
123
|
+
default: return nil
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/// An introductory offer whose payment mode is free trial (an introductory offer of unknown mode
|
|
128
|
+
/// counts as a trial: the lower rung, which a later conversion still raises).
|
|
129
|
+
static func isFreeTrial(_ transaction: Transaction) -> Bool {
|
|
130
|
+
guard offerType(transaction) == .introductory else { return false }
|
|
131
|
+
let mode: String?
|
|
132
|
+
if #available(iOS 17.2, *) {
|
|
133
|
+
mode = transaction.offer?.paymentMode?.rawValue
|
|
134
|
+
} else {
|
|
135
|
+
mode = transaction.offerPaymentModeStringRepresentation
|
|
136
|
+
}
|
|
137
|
+
return mode == nil || mode == "FREE_TRIAL"
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
static func environment(_ transaction: Transaction) -> String? {
|
|
141
|
+
let value: String
|
|
142
|
+
if #available(iOS 16.0, *) {
|
|
143
|
+
value = transaction.environment.rawValue
|
|
144
|
+
} else {
|
|
145
|
+
value = transaction.environmentStringRepresentation
|
|
146
|
+
}
|
|
147
|
+
return value.isEmpty ? nil : value
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
static func isRenewal(_ transaction: Transaction) -> Bool? {
|
|
151
|
+
let reason: String
|
|
152
|
+
if #available(iOS 17.0, *) {
|
|
153
|
+
reason = transaction.reason.rawValue
|
|
154
|
+
} else {
|
|
155
|
+
reason = transaction.reasonStringRepresentation
|
|
156
|
+
}
|
|
157
|
+
switch reason {
|
|
158
|
+
case "RENEWAL": return true
|
|
159
|
+
case "PURCHASE": return false
|
|
160
|
+
default: return nil
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/// `appTransactionID` is read where this SDK's headers have it (Xcode 16.3+ / iOS 18.4 SDK,
|
|
165
|
+
/// back-deployed by StoreKit to iOS 15/16 for `Transaction`/`AppTransaction`); empty → nil.
|
|
166
|
+
/// The server re-derives it from the verified JWS anyway.
|
|
167
|
+
static func appTransactionId(_ transaction: Transaction) -> String? {
|
|
168
|
+
#if compiler(>=6.1)
|
|
169
|
+
let id = transaction.appTransactionID
|
|
170
|
+
return id.isEmpty ? nil : id
|
|
171
|
+
#else
|
|
172
|
+
return nil
|
|
173
|
+
#endif
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
@available(iOS 16.0, *)
|
|
177
|
+
static func appTransactionId(_ transaction: AppTransaction) -> String? {
|
|
178
|
+
#if compiler(>=6.1)
|
|
179
|
+
let id = transaction.appTransactionID
|
|
180
|
+
return id.isEmpty ? nil : id
|
|
181
|
+
#else
|
|
182
|
+
return nil
|
|
183
|
+
#endif
|
|
184
|
+
}
|
|
185
|
+
}
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import Security
|
|
3
|
+
|
|
4
|
+
/// The Keychain copy of the install id: a generic password, service `com.kerdly.sdk`, account
|
|
5
|
+
/// `install_id`, `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`, not synchronizable. It survives
|
|
6
|
+
/// an uninstall and never moves to another device.
|
|
7
|
+
final class SystemKeychain: KeychainStoring {
|
|
8
|
+
static let service = "com.kerdly.sdk"
|
|
9
|
+
/// The service builds before 0.1.0 used. Its item is read when the current one is missing, and
|
|
10
|
+
/// copied to the current service; it is never changed or deleted.
|
|
11
|
+
static let legacyService = "com.afr.sdk"
|
|
12
|
+
static let account = "install_id"
|
|
13
|
+
|
|
14
|
+
private func itemQuery(service: String) -> [String: Any] {
|
|
15
|
+
[
|
|
16
|
+
kSecClass as String: kSecClassGenericPassword,
|
|
17
|
+
kSecAttrService as String: service,
|
|
18
|
+
kSecAttrAccount as String: Self.account,
|
|
19
|
+
]
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
private var baseQuery: [String: Any] { itemQuery(service: Self.service) }
|
|
23
|
+
|
|
24
|
+
func readInstallId() -> KeychainRead {
|
|
25
|
+
let current = read(service: Self.service)
|
|
26
|
+
guard current == .notFound else { return current }
|
|
27
|
+
let legacy = read(service: Self.legacyService)
|
|
28
|
+
if case .found(let id) = legacy {
|
|
29
|
+
_ = writeInstallId(id)
|
|
30
|
+
}
|
|
31
|
+
return legacy
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
private func read(service: String) -> KeychainRead {
|
|
35
|
+
var query = itemQuery(service: service)
|
|
36
|
+
query[kSecReturnData as String] = true
|
|
37
|
+
query[kSecMatchLimit as String] = kSecMatchLimitOne
|
|
38
|
+
var item: CFTypeRef?
|
|
39
|
+
let status = SecItemCopyMatching(query as CFDictionary, &item)
|
|
40
|
+
switch status {
|
|
41
|
+
case errSecSuccess:
|
|
42
|
+
guard let data = item as? Data, let value = String(data: data, encoding: .utf8) else { return .notFound }
|
|
43
|
+
return .found(value)
|
|
44
|
+
case errSecItemNotFound:
|
|
45
|
+
return .notFound
|
|
46
|
+
case errSecInteractionNotAllowed:
|
|
47
|
+
return .locked
|
|
48
|
+
default:
|
|
49
|
+
return .failed(status)
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
func writeInstallId(_ id: String) -> Bool {
|
|
54
|
+
let attributes: [String: Any] = [
|
|
55
|
+
kSecValueData as String: Data(id.utf8),
|
|
56
|
+
kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
|
|
57
|
+
]
|
|
58
|
+
var status = SecItemUpdate(baseQuery as CFDictionary, attributes as CFDictionary)
|
|
59
|
+
if status == errSecItemNotFound {
|
|
60
|
+
var add = baseQuery.merging(attributes) { _, new in new }
|
|
61
|
+
add[kSecAttrSynchronizable as String] = kCFBooleanFalse
|
|
62
|
+
status = SecItemAdd(add as CFDictionary, nil)
|
|
63
|
+
}
|
|
64
|
+
return status == errSecSuccess
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/// The standard UserDefaults suite (thread-safe).
|
|
69
|
+
final class SystemDefaults: DefaultsStoring, @unchecked Sendable {
|
|
70
|
+
private let defaults: UserDefaults
|
|
71
|
+
|
|
72
|
+
init(_ defaults: UserDefaults = .standard) {
|
|
73
|
+
self.defaults = defaults
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
func string(forKey key: String) -> String? { defaults.string(forKey: key) }
|
|
77
|
+
func bool(forKey key: String) -> Bool { defaults.bool(forKey: key) }
|
|
78
|
+
|
|
79
|
+
func set(_ value: String?, forKey key: String) {
|
|
80
|
+
if let value { defaults.set(value, forKey: key) } else { defaults.removeObject(forKey: key) }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
func set(_ value: Bool, forKey key: String) {
|
|
84
|
+
defaults.set(value, forKey: key)
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/// `Application Support/kerdly/`; every write is atomic (write to a temporary file, then rename).
|
|
89
|
+
final class SystemFileStore: FileStoring {
|
|
90
|
+
private let directory: URL?
|
|
91
|
+
private let created = Locked(false)
|
|
92
|
+
|
|
93
|
+
/// `legacyFolder`: where builds before 0.1.0 kept the same files. When only it exists, it is
|
|
94
|
+
/// renamed to `folder`, or used where it is if it cannot be, so an updated app keeps its state
|
|
95
|
+
/// and queued events.
|
|
96
|
+
init(folder: String = "kerdly", legacyFolder: String? = "afr") {
|
|
97
|
+
let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
|
|
98
|
+
let target = base?.appendingPathComponent(folder, isDirectory: true)
|
|
99
|
+
directory = Self.adoptLegacy(base: base, target: target, legacyFolder: legacyFolder)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
private static func adoptLegacy(base: URL?, target: URL?, legacyFolder: String?) -> URL? {
|
|
103
|
+
guard let base, let target, let legacyFolder else { return target }
|
|
104
|
+
let legacy = base.appendingPathComponent(legacyFolder, isDirectory: true)
|
|
105
|
+
let fileManager = FileManager.default
|
|
106
|
+
guard !fileManager.fileExists(atPath: target.path), fileManager.fileExists(atPath: legacy.path) else {
|
|
107
|
+
return target
|
|
108
|
+
}
|
|
109
|
+
do {
|
|
110
|
+
try fileManager.moveItem(at: legacy, to: target)
|
|
111
|
+
return target
|
|
112
|
+
} catch {
|
|
113
|
+
return legacy
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
func read(_ name: String) -> Data? {
|
|
118
|
+
guard let url = directory?.appendingPathComponent(name) else { return nil }
|
|
119
|
+
return try? Data(contentsOf: url)
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
func write(_ data: Data, to name: String) -> Bool {
|
|
123
|
+
guard let directory else { return false }
|
|
124
|
+
do {
|
|
125
|
+
if !created.get() {
|
|
126
|
+
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
|
127
|
+
created.set(true)
|
|
128
|
+
}
|
|
129
|
+
try data.write(to: directory.appendingPathComponent(name), options: .atomic)
|
|
130
|
+
return true
|
|
131
|
+
} catch {
|
|
132
|
+
created.set(false)
|
|
133
|
+
return false
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
func remove(_ name: String) {
|
|
138
|
+
guard let url = directory?.appendingPathComponent(name) else { return }
|
|
139
|
+
try? FileManager.default.removeItem(at: url)
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/// `URLSession` without cookies or a URL cache (the config's ETag is handled by the SDK).
|
|
144
|
+
final class URLSessionTransport: HTTPTransport {
|
|
145
|
+
private let session: URLSession
|
|
146
|
+
|
|
147
|
+
init() {
|
|
148
|
+
let configuration = URLSessionConfiguration.ephemeral
|
|
149
|
+
configuration.timeoutIntervalForRequest = 30
|
|
150
|
+
configuration.timeoutIntervalForResource = 60
|
|
151
|
+
configuration.httpCookieAcceptPolicy = .never
|
|
152
|
+
configuration.httpShouldSetCookies = false
|
|
153
|
+
configuration.urlCache = nil
|
|
154
|
+
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
|
|
155
|
+
configuration.waitsForConnectivity = false
|
|
156
|
+
session = URLSession(configuration: configuration)
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
func send(_ request: HTTPRequest, completion: @escaping @Sendable (HTTPResult) -> Void) {
|
|
160
|
+
var urlRequest = URLRequest(url: request.url)
|
|
161
|
+
urlRequest.httpMethod = request.method
|
|
162
|
+
urlRequest.httpBody = request.body
|
|
163
|
+
for (name, value) in request.headers {
|
|
164
|
+
urlRequest.setValue(value, forHTTPHeaderField: name)
|
|
165
|
+
}
|
|
166
|
+
session.dataTask(with: urlRequest) { data, response, error in
|
|
167
|
+
guard let http = response as? HTTPURLResponse else {
|
|
168
|
+
completion(.failure(error.map { String(describing: $0) } ?? "no HTTP response"))
|
|
169
|
+
return
|
|
170
|
+
}
|
|
171
|
+
var headers: [String: String] = [:]
|
|
172
|
+
for (name, value) in http.allHeaderFields {
|
|
173
|
+
if let name = name as? String {
|
|
174
|
+
headers[name.lowercased()] = "\(value)"
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
completion(.response(status: http.statusCode, headers: headers, body: data ?? Data()))
|
|
178
|
+
}.resume()
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
struct SystemClock: Clock {
|
|
183
|
+
func now() -> Date { Date() }
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/// Runs delayed work on the SDK's queue.
|
|
187
|
+
struct DispatchScheduler: Scheduling {
|
|
188
|
+
let queue: DispatchQueue
|
|
189
|
+
|
|
190
|
+
func schedule(after delay: TimeInterval, _ work: @escaping @Sendable () -> Void) -> Cancellable {
|
|
191
|
+
let item = DispatchWorkItem(block: work)
|
|
192
|
+
queue.asyncAfter(deadline: .now() + max(0, delay), execute: item)
|
|
193
|
+
return WorkItemCancellable(item: item)
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
private struct WorkItemCancellable: Cancellable, @unchecked Sendable {
|
|
198
|
+
let item: DispatchWorkItem
|
|
199
|
+
func cancel() { item.cancel() }
|
|
200
|
+
}
|