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

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.
package/src/purchases.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  // src/purchases.ts
2
+ import { Identity } from "./identity";
2
3
  import { getNativeModule, getEventEmitter } from "./native/module";
3
4
  import { CUSTOMER_INFO_UPDATED_EVENT } from "./native/spec";
4
- import { UninitializedPurchasesError } from "./types";
5
+ import { UninitializedPurchasesError, VERIFICATION_RESULT } from "./types";
5
6
  import type { EmitterSubscription } from "react-native";
6
7
  import type {
7
8
  PurchasesConfiguration,
@@ -57,9 +58,14 @@ const customerInfoSubscriptions = new Map<
57
58
  >();
58
59
 
59
60
  /**
60
- * Guard for surfaces that genuinely need the PURCHASE engine — the store APIs
61
- * and the RC-parity identity aliases that route through the store gateway on
62
- * Android. Checks the JS "configure was called" flag.
61
+ * Guard for surfaces that genuinely need the PURCHASE engine — `getOfferings`,
62
+ * `purchasePackage`, `restorePurchases` and friends. Checks the JS "configure
63
+ * was called" flag.
64
+ *
65
+ * The RC-parity identity aliases used to sit here too, on the grounds that the
66
+ * legacy native bridge methods they called meant different things on iOS and
67
+ * Android. They now delegate to `Identity` and sit on
68
+ * {@link throwIfCoreNotConfigured} — see the block above `logIn`.
63
69
  */
64
70
  function throwIfNotConfigured(): void {
65
71
  if (!configured) {
@@ -101,6 +107,66 @@ async function throwIfCoreNotConfigured(): Promise<void> {
101
107
  );
102
108
  }
103
109
 
110
+ /**
111
+ * The `CustomerInfo` RC's `logOut()` resolves with, for a device that just
112
+ * became anonymous.
113
+ *
114
+ * The store engine is the preferred source, so an app that owns the store
115
+ * keeps getting real post-logout state. Whether it can answer is decided by
116
+ * `isConfigured()` — native truth on both platforms — rather than by trying
117
+ * the read and interpreting the failure, because an *unconfigured* store does
118
+ * not fail the same way on the two platforms: iOS rejects `getCustomerInfo`
119
+ * with `notConfigured`, Android's unconfigured gateway resolves an empty
120
+ * record of its own construction. Discovering the state from the error would
121
+ * hand back two different objects for one situation, in the very module that
122
+ * exists to stop that happening.
123
+ *
124
+ * With no store engine — or with one that cannot answer right now (cold cache
125
+ * plus offline) — the caller gets the entitlement-free record below, built in
126
+ * JS so it is identical on both platforms. Logging out is not a store
127
+ * operation and must not fail because the store is unreachable.
128
+ */
129
+ async function customerInfoAfterLogOut(): Promise<CustomerInfo> {
130
+ if (await nativeBoolean((native) => native.isConfigured())) {
131
+ try {
132
+ return await getNativeModule().getCustomerInfo();
133
+ } catch {
134
+ // Fall through to the empty record.
135
+ }
136
+ }
137
+ const snapshot = await Identity.current();
138
+ return emptyCustomerInfo(snapshot.userId ?? snapshot.anonymousId);
139
+ }
140
+
141
+ /** An entitlement-free `CustomerInfo` for `subjectId`. Mirrors the native
142
+ * `CustomerInfo.empty(originalAppUserId:)` constructors. */
143
+ function emptyCustomerInfo(subjectId: string): CustomerInfo {
144
+ const now = new Date();
145
+ return {
146
+ entitlements: {
147
+ all: {},
148
+ active: {},
149
+ verification: VERIFICATION_RESULT.NOT_REQUESTED,
150
+ },
151
+ activeSubscriptions: [],
152
+ allPurchasedProductIdentifiers: [],
153
+ allPurchaseDates: {},
154
+ subscriptionsByProductIdentifier: {},
155
+ nonSubscriptionTransactions: [],
156
+ firstSeen: now.toISOString(),
157
+ firstSeenMillis: now.getTime(),
158
+ originalAppUserId: subjectId,
159
+ requestDate: now.toISOString(),
160
+ requestDateMillis: now.getTime(),
161
+ latestExpirationDate: null,
162
+ latestExpirationDateMillis: null,
163
+ originalPurchaseDate: null,
164
+ originalPurchaseDateMillis: null,
165
+ originalApplicationVersion: null,
166
+ managementURL: null,
167
+ };
168
+ }
169
+
104
170
  /**
105
171
  * RC-compatible subscriptions SDK entry point. Process-wide singleton; call
106
172
  * `Purchases.configure(...)` once at app start, then use the static methods.
@@ -245,51 +311,140 @@ export class Purchases {
245
311
  return getNativeModule().restorePurchases();
246
312
  }
247
313
 
248
- // The four RC-parity identity aliases below stay on the PURCHASE guard on
249
- // purpose, even though identity is a core concern natively. The two platforms
250
- // disagree about what this specific surface does: the iOS bridge's `logIn`
251
- // reaches `SwissKnife.logIn` → `Identity.logIn`, which is core-gated and POSTs
252
- // `/api/sdk/users/identify`; the Android bridge's `logIn` reaches
253
- // `SwissKnife.logIn` → the purchases `gateway`, which only rebinds the local
254
- // user id and refreshes entitlements. Loosening the guard here would let a
255
- // core-only app call a method that means different things per platform and
256
- // silently skips the identify POST on Android. `Identity.logIn` / `logOut` /
257
- // `current` are the core-safe surface — they route to the unified native
258
- // Identity on both platforms and carry no configure guard in JS at all.
314
+ // MARK: - RC-parity identity aliases
315
+ //
316
+ // ## The guarantee
317
+ //
318
+ // Each of the four aliases below is *exactly* its {@link Identity}
319
+ // counterpart with the RevenueCat name and the RevenueCat return type, on
320
+ // BOTH platforms. There is no per-platform behaviour left in them: they are
321
+ // one-line delegations to `Identity`, which reaches the `identityLogIn` /
322
+ // `identityLogOut` / `identityCurrent` native bridge methods — and those go
323
+ // to the unified native `Identity` (`SwissKnife.Identity` on iOS,
324
+ // `com.appswissknife.identity.Identity` on Android) on both. Concretely, a
325
+ // `Purchases.logIn(...)` POSTs `/api/sdk/users/identify` on iOS AND on
326
+ // Android. Pinned by `identity-parity.test.ts`.
327
+ //
328
+ // ## Why they are written as delegations rather than bridge calls
329
+ //
330
+ // They used to call the legacy `logIn` / `logOut` / `getAppUserID` /
331
+ // `isAnonymous` bridge methods, which bottom out in the *deprecated native
332
+ // facades* — and those facades do NOT agree across platforms:
333
+ //
334
+ // - `logOut`: iOS `SwissKnife.logOut` routes to `Identity.logOut`;
335
+ // Android's routes straight to the purchases `gateway` and only
336
+ // back-syncs Identity's snapshot afterwards.
337
+ // - `getAppUserID`: iOS returns the Identity-synced subject (a stable
338
+ // `$SKAnonymousID:`+DeviceID value when anonymous); Android returns
339
+ // `gateway.getAppUserID()`, whose anonymous form is a fresh random UUID
340
+ // minted per process and unrelated to `Identity.current().anonymousId`.
341
+ // - `isAnonymous`: iOS reads Identity-synced state; Android reads the
342
+ // gateway's, which `Identity.reset()` / `Identity.wipe()` never touch.
343
+ //
344
+ // Delegating in JS makes the RN surface immune to all of that, and it is the
345
+ // only version of the fix that is verifiable from this repo's test suites.
346
+ // The legacy bridge methods stay on the native-module spec (removing them
347
+ // would break the native contract) but nothing in this package calls them
348
+ // any more.
349
+ //
350
+ // ## Second bug this closes
351
+ //
352
+ // `Identity` keeps JS-side caches (`lastSnapshot`, `lastLogIn`) that let a
353
+ // repeat `Identity.logIn(sameId)` skip the bridge. An alias that mutated
354
+ // native identity behind `Identity`'s back left those caches describing a
355
+ // world that no longer existed — after `Identity.logIn("u")` +
356
+ // `Purchases.logOut()`, a following `Identity.logIn("u")` short-circuited on
357
+ // the stale cache and resolved "logged in" without the device ever being
358
+ // re-identified. Routing through `Identity` means one owner for that state.
359
+ //
360
+ // ## The guard
361
+ //
362
+ // These sit on {@link throwIfCoreNotConfigured}, not on the purchase guard.
363
+ // Identity is a core capability — natively both platforms gate it on
364
+ // `isCoreConfigured` — and the single most likely caller of
365
+ // `Purchases.logIn` is an app migrating off RevenueCat that still lets
366
+ // RevenueCat own the store, i.e. one that called `configureCore`. Gating the
367
+ // RC-named alias on the purchase engine would reject exactly that app while
368
+ // the identical `Identity.logIn` call succeeded. The guard is not dropped
369
+ // entirely, because `Identity.current()` before any configure returns a
370
+ // real snapshot on iOS and a `{anonymousId: ""}` placeholder on Android —
371
+ // requiring core is what makes even that case agree.
259
372
 
260
373
  /**
261
- * Identify the user. Aliases/merges anonymous purchases server-side.
374
+ * Identify the user, merging the anonymous subject into `appUserID`
375
+ * server-side.
376
+ *
377
+ * Exactly `Identity.logIn(appUserID)` with the RevenueCat name. On both
378
+ * platforms this POSTs `(anonymous_id, user_id)` to
379
+ * `/api/sdk/users/identify` and resolves once the backend ack and the
380
+ * post-identify entitlements refresh complete; a rejection means the device
381
+ * is NOT merged server-side and the call must be retried. Repeat calls with
382
+ * the id already in effect are free (no bridge hop, no request).
383
+ *
384
+ * Works after `Purchases.configure`, `Purchases.configureCore`, or
385
+ * `Analytics.init` — the store does not have to be ours.
262
386
  *
263
- * @deprecated Wave 1 — prefer `Identity.logIn(userId)`. Routes through
264
- * the unified Identity surface natively, so the bug fix (Android now
265
- * POSTs `/api/sdk/users/identify`) applies whether you call this or
266
- * `Identity.logIn(...)`.
387
+ * @deprecated Wave 1 — prefer `Identity.logIn(userId)`. This alias exists so
388
+ * RevenueCat migrations compile unchanged; it is a pure delegation, so there
389
+ * is nothing to gain by keeping it and one less name to learn by dropping it.
267
390
  */
268
391
  static async logIn(appUserID: string): Promise<LogInResult> {
269
- throwIfNotConfigured();
270
- return getNativeModule().logIn(appUserID);
392
+ await throwIfCoreNotConfigured();
393
+ return Identity.logIn(appUserID);
271
394
  }
272
395
 
273
396
  /**
274
- * Log out the current user and revert to anonymous.
397
+ * Log out the current user and revert to anonymous. The device id survives,
398
+ * so analytics continuity for the same physical install is preserved.
275
399
  *
276
- * @deprecated Wave 1 — prefer `Identity.logOut()`.
400
+ * Exactly `Identity.logOut()` with the RevenueCat name, plus RC's
401
+ * `CustomerInfo` return: after the logout lands, the post-logout customer
402
+ * info is read back from the store engine. **When no store engine is
403
+ * configured** (`configureCore`, `Analytics.init`) there is nothing to read,
404
+ * and you get an entitlement-free `CustomerInfo` for the anonymous subject —
405
+ * the same record, built in JS, on both platforms. Do not read that as a
406
+ * store error; if you want real entitlements, call `getCustomerInfo()`.
407
+ *
408
+ * @deprecated Wave 1 — prefer `Identity.logOut()`, which does not pretend to
409
+ * return store state.
277
410
  */
278
411
  static async logOut(): Promise<CustomerInfo> {
279
- throwIfNotConfigured();
280
- return getNativeModule().logOut();
412
+ await throwIfCoreNotConfigured();
413
+ await Identity.logOut();
414
+ return customerInfoAfterLogOut();
281
415
  }
282
416
 
283
- /** The current app user id (anonymous or identified). */
417
+ /**
418
+ * The current subject id — the identified user id if there is one, else the
419
+ * SDK's anonymous id (`$SKAnonymousID:`-prefixed, stable across launches).
420
+ *
421
+ * Exactly `(await Identity.current()).userId ?? .anonymousId`. Note this is
422
+ * the *Identity* subject on both platforms; on Android the purchase
423
+ * gateway's own anonymous id is a different, per-process value, and this
424
+ * alias deliberately does not report it.
425
+ *
426
+ * @deprecated Wave 1 — prefer `Identity.current()`, which hands back the
427
+ * anonymous id, the user id and `isAnonymous` in one read instead of forcing
428
+ * two calls that can interleave.
429
+ */
284
430
  static async getAppUserID(): Promise<string> {
285
- throwIfNotConfigured();
286
- return getNativeModule().getAppUserID();
431
+ await throwIfCoreNotConfigured();
432
+ const snapshot = await Identity.current();
433
+ return snapshot.userId ?? snapshot.anonymousId;
287
434
  }
288
435
 
289
- /** Whether the current user id is an SDK-generated anonymous id. */
436
+ /**
437
+ * Whether the current subject is the SDK-generated anonymous id.
438
+ *
439
+ * Exactly `(await Identity.current()).isAnonymous`, so it tracks
440
+ * `Identity.reset()` and `Identity.wipe()` on both platforms.
441
+ *
442
+ * @deprecated Wave 1 — prefer `Identity.current()`; see
443
+ * {@link getAppUserID}.
444
+ */
290
445
  static async isAnonymous(): Promise<boolean> {
291
- throwIfNotConfigured();
292
- return getNativeModule().isAnonymous();
446
+ await throwIfCoreNotConfigured();
447
+ return (await Identity.current()).isAnonymous;
293
448
  }
294
449
 
295
450
  // Subscriber attributes. CORE, not store — see {@link throwIfCoreNotConfigured}.
@@ -353,12 +508,20 @@ export class Purchases {
353
508
  }
354
509
  }
355
510
 
356
- /** @internal Test seam: reset singleton state between tests. */
511
+ /**
512
+ * @internal Test seam: reset singleton state between tests.
513
+ *
514
+ * Also resets `Identity`'s caches, because the RC-parity aliases delegate
515
+ * there: without it, a `Purchases.logIn("u")` in one test would leave
516
+ * `Identity`'s `lastLogIn` primed and the next test's identical call would
517
+ * short-circuit before reaching the (freshly mocked) bridge.
518
+ */
357
519
  static __resetForTests(): void {
358
520
  configured = false;
359
521
  coreConfigured = false;
360
522
  configuredApiKey = null;
361
523
  customerInfoSubscriptions.clear();
524
+ Identity.__resetForTests();
362
525
  }
363
526
  }
364
527