@app-swiss-knife/react-native-sdk 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +182 -0
- package/SwissKnifePurchases.podspec +40 -0
- package/android/build.gradle +89 -0
- package/android/gradle.properties +3 -0
- package/android/src/main/AndroidManifest.xml +26 -0
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +216 -0
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingPackage.kt +17 -0
- package/android/src/main/java/com/swissknife/purchases/Conversions.kt +15 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +371 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +497 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesPackage.kt +25 -0
- package/android/vendor/GENERATED.md +10 -0
- package/android/vendor/java/com/appswissknife/SwissKnife.kt +533 -0
- package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +326 -0
- package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +296 -0
- package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +503 -0
- package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +188 -0
- package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +204 -0
- package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +447 -0
- package/android/vendor/java/com/appswissknife/context/AppLifecycle.kt +120 -0
- package/android/vendor/java/com/appswissknife/context/Clock.kt +70 -0
- package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +138 -0
- package/android/vendor/java/com/appswissknife/context/IDs.kt +55 -0
- package/android/vendor/java/com/appswissknife/context/Reachability.kt +145 -0
- package/android/vendor/java/com/appswissknife/context/Session.kt +192 -0
- package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +945 -0
- package/android/vendor/java/com/appswissknife/crashreporting/SKScreenshot.kt +201 -0
- package/android/vendor/java/com/appswissknife/device/DeviceID.kt +172 -0
- package/android/vendor/java/com/appswissknife/diagnostics/SKLog.kt +97 -0
- package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +495 -0
- package/android/vendor/java/com/appswissknife/identity/Identity.kt +522 -0
- package/android/vendor/java/com/appswissknife/models/CustomerInfo.kt +67 -0
- package/android/vendor/java/com/appswissknife/models/Enums.kt +35 -0
- package/android/vendor/java/com/appswissknife/models/Offerings.kt +80 -0
- package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +89 -0
- package/android/vendor/java/com/appswissknife/models/StoreTransaction.kt +17 -0
- package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +507 -0
- package/android/vendor/java/com/appswissknife/net/ExponentialBackoff.kt +69 -0
- package/android/vendor/java/com/appswissknife/net/IngestClient.kt +582 -0
- package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +320 -0
- package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +219 -0
- package/android/vendor/java/com/appswissknife/performance/SKFrameTracker.kt +94 -0
- package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +428 -0
- package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +560 -0
- package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +100 -0
- package/android/vendor/java/com/appswissknife/purchases/PriceEnrichmentProvider.kt +36 -0
- package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +120 -0
- package/android/vendor/res/xml/swissknife_data_extraction_rules.xml +20 -0
- package/ios/SwissKnifeCrashReporting.m +32 -0
- package/ios/SwissKnifeCrashReporting.swift +186 -0
- package/ios/SwissKnifeJSON.swift +347 -0
- package/ios/SwissKnifePurchases.m +124 -0
- package/ios/SwissKnifePurchases.swift +523 -0
- package/ios/vendor/GENERATED.md +10 -0
- package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +488 -0
- package/ios/vendor/SwissKnifeiOS/AttributesClient.swift +460 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/Attribution.swift +307 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/AttributionNetwork.swift +92 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/AttributionState.swift +141 -0
- package/ios/vendor/SwissKnifeiOS/Context/AppLifecycle.swift +130 -0
- package/ios/vendor/SwissKnifeiOS/Context/Clock.swift +100 -0
- package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +190 -0
- package/ios/vendor/SwissKnifeiOS/Context/IDs.swift +64 -0
- package/ios/vendor/SwissKnifeiOS/Context/Reachability.swift +121 -0
- package/ios/vendor/SwissKnifeiOS/Context/Session.swift +223 -0
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +1287 -0
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKScreenshot.swift +175 -0
- package/ios/vendor/SwissKnifeiOS/DeviceID.swift +161 -0
- package/ios/vendor/SwissKnifeiOS/Diagnostics/SKLog.swift +128 -0
- package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +323 -0
- package/ios/vendor/SwissKnifeiOS/Identity/IdentityNetwork.swift +70 -0
- package/ios/vendor/SwissKnifeiOS/Net/BackendHttpClient.swift +329 -0
- package/ios/vendor/SwissKnifeiOS/Net/ExponentialBackoff.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +681 -0
- package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +409 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKFrameTracker.swift +89 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +440 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKURLSessionDelegate.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +646 -0
- package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +458 -0
- package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +374 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+Analytics.swift +46 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+DeviceID.swift +30 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+Session.swift +47 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +417 -0
- package/ios/vendor/SwissKnifeiOS/Types.swift +496 -0
- package/lib/commonjs/attribution.js +55 -0
- package/lib/commonjs/attribution.js.map +1 -0
- package/lib/commonjs/identity.js +126 -0
- package/lib/commonjs/identity.js.map +1 -0
- package/lib/commonjs/index.js +118 -0
- package/lib/commonjs/index.js.map +1 -0
- package/lib/commonjs/modules/analytics.js +646 -0
- package/lib/commonjs/modules/analytics.js.map +1 -0
- package/lib/commonjs/modules/attachments.js +169 -0
- package/lib/commonjs/modules/attachments.js.map +1 -0
- package/lib/commonjs/modules/crash-reporting.js +1327 -0
- package/lib/commonjs/modules/crash-reporting.js.map +1 -0
- package/lib/commonjs/modules/ids.js +50 -0
- package/lib/commonjs/modules/ids.js.map +1 -0
- package/lib/commonjs/modules/log.js +59 -0
- package/lib/commonjs/modules/log.js.map +1 -0
- package/lib/commonjs/modules/offline-store.js +44 -0
- package/lib/commonjs/modules/offline-store.js.map +1 -0
- package/lib/commonjs/modules/performance.js +494 -0
- package/lib/commonjs/modules/performance.js.map +1 -0
- package/lib/commonjs/native/module.js +41 -0
- package/lib/commonjs/native/module.js.map +1 -0
- package/lib/commonjs/native/spec.js +26 -0
- package/lib/commonjs/native/spec.js.map +1 -0
- package/lib/commonjs/package.json +1 -0
- package/lib/commonjs/purchases.js +194 -0
- package/lib/commonjs/purchases.js.map +1 -0
- package/lib/commonjs/types.js +236 -0
- package/lib/commonjs/types.js.map +1 -0
- package/lib/module/attribution.js +51 -0
- package/lib/module/attribution.js.map +1 -0
- package/lib/module/identity.js +122 -0
- package/lib/module/identity.js.map +1 -0
- package/lib/module/index.js +36 -0
- package/lib/module/index.js.map +1 -0
- package/lib/module/modules/analytics.js +642 -0
- package/lib/module/modules/analytics.js.map +1 -0
- package/lib/module/modules/attachments.js +162 -0
- package/lib/module/modules/attachments.js.map +1 -0
- package/lib/module/modules/crash-reporting.js +1320 -0
- package/lib/module/modules/crash-reporting.js.map +1 -0
- package/lib/module/modules/ids.js +44 -0
- package/lib/module/modules/ids.js.map +1 -0
- package/lib/module/modules/log.js +54 -0
- package/lib/module/modules/log.js.map +1 -0
- package/lib/module/modules/offline-store.js +39 -0
- package/lib/module/modules/offline-store.js.map +1 -0
- package/lib/module/modules/performance.js +491 -0
- package/lib/module/modules/performance.js.map +1 -0
- package/lib/module/native/module.js +34 -0
- package/lib/module/native/module.js.map +1 -0
- package/lib/module/native/spec.js +22 -0
- package/lib/module/native/spec.js.map +1 -0
- package/lib/module/package.json +1 -0
- package/lib/module/purchases.js +187 -0
- package/lib/module/purchases.js.map +1 -0
- package/lib/module/types.js +230 -0
- package/lib/module/types.js.map +1 -0
- package/lib/typescript/commonjs/attribution.d.ts +24 -0
- package/lib/typescript/commonjs/attribution.d.ts.map +1 -0
- package/lib/typescript/commonjs/identity.d.ts +37 -0
- package/lib/typescript/commonjs/identity.d.ts.map +1 -0
- package/lib/typescript/commonjs/index.d.ts +15 -0
- package/lib/typescript/commonjs/index.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts +127 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/attachments.d.ts +50 -0
- package/lib/typescript/commonjs/modules/attachments.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts +175 -0
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/ids.d.ts +17 -0
- package/lib/typescript/commonjs/modules/ids.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/log.d.ts +12 -0
- package/lib/typescript/commonjs/modules/log.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/offline-store.d.ts +9 -0
- package/lib/typescript/commonjs/modules/offline-store.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/performance.d.ts +75 -0
- package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -0
- package/lib/typescript/commonjs/native/module.d.ts +6 -0
- package/lib/typescript/commonjs/native/module.d.ts.map +1 -0
- package/lib/typescript/commonjs/native/spec.d.ts +119 -0
- package/lib/typescript/commonjs/native/spec.d.ts.map +1 -0
- package/lib/typescript/commonjs/package.json +1 -0
- package/lib/typescript/commonjs/purchases.d.ts +68 -0
- package/lib/typescript/commonjs/purchases.d.ts.map +1 -0
- package/lib/typescript/commonjs/types.d.ts +384 -0
- package/lib/typescript/commonjs/types.d.ts.map +1 -0
- package/lib/typescript/module/attribution.d.ts +24 -0
- package/lib/typescript/module/attribution.d.ts.map +1 -0
- package/lib/typescript/module/identity.d.ts +37 -0
- package/lib/typescript/module/identity.d.ts.map +1 -0
- package/lib/typescript/module/index.d.ts +15 -0
- package/lib/typescript/module/index.d.ts.map +1 -0
- package/lib/typescript/module/modules/analytics.d.ts +127 -0
- package/lib/typescript/module/modules/analytics.d.ts.map +1 -0
- package/lib/typescript/module/modules/attachments.d.ts +50 -0
- package/lib/typescript/module/modules/attachments.d.ts.map +1 -0
- package/lib/typescript/module/modules/crash-reporting.d.ts +175 -0
- package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -0
- package/lib/typescript/module/modules/ids.d.ts +17 -0
- package/lib/typescript/module/modules/ids.d.ts.map +1 -0
- package/lib/typescript/module/modules/log.d.ts +12 -0
- package/lib/typescript/module/modules/log.d.ts.map +1 -0
- package/lib/typescript/module/modules/offline-store.d.ts +9 -0
- package/lib/typescript/module/modules/offline-store.d.ts.map +1 -0
- package/lib/typescript/module/modules/performance.d.ts +75 -0
- package/lib/typescript/module/modules/performance.d.ts.map +1 -0
- package/lib/typescript/module/native/module.d.ts +6 -0
- package/lib/typescript/module/native/module.d.ts.map +1 -0
- package/lib/typescript/module/native/spec.d.ts +119 -0
- package/lib/typescript/module/native/spec.d.ts.map +1 -0
- package/lib/typescript/module/package.json +1 -0
- package/lib/typescript/module/purchases.d.ts +68 -0
- package/lib/typescript/module/purchases.d.ts.map +1 -0
- package/lib/typescript/module/types.d.ts +384 -0
- package/lib/typescript/module/types.d.ts.map +1 -0
- package/package.json +115 -0
- package/react-native.config.js +23 -0
- package/src/attribution.ts +56 -0
- package/src/identity.ts +133 -0
- package/src/index.ts +54 -0
- package/src/modules/analytics.ts +689 -0
- package/src/modules/attachments.ts +222 -0
- package/src/modules/crash-reporting.ts +1577 -0
- package/src/modules/ids.ts +41 -0
- package/src/modules/log.ts +56 -0
- package/src/modules/offline-store.ts +51 -0
- package/src/modules/performance.ts +589 -0
- package/src/native/module.ts +47 -0
- package/src/native/spec.ts +183 -0
- package/src/purchases.ts +214 -0
- package/src/types.ts +470 -0
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
// packages/swiss-knife-ios/Sources/SwissKnifeiOS/Attribution/Attribution.swift
|
|
2
|
+
//
|
|
3
|
+
// Wave 2 of the SDK architectural audit — Attribution module.
|
|
4
|
+
//
|
|
5
|
+
// Capability gap closed: the backend's `/api/sdk/attribution/install`
|
|
6
|
+
// route accepts `{user_id, anonymous_id, referrer, ip_address,
|
|
7
|
+
// user_agent, installed_at, advertising_id}` and resolves the install
|
|
8
|
+
// to one of `advertising_id → referrer → fingerprint → organic`. Before
|
|
9
|
+
// this commit the iOS SDK had ZERO callers — no ATT prompt, no IDFA
|
|
10
|
+
// collection — so `attribution_method` was always `organic`.
|
|
11
|
+
//
|
|
12
|
+
// Now `SwissKnife.Attribution`:
|
|
13
|
+
//
|
|
14
|
+
// - On first launch (configured via `Attribution.Configuration.
|
|
15
|
+
// sendInstallOnFirstLaunch`, default `true`), automatically registers
|
|
16
|
+
// the install with whatever signals are available.
|
|
17
|
+
// - Auto-prompts ATT (`Attribution.Configuration.autoPromptATT`, default
|
|
18
|
+
// `true`) on iOS 14.5+ so the SDK gathers IDFA without the host
|
|
19
|
+
// wiring `ATTrackingManager` themselves.
|
|
20
|
+
// - Caches the resolved attribution to
|
|
21
|
+
// `cachesDirectory/SwissKnife/attribution.json` so subsequent
|
|
22
|
+
// launches read from disk and don't re-POST.
|
|
23
|
+
// - Exposes a manual `registerInstall(advertisingId:)` so hosts that
|
|
24
|
+
// opt out of auto-prompt (or run their own ATT prompt elsewhere)
|
|
25
|
+
// can pass whatever IDFA they got.
|
|
26
|
+
//
|
|
27
|
+
// User-locked decisions baked in:
|
|
28
|
+
//
|
|
29
|
+
// - **Default `autoPromptATT: true`** — SDK shows
|
|
30
|
+
// `ATTrackingManager.requestTrackingAuthorization`. Hosts disable to
|
|
31
|
+
// prompt elsewhere. NOT a no-op — the audit found that "no callers
|
|
32
|
+
// at all" was the actual production state, so the default needs to
|
|
33
|
+
// actually prompt.
|
|
34
|
+
// - **No DB schema changes for W2** — backend already accepts the
|
|
35
|
+
// install payload as-is.
|
|
36
|
+
// - **Idempotent disk cache** — install is sent once per device, not
|
|
37
|
+
// on every launch, mirrors `EntitlementsService.cacheTTL`'s atomic-
|
|
38
|
+
// write pattern (`.tmp` → rename).
|
|
39
|
+
// - **No new dependencies** — `AdSupport.ASIdentifierManager` and
|
|
40
|
+
// `AppTrackingTransparency.ATTrackingManager` are Apple-provided
|
|
41
|
+
// and weak-linked so the SDK compiles on older iOS without their
|
|
42
|
+
// frameworks being present.
|
|
43
|
+
//
|
|
44
|
+
// Thread safety: all mutable state goes through a serial DispatchQueue
|
|
45
|
+
// owned by `AttributionState`. The public API is `async` so the queue
|
|
46
|
+
// is fully internal — callers never see it.
|
|
47
|
+
|
|
48
|
+
import Foundation
|
|
49
|
+
#if canImport(AppTrackingTransparency)
|
|
50
|
+
import AppTrackingTransparency
|
|
51
|
+
#endif
|
|
52
|
+
#if canImport(AdSupport)
|
|
53
|
+
import AdSupport
|
|
54
|
+
#endif
|
|
55
|
+
|
|
56
|
+
public extension SwissKnife {
|
|
57
|
+
|
|
58
|
+
/// Attribution surface — install registration + ATT prompt orchestration.
|
|
59
|
+
enum Attribution {
|
|
60
|
+
|
|
61
|
+
// MARK: Configuration
|
|
62
|
+
|
|
63
|
+
/// Defaults: ATT prompt OFF (no tracking consent unless the host
|
|
64
|
+
/// explicitly opts in), send install on first launch. Hosts that want
|
|
65
|
+
/// the system ATT prompt set `autoPromptATT: true`.
|
|
66
|
+
public struct Configuration: Sendable {
|
|
67
|
+
/// When `true`, `requestTrackingAuthorizationAndRegister()` shows
|
|
68
|
+
/// the system ATT prompt before collecting IDFA. **Defaults to
|
|
69
|
+
/// `false`** — the SDK never prompts for tracking unless the host
|
|
70
|
+
/// opts in (which also requires `NSUserTrackingUsageDescription`).
|
|
71
|
+
/// Hosts that prompt elsewhere keep this `false` and call
|
|
72
|
+
/// `registerInstall(advertisingId:)` directly.
|
|
73
|
+
public var autoPromptATT: Bool
|
|
74
|
+
|
|
75
|
+
/// When `true` (default), `SwissKnife.configure(...)` triggers
|
|
76
|
+
/// a one-shot install registration on the first launch after
|
|
77
|
+
/// install (organic when `autoPromptATT` is false — no IDFA, no
|
|
78
|
+
/// prompt). Idempotent — subsequent launches return the cached
|
|
79
|
+
/// `ResolvedAttribution` without re-POSTing.
|
|
80
|
+
public var sendInstallOnFirstLaunch: Bool
|
|
81
|
+
|
|
82
|
+
public init(
|
|
83
|
+
autoPromptATT: Bool = false,
|
|
84
|
+
sendInstallOnFirstLaunch: Bool = true
|
|
85
|
+
) {
|
|
86
|
+
self.autoPromptATT = autoPromptATT
|
|
87
|
+
self.sendInstallOnFirstLaunch = sendInstallOnFirstLaunch
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// MARK: Types
|
|
92
|
+
|
|
93
|
+
/// The backend's resolved attribution for this install. Mirrors the
|
|
94
|
+
/// shape of `/api/sdk/attribution/install`'s response.
|
|
95
|
+
public struct ResolvedAttribution: Codable, Sendable, Equatable {
|
|
96
|
+
/// One of `"advertising_id" | "referrer" | "fingerprint" | "organic"`.
|
|
97
|
+
public let method: String
|
|
98
|
+
/// Backend campaign id when the install matched a campaign;
|
|
99
|
+
/// nil for `fingerprint`/`organic` paths that don't resolve to one.
|
|
100
|
+
public let campaignId: String?
|
|
101
|
+
/// When the SDK persisted this resolution. Used for telemetry/
|
|
102
|
+
/// debug — backend already has its own install timestamp.
|
|
103
|
+
public let resolvedAt: Date
|
|
104
|
+
|
|
105
|
+
public init(method: String, campaignId: String?, resolvedAt: Date) {
|
|
106
|
+
self.method = method
|
|
107
|
+
self.campaignId = campaignId
|
|
108
|
+
self.resolvedAt = resolvedAt
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// MARK: Internal state seam (mediated through AttributionState)
|
|
113
|
+
|
|
114
|
+
/// Production network seam — tests inject a stub via
|
|
115
|
+
/// `_setNetworkForTesting`.
|
|
116
|
+
internal static var network: AttributionNetwork = BackendHttpClientAttributionNetwork()
|
|
117
|
+
|
|
118
|
+
/// Production state seam — tests inject a stub with a temp cache
|
|
119
|
+
/// directory via `_setStateForTesting`.
|
|
120
|
+
internal static var state: AttributionState = AttributionState()
|
|
121
|
+
|
|
122
|
+
/// Configuration captured at `SwissKnife.configure(...)`-time.
|
|
123
|
+
/// Lives behind a queue inside `state`.
|
|
124
|
+
private static var configuration: Configuration = Configuration()
|
|
125
|
+
|
|
126
|
+
// MARK: Public surface
|
|
127
|
+
|
|
128
|
+
/// The most recent resolved attribution, read from the disk cache
|
|
129
|
+
/// if present. Synchronous and cheap — used by host apps that
|
|
130
|
+
/// surface the install attribution in their UI.
|
|
131
|
+
public static var resolved: ResolvedAttribution? {
|
|
132
|
+
state.cached
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/// Request App Tracking Transparency permission (when enabled by
|
|
136
|
+
/// `Configuration.autoPromptATT`), then POST to
|
|
137
|
+
/// `/api/sdk/attribution/install` with whatever signals are
|
|
138
|
+
/// available. If the resolved attribution is already cached on
|
|
139
|
+
/// disk this returns the cached value WITHOUT re-prompting or
|
|
140
|
+
/// re-POSTing — idempotent per device.
|
|
141
|
+
///
|
|
142
|
+
/// Returns `nil` only when the SDK is not yet configured (cannot
|
|
143
|
+
/// POST without an api key) AND no cached resolution exists.
|
|
144
|
+
@MainActor
|
|
145
|
+
@discardableResult
|
|
146
|
+
public static func requestTrackingAuthorizationAndRegister() async throws -> ResolvedAttribution? {
|
|
147
|
+
// Fast path: already resolved on disk. ATT prompt does not
|
|
148
|
+
// fire and no network call happens.
|
|
149
|
+
if let cached = state.cached {
|
|
150
|
+
return cached
|
|
151
|
+
}
|
|
152
|
+
guard SwissKnife.isConfigured else {
|
|
153
|
+
// Pre-configure caller — best-effort no-op. The
|
|
154
|
+
// alternative (throwing `.notConfigured`) is correct but
|
|
155
|
+
// hostile for "I called Attribution from didFinishLaunching
|
|
156
|
+
// before configure" patterns. Returning nil mirrors the
|
|
157
|
+
// `resolved` accessor's nil-when-unknown semantic.
|
|
158
|
+
return nil
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
let idfa: String?
|
|
162
|
+
if configuration.autoPromptATT {
|
|
163
|
+
idfa = await requestTrackingAuthorizationAndReadIDFA()
|
|
164
|
+
} else {
|
|
165
|
+
// Host opted out of the auto-prompt. We DO NOT read IDFA
|
|
166
|
+
// here — `ASIdentifierManager.advertisingIdentifier` is
|
|
167
|
+
// all-zero unless ATT has been granted, and the host's own
|
|
168
|
+
// prompt may not have run yet. Callers in this branch
|
|
169
|
+
// should use `registerInstall(advertisingId:)` directly.
|
|
170
|
+
idfa = nil
|
|
171
|
+
}
|
|
172
|
+
return try await postInstall(advertisingId: idfa)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/// For callers who opted out of `autoPromptATT` (or who prompt
|
|
176
|
+
/// elsewhere). Pass `advertisingId` if ATT was granted, `nil` if
|
|
177
|
+
/// denied. POSTs `/api/sdk/attribution/install` with the provided
|
|
178
|
+
/// IDFA. Idempotent — second call returns the cached
|
|
179
|
+
/// resolution without re-POSTing.
|
|
180
|
+
@discardableResult
|
|
181
|
+
public static func registerInstall(
|
|
182
|
+
advertisingId: String? = nil
|
|
183
|
+
) async throws -> ResolvedAttribution? {
|
|
184
|
+
if let cached = state.cached {
|
|
185
|
+
return cached
|
|
186
|
+
}
|
|
187
|
+
guard SwissKnife.isConfigured else {
|
|
188
|
+
return nil
|
|
189
|
+
}
|
|
190
|
+
return try await postInstall(advertisingId: advertisingId)
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// MARK: Internal — SwissKnife configure-time wiring
|
|
194
|
+
|
|
195
|
+
/// Called by `SwissKnife.configure(...)` to snapshot the
|
|
196
|
+
/// configuration and (when `sendInstallOnFirstLaunch` is true)
|
|
197
|
+
/// kick off a background install registration. The kick-off is
|
|
198
|
+
/// fire-and-forget — callers do NOT need to await it.
|
|
199
|
+
internal static func _configure(_ configuration: Configuration) {
|
|
200
|
+
self.configuration = configuration
|
|
201
|
+
guard configuration.sendInstallOnFirstLaunch else { return }
|
|
202
|
+
// Background — never block configure(...) on the network
|
|
203
|
+
// call. The MainActor jump is required by ATTrackingManager.
|
|
204
|
+
Task { @MainActor in
|
|
205
|
+
_ = try? await requestTrackingAuthorizationAndRegister()
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/// Test seam — reset cache + configuration + network seam.
|
|
210
|
+
internal static func _resetForTesting() {
|
|
211
|
+
state.wipe()
|
|
212
|
+
configuration = Configuration()
|
|
213
|
+
network = BackendHttpClientAttributionNetwork()
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/// Test seam — inject a stub network.
|
|
217
|
+
internal static func _setNetworkForTesting(_ network: AttributionNetwork) {
|
|
218
|
+
self.network = network
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/// Test seam — inject a state object with a temp-dir cache so
|
|
222
|
+
/// tests don't pollute the real `cachesDirectory`.
|
|
223
|
+
internal static func _setStateForTesting(_ state: AttributionState) {
|
|
224
|
+
self.state = state
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// MARK: Private
|
|
228
|
+
|
|
229
|
+
private static func postInstall(advertisingId: String?) async throws -> ResolvedAttribution? {
|
|
230
|
+
let identity = SwissKnife.Identity.current
|
|
231
|
+
// Bug fix: never fall back to anonymousId here — that polluted
|
|
232
|
+
// app_users.external_user_id with the `$SKAnonymousID:` prefix on
|
|
233
|
+
// first launch. userId stays nil until an explicit logIn(...).
|
|
234
|
+
let userId = identity.userId
|
|
235
|
+
let (apiKey, baseURL) = SwissKnife.identityConfigSnapshot()
|
|
236
|
+
guard !apiKey.isEmpty else { return nil }
|
|
237
|
+
|
|
238
|
+
let payload = AttributionInstallPayload(
|
|
239
|
+
userId: userId,
|
|
240
|
+
anonymousId: identity.anonymousId,
|
|
241
|
+
advertisingId: advertisingId,
|
|
242
|
+
userAgent: AttributionUserAgent.value,
|
|
243
|
+
installedAt: Date()
|
|
244
|
+
)
|
|
245
|
+
let resolved = try await network.postInstall(
|
|
246
|
+
payload: payload,
|
|
247
|
+
apiKey: apiKey,
|
|
248
|
+
baseURL: baseURL
|
|
249
|
+
)
|
|
250
|
+
if let resolved {
|
|
251
|
+
state.persist(resolved)
|
|
252
|
+
}
|
|
253
|
+
return resolved
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
@MainActor
|
|
257
|
+
private static func requestTrackingAuthorizationAndReadIDFA() async -> String? {
|
|
258
|
+
#if canImport(AppTrackingTransparency) && canImport(AdSupport)
|
|
259
|
+
if #available(iOS 14.5, *) {
|
|
260
|
+
let status = await withCheckedContinuation { (continuation: CheckedContinuation<ATTrackingManager.AuthorizationStatus, Never>) in
|
|
261
|
+
ATTrackingManager.requestTrackingAuthorization { status in
|
|
262
|
+
continuation.resume(returning: status)
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
guard status == .authorized else { return nil }
|
|
266
|
+
let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
|
|
267
|
+
// The "all-zero" IDFA is what ASIdentifierManager returns
|
|
268
|
+
// pre-ATT-grant; treat it as the same as "no permission".
|
|
269
|
+
if idfa == "00000000-0000-0000-0000-000000000000" { return nil }
|
|
270
|
+
return idfa
|
|
271
|
+
}
|
|
272
|
+
#endif
|
|
273
|
+
return nil
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// MARK: - Wire types
|
|
279
|
+
|
|
280
|
+
internal struct AttributionInstallPayload: Sendable {
|
|
281
|
+
/// Nil when SDK is anonymous — the backend must treat it as such,
|
|
282
|
+
/// not as an identified userId. Anything else falsely populates
|
|
283
|
+
/// `app_users.external_user_id`.
|
|
284
|
+
let userId: String?
|
|
285
|
+
let anonymousId: String
|
|
286
|
+
let advertisingId: String?
|
|
287
|
+
let userAgent: String?
|
|
288
|
+
let installedAt: Date
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/// Best-effort User-Agent string the backend uses for fingerprint
|
|
292
|
+
/// matching. Mirrors what the system HTTP client would send for a regular request —
|
|
293
|
+
/// not perfect but consistent enough that the backend's fingerprint
|
|
294
|
+
/// path (`ip + UA + device_type + os_name`) has something to match on.
|
|
295
|
+
internal enum AttributionUserAgent {
|
|
296
|
+
static let value: String? = {
|
|
297
|
+
let bundleId = Bundle.main.bundleIdentifier ?? "app"
|
|
298
|
+
let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "?"
|
|
299
|
+
#if os(iOS)
|
|
300
|
+
return "\(bundleId)/\(appVersion) (iOS)"
|
|
301
|
+
#elseif os(macOS)
|
|
302
|
+
return "\(bundleId)/\(appVersion) (macOS)"
|
|
303
|
+
#else
|
|
304
|
+
return "\(bundleId)/\(appVersion)"
|
|
305
|
+
#endif
|
|
306
|
+
}()
|
|
307
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// packages/swiss-knife-ios/Sources/SwissKnifeiOS/Attribution/AttributionNetwork.swift
|
|
2
|
+
//
|
|
3
|
+
// Backend `/api/sdk/attribution/install` POST. Mirrors the contract in
|
|
4
|
+
// `apps/web/src/app/api/sdk/attribution/install/route.ts`:
|
|
5
|
+
//
|
|
6
|
+
// Request body:
|
|
7
|
+
// { user_id, anonymous_id, advertising_id?, user_agent?, installed_at? }
|
|
8
|
+
// Response body (200):
|
|
9
|
+
// { attribution_method, source, medium, campaign_name, campaign_id }
|
|
10
|
+
//
|
|
11
|
+
// Retry policy mirrors `IdentityNetwork`: 1/2/4s with ±25% jitter, cap
|
|
12
|
+
// of 3 retries (4 HTTP calls max). Install registration is one-shot per
|
|
13
|
+
// device — losing it costs us proper attribution forever, so the retry
|
|
14
|
+
// ceiling is generous compared with the per-call analytics flush.
|
|
15
|
+
|
|
16
|
+
import Foundation
|
|
17
|
+
|
|
18
|
+
internal protocol AttributionNetwork {
|
|
19
|
+
func postInstall(
|
|
20
|
+
payload: AttributionInstallPayload,
|
|
21
|
+
apiKey: String,
|
|
22
|
+
baseURL: String?
|
|
23
|
+
) async throws -> SwissKnife.Attribution.ResolvedAttribution?
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/// Production implementation — delegates to `BackendHttpClient`. Retry,
|
|
27
|
+
/// X-API-Key, and `Date`-header Clock sync are now handled by the
|
|
28
|
+
/// shared client. The 3-retry budget is preserved by passing
|
|
29
|
+
/// `maxRetries: 3` on the call.
|
|
30
|
+
internal final class BackendHttpClientAttributionNetwork: AttributionNetwork {
|
|
31
|
+
private let http: BackendHttpClient
|
|
32
|
+
|
|
33
|
+
init(http: BackendHttpClient = .shared) {
|
|
34
|
+
self.http = http
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
func postInstall(
|
|
38
|
+
payload: AttributionInstallPayload,
|
|
39
|
+
apiKey: String,
|
|
40
|
+
baseURL: String?
|
|
41
|
+
) async throws -> SwissKnife.Attribution.ResolvedAttribution? {
|
|
42
|
+
let bodyData = try Self.encodeBody(payload: payload)
|
|
43
|
+
let respData = try await http.postRaw(
|
|
44
|
+
path: "/api/sdk/attribution/install",
|
|
45
|
+
body: bodyData,
|
|
46
|
+
maxRetries: 3
|
|
47
|
+
)
|
|
48
|
+
return Self.decodeResolved(from: respData)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
private static func encodeBody(payload: AttributionInstallPayload) throws -> Data {
|
|
52
|
+
var body: [String: Any] = [
|
|
53
|
+
"anonymous_id": payload.anonymousId,
|
|
54
|
+
]
|
|
55
|
+
if let userId = payload.userId, !userId.isEmpty {
|
|
56
|
+
body["user_id"] = userId
|
|
57
|
+
}
|
|
58
|
+
if let advertisingId = payload.advertisingId, !advertisingId.isEmpty {
|
|
59
|
+
body["advertising_id"] = advertisingId
|
|
60
|
+
}
|
|
61
|
+
if let userAgent = payload.userAgent, !userAgent.isEmpty {
|
|
62
|
+
body["user_agent"] = userAgent
|
|
63
|
+
}
|
|
64
|
+
let iso = ISO8601DateFormatter()
|
|
65
|
+
iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
|
66
|
+
body["installed_at"] = iso.string(from: payload.installedAt)
|
|
67
|
+
return try JSONSerialization.data(withJSONObject: body, options: [])
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/// Parse the backend's response. The backend returns:
|
|
71
|
+
/// { attribution_method, source, medium, campaign_name, campaign_id,
|
|
72
|
+
/// existing? }
|
|
73
|
+
/// We surface only the fields the SDK consumer cares about
|
|
74
|
+
/// (`method`, `campaignId`), and stamp `resolvedAt` from the client
|
|
75
|
+
/// clock so a stale device clock can be debugged from the cache file.
|
|
76
|
+
internal static func decodeResolved(
|
|
77
|
+
from data: Data
|
|
78
|
+
) -> SwissKnife.Attribution.ResolvedAttribution? {
|
|
79
|
+
guard !data.isEmpty,
|
|
80
|
+
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
|
|
81
|
+
return nil
|
|
82
|
+
}
|
|
83
|
+
let method = (json["attribution_method"] as? String) ?? "organic"
|
|
84
|
+
let campaignId = json["campaign_id"] as? String
|
|
85
|
+
return SwissKnife.Attribution.ResolvedAttribution(
|
|
86
|
+
method: method,
|
|
87
|
+
campaignId: campaignId,
|
|
88
|
+
resolvedAt: Date()
|
|
89
|
+
)
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// packages/swiss-knife-ios/Sources/SwissKnifeiOS/Attribution/AttributionState.swift
|
|
2
|
+
//
|
|
3
|
+
// Disk-backed cache for the resolved attribution. Mirrors the atomic-
|
|
4
|
+
// write pattern (`.tmp` → rename) that `EntitlementsService` uses for
|
|
5
|
+
// `customerInfo.json` — see that file for the rationale on why
|
|
6
|
+
// `cachesDirectory` is the right place (excluded from backups, won't
|
|
7
|
+
// surface in Files.app, "data that can be recreated").
|
|
8
|
+
//
|
|
9
|
+
// File location: `cachesDirectory/SwissKnife/attribution.json`. A
|
|
10
|
+
// single JSON object with the `ResolvedAttribution` codable shape:
|
|
11
|
+
// `{ "method": "...", "campaignId": ..., "resolvedAt": <iso8601> }`.
|
|
12
|
+
//
|
|
13
|
+
// Thread safety: all mutation goes through a serial DispatchQueue. The
|
|
14
|
+
// `cached` read warms an in-memory snapshot on first access so the
|
|
15
|
+
// hot-path `Attribution.resolved` accessor doesn't hit disk on every
|
|
16
|
+
// call.
|
|
17
|
+
|
|
18
|
+
import Foundation
|
|
19
|
+
import os.log
|
|
20
|
+
|
|
21
|
+
/// Owner of the resolved-attribution disk cache. Single instance held by
|
|
22
|
+
/// `Attribution.state`; tests inject one with a temp-dir URL.
|
|
23
|
+
internal final class AttributionState {
|
|
24
|
+
|
|
25
|
+
private let log = OSLog(subsystem: "com.swissknife", category: "attribution")
|
|
26
|
+
private let queue = DispatchQueue(label: "com.swissknife.attribution.state")
|
|
27
|
+
private let fileURL: URL
|
|
28
|
+
|
|
29
|
+
private var loadedFromDisk = false
|
|
30
|
+
private var snapshot: SwissKnife.Attribution.ResolvedAttribution?
|
|
31
|
+
|
|
32
|
+
init(fileURL: URL? = nil) {
|
|
33
|
+
if let fileURL {
|
|
34
|
+
self.fileURL = fileURL
|
|
35
|
+
return
|
|
36
|
+
}
|
|
37
|
+
// Production path: `cachesDirectory/SwissKnife/attribution.json`.
|
|
38
|
+
// The fallback mirrors `EntitlementsService.init` — when caches is
|
|
39
|
+
// unwritable we degrade to no-cache rather than crash.
|
|
40
|
+
let url: URL
|
|
41
|
+
do {
|
|
42
|
+
let caches = try FileManager.default.url(
|
|
43
|
+
for: .cachesDirectory,
|
|
44
|
+
in: .userDomainMask,
|
|
45
|
+
appropriateFor: nil,
|
|
46
|
+
create: true
|
|
47
|
+
)
|
|
48
|
+
let dir = caches.appendingPathComponent("SwissKnife", isDirectory: true)
|
|
49
|
+
var isDir: ObjCBool = false
|
|
50
|
+
if !FileManager.default.fileExists(atPath: dir.path, isDirectory: &isDir) {
|
|
51
|
+
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
|
|
52
|
+
}
|
|
53
|
+
url = dir.appendingPathComponent("attribution.json", isDirectory: false)
|
|
54
|
+
} catch {
|
|
55
|
+
SKLog.error(
|
|
56
|
+
"AttributionState: failed to resolve cachesDirectory (\(error)); cache disabled",
|
|
57
|
+
category: "attribution"
|
|
58
|
+
)
|
|
59
|
+
url = URL(fileURLWithPath: NSTemporaryDirectory())
|
|
60
|
+
.appendingPathComponent("swissknife-attribution-disabled.json")
|
|
61
|
+
}
|
|
62
|
+
self.fileURL = url
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/// Read the cached resolution. Loads from disk on first access then
|
|
66
|
+
/// returns the in-memory snapshot for subsequent reads.
|
|
67
|
+
var cached: SwissKnife.Attribution.ResolvedAttribution? {
|
|
68
|
+
queue.sync {
|
|
69
|
+
if !loadedFromDisk {
|
|
70
|
+
loadedFromDisk = true
|
|
71
|
+
snapshot = readFromDiskLocked()
|
|
72
|
+
}
|
|
73
|
+
return snapshot
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/// Atomically persist `resolution` to disk and update the in-memory
|
|
78
|
+
/// snapshot. Errors are logged and swallowed — failing to cache the
|
|
79
|
+
/// attribution is an annoyance (next launch re-POSTs) not a crash.
|
|
80
|
+
func persist(_ resolution: SwissKnife.Attribution.ResolvedAttribution) {
|
|
81
|
+
queue.sync {
|
|
82
|
+
snapshot = resolution
|
|
83
|
+
loadedFromDisk = true
|
|
84
|
+
do { try writeToDiskLocked(resolution) }
|
|
85
|
+
catch {
|
|
86
|
+
SKLog.error(
|
|
87
|
+
"AttributionState: failed to persist resolved attribution: \(error)",
|
|
88
|
+
category: "attribution"
|
|
89
|
+
)
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/// Test seam — wipe both the in-memory snapshot and the file. Also
|
|
95
|
+
/// used by `Attribution._resetForTesting()` between tests.
|
|
96
|
+
func wipe() {
|
|
97
|
+
queue.sync {
|
|
98
|
+
snapshot = nil
|
|
99
|
+
loadedFromDisk = false
|
|
100
|
+
if FileManager.default.fileExists(atPath: fileURL.path) {
|
|
101
|
+
try? FileManager.default.removeItem(at: fileURL)
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// MARK: - Disk I/O (called under `queue`)
|
|
107
|
+
|
|
108
|
+
private func readFromDiskLocked() -> SwissKnife.Attribution.ResolvedAttribution? {
|
|
109
|
+
guard FileManager.default.fileExists(atPath: fileURL.path) else { return nil }
|
|
110
|
+
do {
|
|
111
|
+
let data = try Data(contentsOf: fileURL)
|
|
112
|
+
guard !data.isEmpty else { return nil }
|
|
113
|
+
let decoder = JSONDecoder()
|
|
114
|
+
decoder.dateDecodingStrategy = .iso8601
|
|
115
|
+
return try decoder.decode(SwissKnife.Attribution.ResolvedAttribution.self, from: data)
|
|
116
|
+
} catch {
|
|
117
|
+
SKLog.error(
|
|
118
|
+
"AttributionState: failed to read cache (\(error)); deleting and starting fresh",
|
|
119
|
+
category: "attribution"
|
|
120
|
+
)
|
|
121
|
+
try? FileManager.default.removeItem(at: fileURL)
|
|
122
|
+
return nil
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
private func writeToDiskLocked(_ resolution: SwissKnife.Attribution.ResolvedAttribution) throws {
|
|
127
|
+
let encoder = JSONEncoder()
|
|
128
|
+
encoder.dateEncodingStrategy = .iso8601
|
|
129
|
+
let data = try encoder.encode(resolution)
|
|
130
|
+
let tmp = fileURL.appendingPathExtension("tmp")
|
|
131
|
+
if FileManager.default.fileExists(atPath: tmp.path) {
|
|
132
|
+
try FileManager.default.removeItem(at: tmp)
|
|
133
|
+
}
|
|
134
|
+
try data.write(to: tmp, options: .atomic)
|
|
135
|
+
if FileManager.default.fileExists(atPath: fileURL.path) {
|
|
136
|
+
_ = try FileManager.default.replaceItemAt(fileURL, withItemAt: tmp)
|
|
137
|
+
} else {
|
|
138
|
+
try FileManager.default.moveItem(at: tmp, to: fileURL)
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// packages/swiss-knife-ios/Sources/SwissKnifeiOS/Context/AppLifecycle.swift
|
|
2
|
+
//
|
|
3
|
+
// Round-A cross-cutting primitive #3 — single source of foreground /
|
|
4
|
+
// background events.
|
|
5
|
+
//
|
|
6
|
+
// Before this primitive each module that cared about lifecycle (Session
|
|
7
|
+
// rotation, IngestClient flush-on-background, CrashReporting flush-on-
|
|
8
|
+
// foreground, Performance start/stop) was wiring its own
|
|
9
|
+
// `NotificationCenter` observer for `UIApplication.didBecomeActiveNotification`
|
|
10
|
+
// & friends. This led to:
|
|
11
|
+
// - N notification subscriptions for the same notification name.
|
|
12
|
+
// - Each module deciding independently which UIKit notifications to use,
|
|
13
|
+
// so e.g. some watched `willResignActive` and others watched
|
|
14
|
+
// `didEnterBackground`.
|
|
15
|
+
// - Hard-to-test paths because every module had to be loaded just to
|
|
16
|
+
// observe an event.
|
|
17
|
+
//
|
|
18
|
+
// AppLifecycle subscribes ONCE to `NotificationCenter.default` for each of
|
|
19
|
+
// the four UIApplication lifecycle notifications and rebroadcasts to its
|
|
20
|
+
// own observer list. Each module then has one cheap subscribe/unsubscribe
|
|
21
|
+
// pair and a unified `Event` enum.
|
|
22
|
+
//
|
|
23
|
+
// Cross-platform
|
|
24
|
+
// --------------
|
|
25
|
+
// The four notification names are gated behind `#if canImport(UIKit)`. On
|
|
26
|
+
// the macOS SPM test target there's no UIApplication so we don't register
|
|
27
|
+
// anything; tests inject events synthetically via `_postForTesting`.
|
|
28
|
+
|
|
29
|
+
import Foundation
|
|
30
|
+
#if canImport(UIKit)
|
|
31
|
+
import UIKit
|
|
32
|
+
#endif
|
|
33
|
+
|
|
34
|
+
// ---------------------------------------------------------------------------
|
|
35
|
+
// MARK: - AppLifecycle
|
|
36
|
+
// ---------------------------------------------------------------------------
|
|
37
|
+
|
|
38
|
+
internal enum AppLifecycle {
|
|
39
|
+
|
|
40
|
+
enum Event: Sendable, Equatable {
|
|
41
|
+
case didBecomeActive
|
|
42
|
+
case willResignActive
|
|
43
|
+
case didEnterBackground
|
|
44
|
+
case willEnterForeground
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Observer registry. Guarded by `lock` because subscribe/unsubscribe can
|
|
48
|
+
// happen from any thread, but the broadcast itself hops to MainActor.
|
|
49
|
+
@MainActor private static var observers: [UUID: (Event) -> Void] = [:]
|
|
50
|
+
@MainActor private static var didRegister: Bool = false
|
|
51
|
+
|
|
52
|
+
/// Subscribe to lifecycle events. Returns a token; pass to
|
|
53
|
+
/// `unsubscribe(_:)` to remove. The block is invoked on the main
|
|
54
|
+
/// thread.
|
|
55
|
+
@MainActor
|
|
56
|
+
@discardableResult
|
|
57
|
+
static func subscribe(_ block: @escaping (Event) -> Void) -> UUID {
|
|
58
|
+
ensureRegistered()
|
|
59
|
+
let token = UUID()
|
|
60
|
+
observers[token] = block
|
|
61
|
+
return token
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
@MainActor
|
|
65
|
+
static func unsubscribe(_ token: UUID) {
|
|
66
|
+
observers.removeValue(forKey: token)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// MARK: - Registration
|
|
70
|
+
|
|
71
|
+
@MainActor
|
|
72
|
+
private static func ensureRegistered() {
|
|
73
|
+
guard !didRegister else { return }
|
|
74
|
+
didRegister = true
|
|
75
|
+
#if canImport(UIKit)
|
|
76
|
+
let center = NotificationCenter.default
|
|
77
|
+
center.addObserver(
|
|
78
|
+
forName: UIApplication.didBecomeActiveNotification,
|
|
79
|
+
object: nil,
|
|
80
|
+
queue: .main
|
|
81
|
+
) { _ in
|
|
82
|
+
Task { @MainActor in broadcast(.didBecomeActive) }
|
|
83
|
+
}
|
|
84
|
+
center.addObserver(
|
|
85
|
+
forName: UIApplication.willResignActiveNotification,
|
|
86
|
+
object: nil,
|
|
87
|
+
queue: .main
|
|
88
|
+
) { _ in
|
|
89
|
+
Task { @MainActor in broadcast(.willResignActive) }
|
|
90
|
+
}
|
|
91
|
+
center.addObserver(
|
|
92
|
+
forName: UIApplication.didEnterBackgroundNotification,
|
|
93
|
+
object: nil,
|
|
94
|
+
queue: .main
|
|
95
|
+
) { _ in
|
|
96
|
+
Task { @MainActor in broadcast(.didEnterBackground) }
|
|
97
|
+
}
|
|
98
|
+
center.addObserver(
|
|
99
|
+
forName: UIApplication.willEnterForegroundNotification,
|
|
100
|
+
object: nil,
|
|
101
|
+
queue: .main
|
|
102
|
+
) { _ in
|
|
103
|
+
Task { @MainActor in broadcast(.willEnterForeground) }
|
|
104
|
+
}
|
|
105
|
+
#endif
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
@MainActor
|
|
109
|
+
private static func broadcast(_ event: Event) {
|
|
110
|
+
for observer in observers.values {
|
|
111
|
+
observer(event)
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// MARK: - Test seam
|
|
116
|
+
|
|
117
|
+
/// Synthetic event injection for unit tests — bypasses NotificationCenter
|
|
118
|
+
/// so we don't need UIApplication on the test host.
|
|
119
|
+
@MainActor
|
|
120
|
+
static func _postForTesting(_ event: Event) {
|
|
121
|
+
broadcast(event)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/// Drop all observers without resetting the registered-once flag.
|
|
125
|
+
/// Used by tests to clean up after themselves.
|
|
126
|
+
@MainActor
|
|
127
|
+
static func _resetObserversForTesting() {
|
|
128
|
+
observers.removeAll()
|
|
129
|
+
}
|
|
130
|
+
}
|