@rocapine/react-native-onboarding 1.77.0 → 1.78.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 (60) hide show
  1. package/README.md +24 -6
  2. package/dist/OnboardingStudio.d.ts +14 -1
  3. package/dist/OnboardingStudio.d.ts.map +1 -1
  4. package/dist/OnboardingStudio.js +5 -1
  5. package/dist/OnboardingStudio.js.map +1 -1
  6. package/dist/OnboardingStudioClient.d.ts +29 -0
  7. package/dist/OnboardingStudioClient.d.ts.map +1 -1
  8. package/dist/OnboardingStudioClient.js +76 -19
  9. package/dist/OnboardingStudioClient.js.map +1 -1
  10. package/dist/assignmentId.d.ts +107 -0
  11. package/dist/assignmentId.d.ts.map +1 -0
  12. package/dist/assignmentId.js +215 -0
  13. package/dist/assignmentId.js.map +1 -0
  14. package/dist/index.d.ts +1 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js.map +1 -1
  17. package/dist/paywalls/customScreens.d.ts +7 -0
  18. package/dist/paywalls/customScreens.d.ts.map +1 -1
  19. package/dist/paywalls/observer.d.ts +2 -0
  20. package/dist/paywalls/observer.d.ts.map +1 -1
  21. package/dist/paywalls/observer.js +21 -9
  22. package/dist/paywalls/observer.js.map +1 -1
  23. package/dist/paywalls/types.d.ts +22 -0
  24. package/dist/paywalls/types.d.ts.map +1 -1
  25. package/dist/products/adapters/expoIap.d.ts +34 -13
  26. package/dist/products/adapters/expoIap.d.ts.map +1 -1
  27. package/dist/products/adapters/expoIap.js +136 -21
  28. package/dist/products/adapters/expoIap.js.map +1 -1
  29. package/dist/types.d.ts +47 -0
  30. package/dist/types.d.ts.map +1 -1
  31. package/dist/types.js +6 -0
  32. package/dist/types.js.map +1 -1
  33. package/dist/userProperties/reserved.d.ts +3 -2
  34. package/dist/userProperties/reserved.d.ts.map +1 -1
  35. package/dist/userProperties/reserved.js +3 -1
  36. package/dist/userProperties/reserved.js.map +1 -1
  37. package/dist/version.d.ts +1 -1
  38. package/dist/version.js +1 -1
  39. package/package.json +1 -1
  40. package/src/OnboardingStudio.ts +19 -1
  41. package/src/OnboardingStudioClient.ts +79 -31
  42. package/src/__tests__/assignmentId.clear.test.ts +413 -0
  43. package/src/__tests__/assignmentId.client.test.ts +288 -0
  44. package/src/__tests__/assignmentId.test.ts +195 -0
  45. package/src/__tests__/onboardingMetadata.client.test.ts +76 -0
  46. package/src/assignmentId.ts +278 -0
  47. package/src/index.ts +1 -0
  48. package/src/paywalls/__tests__/PaywallProvider.observer.test.tsx +51 -0
  49. package/src/paywalls/__tests__/getPaywalls.test.ts +77 -2
  50. package/src/paywalls/__tests__/observer.test.ts +37 -0
  51. package/src/paywalls/__tests__/present.test.ts +14 -0
  52. package/src/paywalls/customScreens.ts +7 -0
  53. package/src/paywalls/observer.ts +22 -2
  54. package/src/paywalls/types.ts +22 -0
  55. package/src/products/adapters/__tests__/expoIap.contract.test.ts +305 -0
  56. package/src/products/adapters/expoIap.ts +171 -32
  57. package/src/types.ts +48 -0
  58. package/src/userProperties/__tests__/primitives.test.ts +1 -1
  59. package/src/userProperties/reserved.ts +3 -1
  60. package/src/version.ts +1 -1
@@ -646,3 +646,308 @@ describe("expoIapProductProvider — a catalog that did not resolve", () => {
646
646
  expect(M.calls.requestPurchase[0].type).toBe("subs");
647
647
  });
648
648
  });
649
+
650
+ describe("expoIapProductProvider — Ask to Buy resolves pending, not error (#337)", () => {
651
+ // openiap-apple maps StoreKit's `.pending` purchase result to
652
+ // `ErrorCode.DeferredPayment` ("deferred-payment"), reporting it on the
653
+ // error listener and rejecting `requestPurchase` with it. It is not a
654
+ // failure: the purchase awaits approval, so the paywall's `onPending` branch
655
+ // must run, not `onError`.
656
+ it("maps deferred-payment delivered through the error listener", async () => {
657
+ const M = makeExpoIap5({
658
+ catalog: [iosYearly],
659
+ platform,
660
+ onDispatch: (sku) => ({
661
+ error: { code: "deferred-payment", message: "Payment is pending approval", productId: sku },
662
+ }),
663
+ });
664
+ const provider = expoIapProductProvider(M);
665
+ const [product] = await provider.getProducts([YEARLY_IOS]);
666
+ expect(await provider.purchase(product)).toEqual({ status: "pending" });
667
+ });
668
+
669
+ it("maps a deferred-payment rejection from requestPurchase", async () => {
670
+ const M = makeExpoIap5({ catalog: [iosYearly], platform });
671
+ (M as any).requestPurchase = async () => {
672
+ throw Object.assign(new Error("Payment is pending approval"), { code: "deferred-payment" });
673
+ };
674
+ const provider = expoIapProductProvider(M);
675
+ const [product] = await provider.getProducts([YEARLY_IOS]);
676
+ expect(await provider.purchase(product)).toEqual({ status: "pending" });
677
+ });
678
+
679
+ it.each(["pending", "E_DEFERRED_PAYMENT", "E_PENDING"])(
680
+ "maps the %s code to pending as well",
681
+ async (code) => {
682
+ const M = makeExpoIap5({
683
+ catalog: [iosYearly],
684
+ platform,
685
+ onDispatch: (sku) => ({ error: { code, productId: sku } }),
686
+ });
687
+ const provider = expoIapProductProvider(M);
688
+ const [product] = await provider.getProducts([YEARLY_IOS]);
689
+ expect(await provider.purchase(product)).toEqual({ status: "pending" });
690
+ }
691
+ );
692
+ });
693
+
694
+ describe("expoIapProductProvider — a dispatched purchase nobody is waiting for (#337)", () => {
695
+ /** An Ask to Buy purchase: StoreKit answers `.pending`, approval comes later. */
696
+ const deferred = () =>
697
+ makeExpoIap5({
698
+ catalog: [iosYearly],
699
+ platform,
700
+ onDispatch: (sku) => ({ error: { code: "deferred-payment", productId: sku } }),
701
+ });
702
+
703
+ it("hands the approved deferred purchase to the host, and finishes it once granted", async () => {
704
+ const unclaimed = vi.fn().mockResolvedValue(true);
705
+ const M = deferred();
706
+ const provider = expoIapProductProvider(M, { onUnclaimedPurchase: unclaimed });
707
+ const [product] = await provider.getProducts([YEARLY_IOS]);
708
+ expect(await provider.purchase(product)).toEqual({ status: "pending" });
709
+
710
+ // The parent approves; the transaction arrives on Transaction.updates.
711
+ M.emitUpdated({ id: "tx-approved", productId: "pro_yearly", purchaseState: "purchased" });
712
+ await settle();
713
+ expect(unclaimed).toHaveBeenCalledTimes(1);
714
+ expect(unclaimed.mock.calls[0][0]).toMatchObject({ id: "tx-approved" });
715
+ expect(M.calls.finishTransaction.map((c: any) => c.purchase.id)).toEqual(["tx-approved"]);
716
+ });
717
+
718
+ it("leaves the approved purchase unfinished when the host declines it", async () => {
719
+ const unclaimed = vi.fn().mockReturnValue(false);
720
+ const M = deferred();
721
+ const provider = expoIapProductProvider(M, { onUnclaimedPurchase: unclaimed });
722
+ const [product] = await provider.getProducts([YEARLY_IOS]);
723
+ await provider.purchase(product);
724
+
725
+ M.emitUpdated({ id: "tx-approved", productId: "pro_yearly", purchaseState: "purchased" });
726
+ await settle();
727
+ expect(unclaimed).toHaveBeenCalledTimes(1);
728
+ expect(M.calls.finishTransaction).toHaveLength(0);
729
+ });
730
+
731
+ it("hands a verdict that lands after the timeout to the host", async () => {
732
+ const unclaimed = vi.fn().mockReturnValue(true);
733
+ const M = makeExpoIap5({ catalog: [iosYearly], platform, onDispatch: () => null });
734
+ const provider = expoIapProductProvider(M, {
735
+ purchaseTimeoutMs: 10,
736
+ onUnclaimedPurchase: unclaimed,
737
+ });
738
+ const [product] = await provider.getProducts([YEARLY_IOS]);
739
+ expect(await provider.purchase(product)).toEqual({ status: "pending" });
740
+
741
+ M.emitUpdated({ id: "tx-late", productId: "pro_yearly", purchaseState: "purchased" });
742
+ await settle();
743
+ expect(unclaimed).toHaveBeenCalledTimes(1);
744
+ expect(M.calls.finishTransaction.map((c: any) => c.purchase.id)).toEqual(["tx-late"]);
745
+ });
746
+
747
+ it("hands a Play purchase that clears after answering pending to the host", async () => {
748
+ rn.Platform.OS = "android";
749
+ const unclaimed = vi.fn().mockReturnValue(true);
750
+ const M = makeExpoIap5({
751
+ catalog: [playYearly],
752
+ platform,
753
+ onDispatch: (sku) => ({ id: "tx-1", productId: sku, purchaseState: "pending" }),
754
+ });
755
+ const provider = expoIapProductProvider(M, { onUnclaimedPurchase: unclaimed });
756
+ const [product] = await provider.getProducts([YEARLY_PLAY]);
757
+ expect(await provider.purchase(product)).toEqual({ status: "pending" });
758
+ expect(unclaimed).not.toHaveBeenCalled(); // an unpaid purchase is nobody's to grant
759
+
760
+ M.emitUpdated({ id: "tx-1", productId: "pro_yearly", purchaseState: "purchased" });
761
+ await settle();
762
+ expect(unclaimed).toHaveBeenCalledTimes(1);
763
+ expect(M.calls.finishTransaction).toHaveLength(1);
764
+ });
765
+
766
+ it("does not hand the host a transaction already answered to its caller", async () => {
767
+ // openiap-apple both EMITS the transaction and RETURNS it from
768
+ // requestPurchase, and the adapter routes both copies. The second copy has
769
+ // no live waiter, but the caller was told "purchased": it is a replay.
770
+ const unclaimed = vi.fn().mockReturnValue(true);
771
+ const M = makeExpoIap5({ catalog: [iosYearly], platform });
772
+ (M as any).requestPurchase = async (args: any) => {
773
+ M.calls.requestPurchase.push(args);
774
+ const tx = { id: "tx-both", productId: "pro_yearly", purchaseState: "purchased" as const };
775
+ M.emitUpdated(tx);
776
+ return tx;
777
+ };
778
+ const provider = expoIapProductProvider(M, { onUnclaimedPurchase: unclaimed });
779
+ const [product] = await provider.getProducts([YEARLY_IOS]);
780
+ expect(await provider.purchase(product)).toEqual({ status: "purchased", productKey: "yearly" });
781
+ await settle();
782
+ expect(unclaimed).not.toHaveBeenCalled();
783
+ expect(M.calls.finishTransaction).toHaveLength(1);
784
+ });
785
+
786
+ it("does not hand the host a replay whose acknowledgement failed", async () => {
787
+ // A failed finish leaves the id out of the finished set; it is still the
788
+ // caller's transaction, queued for retry, not the host's to decide.
789
+ let broken = true;
790
+ const unclaimed = vi.fn().mockReturnValue(true);
791
+ rn.Platform.OS = "android"; // no iOS listener dedupe: the buffered replay arrives
792
+ const M = makeExpoIap5({ catalog: [playYearly], platform, finishFails: () => broken });
793
+ const provider = expoIapProductProvider(M, { onUnclaimedPurchase: unclaimed });
794
+ const [product] = await provider.getProducts([YEARLY_PLAY]);
795
+ expect(await provider.purchase(product)).toEqual({ status: "purchased", productKey: "yearly" });
796
+
797
+ broken = false;
798
+ M.emitUpdated({ id: "tx-pro_yearly-1", productId: "pro_yearly", purchaseState: "purchased" });
799
+ await settle();
800
+ expect(unclaimed).not.toHaveBeenCalled();
801
+ expect(M.calls.finishTransaction.filter((c: any) => c.purchase.id === "tx-pro_yearly-1")).toHaveLength(2);
802
+ });
803
+
804
+ it("never finishes a host-granted transaction twice", async () => {
805
+ rn.Platform.OS = "android"; // no iOS listener dedupe, so the replay reaches the adapter
806
+ const unclaimed = vi.fn().mockReturnValue(true);
807
+ const M = makeExpoIap5({
808
+ catalog: [playYearly],
809
+ platform,
810
+ onDispatch: (sku) => ({ id: "tx-1", productId: sku, purchaseState: "pending" }),
811
+ });
812
+ const provider = expoIapProductProvider(M, { onUnclaimedPurchase: unclaimed });
813
+ const [product] = await provider.getProducts([YEARLY_PLAY]);
814
+ await provider.purchase(product);
815
+
816
+ const cleared = { id: "tx-1", productId: "pro_yearly", purchaseState: "purchased" as const };
817
+ M.emitUpdated(cleared);
818
+ await settle();
819
+ M.emitUpdated(cleared); // a buffered replay of the same transaction
820
+ await settle();
821
+ expect(M.calls.finishTransaction).toHaveLength(1);
822
+ expect(unclaimed).toHaveBeenCalledTimes(1);
823
+ });
824
+
825
+ it("does not hand the host again a granted transaction whose acknowledgement failed", async () => {
826
+ // The host granted it; only the acknowledgement is outstanding. A replay
827
+ // must retry the acknowledgement, not ask the host to grant it twice.
828
+ rn.Platform.OS = "android"; // no iOS listener dedupe, so the replay reaches the adapter
829
+ let broken = true;
830
+ const unclaimed = vi.fn().mockReturnValue(true);
831
+ const M = makeExpoIap5({
832
+ catalog: [playYearly],
833
+ platform,
834
+ onDispatch: (sku) => ({ id: "tx-1", productId: sku, purchaseState: "pending" }),
835
+ finishFails: () => broken,
836
+ });
837
+ const provider = expoIapProductProvider(M, { onUnclaimedPurchase: unclaimed });
838
+ const [product] = await provider.getProducts([YEARLY_PLAY]);
839
+ await provider.purchase(product);
840
+
841
+ const cleared = { id: "tx-1", productId: "pro_yearly", purchaseState: "purchased" as const };
842
+ M.emitUpdated(cleared);
843
+ await settle();
844
+ broken = false;
845
+ M.emitUpdated(cleared); // a buffered replay of the same transaction
846
+ await settle();
847
+ expect(unclaimed).toHaveBeenCalledTimes(1);
848
+ expect(M.calls.finishTransaction.filter((c: any) => c.purchase.id === "tx-1")).toHaveLength(2);
849
+ });
850
+
851
+ // Buying an owned product again hands back the SAME transaction. It is
852
+ // already acknowledged, but the new caller is waiting and must be answered.
853
+ it("answers a re-purchase that returns the finished transaction directly (ios)", async () => {
854
+ const M = makeExpoIap5({ catalog: [iosYearly], platform });
855
+ (M as any).requestPurchase = async (args: any) => {
856
+ M.calls.requestPurchase.push(args);
857
+ return { id: "tx-owned", productId: "pro_yearly", purchaseState: "purchased" as const };
858
+ };
859
+ const provider = expoIapProductProvider(M, { purchaseTimeoutMs: 50 });
860
+ const [product] = await provider.getProducts([YEARLY_IOS]);
861
+ expect(await provider.purchase(product)).toEqual({ status: "purchased", productKey: "yearly" });
862
+ expect(await provider.purchase(product)).toEqual({ status: "purchased", productKey: "yearly" });
863
+ expect(M.calls.finishTransaction).toHaveLength(1);
864
+ });
865
+
866
+ it("answers a re-purchase whose finished transaction is delivered again (android)", async () => {
867
+ rn.Platform.OS = "android";
868
+ const M = makeExpoIap5({
869
+ catalog: [playYearly],
870
+ platform,
871
+ onDispatch: (sku) => ({ id: "tx-owned", productId: sku, purchaseState: "purchased" }),
872
+ });
873
+ const provider = expoIapProductProvider(M, { purchaseTimeoutMs: 50 });
874
+ const [product] = await provider.getProducts([YEARLY_PLAY]);
875
+ expect(await provider.purchase(product)).toEqual({ status: "purchased", productKey: "yearly" });
876
+ expect(await provider.purchase(product)).toEqual({ status: "purchased", productKey: "yearly" });
877
+ expect(M.calls.finishTransaction).toHaveLength(1);
878
+ });
879
+
880
+ it("answers a later purchase of the same sku itself, not through the host", async () => {
881
+ const unclaimed = vi.fn().mockReturnValue(true);
882
+ let ask = true;
883
+ const M = makeExpoIap5({
884
+ catalog: [iosYearly],
885
+ platform,
886
+ onDispatch: (sku) =>
887
+ ask ? { error: { code: "deferred-payment", productId: sku } } : { id: "tx-again", productId: sku },
888
+ });
889
+ const provider = expoIapProductProvider(M, { onUnclaimedPurchase: unclaimed });
890
+ const [product] = await provider.getProducts([YEARLY_IOS]);
891
+ expect(await provider.purchase(product)).toEqual({ status: "pending" });
892
+
893
+ ask = false;
894
+ expect(await provider.purchase(product)).toEqual({ status: "purchased", productKey: "yearly" });
895
+ expect(unclaimed).not.toHaveBeenCalled();
896
+ expect(M.calls.finishTransaction.map((c: any) => c.purchase.id)).toEqual(["tx-again"]);
897
+ });
898
+
899
+ it("answers purchased even when acknowledging outlasts the wait", async () => {
900
+ // Ownership is decided when the transaction arrives, not after the
901
+ // acknowledgement round-trip: a timeout firing during `finishTransaction`
902
+ // used to drop the caller's answer, so a finished purchase read "pending".
903
+ const M = makeExpoIap5({ catalog: [iosYearly], platform });
904
+ const realFinish = M.finishTransaction.bind(M);
905
+ (M as any).finishTransaction = async (args: any) => {
906
+ await new Promise((r) => setTimeout(r, 30));
907
+ return realFinish(args);
908
+ };
909
+ const provider = expoIapProductProvider(M, { purchaseTimeoutMs: 10 });
910
+ const [product] = await provider.getProducts([YEARLY_IOS]);
911
+ expect(await provider.purchase(product)).toEqual({ status: "purchased", productKey: "yearly" });
912
+ });
913
+
914
+ it("acknowledges a transaction once while a second copy lands mid-acknowledgement", async () => {
915
+ // A real acknowledgement is a native round-trip. The returned copy of a
916
+ // transaction the listener already delivered arrives while it is in flight,
917
+ // and a second acknowledge on Play fails and leaves it queued forever.
918
+ const M = makeExpoIap5({ catalog: [iosYearly], platform });
919
+ const realFinish = M.finishTransaction.bind(M);
920
+ (M as any).finishTransaction = async (args: any) => {
921
+ await new Promise((r) => setTimeout(r, 30));
922
+ return realFinish(args);
923
+ };
924
+ (M as any).requestPurchase = async (args: any) => {
925
+ M.calls.requestPurchase.push(args);
926
+ const tx = { id: "tx-both", productId: "pro_yearly", purchaseState: "purchased" as const };
927
+ M.emitUpdated(tx);
928
+ return tx;
929
+ };
930
+ const provider = expoIapProductProvider(M);
931
+ const [product] = await provider.getProducts([YEARLY_IOS]);
932
+ expect(await provider.purchase(product)).toEqual({ status: "purchased", productKey: "yearly" });
933
+ await new Promise((r) => setTimeout(r, 60));
934
+ expect(M.calls.finishTransaction).toHaveLength(1);
935
+ });
936
+
937
+ describe("with no onUnclaimedPurchase", () => {
938
+ it("still finishes the dispatched purchase, and says the host was never told", async () => {
939
+ // Kept from before #337: the sku was dispatched by this process, so it is
940
+ // acknowledged rather than left to replay. It is no longer silent.
941
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
942
+ const M = deferred();
943
+ const provider = expoIapProductProvider(M);
944
+ const [product] = await provider.getProducts([YEARLY_IOS]);
945
+ expect(await provider.purchase(product)).toEqual({ status: "pending" });
946
+
947
+ M.emitUpdated({ id: "tx-approved", productId: "pro_yearly", purchaseState: "purchased" });
948
+ await settle();
949
+ expect(M.calls.finishTransaction.map((c: any) => c.purchase.id)).toEqual(["tx-approved"]);
950
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining("onUnclaimedPurchase"));
951
+ });
952
+ });
953
+ });
@@ -212,8 +212,30 @@ const asError = (e: unknown): Error => {
212
212
  return error;
213
213
  };
214
214
 
215
+ /**
216
+ * A purchase the store accepted but has not charged yet: StoreKit's `.pending`
217
+ * result, which is Ask to Buy (a parent must approve) or a purchase awaiting
218
+ * another approval step.
219
+ *
220
+ * openiap-apple does not report that as a result. It throws
221
+ * `PurchaseError.make(code: .deferredPayment)` from the `.pending` branch of
222
+ * `requestPurchase` (`OpenIapStoreKitModule.swift`), so it reaches this adapter
223
+ * both on the error listener and as the `requestPurchase` rejection, with the
224
+ * code `"deferred-payment"` (`ErrorCode.DeferredPayment`, `build/types.js` in
225
+ * expo-iap 4.x through 6.x). One of openiap-google's non-Play backends raises
226
+ * the same code for a pending purchase. `"pending"` (`ErrorCode.Pending`) is declared
227
+ * alongside it, and the screaming-snake pair is the same two codes on peers
228
+ * before 4.x. Reading any of them as an error ran the paywall's `onError` for a
229
+ * purchase that may still be approved and charged.
230
+ */
231
+ const PENDING_CODES = new Set(["deferred-payment", "pending", "E_DEFERRED_PAYMENT", "E_PENDING"]);
232
+
215
233
  const failureFor = (e: any): PurchaseResult =>
216
- isCancellation(e) ? { status: "cancelled" } : { status: "error", error: asError(e) };
234
+ isCancellation(e)
235
+ ? { status: "cancelled" }
236
+ : PENDING_CODES.has(String(e?.code))
237
+ ? { status: "pending" }
238
+ : { status: "error", error: asError(e) };
217
239
 
218
240
  /** What `getProducts` remembers per ref so `purchase` can dispatch correctly. */
219
241
  type ResolvedMeta = {
@@ -240,24 +262,45 @@ export type ExpoIapProviderOptions = {
240
262
  * store sheet — Ask to Buy, an SCA step-up, or adding a card inside the sheet
241
263
  * routinely exceed the default — so this bounds only how long the CALLER
242
264
  * waits. It does not end the transaction: the provider's listeners stay
243
- * attached, and a verdict arriving after the timeout is still acknowledged.
244
- * It resolves `"pending"`, never `"purchased"`.
265
+ * attached, and a verdict arriving after the timeout is handed to
266
+ * `onUnclaimedPurchase` (or, with no handler, still acknowledged). It
267
+ * resolves `"pending"`, never `"purchased"`.
245
268
  */
246
269
  purchaseTimeoutMs?: number;
247
270
  /**
248
- * Honour a transaction this process never asked for, so it can be finished.
271
+ * Honour a purchase no `purchase()` call is waiting for, so it can be
272
+ * granted and finished. **Pass it** if you use this provider on a paywall.
273
+ *
274
+ * Called for every completed transaction that arrives with no caller
275
+ * waiting on its product:
276
+ * - a replay: StoreKit re-delivers an unfinished transaction on **every
277
+ * launch**, and a pending Play purchase can clear while the app is closed;
278
+ * - a promoted product, bought from the store page;
279
+ * - a purchase this provider dispatched whose `purchase()` already
280
+ * resolved `"pending"`: an **Ask to Buy** purchase approved later (StoreKit
281
+ * answers `.pending` first, so `purchase()` resolves `"pending"` and the
282
+ * approved transaction arrives afterwards), a verdict landing after
283
+ * `purchaseTimeoutMs`, or a Play slow-payment purchase that cleared. The
284
+ * paywall's `onPending` branch has already run for these, so this
285
+ * callback is the only place they can be granted.
249
286
  *
250
- * StoreKit re-delivers an unfinished transaction on **every launch**, and a
251
- * purchase can also arrive from an Ask to Buy approval, a promoted product,
252
- * or a pending Play purchase that cleared while the app was closed. None of
253
- * those has a caller waiting, and finishing one blind would take the money
254
- * while granting nothing — destroying the very replay that lets the app
255
- * recover. So the host decides: return `true` once entitlement is granted and
256
- * the transaction is finished; return `false` (or leave this unset) and it is
257
- * left alone to be re-delivered next launch.
287
+ * Finishing one blind would take the money while granting nothing, so the
288
+ * host decides: return `true` once entitlement is granted and the
289
+ * transaction may be finished; return `false` and it is left unfinished. A
290
+ * throw is treated as `false`. On iOS, StoreKit re-delivers an unfinished
291
+ * transaction on the next launch. On Android this provider does not re-query
292
+ * it at launch, and Play refunds a purchase left unacknowledged for three
293
+ * days, so return `false` only for a purchase you will not grant.
258
294
  *
259
- * A purchase this provider DISPATCHED in this process never comes here — the
260
- * caller was told about it, so acknowledging it needs no second opinion.
295
+ * A transaction answered `"purchased"` to its caller in this process never
296
+ * comes here. That memory does not survive a restart: if its acknowledgement
297
+ * failed and the app was killed before the retry, the next launch's replay
298
+ * does come here, so grant idempotently (by transaction id).
299
+ *
300
+ * Left unset: a transaction this process never dispatched is left unfinished
301
+ * (with a warning), and one it did dispatch is finished (with a warning) —
302
+ * so an approved Ask to Buy purchase is charged and acknowledged but never
303
+ * granted by the paywall flow.
261
304
  */
262
305
  onUnclaimedPurchase?: (purchase: any) => boolean | Promise<boolean>;
263
306
  };
@@ -308,18 +351,52 @@ export const expoIapProductProvider = (
308
351
  // subscription sees each transaction exactly once instead.
309
352
  // ---------------------------------------------------------------------------
310
353
  let subscriptions: { remove?(): void }[] | null = null;
311
- /** Skus this process asked to buy. A delivery for one of these is ours. */
354
+ /**
355
+ * Skus this process asked to buy. Consulted only when there is no
356
+ * `onUnclaimedPurchase`, to keep finishing a dispatched purchase whose caller
357
+ * has already been answered. Routing is by LIVE WAITER, not by this set, so a
358
+ * stale entry cannot answer a later purchase; it holds one entry per sku ever
359
+ * bought, which is bounded by the catalog.
360
+ */
312
361
  const dispatchedSkus = new Set<string>();
313
362
  /** Transaction ids already acknowledged, so no delivery finishes twice. */
314
363
  const finishedTxIds = new Set<string>();
315
364
  /** Acknowledgements that threw, retried on the next store round-trip. */
316
365
  const unfinished = new Map<string, { purchase: any; isConsumable: boolean }>();
366
+ /**
367
+ * Transactions answered `"purchased"` to a waiting caller. A later copy of
368
+ * one is a replay to acknowledge, never the host's to decide — even when its
369
+ * acknowledgement failed and it is not in `finishedTxIds` yet.
370
+ */
371
+ const answeredTxIds = new Set<string>();
372
+ /** Transactions the host is deciding right now, so a copy is not offered twice. */
373
+ const offeredTxIds = new Set<string>();
317
374
  const waiters = new Set<Waiter>();
318
375
  let warnedUnclaimed = false;
376
+ let warnedDispatchedUnclaimed = false;
319
377
  /** Only iOS publishes a consumable discriminator; see `getProducts`. */
320
378
  const consumableBySku = new Map<string, boolean>();
321
379
 
322
- const finish = async (purchase: any, isConsumable: boolean) => {
380
+ /**
381
+ * Acknowledgements in flight, per transaction id. A second copy of a
382
+ * transaction (iOS emits it AND returns it; Android replays buffered events)
383
+ * can land while the first acknowledgement is still a native round-trip
384
+ * away, before `finishedTxIds` records it. It joins that attempt instead of
385
+ * starting a second one, which Play would reject.
386
+ */
387
+ const finishing = new Map<string, Promise<void>>();
388
+
389
+ const finish = (purchase: any, isConsumable: boolean): Promise<void> => {
390
+ const tx = txIdOf(purchase);
391
+ const inFlight = tx ? finishing.get(tx) : undefined;
392
+ if (inFlight) return inFlight;
393
+ const attempt = finishOnce(purchase, isConsumable);
394
+ if (!tx) return attempt;
395
+ finishing.set(tx, attempt);
396
+ return attempt.finally(() => finishing.delete(tx));
397
+ };
398
+
399
+ const finishOnce = async (purchase: any, isConsumable: boolean) => {
323
400
  const M = required();
324
401
  const tx = txIdOf(purchase);
325
402
  if (tx && finishedTxIds.has(tx)) return;
@@ -353,18 +430,18 @@ export const expoIapProductProvider = (
353
430
  }
354
431
  };
355
432
 
356
- /** Hand a result to the one caller waiting on this transaction's sku, if any. */
357
- const answer = (purchase: any, result: PurchaseResult) => {
433
+ /** The caller still waiting on this delivery's sku, if there is one. */
434
+ const liveWaiterFor = (purchase: any): Waiter | undefined => {
358
435
  for (const w of waiters) {
359
- if (w.settled || !deliversFor(purchase, w.sku)) continue;
360
- w.answer(result.status === "purchased" ? { ...result, productKey: w.productKey } : result);
361
- return;
436
+ if (!w.settled && deliversFor(purchase, w.sku)) return w;
362
437
  }
438
+ return undefined;
363
439
  };
364
440
 
365
441
  const handleUpdated = async (purchase: any) => {
366
442
  const sku: string | undefined = purchase?.productId;
367
443
  const isConsumable = (sku != null && consumableBySku.get(sku)) || false;
444
+ const tx = txIdOf(purchase);
368
445
 
369
446
  // Play's slow-payment path: the user has committed but the money has not
370
447
  // moved, and Android cannot acknowledge it anyway (no `purchaseToken` yet,
@@ -372,24 +449,86 @@ export const expoIapProductProvider = (
372
449
  // Play emits `purchased` for the SAME transaction once it clears. Treating
373
450
  // this as terminal is what left a cleared purchase unfinished.
374
451
  if (purchase?.purchaseState === "pending") {
375
- answer(purchase, { status: "pending" });
452
+ liveWaiterFor(purchase)?.answer({ status: "pending" });
376
453
  return;
377
454
  }
378
455
 
379
- if (sku != null && dispatchedSkus.has(sku)) {
456
+ // A copy of a transaction already dealt with. iOS hands one transaction
457
+ // over twice (openiap EMITS it and RETURNS it from `requestPurchase`), and
458
+ // Android replays buffered events. Its caller has been answered, or the
459
+ // host has granted it, so the only thing left to do is the acknowledgement
460
+ // — a no-op once it has succeeded, a retry if it failed. `unfinished` and
461
+ // `finishing` cover a host-granted transaction: its acknowledgement failed
462
+ // or is in flight, and asking the host again would grant it twice.
463
+ // `answeredTxIds` still matters on a peer with no `finishTransaction`,
464
+ // where `finishOnce` records nothing.
465
+ if (
466
+ tx &&
467
+ (finishedTxIds.has(tx) || answeredTxIds.has(tx) || unfinished.has(tx) || finishing.has(tx))
468
+ ) {
469
+ // Still answer a caller waiting on this sku: buying an owned product
470
+ // again hands back the same transaction, and that caller is otherwise
471
+ // left to time out. The copy of a transaction its own caller was already
472
+ // answered for finds that waiter settled, so nothing is answered twice.
473
+ const waiting = liveWaiterFor(purchase);
474
+ if (waiting) {
475
+ answeredTxIds.add(tx);
476
+ waiting.answer({ status: "purchased", productKey: waiting.productKey });
477
+ }
380
478
  await finish(purchase, isConsumable);
381
- // `productKey` is filled in by `answer` from the waiting caller's ref.
382
- answer(purchase, { status: "purchased", productKey: "" });
383
479
  return;
384
480
  }
385
481
 
386
- // Nobody here asked for this one: a replay from a previous process, an Ask
387
- // to Buy approval, a promoted product. Only the host knows whether it has
388
- // been honoured, so only the host can authorise finishing it.
482
+ // Ownership is decided NOW, before any await. Answering after the
483
+ // acknowledgement round-trip let the timeout fire in between: the caller
484
+ // was told "pending" for a purchase that had just been finished.
485
+ const waiter = liveWaiterFor(purchase);
486
+ if (waiter) {
487
+ if (tx) answeredTxIds.add(tx);
488
+ waiter.answer({ status: "purchased", productKey: waiter.productKey });
489
+ await finish(purchase, isConsumable);
490
+ return;
491
+ }
492
+
493
+ // Nobody is waiting on this one. It may be a replay from a previous
494
+ // process or a promoted product, but it may equally be a purchase THIS
495
+ // process dispatched whose caller has already been answered: an Ask to Buy
496
+ // purchase approved after `"pending"`, a verdict landing after the
497
+ // timeout, or a Play purchase that cleared after `"pending"`. In every
498
+ // case no caller will grant it, so only the host can — and only the host
499
+ // can authorise finishing it.
389
500
  if (options.onUnclaimedPurchase) {
390
- if (await options.onUnclaimedPurchase(purchase)) await finish(purchase, isConsumable);
501
+ if (tx && offeredTxIds.has(tx)) return; // the host is already deciding this one
502
+ if (tx) offeredTxIds.add(tx);
503
+ try {
504
+ if (await options.onUnclaimedPurchase(purchase)) await finish(purchase, isConsumable);
505
+ } catch (e) {
506
+ console.warn(
507
+ `expoIapProductProvider: onUnclaimedPurchase threw for "${sku}" — the transaction is ` +
508
+ `left unfinished. ${String(e)}`
509
+ );
510
+ } finally {
511
+ if (tx) offeredTxIds.delete(tx);
512
+ }
391
513
  return;
392
514
  }
515
+
516
+ // No host handler. A purchase this process dispatched is still finished, as
517
+ // it was before #337, so it is not re-delivered on every launch — but no
518
+ // caller is left to grant it, so say so once.
519
+ if (sku != null && dispatchedSkus.has(sku)) {
520
+ if (!warnedDispatchedUnclaimed) {
521
+ warnedDispatchedUnclaimed = true;
522
+ console.warn(
523
+ `expoIapProductProvider: the store delivered "${sku}" with no purchase() call waiting ` +
524
+ `for it (for example an approved Ask to Buy purchase, or a verdict after "pending"). ` +
525
+ `It is finished, but nothing grants it. Pass onUnclaimedPurchase to grant it.`
526
+ );
527
+ }
528
+ await finish(purchase, isConsumable);
529
+ return;
530
+ }
531
+
393
532
  if (!warnedUnclaimed) {
394
533
  warnedUnclaimed = true;
395
534
  console.warn(
@@ -697,9 +836,9 @@ export const expoIapProductProvider = (
697
836
  return waiter.settled ?? failureFor(e);
698
837
  } finally {
699
838
  if (timer) clearTimeout(timer);
700
- // Only the ANSWER slot closes here. The listeners stay attached and the
701
- // sku stays in `dispatchedSkus`, so a verdict arriving after this call
702
- // has returned is still acknowledged.
839
+ // Only the ANSWER slot closes here. The listeners stay attached, so a
840
+ // verdict arriving after this call has returned still reaches
841
+ // `onUnclaimedPurchase` (or, with none, is still acknowledged).
703
842
  waiters.delete(waiter);
704
843
  }
705
844
  },
package/src/types.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { NextStep } from "./steps/common.types";
2
+ import type { AssignmentIdOption } from "./assignmentId";
2
3
 
3
4
  /**
4
5
  * Base step type that all onboarding steps must conform to.
@@ -37,9 +38,36 @@ export type OnboardingStudioClientOptions<
37
38
  * characters before it is sent. An audience rule can target it.
38
39
  */
39
40
  environment?: string;
41
+ /**
42
+ * The stable per-person id sent as `assignmentId`, so the server can keep a
43
+ * person in the same variant across launches. A string, or a getter called
44
+ * on every request (sync or async) — e.g. `() => Purchases.getAppUserID()`
45
+ * to use the RevenueCat App User ID (call `Purchases.configure()` before
46
+ * the first request). When omitted, or when the value is `undefined`,
47
+ * `null` or `""`, the SDK sends an installation id it generates once and
48
+ * persists. Absent from the request when neither is available.
49
+ *
50
+ * `false` (or a getter returning `false`) opts out: nothing is sent, and the
51
+ * installation id is never read, created or written. Use it until the user
52
+ * has consented. `null` and `""` are not an opt-out.
53
+ *
54
+ * Fails closed: a getter that throws, rejects or takes longer than 2s is
55
+ * treated like `false` for that request — nothing is sent and the
56
+ * installation id is not touched. Resolving it counts against `timeout`.
57
+ *
58
+ * Changing the value (e.g. anonymous → identified on login) can move the
59
+ * person to another variant, once.
60
+ */
61
+ assignmentId?: AssignmentIdOption;
40
62
  isSandbox?: boolean;
41
63
  baseUrl?: string;
42
64
  fallbackOnboarding?: Onboarding<StepType>;
65
+ /**
66
+ * End-to-end budget in ms for each `getSteps` / `getPaywalls` request:
67
+ * resolving the request identity (including the `assignmentId` getter) and
68
+ * the fetch together. On expiry `getSteps` returns `fallbackOnboarding` if
69
+ * set; otherwise both reject with `Error("timeout")`.
70
+ */
43
71
  timeout?: number;
44
72
  /**
45
73
  * Optional custom cache key. When provided, the fetched onboarding is
@@ -61,6 +89,12 @@ export type UserDefinedParams = {
61
89
  [key: string]: string;
62
90
  };
63
91
 
92
+ /**
93
+ * Reserved `OnboardingMetadata.variantKey` reported by the parent (main)
94
+ * onboarding, as opposed to one of its variants.
95
+ */
96
+ export const MAIN_VARIANT_KEY = "main" as const;
97
+
64
98
  export interface OnboardingMetadata {
65
99
  id: string;
66
100
  name?: string;
@@ -69,6 +103,20 @@ export interface OnboardingMetadata {
69
103
  audienceOrder?: number;
70
104
  locale?: string;
71
105
  draft?: boolean;
106
+ /**
107
+ * Which variant of the onboarding this user was served. The parent (main)
108
+ * onboarding reports the reserved key `MAIN_VARIANT_KEY` (`"main"`).
109
+ * `null` and absent mean the same thing — the server sent no variant
110
+ * information (e.g. an older server) — and hosts should treat them
111
+ * identically (e.g. `metadata.variantKey ?? undefined`).
112
+ */
113
+ variantKey?: string | null;
114
+ /**
115
+ * Id of the published deployment that was served. `null` for a draft
116
+ * (sandbox) payload, which has no deployment; absent when the server does
117
+ * not send it.
118
+ */
119
+ deploymentId?: number | null;
72
120
  }
73
121
 
74
122
  /**