@app-swiss-knife/react-native-sdk 0.2.7 → 0.3.1

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 (66) hide show
  1. package/README.md +100 -47
  2. package/SwissKnifePurchases.podspec +8 -5
  3. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  4. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +1 -1
  5. package/ios/SwissKnifeCrashReporting.swift +59 -18
  6. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  7. package/ios/vendor/SwissKnifeiOS/Context/Reachability.swift +1 -1
  8. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +51 -1
  9. package/ios/vendor/SwissKnifeiOS/DeviceID.swift +22 -1
  10. package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +105 -7
  11. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +14 -0
  12. package/lib/commonjs/attributes.js +103 -0
  13. package/lib/commonjs/attributes.js.map +1 -0
  14. package/lib/commonjs/index.js +31 -2
  15. package/lib/commonjs/index.js.map +1 -1
  16. package/lib/commonjs/internal/config.js +237 -0
  17. package/lib/commonjs/internal/config.js.map +1 -0
  18. package/lib/commonjs/purchases.js +152 -209
  19. package/lib/commonjs/purchases.js.map +1 -1
  20. package/lib/commonjs/swiss-knife.js +115 -0
  21. package/lib/commonjs/swiss-knife.js.map +1 -0
  22. package/lib/commonjs/types.js +11 -0
  23. package/lib/commonjs/types.js.map +1 -1
  24. package/lib/module/attributes.js +100 -0
  25. package/lib/module/attributes.js.map +1 -0
  26. package/lib/module/index.js +19 -2
  27. package/lib/module/index.js.map +1 -1
  28. package/lib/module/internal/config.js +225 -0
  29. package/lib/module/internal/config.js.map +1 -0
  30. package/lib/module/purchases.js +132 -198
  31. package/lib/module/purchases.js.map +1 -1
  32. package/lib/module/swiss-knife.js +112 -0
  33. package/lib/module/swiss-knife.js.map +1 -0
  34. package/lib/module/types.js +11 -0
  35. package/lib/module/types.js.map +1 -1
  36. package/lib/typescript/commonjs/attributes.d.ts +41 -0
  37. package/lib/typescript/commonjs/attributes.d.ts.map +1 -0
  38. package/lib/typescript/commonjs/index.d.ts +2 -0
  39. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  40. package/lib/typescript/commonjs/internal/config.d.ts +121 -0
  41. package/lib/typescript/commonjs/internal/config.d.ts.map +1 -0
  42. package/lib/typescript/commonjs/purchases.d.ts +47 -91
  43. package/lib/typescript/commonjs/purchases.d.ts.map +1 -1
  44. package/lib/typescript/commonjs/swiss-knife.d.ts +56 -0
  45. package/lib/typescript/commonjs/swiss-knife.d.ts.map +1 -0
  46. package/lib/typescript/commonjs/types.d.ts +13 -0
  47. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  48. package/lib/typescript/module/attributes.d.ts +41 -0
  49. package/lib/typescript/module/attributes.d.ts.map +1 -0
  50. package/lib/typescript/module/index.d.ts +2 -0
  51. package/lib/typescript/module/index.d.ts.map +1 -1
  52. package/lib/typescript/module/internal/config.d.ts +121 -0
  53. package/lib/typescript/module/internal/config.d.ts.map +1 -0
  54. package/lib/typescript/module/purchases.d.ts +47 -91
  55. package/lib/typescript/module/purchases.d.ts.map +1 -1
  56. package/lib/typescript/module/swiss-knife.d.ts +56 -0
  57. package/lib/typescript/module/swiss-knife.d.ts.map +1 -0
  58. package/lib/typescript/module/types.d.ts +13 -0
  59. package/lib/typescript/module/types.d.ts.map +1 -1
  60. package/package.json +1 -1
  61. package/src/attributes.ts +97 -0
  62. package/src/index.ts +19 -2
  63. package/src/internal/config.ts +233 -0
  64. package/src/purchases.ts +142 -213
  65. package/src/swiss-knife.ts +134 -0
  66. 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.
@@ -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.7"
45
+ const val SDK_VERSION: String = "0.3.1"
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.7",
211
+ sdkVersion = "0.3.1",
212
212
  bundleIdentifier = null,
213
213
  )
214
214
  }
@@ -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
  }
@@ -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.7"
102
+ static let sdkVersionConstant: String = "0.3.1"
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.
@@ -1009,6 +1033,13 @@ public final class SKCrashReporting {
1009
1033
  return frames
1010
1034
  }
1011
1035
 
1036
+ /// Path of the running app bundle, resolved once. Everything dyld loaded
1037
+ /// from under it is the app; everything else is the system or the OS's
1038
+ /// shared cache. Resolved lazily rather than at init because this is only
1039
+ /// ever needed while BUILDING a report — never inside a signal handler,
1040
+ /// where a Foundation call would be unsafe.
1041
+ private static let appBundlePath: String = Bundle.main.bundlePath
1042
+
1012
1043
  /// Resolve a single instruction address into a structured frame via
1013
1044
  /// `dladdr()` — symbol name, image name, in-app heuristic. The raw
1014
1045
  /// address is always carried in `instructionAddress` for server-side
@@ -1024,13 +1055,32 @@ public final class SKCrashReporting {
1024
1055
 
1025
1056
  if resolved {
1026
1057
  symbolName = info.dli_sname.map { String(cString: $0) }
1058
+ var imagePath: String?
1027
1059
  if let fname = info.dli_fname {
1028
1060
  let fullPath = String(cString: fname)
1061
+ imagePath = fullPath
1029
1062
  imageName = (fullPath as NSString).lastPathComponent
1030
1063
  } else {
1031
1064
  imageName = nil
1032
1065
  }
1033
- if let appExec = appExecutable {
1066
+ // Anything loaded from INSIDE the app bundle is the app: the main
1067
+ // executable and every embedded framework under `.../Frameworks/`.
1068
+ // System images live in /usr/lib, /System/Library, or the dyld
1069
+ // shared cache, none of which are under the bundle.
1070
+ //
1071
+ // Comparing against the main executable alone — which is what this
1072
+ // did — marks the entire native stack of a React Native app as
1073
+ // NOT-in-app, because such an app's native code is essentially all
1074
+ // frameworks: React, Hermes, whatever the host embeds. Server-side
1075
+ // grouping drops non-in-app frames before fingerprinting, so a
1076
+ // stack of 35 real frames contributed NOTHING and every SIGSEGV in
1077
+ // the app fell back to the constant "Signal|Signal 11" and landed
1078
+ // in one undifferentiated issue.
1079
+ if let path = imagePath,
1080
+ !SKCrashReporting.appBundlePath.isEmpty,
1081
+ path.hasPrefix(SKCrashReporting.appBundlePath) {
1082
+ isInApp = true
1083
+ } else if let appExec = appExecutable {
1034
1084
  isInApp = imageName == appExec
1035
1085
  } else {
1036
1086
  let img = imageName ?? ""
@@ -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