@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
@@ -4,311 +4,411 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.Purchases = void 0;
7
- exports.__throwIfCoreNotConfigured = throwIfCoreNotConfigured;
8
- exports.__throwIfNotConfigured = throwIfNotConfigured;
7
+ Object.defineProperty(exports, "__throwIfCoreNotConfigured", {
8
+ enumerable: true,
9
+ get: function () {
10
+ return _config.throwIfCoreNotConfigured;
11
+ }
12
+ });
13
+ Object.defineProperty(exports, "__throwIfNotConfigured", {
14
+ enumerable: true,
15
+ get: function () {
16
+ return _config.throwIfNotConfigured;
17
+ }
18
+ });
9
19
  exports.default = void 0;
20
+ var _attributes = require("./attributes.js");
21
+ var _identity = require("./identity.js");
22
+ var _config = require("./internal/config.js");
10
23
  var _module = require("./native/module.js");
11
24
  var _spec = require("./native/spec.js");
12
25
  var _types = require("./types.js");
13
26
  // src/purchases.ts
27
+ //
28
+ // The RevenueCat-compatible surface. Everything a `react-native-purchases`
29
+ // migration can call, spelled the way RevenueCat spells it.
30
+ //
31
+ // ## What this file is, after the namespace split
32
+ //
33
+ // `Purchases` used to be the whole SDK: the store, both bootstraps, subscriber
34
+ // attributes and the identity aliases, twenty-one statics across four unrelated
35
+ // concerns — while `Identity`, `Attribution`, `Analytics`, `CrashReporting` and
36
+ // `Performance` sat beside it as peer namespaces. Two organising principles at
37
+ // once, and the seams showed: `Purchases.configureCore()` is a call whose entire
38
+ // meaning is "I do not want the store", and an app with no purchases in it set
39
+ // its user data through `Purchases.setAttributes`.
40
+ //
41
+ // The store methods below are the ones that genuinely belong here. The rest are
42
+ // **RC-compatibility aliases**, and they are not going anywhere:
43
+ //
44
+ // - bootstrap → `SwissKnife.configure` / `configureCore` / `isConfigured` /
45
+ // `isCoreConfigured` / `setLogLevel` (src/swiss-knife.ts)
46
+ // - attributes → `Attributes.set` / `setEmail` / `setDisplayName` /
47
+ // `setPhoneNumber` / `setPushToken` (src/attributes.ts)
48
+ // - identity → `Identity.logIn` / `logOut` / `current` (src/identity.ts)
49
+ //
50
+ // ## Why the aliases are not deprecated
51
+ //
52
+ // This class exists so that someone migrating off `react-native-purchases` can
53
+ // keep their call sites. Emitting deprecation warnings at exactly those call
54
+ // sites would punish the users the compatibility surface was built for — the
55
+ // migration would arrive pre-broken, with a console full of warnings for code
56
+ // that is doing the right thing. They are documented as aliases and left alone.
57
+ //
58
+ // The four identity aliases are the exception and keep their `@deprecated` tags,
59
+ // because they are a different case: `Identity` is genuinely the canonical home,
60
+ // and the RC names carry return types (`logOut` resolving a `CustomerInfo`) that
61
+ // misdescribe what the call does in a store-less app.
62
+ //
63
+ // ## Why they cannot drift
64
+ //
65
+ // The aliases are not re-implementations and not one-line wrappers: they are the
66
+ // *same function objects* as the canonical methods, assigned as static fields
67
+ // from the modules that own them. `Purchases.configure === SwissKnife.configure`
68
+ // and `Purchases.setAttributes === Attributes.set` are literally true. There is
69
+ // no second copy of the bootstrap state either — see `src/internal/config.ts`.
70
+ // Pinned by `src/namespaces.test.ts`.
14
71
 
15
- let configured = false;
16
- let configuredApiKey = null;
17
- let coreConfigured = false;
72
+ // Maps a caller's listener fn to its native subscription so we can remove it.
73
+ const customerInfoSubscriptions = new Map();
18
74
 
19
75
  /**
20
- * Read a boolean off the native module without ever letting a missing native
21
- * module escape as an exception.
76
+ * The `CustomerInfo` RC's `logOut()` resolves with, for a device that just
77
+ * became anonymous.
22
78
  *
23
- * `getNativeModule()` THROWS when the module is not linked (Expo Go, a bare RN
24
- * app that skipped `pod install` / a Gradle sync, web) — precisely the state a
25
- * developer is in while wiring the SDK up, and precisely when they are most
26
- * likely to be calling one of these accessors to find out what is wrong. A
27
- * boolean accessor rejecting with "native module is not linked" is a worse
28
- * answer than `false`: an unlinked module cannot have configured anything, so
29
- * `false` is not merely safe, it is correct.
79
+ * The store engine is the preferred source, so an app that owns the store
80
+ * keeps getting real post-logout state. Whether it can answer is decided by
81
+ * `isConfigured()` — native truth on both platforms — rather than by trying
82
+ * the read and interpreting the failure, because an *unconfigured* store does
83
+ * not fail the same way on the two platforms: iOS rejects `getCustomerInfo`
84
+ * with `notConfigured`, Android's unconfigured gateway resolves an empty
85
+ * record of its own construction. Discovering the state from the error would
86
+ * hand back two different objects for one situation, in the very module that
87
+ * exists to stop that happening.
30
88
  *
31
- * The `.catch` covers the adjacent case where the module IS linked but predates
32
- * the method (JS upgraded without rebuilding the app) — same reasoning, same
33
- * answer. Mirrors the tolerance `Analytics.init` already applies to
34
- * `configureObservability`.
89
+ * With no store engine — or with one that cannot answer right now (cold cache
90
+ * plus offline) — the caller gets the entitlement-free record below, built in
91
+ * JS so it is identical on both platforms. Logging out is not a store
92
+ * operation and must not fail because the store is unreachable.
35
93
  */
36
- function nativeBoolean(read) {
37
- try {
38
- return Promise.resolve(read((0, _module.getNativeModule)())).catch(() => false);
39
- } catch {
40
- return Promise.resolve(false);
94
+ async function customerInfoAfterLogOut() {
95
+ if (await (0, _config.nativeBoolean)(native => native.isConfigured())) {
96
+ try {
97
+ return await (0, _module.getNativeModule)().getCustomerInfo();
98
+ } catch {
99
+ // Fall through to the empty record.
100
+ }
41
101
  }
102
+ const snapshot = await _identity.Identity.current();
103
+ return emptyCustomerInfo(snapshot.userId ?? snapshot.anonymousId);
42
104
  }
43
105
 
44
- // Maps a caller's listener fn to its native subscription so we can remove it.
45
- const customerInfoSubscriptions = new Map();
46
-
47
- /**
48
- * Guard for surfaces that genuinely need the PURCHASE engine — the store APIs
49
- * and the RC-parity identity aliases that route through the store gateway on
50
- * Android. Checks the JS "configure was called" flag.
51
- */
52
- function throwIfNotConfigured() {
53
- if (!configured) {
54
- throw new _types.UninitializedPurchasesError();
55
- }
106
+ /** An entitlement-free `CustomerInfo` for `subjectId`. Mirrors the native
107
+ * `CustomerInfo.empty(originalAppUserId:)` constructors. */
108
+ function emptyCustomerInfo(subjectId) {
109
+ const now = new Date();
110
+ return {
111
+ entitlements: {
112
+ all: {},
113
+ active: {},
114
+ verification: _types.VERIFICATION_RESULT.NOT_REQUESTED
115
+ },
116
+ activeSubscriptions: [],
117
+ allPurchasedProductIdentifiers: [],
118
+ allPurchaseDates: {},
119
+ subscriptionsByProductIdentifier: {},
120
+ nonSubscriptionTransactions: [],
121
+ firstSeen: now.toISOString(),
122
+ firstSeenMillis: now.getTime(),
123
+ originalAppUserId: subjectId,
124
+ requestDate: now.toISOString(),
125
+ requestDateMillis: now.getTime(),
126
+ latestExpirationDate: null,
127
+ latestExpirationDateMillis: null,
128
+ originalPurchaseDate: null,
129
+ originalPurchaseDateMillis: null,
130
+ originalApplicationVersion: null,
131
+ managementURL: null
132
+ };
56
133
  }
57
134
 
58
135
  /**
59
- * Guard for surfaces that only need CORE — the subscriber-attribute setters.
60
- *
61
- * Attributes describe the *person*, not the purchase: natively they land in
62
- * `AttributesClient` → `POST /api/sdk/users/attributes` → `app_users.properties`,
63
- * which is what the dashboard person card reads. Neither platform's attributes
64
- * path touches StoreKit or Play Billing — iOS gates on `SwissKnife.isCoreConfigured`
65
- * (`SwissKnife.currentAnonymousIdForAttributes`), and Android's `configureCore`
66
- * wires `AttributesClient` with an `Identity`-snapshot id fallback precisely so a
67
- * store-less app still resolves ids. Gating these on the purchase flag left an app
68
- * that uses `configureCore` (because another library owns the store) with **no way
69
- * at all** to populate the person card.
136
+ * RC-compatible subscriptions SDK entry point. Process-wide singleton.
70
137
  *
71
- * Two-step check, and the second step is load-bearing:
72
- *
73
- * 1. The JS flag, set by `configure` / `configureCore`. Free, no bridge hop.
74
- * 2. Native truth. `Analytics.init(...)` wires core natively via
75
- * `configureObservability` and touches no JS flag, so an analytics-only app
76
- * has core configured while every JS flag reads `false` — exactly the case
77
- * {@link isCoreConfigured} documents. Skipping this step would keep the most
78
- * common core-only integration broken.
79
- *
80
- * Never consults the purchase flag. Strictly more permissive than
81
- * {@link throwIfNotConfigured}, so no existing caller can break.
82
- */
83
- async function throwIfCoreNotConfigured() {
84
- if (coreConfigured) return;
85
- if (await nativeBoolean(native => native.isCoreConfigured())) return;
86
- throw new _types.UninitializedPurchasesError("Purchases core is not configured. Call Purchases.configure(), " + "Purchases.configureCore(), or Analytics.init() first.");
87
- }
88
-
89
- /**
90
- * RC-compatible subscriptions SDK entry point. Process-wide singleton; call
91
- * `Purchases.configure(...)` once at app start, then use the static methods.
138
+ * New code should bootstrap through {@link SwissKnife} — `SwissKnife.configure(…)`
139
+ * — and reach the store through this class. Code migrating from
140
+ * `react-native-purchases` can keep calling `Purchases.configure(…)`: it is the
141
+ * same function.
92
142
  */
93
143
  class Purchases {
144
+ // MARK: - Bootstrap (RC-compatibility aliases for `SwissKnife.*`)
145
+ //
146
+ // Assigned, not wrapped: these ARE `SwissKnife.configure` and friends. The
147
+ // configure state lives in one module (`./internal/config`), so mixing the two
148
+ // spellings in one app is not merely allowed, it is indistinguishable.
149
+
94
150
  /**
95
151
  * Configure the SDK. Must be called before any other method. Calling again
96
- * with the same API key is a no-op (matches the common "configure once" guard);
97
- * the native layer owns full reconfiguration.
152
+ * with the same API key is a no-op; the native layer owns full reconfiguration.
153
+ *
154
+ * RC-compatibility alias for `SwissKnife.configure(...)` — the same function
155
+ * under the name `react-native-purchases` uses. Neither is deprecated.
98
156
  */
99
- static configure(options) {
100
- if (configured && configuredApiKey === options.apiKey) return;
101
- const native = (0, _module.getNativeModule)();
102
- const nativeOptions = {
103
- apiKey: options.apiKey,
104
- appUserID: options.appUserID ?? null,
105
- // proxyURL points the native SDK at the Swiss Knife backend. Without it the
106
- // native layer falls back to its hardcoded default host (api.swiss-knife.dev),
107
- // which is unreachable for self-hosted tenants. Forward it so callers can
108
- // target their own backend (e.g. https://swiss.remneys.com).
109
- proxyURL: options.proxyURL ?? null,
110
- // Hardening pass (spec): diagnostics opt-in only — default OFF.
111
- diagnosticsEnabled: options.diagnosticsEnabled ?? false,
112
- storeKitVersion: options.storeKitVersion,
113
- useAmazon: options.useAmazon,
114
- // iOS ATT — default off (no tracking prompt) unless the host opts in.
115
- autoPromptATT: options.autoPromptATT,
116
- sendInstallOnFirstLaunch: options.sendInstallOnFirstLaunch,
117
- logLevel: options.logLevel
118
- };
119
- // Fire-and-forget: native configure resolves async but RC's configure is sync.
120
- void native.configure(nativeOptions);
121
- configured = true;
122
- coreConfigured = true;
123
- configuredApiKey = options.apiKey;
124
- }
157
+ static configure = _config.configure;
125
158
 
126
159
  /**
127
160
  * Configure everything EXCEPT the store: ingest, `Identity`, `Attribution`,
128
- * subscriber attributes.
161
+ * `Attributes`. Use it when another library already owns in-app purchases.
129
162
  *
130
- * Use this when another library already owns in-app purchases. `configure`
131
- * starts a `StoreKit.Transaction.updates` observer on iOS (whose handler
132
- * calls `transaction.finish()`) and builds a `BillingClient` on Android —
133
- * both of which contend with an incumbent IAP SDK. `configureCore` creates
134
- * neither, and registers no install as a side effect.
135
- *
136
- * Analytics-only apps don't even need this: `Analytics.init(...)` already
137
- * wires core natively. Reach for `configureCore` when you want to pass an
138
- * `appUserID`, an attribution configuration, or a log level up front.
163
+ * Alias for `SwissKnife.configureCore(...)`, which is the name that actually
164
+ * describes the call — nothing about this method concerns purchases, and it is
165
+ * only spelled `Purchases.configureCore` here so that no existing call site
166
+ * breaks. Prefer the `SwissKnife` spelling in new code.
139
167
  */
140
- static configureCore(options) {
141
- if (coreConfigured && configuredApiKey === options.apiKey) return;
142
- const native = (0, _module.getNativeModule)();
143
- const nativeOptions = {
144
- apiKey: options.apiKey,
145
- appUserID: options.appUserID ?? null,
146
- proxyURL: options.proxyURL ?? null,
147
- diagnosticsEnabled: options.diagnosticsEnabled ?? false,
148
- autoPromptATT: options.autoPromptATT,
149
- // Forwarded but inert on this path — core never auto-registers an
150
- // install. Kept on the payload so the same options object can be handed
151
- // to `configure` later without surprises.
152
- sendInstallOnFirstLaunch: options.sendInstallOnFirstLaunch,
153
- logLevel: options.logLevel
154
- };
155
- void native.configureCore(nativeOptions);
156
- coreConfigured = true;
157
- configuredApiKey = options.apiKey;
158
- }
168
+ static configureCore = _config.configureCore;
159
169
 
160
170
  /**
161
171
  * Whether the PURCHASE engine has been configured — i.e. whether the store
162
- * APIs (`getOfferings`, `purchasePackage`, `restorePurchases`, …) can work.
172
+ * APIs below can work. Native is the source of truth; never throws or rejects.
163
173
  *
164
- * **Native is the source of truth.** This does not consult the JS-side
165
- * "configure was called" flag: a brownfield app can configure the SDK from
166
- * native code, and `Purchases.configure` itself is fire-and-forget, so the
167
- * JS flag is a request, not a fact.
168
- *
169
- * Never throws and never rejects. Resolves `false` when the native module is
170
- * not linked — see {@link nativeBoolean}. Exactly the same failure semantics
171
- * as {@link isCoreConfigured}; the two differ only in which native flag they
172
- * report.
174
+ * RC-compatibility alias for `SwissKnife.isConfigured()`.
173
175
  */
174
- static isConfigured() {
175
- return nativeBoolean(native => native.isConfigured());
176
- }
176
+ static isConfigured = _config.isConfigured;
177
177
 
178
178
  /**
179
- * Whether the CORE (ingest / Identity / Attribution / attributes) is
179
+ * Whether the CORE (ingest / Identity / Attribution / Attributes) is
180
180
  * configured. True after `configure`, `configureCore`, or `Analytics.init`.
181
+ * Native is the source of truth; never throws or rejects.
181
182
  *
182
- * **Native is the source of truth**, and here that is load-bearing rather
183
- * than merely principled: `Analytics.init` wires core natively via
184
- * `configureObservability` and touches no JS configure flag, so an
185
- * analytics-only app has core configured while every JS flag reads false.
186
- * Short-circuiting on JS state would report `false` in the single most
187
- * common core-only integration.
183
+ * Alias for `SwissKnife.isCoreConfigured()`.
184
+ */
185
+ static isCoreConfigured = _config.isCoreConfigured;
186
+
187
+ /**
188
+ * Set the native log level. Process-wide — it governs the store engine, the
189
+ * ingest client, Identity, Attribution and the observability modules alike.
188
190
  *
189
- * Never throws and never rejects. Resolves `false` when the native module is
190
- * not linked — see {@link nativeBoolean}.
191
+ * Alias for `SwissKnife.setLogLevel(...)`, which is where a process-wide
192
+ * setting belongs (and where both native SDKs already put it).
191
193
  */
192
- static isCoreConfigured() {
193
- return nativeBoolean(native => native.isCoreConfigured());
194
- }
194
+ static setLogLevel = _config.setLogLevel;
195
+
196
+ // MARK: - The store
197
+ //
198
+ // These are the methods that genuinely belong on `Purchases`. All of them are
199
+ // gated on the PURCHASE flag.
195
200
 
196
201
  /** Latest CustomerInfo (entitlements + subscriptions), computed server-side. */
197
202
  static async getCustomerInfo() {
198
- throwIfNotConfigured();
203
+ (0, _config.throwIfNotConfigured)();
199
204
  return (0, _module.getNativeModule)().getCustomerInfo();
200
205
  }
201
206
 
202
207
  /** Current + all offerings configured for this app. */
203
208
  static async getOfferings() {
204
- throwIfNotConfigured();
209
+ (0, _config.throwIfNotConfigured)();
205
210
  return (0, _module.getNativeModule)().getOfferings();
206
211
  }
207
212
 
208
213
  /** Purchase a package from an offering. Drives the native store payment sheet. */
209
214
  static async purchasePackage(pkg) {
210
- throwIfNotConfigured();
215
+ (0, _config.throwIfNotConfigured)();
211
216
  const offeringId = pkg.presentedOfferingContext?.offeringIdentifier ?? '';
212
217
  return (0, _module.getNativeModule)().purchasePackage(pkg.identifier, offeringId);
213
218
  }
214
219
 
215
220
  /** Purchase a store product directly by its store SKU. */
216
221
  static async purchaseStoreProduct(product) {
217
- throwIfNotConfigured();
222
+ (0, _config.throwIfNotConfigured)();
218
223
  return (0, _module.getNativeModule)().purchaseStoreProduct(product.identifier);
219
224
  }
220
225
 
221
226
  /** Restore purchases tied to the underlying store account. */
222
227
  static async restorePurchases() {
223
- throwIfNotConfigured();
228
+ (0, _config.throwIfNotConfigured)();
224
229
  return (0, _module.getNativeModule)().restorePurchases();
225
230
  }
226
231
 
227
- // The four RC-parity identity aliases below stay on the PURCHASE guard on
228
- // purpose, even though identity is a core concern natively. The two platforms
229
- // disagree about what this specific surface does: the iOS bridge's `logIn`
230
- // reaches `SwissKnife.logIn` → `Identity.logIn`, which is core-gated and POSTs
231
- // `/api/sdk/users/identify`; the Android bridge's `logIn` reaches
232
- // `SwissKnife.logIn` → the purchases `gateway`, which only rebinds the local
233
- // user id and refreshes entitlements. Loosening the guard here would let a
234
- // core-only app call a method that means different things per platform and
235
- // silently skips the identify POST on Android. `Identity.logIn` / `logOut` /
236
- // `current` are the core-safe surface — they route to the unified native
237
- // Identity on both platforms and carry no configure guard in JS at all.
232
+ // MARK: - RC-parity identity aliases
233
+ //
234
+ // ## The guarantee
235
+ //
236
+ // Each of the four aliases below is *exactly* its {@link Identity}
237
+ // counterpart with the RevenueCat name and the RevenueCat return type, on
238
+ // BOTH platforms. There is no per-platform behaviour left in them: they are
239
+ // one-line delegations to `Identity`, which reaches the `identityLogIn` /
240
+ // `identityLogOut` / `identityCurrent` native bridge methods — and those go
241
+ // to the unified native `Identity` (`SwissKnife.Identity` on iOS,
242
+ // `com.appswissknife.identity.Identity` on Android) on both. Concretely, a
243
+ // `Purchases.logIn(...)` POSTs `/api/sdk/users/identify` on iOS AND on
244
+ // Android. Pinned by `identity-parity.test.ts`.
245
+ //
246
+ // ## Why they are written as delegations rather than bridge calls
247
+ //
248
+ // They used to call the legacy `logIn` / `logOut` / `getAppUserID` /
249
+ // `isAnonymous` bridge methods, which bottom out in the *deprecated native
250
+ // facades* — and those facades do NOT agree across platforms:
251
+ //
252
+ // - `logOut`: iOS `SwissKnife.logOut` routes to `Identity.logOut`;
253
+ // Android's routes straight to the purchases `gateway` and only
254
+ // back-syncs Identity's snapshot afterwards.
255
+ // - `getAppUserID`: iOS returns the Identity-synced subject (a stable
256
+ // `$SKAnonymousID:`+DeviceID value when anonymous); Android returns
257
+ // `gateway.getAppUserID()`, whose anonymous form is a fresh random UUID
258
+ // minted per process and unrelated to `Identity.current().anonymousId`.
259
+ // - `isAnonymous`: iOS reads Identity-synced state; Android reads the
260
+ // gateway's, which `Identity.reset()` / `Identity.wipe()` never touch.
261
+ //
262
+ // Delegating in JS makes the RN surface immune to all of that, and it is the
263
+ // only version of the fix that is verifiable from this repo's test suites.
264
+ // The legacy bridge methods stay on the native-module spec (removing them
265
+ // would break the native contract) but nothing in this package calls them
266
+ // any more.
267
+ //
268
+ // ## Second bug this closes
269
+ //
270
+ // `Identity` keeps JS-side caches (`lastSnapshot`, `lastLogIn`) that let a
271
+ // repeat `Identity.logIn(sameId)` skip the bridge. An alias that mutated
272
+ // native identity behind `Identity`'s back left those caches describing a
273
+ // world that no longer existed — after `Identity.logIn("u")` +
274
+ // `Purchases.logOut()`, a following `Identity.logIn("u")` short-circuited on
275
+ // the stale cache and resolved "logged in" without the device ever being
276
+ // re-identified. Routing through `Identity` means one owner for that state.
277
+ //
278
+ // ## Why these four ARE deprecated, when the aliases above are not
279
+ //
280
+ // The bootstrap and attribute aliases are pure renames: same arguments, same
281
+ // return type, same behaviour, and keeping them costs a migrating app nothing.
282
+ // These four are not. `logOut` returns a `CustomerInfo` that is fabricated in
283
+ // a store-less app, `getAppUserID` collapses a three-field snapshot into one
284
+ // string, and `isAnonymous` forces a second round trip to learn what
285
+ // `Identity.current()` already returned. The RC names describe the RC model,
286
+ // not ours, so `Identity.*` is genuinely the better call and not merely the
287
+ // better-organised one. They still work, and will keep working.
288
+ //
289
+ // ## The guard
290
+ //
291
+ // These sit on `throwIfCoreNotConfigured`, not on the purchase guard.
292
+ // Identity is a core capability — natively both platforms gate it on
293
+ // `isCoreConfigured` — and the single most likely caller of
294
+ // `Purchases.logIn` is an app migrating off RevenueCat that still lets
295
+ // RevenueCat own the store, i.e. one that called `configureCore`. Gating the
296
+ // RC-named alias on the purchase engine would reject exactly that app while
297
+ // the identical `Identity.logIn` call succeeded. The guard is not dropped
298
+ // entirely, because `Identity.current()` before any configure returns a
299
+ // real snapshot on iOS and a `{anonymousId: ""}` placeholder on Android —
300
+ // requiring core is what makes even that case agree.
238
301
 
239
302
  /**
240
- * Identify the user. Aliases/merges anonymous purchases server-side.
303
+ * Identify the user, merging the anonymous subject into `appUserID`
304
+ * server-side.
241
305
  *
242
- * @deprecated Wave 1 — prefer `Identity.logIn(userId)`. Routes through
243
- * the unified Identity surface natively, so the bug fix (Android now
244
- * POSTs `/api/sdk/users/identify`) applies whether you call this or
245
- * `Identity.logIn(...)`.
306
+ * Exactly `Identity.logIn(appUserID)` with the RevenueCat name. On both
307
+ * platforms this POSTs `(anonymous_id, user_id)` to
308
+ * `/api/sdk/users/identify` and resolves once the backend ack and the
309
+ * post-identify entitlements refresh complete; a rejection means the device
310
+ * is NOT merged server-side and the call must be retried. Repeat calls with
311
+ * the id already in effect are free (no bridge hop, no request).
312
+ *
313
+ * Works after `SwissKnife.configure`, `SwissKnife.configureCore`, or
314
+ * `Analytics.init` — the store does not have to be ours.
315
+ *
316
+ * @deprecated Wave 1 — prefer `Identity.logIn(userId)`. This alias exists so
317
+ * RevenueCat migrations compile unchanged; it is a pure delegation, so there
318
+ * is nothing to gain by keeping it and one less name to learn by dropping it.
246
319
  */
247
320
  static async logIn(appUserID) {
248
- throwIfNotConfigured();
249
- return (0, _module.getNativeModule)().logIn(appUserID);
321
+ await (0, _config.throwIfCoreNotConfigured)();
322
+ return _identity.Identity.logIn(appUserID);
250
323
  }
251
324
 
252
325
  /**
253
- * Log out the current user and revert to anonymous.
326
+ * Log out the current user and revert to anonymous. The device id survives,
327
+ * so analytics continuity for the same physical install is preserved.
328
+ *
329
+ * Exactly `Identity.logOut()` with the RevenueCat name, plus RC's
330
+ * `CustomerInfo` return: after the logout lands, the post-logout customer
331
+ * info is read back from the store engine. **When no store engine is
332
+ * configured** (`configureCore`, `Analytics.init`) there is nothing to read,
333
+ * and you get an entitlement-free `CustomerInfo` for the anonymous subject —
334
+ * the same record, built in JS, on both platforms. Do not read that as a
335
+ * store error; if you want real entitlements, call `getCustomerInfo()`.
254
336
  *
255
- * @deprecated Wave 1 — prefer `Identity.logOut()`.
337
+ * @deprecated Wave 1 — prefer `Identity.logOut()`, which does not pretend to
338
+ * return store state.
256
339
  */
257
340
  static async logOut() {
258
- throwIfNotConfigured();
259
- return (0, _module.getNativeModule)().logOut();
341
+ await (0, _config.throwIfCoreNotConfigured)();
342
+ await _identity.Identity.logOut();
343
+ return customerInfoAfterLogOut();
260
344
  }
261
345
 
262
- /** The current app user id (anonymous or identified). */
346
+ /**
347
+ * The current subject id — the identified user id if there is one, else the
348
+ * SDK's anonymous id (`$SKAnonymousID:`-prefixed, stable across launches).
349
+ *
350
+ * Exactly `(await Identity.current()).userId ?? .anonymousId`. Note this is
351
+ * the *Identity* subject on both platforms; on Android the purchase
352
+ * gateway's own anonymous id is a different, per-process value, and this
353
+ * alias deliberately does not report it.
354
+ *
355
+ * @deprecated Wave 1 — prefer `Identity.current()`, which hands back the
356
+ * anonymous id, the user id and `isAnonymous` in one read instead of forcing
357
+ * two calls that can interleave.
358
+ */
263
359
  static async getAppUserID() {
264
- throwIfNotConfigured();
265
- return (0, _module.getNativeModule)().getAppUserID();
360
+ await (0, _config.throwIfCoreNotConfigured)();
361
+ const snapshot = await _identity.Identity.current();
362
+ return snapshot.userId ?? snapshot.anonymousId;
266
363
  }
267
364
 
268
- /** Whether the current user id is an SDK-generated anonymous id. */
365
+ /**
366
+ * Whether the current subject is the SDK-generated anonymous id.
367
+ *
368
+ * Exactly `(await Identity.current()).isAnonymous`, so it tracks
369
+ * `Identity.reset()` and `Identity.wipe()` on both platforms.
370
+ *
371
+ * @deprecated Wave 1 — prefer `Identity.current()`; see
372
+ * {@link getAppUserID}.
373
+ */
269
374
  static async isAnonymous() {
270
- throwIfNotConfigured();
271
- return (0, _module.getNativeModule)().isAnonymous();
375
+ await (0, _config.throwIfCoreNotConfigured)();
376
+ return (await _identity.Identity.current()).isAnonymous;
272
377
  }
273
378
 
274
- // Subscriber attributes. CORE, not store — see {@link throwIfCoreNotConfigured}.
275
- // These work in an app that only called `configureCore` (another library owns
276
- // the store) or only `Analytics.init`.
379
+ // MARK: - Subscriber attributes (RC-compatibility aliases for `Attributes.*`)
380
+ //
381
+ // CORE, not store: all five are gated on `throwIfCoreNotConfigured`, so they
382
+ // work in an app that only called `configureCore` (another library owns the
383
+ // store) or only `Analytics.init`. That is the tell that they never belonged
384
+ // on this class — an app with no purchases at all still needs them, because
385
+ // they are the only path to the dashboard person card.
386
+ //
387
+ // Assigned, not wrapped: `Purchases.setAttributes === Attributes.set`.
277
388
 
278
- /** Set arbitrary subscriber attributes. null clears an attribute. */
279
- static async setAttributes(attributes) {
280
- await throwIfCoreNotConfigured();
281
- return (0, _module.getNativeModule)().setAttributes(attributes);
282
- }
389
+ /**
390
+ * Set arbitrary subscriber attributes. `null` clears an attribute.
391
+ *
392
+ * RC-compatibility alias for `Attributes.set(...)`. Not deprecated.
393
+ */
394
+ static setAttributes = _attributes.Attributes.set;
283
395
 
284
- /** Reserved attribute: email. */
285
- static async setEmail(email) {
286
- await throwIfCoreNotConfigured();
287
- return (0, _module.getNativeModule)().setEmail(email);
288
- }
396
+ /** Reserved attribute: email. Alias for `Attributes.setEmail(...)`. */
397
+ static setEmail = _attributes.Attributes.setEmail;
289
398
 
290
- /** Reserved attribute: display name. */
291
- static async setDisplayName(displayName) {
292
- await throwIfCoreNotConfigured();
293
- return (0, _module.getNativeModule)().setDisplayName(displayName);
294
- }
399
+ /** Reserved attribute: display name. Alias for `Attributes.setDisplayName(...)`. */
400
+ static setDisplayName = _attributes.Attributes.setDisplayName;
295
401
 
296
- /** Reserved attribute: phone number. */
297
- static async setPhoneNumber(phoneNumber) {
298
- await throwIfCoreNotConfigured();
299
- return (0, _module.getNativeModule)().setPhoneNumber(phoneNumber);
300
- }
402
+ /** Reserved attribute: phone number. Alias for `Attributes.setPhoneNumber(...)`. */
403
+ static setPhoneNumber = _attributes.Attributes.setPhoneNumber;
301
404
 
302
- /** Reserved attribute: push token. */
303
- static async setPushToken(pushToken) {
304
- await throwIfCoreNotConfigured();
305
- return (0, _module.getNativeModule)().setPushToken(pushToken);
306
- }
405
+ /** Reserved attribute: push token. Alias for `Attributes.setPushToken(...)`. */
406
+ static setPushToken = _attributes.Attributes.setPushToken;
307
407
 
308
- /** Set the native log level. Accepts a LOG_LEVEL enum value. */
309
- static async setLogLevel(level) {
310
- return (0, _module.getNativeModule)().setLogLevel(level);
311
- }
408
+ // MARK: - CustomerInfo listeners
409
+ //
410
+ // Store surface: these fire on purchase, renewal and dashboard grant, so they
411
+ // stay here rather than moving to the root.
312
412
 
313
413
  /** Subscribe to CustomerInfo changes (purchase, renewal, dashboard grant). */
314
414
  static addCustomerInfoUpdateListener(listener) {
@@ -325,12 +425,18 @@ class Purchases {
325
425
  }
326
426
  }
327
427
 
328
- /** @internal Test seam: reset singleton state between tests. */
428
+ /**
429
+ * @internal Test seam: reset singleton state between tests.
430
+ *
431
+ * Also resets `Identity`'s caches, because the RC-parity aliases delegate
432
+ * there: without it, a `Purchases.logIn("u")` in one test would leave
433
+ * `Identity`'s `lastLogIn` primed and the next test's identical call would
434
+ * short-circuit before reaching the (freshly mocked) bridge.
435
+ */
329
436
  static __resetForTests() {
330
- configured = false;
331
- coreConfigured = false;
332
- configuredApiKey = null;
437
+ (0, _config.resetConfigForTests)();
333
438
  customerInfoSubscriptions.clear();
439
+ _identity.Identity.__resetForTests();
334
440
  }
335
441
  }
336
442