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