@app-swiss-knife/react-native-sdk 0.2.5 → 0.3.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 (69) hide show
  1. package/README.md +100 -47
  2. package/SwissKnifePurchases.podspec +8 -5
  3. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +18 -1
  4. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  5. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +1 -1
  6. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +53 -9
  7. package/ios/SwissKnifeCrashReporting.swift +59 -18
  8. package/ios/SwissKnifePurchases.swift +16 -1
  9. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  10. package/ios/vendor/SwissKnifeiOS/Context/Reachability.swift +1 -1
  11. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +24 -0
  12. package/ios/vendor/SwissKnifeiOS/DeviceID.swift +22 -1
  13. package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +49 -0
  14. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +14 -0
  15. package/lib/commonjs/attributes.js +103 -0
  16. package/lib/commonjs/attributes.js.map +1 -0
  17. package/lib/commonjs/index.js +31 -2
  18. package/lib/commonjs/index.js.map +1 -1
  19. package/lib/commonjs/internal/config.js +237 -0
  20. package/lib/commonjs/internal/config.js.map +1 -0
  21. package/lib/commonjs/purchases.js +324 -218
  22. package/lib/commonjs/purchases.js.map +1 -1
  23. package/lib/commonjs/swiss-knife.js +115 -0
  24. package/lib/commonjs/swiss-knife.js.map +1 -0
  25. package/lib/commonjs/types.js +11 -0
  26. package/lib/commonjs/types.js.map +1 -1
  27. package/lib/module/attributes.js +100 -0
  28. package/lib/module/attributes.js.map +1 -0
  29. package/lib/module/index.js +19 -2
  30. package/lib/module/index.js.map +1 -1
  31. package/lib/module/internal/config.js +225 -0
  32. package/lib/module/internal/config.js.map +1 -0
  33. package/lib/module/purchases.js +309 -212
  34. package/lib/module/purchases.js.map +1 -1
  35. package/lib/module/swiss-knife.js +112 -0
  36. package/lib/module/swiss-knife.js.map +1 -0
  37. package/lib/module/types.js +11 -0
  38. package/lib/module/types.js.map +1 -1
  39. package/lib/typescript/commonjs/attributes.d.ts +41 -0
  40. package/lib/typescript/commonjs/attributes.d.ts.map +1 -0
  41. package/lib/typescript/commonjs/index.d.ts +2 -0
  42. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  43. package/lib/typescript/commonjs/internal/config.d.ts +121 -0
  44. package/lib/typescript/commonjs/internal/config.d.ts.map +1 -0
  45. package/lib/typescript/commonjs/purchases.d.ts +103 -95
  46. package/lib/typescript/commonjs/purchases.d.ts.map +1 -1
  47. package/lib/typescript/commonjs/swiss-knife.d.ts +56 -0
  48. package/lib/typescript/commonjs/swiss-knife.d.ts.map +1 -0
  49. package/lib/typescript/commonjs/types.d.ts +13 -0
  50. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  51. package/lib/typescript/module/attributes.d.ts +41 -0
  52. package/lib/typescript/module/attributes.d.ts.map +1 -0
  53. package/lib/typescript/module/index.d.ts +2 -0
  54. package/lib/typescript/module/index.d.ts.map +1 -1
  55. package/lib/typescript/module/internal/config.d.ts +121 -0
  56. package/lib/typescript/module/internal/config.d.ts.map +1 -0
  57. package/lib/typescript/module/purchases.d.ts +103 -95
  58. package/lib/typescript/module/purchases.d.ts.map +1 -1
  59. package/lib/typescript/module/swiss-knife.d.ts +56 -0
  60. package/lib/typescript/module/swiss-knife.d.ts.map +1 -0
  61. package/lib/typescript/module/types.d.ts +13 -0
  62. package/lib/typescript/module/types.d.ts.map +1 -1
  63. package/package.json +1 -1
  64. package/src/attributes.ts +97 -0
  65. package/src/index.ts +19 -2
  66. package/src/internal/config.ts +233 -0
  67. package/src/purchases.ts +320 -228
  68. package/src/swiss-knife.ts +134 -0
  69. package/src/types.ts +14 -0
package/README.md CHANGED
@@ -48,9 +48,13 @@ anything under `ios/vendor` or `android/vendor`.
48
48
  `SwissKnifeJSON`). Because the vendored Swift compiles into the **same** pod
49
49
  module as the bridge, the bridge files use
50
50
  `#if canImport(SwissKnifeiOS) / import SwissKnifeiOS` (false, and unnecessary,
51
- in the pod) and the podspec defines `SWISSKNIFE_VENDORED` so conditional code
52
- paths stay live. The vendored Swift imports only system frameworks — zero
53
- third-party pods.
51
+ in the pod) purely to satisfy SPM consumers. **No bridge method body is
52
+ conditionally compiled.** They used to be gated on the podspec's
53
+ `SWISSKNIFE_VENDORED` flag, which meant a Podfile `post_install` that assigned
54
+ rather than appended to `SWIFT_ACTIVE_COMPILATION_CONDITIONS` silently
55
+ compiled the native crash reporter down to empty method bodies while the
56
+ build stayed green. A missing SDK is now a compile error instead. The
57
+ vendored Swift imports only system frameworks — zero third-party pods.
54
58
 
55
59
  Phase 7 of the SDK rip-and-replace removed every RevenueCat / PHC dependency
56
60
  from the bridge — neither the iOS pod graph nor the Android AAR graph pulls
@@ -88,39 +92,76 @@ npm install @react-native-async-storage/async-storage react-native-webview
88
92
  ## Quick Start
89
93
 
90
94
  ```typescript
91
- import { SwissKnifeClient } from "@app-swiss-knife/react-native-sdk";
95
+ import {
96
+ SwissKnife,
97
+ Purchases,
98
+ Identity,
99
+ Attributes,
100
+ } from "@app-swiss-knife/react-native-sdk";
92
101
 
93
- const client = new SwissKnifeClient({
94
- apiKey: "your-api-key",
95
- baseURL: "https://your-app.com",
96
- debug: true, // Enable request/response logging
102
+ // Once, at app start.
103
+ SwissKnife.configure({
104
+ apiKey: "sk_...",
105
+ proxyURL: "https://your-swiss-knife-host",
97
106
  });
98
107
 
99
- // Fetch SDK config
100
- const config = await client.get("/api/sdk/config");
101
-
102
- // Track events
103
- await client.post("/api/sdk/events/batch", {
104
- user_id: "user-123",
105
- events: [
106
- {
107
- name: "app_open",
108
- properties: { screen: "home" },
109
- timestamp: new Date().toISOString(),
110
- },
111
- ],
112
- });
108
+ // Who is this device?
109
+ await Identity.logIn("user_42");
113
110
 
114
- // Evaluate feature flags
115
- const flags = await client.get("/api/sdk/flags/evaluate", {
116
- user_id: "user-123",
117
- });
111
+ // What do we know about them? (This is the dashboard person card.)
112
+ await Attributes.setEmail("ann@example.com");
113
+ await Attributes.set({ plan: "gold", cohort: "2026-08" });
114
+
115
+ // Sell them something.
116
+ const offerings = await Purchases.getOfferings();
117
+ const pkg = offerings.current?.availablePackages[0];
118
+ if (pkg) await Purchases.purchasePackage(pkg);
118
119
  ```
119
120
 
121
+ ## The namespaces
122
+
123
+ Everything hangs off `SwissKnife`, the same way it does in the native iOS and
124
+ Android SDKs. Each namespace is also exported by name, so
125
+ `SwissKnife.Identity` and `Identity` are the same object — import whichever
126
+ reads better.
127
+
128
+ | Namespace | What it is | Needs |
129
+ | ---------------- | ------------------------------------------------------------------------------------------ | ----------- |
130
+ | `SwissKnife` | Bootstrap: `configure`, `configureCore`, `isConfigured`, `isCoreConfigured`, `setLogLevel` | — |
131
+ | `Purchases` | The store: offerings, purchases, restores, `CustomerInfo` | `configure` |
132
+ | `Identity` | `logIn` / `logOut` / `current` / `reset` / `wipe` | core |
133
+ | `Attributes` | Subscriber attributes — **the dashboard person card** | core |
134
+ | `Attribution` | Install attribution: ATT / IDFA / advertising id / referrer | core |
135
+ | `Analytics` | `init` / `track` / `identify` / `screen` | — |
136
+ | `CrashReporting` | Crash + error reporting | — |
137
+ | `Performance` | Transactions and spans | — |
138
+
139
+ "core" means `SwissKnife.configure(...)`, `SwissKnife.configureCore(...)` **or**
140
+ `Analytics.init(...)` — no store required.
141
+
142
+ ### Migrating from `react-native-purchases`?
143
+
144
+ Change nothing. `Purchases` keeps every member it has ever had, including
145
+ `Purchases.configure`, `Purchases.configureCore`, `Purchases.isConfigured`,
146
+ `Purchases.isCoreConfigured`, `Purchases.setLogLevel`, `Purchases.setAttributes`,
147
+ `Purchases.setEmail`, `Purchases.setDisplayName`, `Purchases.setPhoneNumber` and
148
+ `Purchases.setPushToken`. They are **not deprecated** and they are not wrappers —
149
+ `Purchases.configure === SwissKnife.configure` and
150
+ `Purchases.setAttributes === Attributes.set` are literally true, so the two
151
+ spellings share one bootstrap state and cannot drift apart. Mix them freely
152
+ while you migrate, or never migrate at all.
153
+
154
+ The four identity aliases (`Purchases.logIn`, `logOut`, `getAppUserID`,
155
+ `isAnonymous`) are the exception and stay marked deprecated: they still work, but
156
+ `Identity.*` is the canonical home and the RC return types misdescribe what those
157
+ calls do in a store-less app.
158
+
159
+ New namespaces require SDK `>= 0.3.0`.
160
+
120
161
  ## Already using another IAP library? Use `configureCore`
121
162
 
122
- `Purchases.configure(...)` sets up two independent things: the **core** (event
123
- ingest, `Identity`, `Attribution`, subscriber attributes) and the **purchase
163
+ `SwissKnife.configure(...)` sets up two independent things: the **core** (event
164
+ ingest, `Identity`, `Attribution`, `Attributes`) and the **purchase
124
165
  engine** (StoreKit 2 on iOS, Google Play Billing on Android).
125
166
 
126
167
  The purchase engine is not passive. On iOS it starts a process-wide
@@ -133,40 +174,46 @@ So the two halves are separately callable:
133
174
 
134
175
  ```typescript
135
176
  import {
136
- Purchases,
177
+ SwissKnife,
137
178
  Identity,
179
+ Attributes,
138
180
  Attribution,
139
- Analytics,
140
181
  } from "@app-swiss-knife/react-native-sdk";
141
182
 
142
- // Analytics + identity + attribution. No StoreKit observer. No BillingClient.
143
- // No install registered as a side effect.
144
- Purchases.configureCore({
183
+ // Analytics + identity + attribution + attributes. No StoreKit observer.
184
+ // No BillingClient. No install registered as a side effect.
185
+ SwissKnife.configureCore({
145
186
  apiKey: "sk_...",
146
187
  proxyURL: "https://your-swiss-knife-host",
147
188
  });
148
189
 
149
190
  await Identity.logIn("user_42");
191
+ await Attributes.setEmail("ann@example.com"); // person card, no store needed
150
192
  await Attribution.registerInstall(); // explicit — core never does this for you
151
193
  ```
152
194
 
153
195
  - **Analytics only?** `Analytics.init({ apiKey, serverURL })` already wires core
154
- natively — identity and attribution work from that call alone. Reach for
155
- `configureCore` when you also want to pass an `appUserID`, an attribution
156
- configuration, or a log level up front.
157
- - **`Purchases.configure(...)` is unchanged** — it is exactly core + purchases,
196
+ natively — identity, attribution and attributes work from that call alone.
197
+ Reach for `configureCore` when you also want to pass an `appUserID`, an
198
+ attribution configuration, or a log level up front.
199
+ - **`SwissKnife.configure(...)` is unchanged** — it is exactly core + purchases,
158
200
  including the first-launch install registration
159
201
  (`sendInstallOnFirstLaunch`, default `true`). Existing integrations need no
160
202
  changes.
161
- - `Purchases.isConfigured()` reports the **purchase engine** and stays `false`
162
- in a core-only app; `Purchases.isCoreConfigured()` reports the core. Both read
203
+ - **`Attributes.*` works here.** All five setters need core only, which is why
204
+ they are a namespace of their own rather than members of `Purchases`: an app
205
+ that never sells anything still wants its person card filled in. They are the
206
+ only path to `POST /api/sdk/users/attributes`.
207
+ - `SwissKnife.isConfigured()` reports the **purchase engine** and stays `false`
208
+ in a core-only app; `SwissKnife.isCoreConfigured()` reports the core. Both read
163
209
  the answer from native — which is what makes `isCoreConfigured()` return
164
210
  `true` in an `Analytics.init`-only app, where no JS configure call ever
165
211
  happened. Neither ever throws or rejects: if the native module is not linked
166
212
  (Expo Go, a build without `pod install` / a Gradle sync, web) they both
167
213
  resolve `false`, because an unlinked module cannot have configured anything.
168
214
  - Native equivalents: `SwissKnife.configureCore(...)` /
169
- `SwissKnife.configurePurchases(...)` on both iOS and Android.
215
+ `SwissKnife.configurePurchases(...)` on both iOS and Android — the JS root is
216
+ named to match.
170
217
 
171
218
  ## IDFA/GAID Collection (Advertising ID)
172
219
 
@@ -196,16 +243,22 @@ The SDK automatically:
196
243
  - Includes `advertising_id` in the install attribution request
197
244
  - Falls back gracefully if the user denies tracking or the libraries are not installed
198
245
 
199
- You can also use the helpers directly:
246
+ You can also drive it yourself through the `Attribution` namespace — prompt
247
+ orchestration and the idempotency cache live natively, so a second call returns
248
+ the cached resolution without re-prompting or re-POSTing:
200
249
 
201
250
  ```typescript
202
- import {
203
- requestTrackingPermission,
204
- getAdvertisingId,
205
- } from "@app-swiss-knife/react-native-sdk";
251
+ import { Attribution } from "@app-swiss-knife/react-native-sdk";
252
+
253
+ // Auto-collect (ATT prompt + IDFA on iOS, advertising id + referrer on Android)
254
+ // and register the install.
255
+ const resolved = await Attribution.requestAndRegister();
256
+
257
+ // Or collect consent yourself and hand us the id (pass null if denied):
258
+ await Attribution.registerInstall(advertisingId);
206
259
 
207
- const status = await requestTrackingPermission(); // 'authorized' | 'denied' | 'not-determined' | 'restricted'
208
- const { id, isLimitedAdTracking } = await getAdvertisingId();
260
+ // Read the cached resolution without touching the network:
261
+ const current = await Attribution.resolved();
209
262
  ```
210
263
 
211
264
  ## Custom Storage
@@ -13,11 +13,14 @@ Pod::Spec.new do |s|
13
13
  # 15.1 == the React Native / Expo default `ios.deploymentTarget`, so this pod
14
14
  # resolves in a stock app with no `expo-build-properties` override.
15
15
  #
16
- # This is deliberately NOT the `.iOS(.v16)` from the standalone SPM package
17
- # (packages/swiss-knife-ios/Package.swift). That floor is an SPM-consumer
18
- # contract; here the SDK's Swift is VENDORED and compiled in-tree, so the real
19
- # floor is whatever the code needs. Verified empirically: the vendored sources
20
- # compile clean at 15.1 and use no iOS 16 API. Everything StoreKit 2 is behind
16
+ # Deliberately 15.1 rather than the standalone SPM package's 15.0
17
+ # (packages/swiss-knife-ios/Package.swift). Both floors sit above the real
18
+ # requirement; this one is pinned to the RN/Expo default so a stock app
19
+ # resolves without touching its config, while the SPM package declares the
20
+ # true minimum for consumers who set their own target. The SDK's Swift is
21
+ # VENDORED here and compiled in-tree, so the real floor is whatever the code
22
+ # needs. Verified empirically: the vendored sources compile clean at 15.1 and
23
+ # at 15.0, and use no iOS 16 API. Everything StoreKit 2 is behind
21
24
  # `@available(iOS 15.0, *)` (Services/PurchaseService.swift,
22
25
  # Services/OfferingsService.swift), which is what sets the true floor —
23
26
  # do not drop below 15.0 or the entire purchase path becomes dead code.
@@ -194,7 +194,24 @@ class SwissKnifePurchasesModule(
194
194
  )
195
195
  }
196
196
 
197
- // ----- Identity -----
197
+ // ----- Identity (legacy bridge methods — no longer called by our JS) -----
198
+ //
199
+ // `Purchases.logIn` / `logOut` / `getAppUserID` / `isAnonymous` in JS now
200
+ // delegate to the `Identity` module, which uses the `identity*` methods
201
+ // further down. These four stay on the spec because removing a method from
202
+ // the native-module contract breaks any app pinned to an older JS, but they
203
+ // are dead from this package's point of view.
204
+ //
205
+ // Do NOT re-point JS at them. They bottom out in the deprecated
206
+ // `SwissKnife.*` facades, which on THIS platform are not equivalent to the
207
+ // iOS ones: `SwissKnife.logOut` goes straight to the purchases gateway
208
+ // instead of `Identity.logOut`, and `SwissKnife.appUserID` /
209
+ // `SwissKnife.isAnonymous()` read gateway state — whose anonymous id is a
210
+ // fresh random UUID per process, not the DeviceID-derived
211
+ // `$SKAnonymousID:` subject `Identity.current()` reports, and which
212
+ // `Identity.reset()` / `Identity.wipe()` never clear. That split is what
213
+ // `packages/react-native-sdk/src/identity-parity.test.ts` exists to keep out
214
+ // of the JS surface.
198
215
 
199
216
  @ReactMethod
200
217
  fun logIn(appUserID: String, promise: Promise) {
@@ -42,7 +42,7 @@ internal object DeviceContextProvider {
42
42
  * eventually inject this via `BuildConfig`, but for now keep it in
43
43
  * source so we don't have to thread build settings through every test.
44
44
  */
45
- const val SDK_VERSION: String = "0.2.5"
45
+ const val SDK_VERSION: String = "0.3.0"
46
46
 
47
47
  private val cacheLock = Any()
48
48
 
@@ -208,7 +208,7 @@ internal object IngestPlaceholderDevice {
208
208
  appBuild = "unknown",
209
209
  locale = Locale.getDefault().toString(),
210
210
  timezone = TimeZone.getDefault().id,
211
- sdkVersion = "0.2.5",
211
+ sdkVersion = "0.3.0",
212
212
  bundleIdentifier = null,
213
213
  )
214
214
  }
@@ -47,6 +47,7 @@ import com.appswissknife.StoreTransactionResult
47
47
  import com.appswissknife.entitlements.EntitlementsRepository
48
48
  import com.appswissknife.entitlements.SimpleCustomerInfo
49
49
  import com.appswissknife.entitlements.SimpleEntitlementInfos
50
+ import com.appswissknife.identity.Identity
50
51
  import com.appswissknife.models.CustomerInfo
51
52
  import com.appswissknife.models.LogLevel
52
53
  import com.appswissknife.models.Offerings
@@ -91,12 +92,19 @@ class BillingClientGateway(
91
92
  @Volatile private var serverUrl: String = ""
92
93
  @Volatile private var apiKey: String = ""
93
94
  @Volatile private var explicitAppUserId: String? = null
94
- // Wave 1: unified `$SKAnonymousID:` prefix across iOS / Android / RN.
95
- // Was `$RCAnonymousID:` (RC legacy) before the audit. Per the
96
- // user-locked decision we do NOT backfill on-device caches with the
97
- // new prefix — whatever's already there stays; only fresh installs
98
- // and logOut() rotations pick it up.
99
- @Volatile private var anonymousAppUserId: String = "\$SKAnonymousID:${UUID.randomUUID().toString().replace("-", "")}"
95
+
96
+ /**
97
+ * Last-resort anonymous subject.
98
+ *
99
+ * Used ONLY when [Identity] has no application context yet — i.e. a
100
+ * purchase or entitlement check attempted before `SwissKnife.configure`.
101
+ * It is minted per process and never persisted, so it is not a stable
102
+ * identity and anything keyed on it is unreachable after the process
103
+ * dies. That is precisely why it must not be the normal path; see
104
+ * [getAppUserID].
105
+ */
106
+ @Volatile private var fallbackAnonymousAppUserId: String =
107
+ "\$SKAnonymousID:${UUID.randomUUID().toString().replace("-", "")}"
100
108
 
101
109
  private val configured = AtomicBoolean(false)
102
110
  private val reconnectAttempt = AtomicInteger(0)
@@ -172,9 +180,39 @@ class BillingClientGateway(
172
180
 
173
181
  override fun isConfigured(): Boolean = configured.get()
174
182
 
175
- override fun getAppUserID(): String = explicitAppUserId ?: anonymousAppUserId
183
+ /**
184
+ * The subject the backend keys purchases and entitlements on.
185
+ *
186
+ * Mirrors iOS `SwissKnife.backendSubjectId()`: an explicit id wins,
187
+ * otherwise the [Identity] snapshot.
188
+ *
189
+ * **Why this is not a random UUID any more.** The anonymous branch used to
190
+ * return `"${'$'}SKAnonymousID:" + UUID.randomUUID()`, minted once per
191
+ * process in a field initializer and never persisted, while
192
+ * `Identity.current()` — and therefore the `/api/sdk/users/identify` POST —
193
+ * reported `"${'$'}SKAnonymousID:" + DeviceID.get(ctx)` from
194
+ * EncryptedSharedPreferences. Android was posting two different subjects for
195
+ * the same anonymous person: one on `validate`/entitlements, another on
196
+ * `identify`. The merge looked for rows under the id it was told about and
197
+ * found none, so an anonymous purchase never followed the user into their
198
+ * account. iOS never had this half of the bug because both paths already
199
+ * went through `backendSubjectId()`.
200
+ */
201
+ override fun getAppUserID(): String {
202
+ explicitAppUserId?.takeIf { it.isNotEmpty() }?.let { return it }
203
+ val snapshot = Identity.current()
204
+ val fromIdentity = snapshot.userId ?: snapshot.anonymousId
205
+ return fromIdentity.takeIf { it.isNotEmpty() } ?: fallbackAnonymousAppUserId
206
+ }
176
207
 
177
- override fun isAnonymous(): Boolean = explicitAppUserId == null
208
+ /**
209
+ * Anonymous iff neither this gateway nor [Identity] holds an explicit user.
210
+ * Consulting Identity too keeps this consistent with [getAppUserID] — a
211
+ * host that identified through `Identity.logIn` directly must not be
212
+ * reported as anonymous while its subject is a real user id.
213
+ */
214
+ override fun isAnonymous(): Boolean =
215
+ explicitAppUserId == null && Identity.current().userId == null
178
216
 
179
217
  override fun getCustomerInfo(
180
218
  onSuccess: (CustomerInfo) -> Unit,
@@ -342,7 +380,13 @@ class BillingClientGateway(
342
380
  return
343
381
  }
344
382
  explicitAppUserId = null
345
- anonymousAppUserId = "\$SKAnonymousID:${UUID.randomUUID().toString().replace("-", "")}"
383
+ // Rotates the pre-configure fallback only. The real post-logout subject
384
+ // comes from `Identity`, whose DeviceID deliberately survives logout so
385
+ // analytics stay continuous for the same physical install — same as iOS,
386
+ // where logOut also returns to the stable device anonymous id rather than
387
+ // inventing a new one.
388
+ fallbackAnonymousAppUserId =
389
+ "\$SKAnonymousID:${UUID.randomUUID().toString().replace("-", "")}"
346
390
  val repo = entitlementsRepo
347
391
  repo?.invalidate()
348
392
  onSuccess(emptyCustomerInfo())
@@ -12,14 +12,30 @@
12
12
  // Two link modes, one source file:
13
13
  // * CocoaPods (the RN package) — the SDK's Swift sources are VENDORED into
14
14
  // this same module from ios/vendor/SwissKnifeiOS/**, so there is no
15
- // `SwissKnifeiOS` module to import and the podspec defines
16
- // SWISSKNIFE_VENDORED to keep the code paths live.
15
+ // `SwissKnifeiOS` module to import and the types are already in scope.
17
16
  // * SPM / a separately-linked SwissKnifeiOS module — `canImport` is true and
18
17
  // the import supplies the types.
19
- // If somehow neither holds, the module degrades to a safe no-op (JS-side
20
- // reporting still works) rather than failing to compile.
18
+ //
19
+ // EVERY METHOD BODY BELOW IS UNCONDITIONAL. They used to be wrapped in
20
+ // `#if SWISSKNIFE_VENDORED || canImport(SwissKnifeiOS)`, which made the whole
21
+ // native crash reporter contingent on one xcconfig string surviving into the
22
+ // pod's build settings. `SWISSKNIFE_VENDORED` is set by `s.pod_target_xcconfig`
23
+ // in SwissKnifePurchases.podspec, and a Podfile `post_install` hook that
24
+ // ASSIGNS `SWIFT_ACTIVE_COMPILATION_CONDITIONS` instead of appending to it — a
25
+ // routine RN/Expo workaround — drops it. The failure was total and completely
26
+ // silent: the vendored sources still compiled, `SwissKnifePurchases.swift`
27
+ // (which never carried these guards) kept working, the build stayed green,
28
+ // `crashNative*` still crashed the app because those hooks sit OUTSIDE the
29
+ // guard, and `start(...)` compiled down to an empty body — so no signal
30
+ // handler was ever installed and not one native crash was ever reported.
31
+ //
32
+ // A missing SDK is now a COMPILE ERROR, exactly as it already is in
33
+ // SwissKnifePurchases.swift. "Degrades to a safe no-op" reads as safe and is
34
+ // not: it turns a build misconfiguration into a production outage nobody can
35
+ // see from the outside.
21
36
 
22
37
  import Foundation
38
+ import os.log
23
39
  #if canImport(SwissKnifeiOS)
24
40
  import SwissKnifeiOS
25
41
  #endif
@@ -49,10 +65,16 @@ private final class SKResolveOnce {
49
65
  @objc(SKCrashReporting)
50
66
  class SwissKnifeCrashReporting: NSObject {
51
67
 
68
+ /// Log channel for the one thing the field could never establish from the
69
+ /// outside: whether the native handler armed at all. A crash reporter that
70
+ /// silently does nothing looks identical to one that has nothing to report.
71
+ private static let log = OSLog(
72
+ subsystem: "com.swissknife.rn", category: "CrashReporting"
73
+ )
74
+
52
75
  @objc
53
76
  func start(_ config: NSDictionary) {
54
77
  guard let apiKey = config["apiKey"] as? String, !apiKey.isEmpty else { return }
55
- #if SWISSKNIFE_VENDORED || canImport(SwissKnifeiOS)
56
78
  let serverURL = (config["serverURL"] as? String) ?? ""
57
79
  let environment = (config["environment"] as? String) ?? "production"
58
80
  let release = config["release"] as? String
@@ -96,12 +118,22 @@ class SwissKnifeCrashReporting: NSObject {
96
118
  tracesSampleRate: tracesSampleRate
97
119
  )
98
120
  SKCrashReporting.shared.start(configuration: configuration)
99
- #endif
121
+
122
+ // Deliberately `.info` and unconditional. This one line is the difference
123
+ // between "no crashes happened" and "the crash reporter was never armed" —
124
+ // the two states the field could not tell apart. Grep the device log for
125
+ // `com.swissknife.rn`.
126
+ os_log(
127
+ "native crash handler armed (env %{public}@, serverURL %{public}@)",
128
+ log: Self.log,
129
+ type: .info,
130
+ environment,
131
+ serverURL.isEmpty ? "default" : serverURL
132
+ )
100
133
  }
101
134
 
102
135
  @objc
103
136
  func setUser(_ user: NSDictionary?) {
104
- #if SWISSKNIFE_VENDORED || canImport(SwissKnifeiOS)
105
137
  guard let user else {
106
138
  SKCrashReporting.shared.setUser(nil)
107
139
  return
@@ -113,12 +145,10 @@ class SwissKnifeCrashReporting: NSObject {
113
145
  username: user["username"] as? String
114
146
  )
115
147
  )
116
- #endif
117
148
  }
118
149
 
119
150
  @objc
120
151
  func addBreadcrumb(_ breadcrumb: NSDictionary) {
121
- #if SWISSKNIFE_VENDORED || canImport(SwissKnifeiOS)
122
152
  let level = SKErrorLevel(rawValue: breadcrumb["level"] as? String ?? "info") ?? .info
123
153
  SKCrashReporting.shared.addBreadcrumb(
124
154
  SKBreadcrumb(
@@ -128,14 +158,11 @@ class SwissKnifeCrashReporting: NSObject {
128
158
  data: breadcrumb["data"] as? [String: String]
129
159
  )
130
160
  )
131
- #endif
132
161
  }
133
162
 
134
163
  @objc
135
164
  func setTag(_ key: NSString, value: NSString) {
136
- #if SWISSKNIFE_VENDORED || canImport(SwissKnifeiOS)
137
165
  SKCrashReporting.shared.setTag(key as String, value: value as String)
138
- #endif
139
166
  }
140
167
 
141
168
  // MARK: - Screenshot capture (wave-2 contract C1)
@@ -166,13 +193,9 @@ class SwissKnifeCrashReporting: NSObject {
166
193
  once.resolve(nil)
167
194
  }
168
195
 
169
- #if SWISSKNIFE_VENDORED || canImport(SwissKnifeiOS)
170
196
  DispatchQueue.main.async {
171
197
  once.resolve(SKScreenshot.captureMaskedBase64())
172
198
  }
173
- #else
174
- once.resolve(nil)
175
- #endif
176
199
  }
177
200
 
178
201
  // MARK: - Deliberate native crashes (e2e verification only)
@@ -192,11 +215,29 @@ class SwissKnifeCrashReporting: NSObject {
192
215
  /// Crash the app with SIGSEGV/SIGBUS by writing through a near-NULL
193
216
  /// pointer. Same next-launch recovery path as crashNative(), different
194
217
  /// signal.
218
+ ///
219
+ /// The store must be the ONLY thing that can fault here. The previous
220
+ /// implementation built the pointer with
221
+ /// `UnsafeMutablePointer<Int>(bitPattern: 0x10)!` — that initialiser is
222
+ /// failable purely because 0 is not a valid address, so the `!` is a
223
+ /// force-unwrap that can never actually fail. It still cost us: the
224
+ /// implicit-unwrap trap lives in the same frame as the store, and every
225
+ /// symbolicator (Sentry included) attributed the fault to "Unexpectedly
226
+ /// found nil while unwrapping an Optional value" rather than to the wild
227
+ /// write. A hook that claims "make a segfault" and reports as a nil unwrap
228
+ /// is a hook nobody can trust — the first thing a reader concludes is that
229
+ /// the harness broke before it could stage the crash.
230
+ ///
231
+ /// `unsafeBitCast` removes the Optional from the picture entirely, so the
232
+ /// only instruction that can trap is the store to 0x10 — which surfaces as
233
+ /// EXC_BAD_ACCESS / KERN_INVALID_ADDRESS at 0x10, i.e. what was asked for.
234
+ /// 0x10 rather than 0x0 keeps it a page-zero access without tripping the
235
+ /// "null pointer dereference" special-casing some tools apply to 0x0.
195
236
  @objc
196
237
  func crashNativeSegfault() {
197
238
  DispatchQueue.main.async {
198
- let pointer = UnsafeMutablePointer<Int>(bitPattern: 0x10)!
199
- pointer.pointee = 42
239
+ let pointer = unsafeBitCast(UInt(0x10), to: UnsafeMutableRawPointer.self)
240
+ pointer.storeBytes(of: UInt8(42), toByteOffset: 0, as: UInt8.self)
200
241
  }
201
242
  }
202
243
  }
@@ -246,7 +246,22 @@ class SwissKnifePurchases: RCTEventEmitter {
246
246
  }
247
247
  }
248
248
 
249
- // MARK: Identity
249
+ // MARK: Identity (legacy bridge methods — no longer called by our JS)
250
+ //
251
+ // `Purchases.logIn` / `logOut` / `getAppUserID` / `isAnonymous` in JS now
252
+ // delegate to the `Identity` module, which uses the `identity*` methods
253
+ // further down. These four stay on the spec because removing a method from
254
+ // the native-module contract breaks any app pinned to an older JS, but they
255
+ // are dead from this package's point of view.
256
+ //
257
+ // Do NOT re-point JS at them. They bottom out in the deprecated
258
+ // `SwissKnife.*` facades, and those facades are not equivalent across
259
+ // platforms: Android's `SwissKnife.logOut` bypasses `Identity.logOut` for
260
+ // the purchases gateway, and its `appUserID` / `isAnonymous` read gateway
261
+ // state whose anonymous id is a per-process random UUID rather than the
262
+ // DeviceID-derived `$SKAnonymousID:` subject this side reports. That split
263
+ // is what `packages/react-native-sdk/src/identity-parity.test.ts` exists to
264
+ // keep out of the JS surface.
250
265
 
251
266
  @objc(logIn:resolver:rejecter:)
252
267
  func logIn(_ appUserID: String,
@@ -99,7 +99,7 @@ internal enum DeviceContextProvider {
99
99
  /// Round A baseline. The build pipeline (`swiss-build`) will eventually
100
100
  /// inject this via `-D` flag, but for now keep it in source so we don't
101
101
  /// have to thread build settings through the SPM Package.swift.
102
- static let sdkVersionConstant: String = "0.2.5"
102
+ static let sdkVersionConstant: String = "0.3.0"
103
103
 
104
104
  private static let cacheLock = DispatchQueue(label: "com.swissknife.context.device")
105
105
  private static var cached: DeviceContext?
@@ -21,7 +21,7 @@
21
21
  // Cross-platform
22
22
  // --------------
23
23
  // Network.framework is available on iOS 12+ and macOS 10.14+ — within our
24
- // support floor (iOS 16, macOS 12). No `#if available` gating needed.
24
+ // support floor (iOS 15, macOS 12). No `#if available` gating needed.
25
25
 
26
26
  import Foundation
27
27
  import Network
@@ -407,6 +407,30 @@ public final class SKCrashReporting {
407
407
  self.configuration = configuration
408
408
  self.breadcrumbs = RingBuffer(capacity: configuration.maxBreadcrumbs)
409
409
 
410
+ // Wire the shared backend transport from THIS configuration.
411
+ //
412
+ // `Configuration` carries `apiKey` and `serverURL`, but nothing used
413
+ // them: every send goes IngestClient → BackendHttpClient, and that
414
+ // resolves its credentials from `SwissKnife.identityConfigSnapshot()`
415
+ // instead. A host that only calls `SKCrashReporting.start(...)` —
416
+ // which is the entire public contract of this type — therefore built
417
+ // perfectly good crash reports that could never be sent.
418
+ // `makeRequest` throws `.notConfigured` on an empty apiKey, `flush()`
419
+ // swallows it as best-effort, and the report sits on the durable disk
420
+ // queue for the life of the install. Silent, permanent, and invisible
421
+ // from the outside: detection worked, recovery worked, the report
422
+ // existed, and it went nowhere.
423
+ //
424
+ // `ensureObservabilityBackend` is idempotent (process-wide once-flag)
425
+ // and marks CORE configured only — it never starts the StoreKit
426
+ // observer, so the configureCore / configurePurchases split is
427
+ // preserved. The RN bridge already calls it immediately before this,
428
+ // so that path is unchanged.
429
+ SwissKnife.ensureObservabilityBackend(
430
+ apiKey: configuration.apiKey,
431
+ serverURL: configuration.serverURL.isEmpty ? nil : configuration.serverURL
432
+ )
433
+
410
434
  // Warm the identity cache before anything can build an event, so a
411
435
  // host that logged in BEFORE starting crash reporting is already
412
436
  // attributed. The observer below covers the opposite order.
@@ -48,10 +48,31 @@ internal enum DeviceID {
48
48
  private static var cache: [String: String] = [:]
49
49
  private static let lock = NSLock()
50
50
 
51
+ /// Environment variable that supplies the device ID outright, bypassing
52
+ /// the Keychain entirely.
53
+ ///
54
+ /// Exists for ONE caller: `SKCrashProbe`, the headless helper the live
55
+ /// crash tests spawn. A bare command-line binary has no code-signed
56
+ /// keychain identity, so `SecItemAdd` does not fail — it asks securityd to
57
+ /// prompt, and a prompt nobody can answer blocks the process forever. That
58
+ /// hung roughly three probe launches in five and papered the developer's
59
+ /// screen with keychain dialogs, all of it downstream of a device ID the
60
+ /// probe never actually needed to persist.
61
+ ///
62
+ /// Only ever read here, and only when the variable is present, so an app —
63
+ /// which never sets it — keeps the Keychain-backed path unchanged. It is
64
+ /// deliberately NOT a general override: hosts that want to choose their own
65
+ /// identifier go through `SKAnalytics.setDeviceId(_:)`.
66
+ static let overrideEnvVar = "SWISSKNIFE_DEVICE_ID_OVERRIDE"
67
+
51
68
  /// Production entry point. Returns the persistent device ID, generating
52
69
  /// and storing one on first run.
53
70
  static func get() -> String {
54
- get(service: productionService, account: defaultAccount)
71
+ if let injected = ProcessInfo.processInfo.environment[overrideEnvVar],
72
+ !injected.isEmpty {
73
+ return injected
74
+ }
75
+ return get(service: productionService, account: defaultAccount)
55
76
  }
56
77
 
57
78
  /// Test-friendly overload — allows passing a unique service per test so