@app-swiss-knife/react-native-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/README.md +182 -0
  2. package/SwissKnifePurchases.podspec +40 -0
  3. package/android/build.gradle +89 -0
  4. package/android/gradle.properties +3 -0
  5. package/android/src/main/AndroidManifest.xml +26 -0
  6. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +216 -0
  7. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingPackage.kt +17 -0
  8. package/android/src/main/java/com/swissknife/purchases/Conversions.kt +15 -0
  9. package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +371 -0
  10. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +497 -0
  11. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesPackage.kt +25 -0
  12. package/android/vendor/GENERATED.md +10 -0
  13. package/android/vendor/java/com/appswissknife/SwissKnife.kt +533 -0
  14. package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +326 -0
  15. package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +296 -0
  16. package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +503 -0
  17. package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +188 -0
  18. package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +204 -0
  19. package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +447 -0
  20. package/android/vendor/java/com/appswissknife/context/AppLifecycle.kt +120 -0
  21. package/android/vendor/java/com/appswissknife/context/Clock.kt +70 -0
  22. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +138 -0
  23. package/android/vendor/java/com/appswissknife/context/IDs.kt +55 -0
  24. package/android/vendor/java/com/appswissknife/context/Reachability.kt +145 -0
  25. package/android/vendor/java/com/appswissknife/context/Session.kt +192 -0
  26. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +945 -0
  27. package/android/vendor/java/com/appswissknife/crashreporting/SKScreenshot.kt +201 -0
  28. package/android/vendor/java/com/appswissknife/device/DeviceID.kt +172 -0
  29. package/android/vendor/java/com/appswissknife/diagnostics/SKLog.kt +97 -0
  30. package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +495 -0
  31. package/android/vendor/java/com/appswissknife/identity/Identity.kt +522 -0
  32. package/android/vendor/java/com/appswissknife/models/CustomerInfo.kt +67 -0
  33. package/android/vendor/java/com/appswissknife/models/Enums.kt +35 -0
  34. package/android/vendor/java/com/appswissknife/models/Offerings.kt +80 -0
  35. package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +89 -0
  36. package/android/vendor/java/com/appswissknife/models/StoreTransaction.kt +17 -0
  37. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +507 -0
  38. package/android/vendor/java/com/appswissknife/net/ExponentialBackoff.kt +69 -0
  39. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +582 -0
  40. package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +320 -0
  41. package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +219 -0
  42. package/android/vendor/java/com/appswissknife/performance/SKFrameTracker.kt +94 -0
  43. package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +428 -0
  44. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +560 -0
  45. package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +100 -0
  46. package/android/vendor/java/com/appswissknife/purchases/PriceEnrichmentProvider.kt +36 -0
  47. package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +120 -0
  48. package/android/vendor/res/xml/swissknife_data_extraction_rules.xml +20 -0
  49. package/ios/SwissKnifeCrashReporting.m +32 -0
  50. package/ios/SwissKnifeCrashReporting.swift +186 -0
  51. package/ios/SwissKnifeJSON.swift +347 -0
  52. package/ios/SwissKnifePurchases.m +124 -0
  53. package/ios/SwissKnifePurchases.swift +523 -0
  54. package/ios/vendor/GENERATED.md +10 -0
  55. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +488 -0
  56. package/ios/vendor/SwissKnifeiOS/AttributesClient.swift +460 -0
  57. package/ios/vendor/SwissKnifeiOS/Attribution/Attribution.swift +307 -0
  58. package/ios/vendor/SwissKnifeiOS/Attribution/AttributionNetwork.swift +92 -0
  59. package/ios/vendor/SwissKnifeiOS/Attribution/AttributionState.swift +141 -0
  60. package/ios/vendor/SwissKnifeiOS/Context/AppLifecycle.swift +130 -0
  61. package/ios/vendor/SwissKnifeiOS/Context/Clock.swift +100 -0
  62. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +190 -0
  63. package/ios/vendor/SwissKnifeiOS/Context/IDs.swift +64 -0
  64. package/ios/vendor/SwissKnifeiOS/Context/Reachability.swift +121 -0
  65. package/ios/vendor/SwissKnifeiOS/Context/Session.swift +223 -0
  66. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +1287 -0
  67. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKScreenshot.swift +175 -0
  68. package/ios/vendor/SwissKnifeiOS/DeviceID.swift +161 -0
  69. package/ios/vendor/SwissKnifeiOS/Diagnostics/SKLog.swift +128 -0
  70. package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +323 -0
  71. package/ios/vendor/SwissKnifeiOS/Identity/IdentityNetwork.swift +70 -0
  72. package/ios/vendor/SwissKnifeiOS/Net/BackendHttpClient.swift +329 -0
  73. package/ios/vendor/SwissKnifeiOS/Net/ExponentialBackoff.swift +87 -0
  74. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +681 -0
  75. package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +409 -0
  76. package/ios/vendor/SwissKnifeiOS/Performance/SKFrameTracker.swift +89 -0
  77. package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +440 -0
  78. package/ios/vendor/SwissKnifeiOS/Performance/SKURLSessionDelegate.swift +87 -0
  79. package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +646 -0
  80. package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +458 -0
  81. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +374 -0
  82. package/ios/vendor/SwissKnifeiOS/SwissKnife+Analytics.swift +46 -0
  83. package/ios/vendor/SwissKnifeiOS/SwissKnife+DeviceID.swift +30 -0
  84. package/ios/vendor/SwissKnifeiOS/SwissKnife+Session.swift +47 -0
  85. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +417 -0
  86. package/ios/vendor/SwissKnifeiOS/Types.swift +496 -0
  87. package/lib/commonjs/attribution.js +55 -0
  88. package/lib/commonjs/attribution.js.map +1 -0
  89. package/lib/commonjs/identity.js +126 -0
  90. package/lib/commonjs/identity.js.map +1 -0
  91. package/lib/commonjs/index.js +118 -0
  92. package/lib/commonjs/index.js.map +1 -0
  93. package/lib/commonjs/modules/analytics.js +646 -0
  94. package/lib/commonjs/modules/analytics.js.map +1 -0
  95. package/lib/commonjs/modules/attachments.js +169 -0
  96. package/lib/commonjs/modules/attachments.js.map +1 -0
  97. package/lib/commonjs/modules/crash-reporting.js +1327 -0
  98. package/lib/commonjs/modules/crash-reporting.js.map +1 -0
  99. package/lib/commonjs/modules/ids.js +50 -0
  100. package/lib/commonjs/modules/ids.js.map +1 -0
  101. package/lib/commonjs/modules/log.js +59 -0
  102. package/lib/commonjs/modules/log.js.map +1 -0
  103. package/lib/commonjs/modules/offline-store.js +44 -0
  104. package/lib/commonjs/modules/offline-store.js.map +1 -0
  105. package/lib/commonjs/modules/performance.js +494 -0
  106. package/lib/commonjs/modules/performance.js.map +1 -0
  107. package/lib/commonjs/native/module.js +41 -0
  108. package/lib/commonjs/native/module.js.map +1 -0
  109. package/lib/commonjs/native/spec.js +26 -0
  110. package/lib/commonjs/native/spec.js.map +1 -0
  111. package/lib/commonjs/package.json +1 -0
  112. package/lib/commonjs/purchases.js +194 -0
  113. package/lib/commonjs/purchases.js.map +1 -0
  114. package/lib/commonjs/types.js +236 -0
  115. package/lib/commonjs/types.js.map +1 -0
  116. package/lib/module/attribution.js +51 -0
  117. package/lib/module/attribution.js.map +1 -0
  118. package/lib/module/identity.js +122 -0
  119. package/lib/module/identity.js.map +1 -0
  120. package/lib/module/index.js +36 -0
  121. package/lib/module/index.js.map +1 -0
  122. package/lib/module/modules/analytics.js +642 -0
  123. package/lib/module/modules/analytics.js.map +1 -0
  124. package/lib/module/modules/attachments.js +162 -0
  125. package/lib/module/modules/attachments.js.map +1 -0
  126. package/lib/module/modules/crash-reporting.js +1320 -0
  127. package/lib/module/modules/crash-reporting.js.map +1 -0
  128. package/lib/module/modules/ids.js +44 -0
  129. package/lib/module/modules/ids.js.map +1 -0
  130. package/lib/module/modules/log.js +54 -0
  131. package/lib/module/modules/log.js.map +1 -0
  132. package/lib/module/modules/offline-store.js +39 -0
  133. package/lib/module/modules/offline-store.js.map +1 -0
  134. package/lib/module/modules/performance.js +491 -0
  135. package/lib/module/modules/performance.js.map +1 -0
  136. package/lib/module/native/module.js +34 -0
  137. package/lib/module/native/module.js.map +1 -0
  138. package/lib/module/native/spec.js +22 -0
  139. package/lib/module/native/spec.js.map +1 -0
  140. package/lib/module/package.json +1 -0
  141. package/lib/module/purchases.js +187 -0
  142. package/lib/module/purchases.js.map +1 -0
  143. package/lib/module/types.js +230 -0
  144. package/lib/module/types.js.map +1 -0
  145. package/lib/typescript/commonjs/attribution.d.ts +24 -0
  146. package/lib/typescript/commonjs/attribution.d.ts.map +1 -0
  147. package/lib/typescript/commonjs/identity.d.ts +37 -0
  148. package/lib/typescript/commonjs/identity.d.ts.map +1 -0
  149. package/lib/typescript/commonjs/index.d.ts +15 -0
  150. package/lib/typescript/commonjs/index.d.ts.map +1 -0
  151. package/lib/typescript/commonjs/modules/analytics.d.ts +127 -0
  152. package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -0
  153. package/lib/typescript/commonjs/modules/attachments.d.ts +50 -0
  154. package/lib/typescript/commonjs/modules/attachments.d.ts.map +1 -0
  155. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +175 -0
  156. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -0
  157. package/lib/typescript/commonjs/modules/ids.d.ts +17 -0
  158. package/lib/typescript/commonjs/modules/ids.d.ts.map +1 -0
  159. package/lib/typescript/commonjs/modules/log.d.ts +12 -0
  160. package/lib/typescript/commonjs/modules/log.d.ts.map +1 -0
  161. package/lib/typescript/commonjs/modules/offline-store.d.ts +9 -0
  162. package/lib/typescript/commonjs/modules/offline-store.d.ts.map +1 -0
  163. package/lib/typescript/commonjs/modules/performance.d.ts +75 -0
  164. package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -0
  165. package/lib/typescript/commonjs/native/module.d.ts +6 -0
  166. package/lib/typescript/commonjs/native/module.d.ts.map +1 -0
  167. package/lib/typescript/commonjs/native/spec.d.ts +119 -0
  168. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -0
  169. package/lib/typescript/commonjs/package.json +1 -0
  170. package/lib/typescript/commonjs/purchases.d.ts +68 -0
  171. package/lib/typescript/commonjs/purchases.d.ts.map +1 -0
  172. package/lib/typescript/commonjs/types.d.ts +384 -0
  173. package/lib/typescript/commonjs/types.d.ts.map +1 -0
  174. package/lib/typescript/module/attribution.d.ts +24 -0
  175. package/lib/typescript/module/attribution.d.ts.map +1 -0
  176. package/lib/typescript/module/identity.d.ts +37 -0
  177. package/lib/typescript/module/identity.d.ts.map +1 -0
  178. package/lib/typescript/module/index.d.ts +15 -0
  179. package/lib/typescript/module/index.d.ts.map +1 -0
  180. package/lib/typescript/module/modules/analytics.d.ts +127 -0
  181. package/lib/typescript/module/modules/analytics.d.ts.map +1 -0
  182. package/lib/typescript/module/modules/attachments.d.ts +50 -0
  183. package/lib/typescript/module/modules/attachments.d.ts.map +1 -0
  184. package/lib/typescript/module/modules/crash-reporting.d.ts +175 -0
  185. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -0
  186. package/lib/typescript/module/modules/ids.d.ts +17 -0
  187. package/lib/typescript/module/modules/ids.d.ts.map +1 -0
  188. package/lib/typescript/module/modules/log.d.ts +12 -0
  189. package/lib/typescript/module/modules/log.d.ts.map +1 -0
  190. package/lib/typescript/module/modules/offline-store.d.ts +9 -0
  191. package/lib/typescript/module/modules/offline-store.d.ts.map +1 -0
  192. package/lib/typescript/module/modules/performance.d.ts +75 -0
  193. package/lib/typescript/module/modules/performance.d.ts.map +1 -0
  194. package/lib/typescript/module/native/module.d.ts +6 -0
  195. package/lib/typescript/module/native/module.d.ts.map +1 -0
  196. package/lib/typescript/module/native/spec.d.ts +119 -0
  197. package/lib/typescript/module/native/spec.d.ts.map +1 -0
  198. package/lib/typescript/module/package.json +1 -0
  199. package/lib/typescript/module/purchases.d.ts +68 -0
  200. package/lib/typescript/module/purchases.d.ts.map +1 -0
  201. package/lib/typescript/module/types.d.ts +384 -0
  202. package/lib/typescript/module/types.d.ts.map +1 -0
  203. package/package.json +115 -0
  204. package/react-native.config.js +23 -0
  205. package/src/attribution.ts +56 -0
  206. package/src/identity.ts +133 -0
  207. package/src/index.ts +54 -0
  208. package/src/modules/analytics.ts +689 -0
  209. package/src/modules/attachments.ts +222 -0
  210. package/src/modules/crash-reporting.ts +1577 -0
  211. package/src/modules/ids.ts +41 -0
  212. package/src/modules/log.ts +56 -0
  213. package/src/modules/offline-store.ts +51 -0
  214. package/src/modules/performance.ts +589 -0
  215. package/src/native/module.ts +47 -0
  216. package/src/native/spec.ts +183 -0
  217. package/src/purchases.ts +214 -0
  218. package/src/types.ts +470 -0
@@ -0,0 +1,689 @@
1
+ // packages/react-native-sdk/src/modules/analytics.ts
2
+ //
3
+ // Amplitude/Mixpanel-compatible analytics SDK for swiss-knife (React Native).
4
+ // Drop-in replacement interface.
5
+ //
6
+ // ## Architecture: thin pass-through to native
7
+ //
8
+ // Phase 2.3 of the RC rip-and-replace makes the RN Analytics layer a thin
9
+ // pass-through to the native event queue:
10
+ //
11
+ // - **JS owns the payload shape** — `event_id`, `device_id`, super
12
+ // properties, timed-event duration, identify merging, session id, user
13
+ // id, user properties, groups. These are constructed client-side because
14
+ // they depend on JS-only state (super properties + timed events + user
15
+ // properties live in this module).
16
+ //
17
+ // - **Native owns the queue** — disk persistence (iOS Caches /
18
+ // Android cacheDir), exponential back-off with jitter, dead-letter on
19
+ // permanent failure, 5-retry cap. JS can't provide any of that: a JS
20
+ // queue is lost on every JS reload and there is no reliable way to
21
+ // persist + retry from within an RN bridge thread.
22
+ //
23
+ // The bridge surface is just two methods: `trackEvent(event)` and
24
+ // `flushEvents()`. JS calls `trackEvent` once per event with the fully-built
25
+ // payload; native persists it and runs its own scheduler. Auto-flush
26
+ // scheduling lives in native too (iOS Timer / Android WorkManager). The JS
27
+ // `flushIntervalMs` timer is kept as a defensive nudge but the native side
28
+ // is the source of truth.
29
+ //
30
+ // ## device_id source-of-truth: native bridge
31
+ //
32
+ // `device_id` is sourced from the native SDK (iOS Keychain via
33
+ // `SwissKnife.getDeviceId()`, Android EncryptedSharedPreferences via
34
+ // `SwissKnife.getDeviceId(context)`) — NEVER generated in JS.
35
+ //
36
+ // Why: a JS-generated UUID lives in module scope and is reset on every cold
37
+ // start. That fragments every user's analytics timeline on every app restart
38
+ // (one anonymous user becomes N anonymous users). Native persistence (Keychain
39
+ // / EncryptedSharedPreferences) survives process restart AND app reinstall on
40
+ // iOS, and survives process restart but NOT auto-backup transfer on Android —
41
+ // see `packages/swiss-knife-{ios,android}` for the storage rationale.
42
+ //
43
+ // ## event_id generation policy
44
+ //
45
+ // `event_id` is generated **in JS at event-construction time** (the moment
46
+ // `track()` is called). Native receives it as-is and writes it to disk.
47
+ //
48
+ // Why JS-side: the idempotency key needs to be stable across bridge
49
+ // round-trips. If native generated it on receipt, a bridge crash mid-call
50
+ // could (in theory) result in JS retrying `trackEvent` and native assigning
51
+ // a fresh id to what is logically the same event — defeating dedupe at the
52
+ // backend `(app_project_id, event_id)` unique index. Generating it in JS,
53
+ // before the bridge call, eliminates that window.
54
+ //
55
+ // ## Startup-race handling
56
+ //
57
+ // The native `getDeviceId()` call is async. Code that calls `Analytics.track()`
58
+ // immediately after `Analytics.init()` may build events before the native
59
+ // promise resolves. We handle this by:
60
+ // 1. Stamping `device_id` synchronously when the value is already known.
61
+ // 2. Awaiting the native promise inside `track()` when it's still pending,
62
+ // then handing the now-stamped event to the native bridge.
63
+ //
64
+ // Bridge failure falls back to the sentinel string `"unknown-device"` so the
65
+ // backend `events.device_id` column stays populated. See the FALLBACK_DEVICE_ID
66
+ // constant.
67
+
68
+ import { getNativeModule } from "../native/module";
69
+
70
+ // MARK: - Types
71
+
72
+ export interface SKAnalyticsConfig {
73
+ apiKey: string;
74
+ serverURL?: string;
75
+ flushQueueSize?: number;
76
+ flushIntervalMs?: number;
77
+ optOut?: boolean;
78
+ trackingSessionEvents?: boolean;
79
+ }
80
+
81
+ export interface SKEvent {
82
+ /**
83
+ * Client-supplied idempotency key (UUID). Generated in JS at event-create
84
+ * time so the key is stable across bridge crashes and the backend dedupes
85
+ * via the `(app_project_id, event_id)` unique index. See the module
86
+ * doc-comment for the rationale.
87
+ */
88
+ event_id: string;
89
+ event_type: string;
90
+ event_properties?: Record<string, unknown>;
91
+ user_id?: string;
92
+ /**
93
+ * Wave 1: derived from the native Identity snapshot at event-build
94
+ * time. Carries the unified `$SKAnonymousID:` prefix on both iOS and
95
+ * Android.
96
+ */
97
+ anonymous_id?: string;
98
+ device_id?: string;
99
+ /**
100
+ * Post-#136 audit: now a UUID string sourced from the native
101
+ * `Session.shared` primitive (was `Date.now()` number which diverged
102
+ * from envelope-level `ContextSnapshot.session_id`). Optional so
103
+ * synthetic events constructed by callers (tests / overrides) can
104
+ * still omit it without a typecheck error.
105
+ */
106
+ session_id?: string;
107
+ time?: number;
108
+ platform?: string;
109
+ os_name?: string;
110
+ user_properties?: Record<string, unknown>;
111
+ groups?: Record<string, unknown>;
112
+ }
113
+
114
+ // MARK: - Identify (user properties — Amplitude-compatible)
115
+
116
+ export class SKIdentify {
117
+ private operations: Array<{ op: string; key?: string; value?: unknown }> = [];
118
+
119
+ set(property: string, value: unknown): this {
120
+ this.operations.push({ op: "$set", key: property, value });
121
+ return this;
122
+ }
123
+
124
+ setOnce(property: string, value: unknown): this {
125
+ this.operations.push({ op: "$setOnce", key: property, value });
126
+ return this;
127
+ }
128
+
129
+ unset(property: string): this {
130
+ this.operations.push({ op: "$unset", key: property });
131
+ return this;
132
+ }
133
+
134
+ add(property: string, value: number): this {
135
+ this.operations.push({ op: "$add", key: property, value });
136
+ return this;
137
+ }
138
+
139
+ append(property: string, value: unknown): this {
140
+ this.operations.push({ op: "$append", key: property, value });
141
+ return this;
142
+ }
143
+
144
+ prepend(property: string, value: unknown): this {
145
+ this.operations.push({ op: "$prepend", key: property, value });
146
+ return this;
147
+ }
148
+
149
+ remove(property: string, value: unknown): this {
150
+ this.operations.push({ op: "$remove", key: property, value });
151
+ return this;
152
+ }
153
+
154
+ union(property: string, values: unknown[]): this {
155
+ this.operations.push({ op: "$union", key: property, value: values });
156
+ return this;
157
+ }
158
+
159
+ clearAll(): this {
160
+ this.operations.push({ op: "$clearAll" });
161
+ return this;
162
+ }
163
+
164
+ /** @internal */
165
+ _getOperations() {
166
+ return this.operations;
167
+ }
168
+ }
169
+
170
+ // MARK: - Revenue
171
+
172
+ export class SKRevenue {
173
+ productId: string = "";
174
+ quantity: number = 1;
175
+ price: number = 0;
176
+ revenueType?: string;
177
+ receipt?: string;
178
+ eventProperties?: Record<string, unknown>;
179
+ }
180
+
181
+ // MARK: - Main SDK
182
+
183
+ /** Sentinel device_id when the native bridge fails. Documented in module doc-comment. */
184
+ const FALLBACK_DEVICE_ID = "unknown-device";
185
+
186
+ let _config: SKAnalyticsConfig | null = null;
187
+ let _userId: string | undefined;
188
+ /**
189
+ * The resolved device id. `null` until the native bridge resolves (or until
190
+ * `setDeviceId` is called). When `null`, `track()` awaits the native promise
191
+ * before stamping the outgoing event so every event sent across the bridge
192
+ * carries a `device_id`.
193
+ */
194
+ let _deviceId: string | null = null;
195
+ /**
196
+ * In-flight (or settled) promise for the native `getDeviceId()` call. `track()`
197
+ * awaits this to guarantee every emitted event carries a `device_id`. Resolves
198
+ * to the sentinel on bridge failure (never rejects to callers).
199
+ */
200
+ let _deviceIdPromise: Promise<string> | null = null;
201
+ // Cached session id from the native canonical `Session.shared` primitive.
202
+ // Resolved lazily on the first `track()` call and refreshed when native
203
+ // rotates the session (which itself is canonical at flush time too — JS
204
+ // merely reads the latest snapshot). `null` until the first successful
205
+ // native call; falls back to a one-shot millis sentinel only if the native
206
+ // bridge errors out.
207
+ let _sessionId: string | null = null;
208
+ let _sessionIdPromise: Promise<string> | null = null;
209
+ let _userProperties: Record<string, unknown> = {};
210
+ let _groups: Record<string, unknown> = {};
211
+ let _superProperties: Record<string, unknown> = {};
212
+ let _timedEvents: Record<string, number> = {};
213
+ let _flushTimer: ReturnType<typeof setInterval> | null = null;
214
+
215
+ // Post-#136 audit: `generateUUID` used to live inline here. It has been
216
+ // centralized in `./ids.ts` so future callers can import rather than
217
+ // copy-paste.
218
+ import { generateUUID } from "./ids";
219
+
220
+ /**
221
+ * Detect whether we're in a React Native runtime (`navigator` is defined by RN's
222
+ * polyfill) vs plain Node. Wrapped in a function so the `navigator` global
223
+ * reference is hidden behind a runtime check the TS lib doesn't have to know
224
+ * about — we set `tsconfig.lib = ES2020` which omits `dom`/`webworker`, so a
225
+ * bare `typeof navigator` triggers `Cannot find name 'navigator'`.
226
+ */
227
+ function detectOsName(): string {
228
+ return typeof (globalThis as { navigator?: unknown }).navigator !== "undefined"
229
+ ? "rn"
230
+ : "node";
231
+ }
232
+
233
+ /**
234
+ * Kick off the native `getDeviceId()` call and resolve `_deviceIdPromise`.
235
+ * Always resolves (never rejects) — bridge failure produces the sentinel so
236
+ * `track()` can always make progress.
237
+ */
238
+ /**
239
+ * Read the canonical session id from the native `Session.shared` primitive.
240
+ * Cached after first resolve. Falls back to a string-encoded `Date.now()`
241
+ * sentinel ONLY if the native bridge fails — that preserves the
242
+ * fire-and-forget nature of analytics without ever surfacing the error to
243
+ * app code.
244
+ */
245
+ function loadSessionIdFromNative(): Promise<string> {
246
+ const p = (async () => {
247
+ try {
248
+ const snap = await getNativeModule().sessionCurrent();
249
+ if (snap && typeof snap.id === "string" && snap.id.length > 0) {
250
+ _sessionId = snap.id;
251
+ return snap.id;
252
+ }
253
+ const fallback = String(Date.now());
254
+ _sessionId = fallback;
255
+ return fallback;
256
+ } catch (e) {
257
+ console.warn(
258
+ `[SwissKnife Analytics] native sessionCurrent() failed; falling back to Date.now()-derived id:`,
259
+ e,
260
+ );
261
+ const fallback = String(Date.now());
262
+ _sessionId = fallback;
263
+ return fallback;
264
+ }
265
+ })();
266
+ _sessionIdPromise = p;
267
+ return p;
268
+ }
269
+
270
+ function loadDeviceIdFromNative(): Promise<string> {
271
+ const p = (async () => {
272
+ try {
273
+ const id = await getNativeModule().getDeviceId();
274
+ if (typeof id === "string" && id.length > 0) {
275
+ _deviceId = id;
276
+ return id;
277
+ }
278
+ console.warn(
279
+ `[SwissKnife Analytics] native getDeviceId() returned an empty value; falling back to "${FALLBACK_DEVICE_ID}"`
280
+ );
281
+ _deviceId = FALLBACK_DEVICE_ID;
282
+ return FALLBACK_DEVICE_ID;
283
+ } catch (e) {
284
+ console.warn(
285
+ `[SwissKnife Analytics] native getDeviceId() failed; falling back to "${FALLBACK_DEVICE_ID}":`,
286
+ e
287
+ );
288
+ _deviceId = FALLBACK_DEVICE_ID;
289
+ return FALLBACK_DEVICE_ID;
290
+ }
291
+ })();
292
+ _deviceIdPromise = p;
293
+ return p;
294
+ }
295
+
296
+ /**
297
+ * Fire-and-forget send to the native bridge. We do NOT throw out of the public
298
+ * `track()`/`identify()`/etc. surface because analytics is fire-and-forget for
299
+ * app code — app authors don't want a typo-in-event-name or a bridge hiccup to
300
+ * propagate up the call stack. Failures are logged once.
301
+ */
302
+ function sendToNativeFireAndForget(event: SKEvent): void {
303
+ void (async () => {
304
+ try {
305
+ await getNativeModule().trackEvent(event as unknown as Record<string, unknown>);
306
+ } catch (e) {
307
+ console.warn(
308
+ `[SwissKnife Analytics] native trackEvent() failed (event will be dropped):`,
309
+ e
310
+ );
311
+ }
312
+ })();
313
+ }
314
+
315
+ /**
316
+ * Build a fully-stamped event from `eventType` + props + current SDK state.
317
+ * Awaits the native device-id promise when the cached id is still null.
318
+ * The returned event is ready to hand to the native bridge.
319
+ *
320
+ * Wave 1: `user_id` is derived from the native `Identity.current()`
321
+ * snapshot at event-build time — NOT from the JS-local `_userId` cache
322
+ * that historically drifted from native. Pre-Wave-1: calling
323
+ * `Purchases.logIn("u_42")` and immediately `Analytics.track(...)`
324
+ * emitted with `user_id: ""` because the JS-side `setUserId(...)` was
325
+ * never called. Now native is the single source of truth.
326
+ */
327
+ async function buildEvent(
328
+ eventType: string,
329
+ eventProperties: Record<string, unknown> | undefined,
330
+ overrides?: Partial<SKEvent>
331
+ ): Promise<SKEvent> {
332
+ // Merge super properties (event props override)
333
+ const mergedProps: Record<string, unknown> = { ..._superProperties, ...eventProperties };
334
+
335
+ // Timed event duration
336
+ if (_timedEvents[eventType]) {
337
+ mergedProps.$duration = (Date.now() - _timedEvents[eventType]) / 1000;
338
+ delete _timedEvents[eventType];
339
+ }
340
+
341
+ // Resolve device_id. Synchronous when already cached; otherwise await the
342
+ // native bridge promise (kicked off in init()) so every event handed to
343
+ // native has a device_id stamped.
344
+ let deviceId = _deviceId;
345
+ if (deviceId == null) {
346
+ if (_deviceIdPromise == null) loadDeviceIdFromNative();
347
+ deviceId = (await _deviceIdPromise) ?? FALLBACK_DEVICE_ID;
348
+ }
349
+
350
+ // Resolve session_id from the canonical native primitive. Same lazy
351
+ // pattern as device_id — synchronous when cached, otherwise await the
352
+ // in-flight promise kicked off in init(). Pre-audit this was a JS-side
353
+ // `Date.now()` which diverged from envelope-level
354
+ // ContextSnapshot.session_id.
355
+ let sessionId = _sessionId;
356
+ if (sessionId == null) {
357
+ if (_sessionIdPromise == null) loadSessionIdFromNative();
358
+ sessionId = (await _sessionIdPromise) ?? String(Date.now());
359
+ }
360
+
361
+ // Wave 1: derive user_id from the native Identity snapshot. Fall back
362
+ // to the JS-local `_userId` only when the native call throws (e.g.
363
+ // test harness without the Identity bridge methods stubbed) — that
364
+ // preserves the legacy `Analytics.setUserId(...)` test seam.
365
+ let userId: string;
366
+ let anonymousId: string | undefined;
367
+ try {
368
+ const snapshot = await getNativeModule().identityCurrent();
369
+ userId = snapshot.userId ?? "";
370
+ anonymousId = snapshot.anonymousId;
371
+ } catch {
372
+ userId = _userId ?? "";
373
+ anonymousId = undefined;
374
+ }
375
+
376
+ const event: SKEvent = {
377
+ event_id: generateUUID(),
378
+ event_type: eventType,
379
+ event_properties: mergedProps,
380
+ user_id: userId,
381
+ device_id: deviceId,
382
+ session_id: sessionId,
383
+ time: Date.now(),
384
+ platform: "React Native",
385
+ os_name: detectOsName(),
386
+ // User properties are canonical server-side state (app_users.properties)
387
+ // mutated via $identify operations — regular events carry them only when
388
+ // the local cache is non-empty (matches the iOS SDK, which omits empty
389
+ // maps). Same for groups. `overrides` (used by $identify/$groupidentify
390
+ // to send their operation payloads) still wins over both.
391
+ ...(Object.keys(_userProperties).length > 0
392
+ ? { user_properties: { ..._userProperties } }
393
+ : {}),
394
+ ...(Object.keys(_groups).length > 0 ? { groups: { ..._groups } } : {}),
395
+ ...overrides,
396
+ };
397
+ // Stamp anonymous_id when we resolved it from native — Wave 1's
398
+ // unified $SKAnonymousID: prefix flows through here.
399
+ if (anonymousId !== undefined) {
400
+ (event as SKEvent & { anonymous_id?: string }).anonymous_id = anonymousId;
401
+ }
402
+ return event;
403
+ }
404
+
405
+ export const Analytics = {
406
+ // MARK: Initialize
407
+
408
+ /**
409
+ * Configure the analytics SDK. Kicks off (but does not block on) the native
410
+ * `device_id` fetch — callers do not need to `await init()`. Events tracked
411
+ * before the native promise resolves are still sent with `device_id`
412
+ * stamped because `track()` internally awaits the native promise before
413
+ * crossing the bridge.
414
+ */
415
+ init(config: SKAnalyticsConfig): Promise<void> {
416
+ _config = {
417
+ flushQueueSize: 30,
418
+ flushIntervalMs: 30_000,
419
+ optOut: false,
420
+ trackingSessionEvents: true,
421
+ ...config,
422
+ };
423
+ // Reset cached session id so the next track() refetches from the
424
+ // canonical native primitive. Pre-audit this was `Date.now()`.
425
+ _sessionId = null;
426
+ _sessionIdPromise = null;
427
+
428
+ // Wire the native observability backend (BackendHttpClient + IngestClient)
429
+ // independently of Purchases.configure, so builds that never configure the
430
+ // purchase engine (e.g. RuStore-only Android) still send analytics. Android
431
+ // implements `configureObservability`; on iOS it's absent (the backend is
432
+ // wired by Purchases.configure), so the optional-chained call no-ops.
433
+ // Fire-and-forget: events queue natively regardless and flush once wired.
434
+ if (config.serverURL) {
435
+ try {
436
+ void getNativeModule()
437
+ .configureObservability?.(config.apiKey, config.serverURL)
438
+ ?.catch(() => {});
439
+ } catch {
440
+ // getNativeModule throws only when unlinked (web/Expo Go); harmless here.
441
+ }
442
+ }
443
+
444
+ if (_flushTimer) clearInterval(_flushTimer);
445
+ // Native owns the authoritative flush scheduling (iOS Timer / Android
446
+ // WorkManager). The JS-side interval is kept as a defensive nudge for
447
+ // cases where native scheduling is delayed (e.g. WorkManager under
448
+ // app standby) — it just delegates to the native flush.
449
+ _flushTimer = setInterval(() => {
450
+ void Analytics.flush();
451
+ }, _config.flushIntervalMs!);
452
+
453
+ // Kick off the native device-id fetch unless an explicit `setDeviceId`
454
+ // already seeded a value during this process (test seam / consumer
455
+ // override). When already seeded, keep that promise resolved.
456
+ if (_deviceId == null && _deviceIdPromise == null) {
457
+ loadDeviceIdFromNative();
458
+ }
459
+ // Same lazy warmup for session_id — first track() will await this.
460
+ if (_sessionId == null && _sessionIdPromise == null) {
461
+ loadSessionIdFromNative();
462
+ }
463
+
464
+ if (_config.trackingSessionEvents) {
465
+ Analytics.track("[SwissKnife] Session Start");
466
+ }
467
+
468
+ // Return the device-id promise so tests / consumers that want to await
469
+ // initialization can. Resolves to void; the inner string is captured in
470
+ // `_deviceId`. We swallow the result because consumers should read it via
471
+ // `Analytics.getDeviceId()` once init resolves.
472
+ return (_deviceIdPromise ?? Promise.resolve("")).then(() => undefined);
473
+ },
474
+
475
+ // MARK: Track events (Amplitude-compatible)
476
+
477
+ track(eventType: string, eventProperties?: Record<string, unknown>) {
478
+ if (_config?.optOut) return;
479
+ // Fire-and-forget: build the event (await native device-id if needed),
480
+ // then push it across the bridge. The caller does not need to `await`.
481
+ void (async () => {
482
+ const event = await buildEvent(eventType, eventProperties);
483
+ sendToNativeFireAndForget(event);
484
+ })();
485
+ },
486
+
487
+ // MARK: Screen tracking (Mixpanel-compatible)
488
+
489
+ trackScreen(name: string, properties?: Record<string, unknown>) {
490
+ Analytics.track("[SwissKnife] Screen Viewed", {
491
+ ...properties,
492
+ "[SwissKnife] Screen Name": name,
493
+ });
494
+ },
495
+
496
+ // MARK: User identity
497
+
498
+ setUserId(userId: string | undefined) {
499
+ _userId = userId;
500
+ },
501
+
502
+ getUserId(): string | undefined {
503
+ return _userId;
504
+ },
505
+
506
+ /**
507
+ * Override the device id. Useful for tests and for consumers who want to
508
+ * tie analytics to an external identity. Once called, the native bridge
509
+ * value is ignored for the lifetime of this Analytics module (until
510
+ * `reset()`).
511
+ */
512
+ setDeviceId(deviceId: string) {
513
+ _deviceId = deviceId;
514
+ _deviceIdPromise = Promise.resolve(deviceId);
515
+ },
516
+
517
+ /**
518
+ * Returns the resolved device id, or `null` if the native bridge has not yet
519
+ * resolved AND no explicit override has been set. Most callers should await
520
+ * `init()` first.
521
+ */
522
+ getDeviceId(): string | null {
523
+ return _deviceId;
524
+ },
525
+
526
+ /**
527
+ * Current session id from the native `Session.shared` primitive.
528
+ * Returns `null` until the first `track()` (or explicit await on
529
+ * `init()`'s session warm) has resolved the native call. Pre-audit
530
+ * this returned a `Date.now()` number; the new return type is `string |
531
+ * null` reflecting both the native UUID format and the lazy resolution.
532
+ */
533
+ getSessionId(): string | null {
534
+ return _sessionId;
535
+ },
536
+
537
+ identify(identify: SKIdentify) {
538
+ if (_config?.optOut) return;
539
+ // Snapshot operations before async hop in case the caller mutates `identify`
540
+ // (defensive — SKIdentify is a builder and re-use is unusual but possible).
541
+ const operations = identify._getOperations();
542
+
543
+ // Apply locally before the async hop so any subsequent track() picks up
544
+ // the new user properties without waiting on the bridge round-trip.
545
+ for (const op of operations) {
546
+ if (op.op === "$set" && op.key) {
547
+ _userProperties[op.key] = op.value;
548
+ }
549
+ }
550
+
551
+ void (async () => {
552
+ const event = await buildEvent("$identify", undefined, {
553
+ event_type: "$identify",
554
+ user_properties: { $set: operations },
555
+ });
556
+ sendToNativeFireAndForget(event);
557
+ })();
558
+ },
559
+
560
+ // Super properties (Mixpanel-compatible)
561
+ registerSuperProperties(properties: Record<string, unknown>) {
562
+ Object.assign(_superProperties, properties);
563
+ },
564
+
565
+ registerSuperPropertiesOnce(properties: Record<string, unknown>) {
566
+ for (const [k, v] of Object.entries(properties)) {
567
+ if (!(k in _superProperties)) _superProperties[k] = v;
568
+ }
569
+ },
570
+
571
+ getSuperProperties(): Record<string, unknown> {
572
+ return { ..._superProperties };
573
+ },
574
+
575
+ unregisterSuperProperty(property: string) {
576
+ delete _superProperties[property];
577
+ },
578
+
579
+ clearSuperProperties() {
580
+ _superProperties = {};
581
+ },
582
+
583
+ // Time events (Mixpanel-compatible)
584
+ timeEvent(eventName: string) {
585
+ _timedEvents[eventName] = Date.now();
586
+ },
587
+
588
+ // Group helper (Mixpanel-compatible)
589
+ addGroup(groupType: string, groupName: string) {
590
+ const existing = _groups[groupType];
591
+ if (Array.isArray(existing)) {
592
+ if (!existing.includes(groupName)) existing.push(groupName);
593
+ } else {
594
+ _groups[groupType] = [groupName];
595
+ }
596
+ },
597
+
598
+ reset() {
599
+ _userId = undefined;
600
+ // Drop both the cached id and the in-flight promise; next init() (or the
601
+ // explicit kickoff below) will refetch from native. This matches the
602
+ // "fresh anonymous identity" semantics callers expect from reset().
603
+ _deviceId = null;
604
+ _deviceIdPromise = null;
605
+ _userProperties = {};
606
+ _groups = {};
607
+ _superProperties = {};
608
+ _timedEvents = {};
609
+ // Drop the cached session id so the next track() refetches from the
610
+ // native primitive (`Session.shared`). Pre-audit this was set to
611
+ // `Date.now()` here, which fragmented the analytics timeline at
612
+ // every reset because the JS-side number drifted from the native
613
+ // session UUID stamped on the envelope.
614
+ _sessionId = null;
615
+ _sessionIdPromise = null;
616
+ },
617
+
618
+ // MARK: Groups (Amplitude-compatible)
619
+
620
+ setGroup(groupType: string, groupName: string | string[]) {
621
+ _groups[groupType] = groupName;
622
+ },
623
+
624
+ groupIdentify(groupType: string, groupName: string, identify: SKIdentify) {
625
+ if (_config?.optOut) return;
626
+ const operations = identify._getOperations();
627
+ void (async () => {
628
+ const event = await buildEvent("$groupidentify", undefined, {
629
+ event_type: "$groupidentify",
630
+ groups: { [groupType]: groupName },
631
+ user_properties: { $set: operations },
632
+ });
633
+ sendToNativeFireAndForget(event);
634
+ })();
635
+ },
636
+
637
+ // MARK: Revenue (Amplitude + Mixpanel compatible)
638
+
639
+ revenue(revenue: SKRevenue) {
640
+ const props: Record<string, unknown> = {
641
+ ...revenue.eventProperties,
642
+ $productId: revenue.productId,
643
+ $quantity: revenue.quantity,
644
+ $price: revenue.price,
645
+ };
646
+ if (revenue.revenueType) props.$revenueType = revenue.revenueType;
647
+ Analytics.track("revenue_amount", props);
648
+ },
649
+
650
+ // Mixpanel-compatible
651
+ trackCharge(amount: number, properties?: Record<string, unknown>) {
652
+ Analytics.track("revenue_amount", { ...properties, $amount: amount });
653
+ },
654
+
655
+ // MARK: Flush
656
+
657
+ /**
658
+ * Ask the native side to flush its disk-backed queue. Fire-and-forget — the
659
+ * actual HTTP work runs natively (iOS GCD with back-off; Android
660
+ * WorkManager). This promise resolves as soon as the flush job is scheduled.
661
+ *
662
+ * No-op when the bridge is not linked (we don't keep a JS-side queue any
663
+ * more — there's nothing to send). Errors are swallowed with a single warning
664
+ * so background flushers don't crash the host app.
665
+ */
666
+ async flush() {
667
+ try {
668
+ await getNativeModule().flushEvents();
669
+ } catch (e) {
670
+ console.warn(`[SwissKnife Analytics] native flushEvents() failed:`, e);
671
+ }
672
+ },
673
+
674
+ // MARK: Opt out
675
+
676
+ setOptOut(optOut: boolean) {
677
+ if (_config) _config.optOut = optOut;
678
+ },
679
+
680
+ // MARK: Shutdown
681
+
682
+ shutdown() {
683
+ if (_flushTimer) {
684
+ clearInterval(_flushTimer);
685
+ _flushTimer = null;
686
+ }
687
+ void Analytics.flush();
688
+ },
689
+ };