@rocapine/react-native-onboarding 1.73.0 → 1.74.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/README.md +164 -3
  2. package/dist/OnboardingStudio.d.ts +82 -0
  3. package/dist/OnboardingStudio.d.ts.map +1 -0
  4. package/dist/OnboardingStudio.js +91 -0
  5. package/dist/OnboardingStudio.js.map +1 -0
  6. package/dist/OnboardingStudioClient.d.ts +14 -5
  7. package/dist/OnboardingStudioClient.d.ts.map +1 -1
  8. package/dist/OnboardingStudioClient.js +24 -9
  9. package/dist/OnboardingStudioClient.js.map +1 -1
  10. package/dist/index.d.ts +7 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +40 -4
  13. package/dist/index.js.map +1 -1
  14. package/dist/infra/provider/OnboardingProvider.d.ts +15 -2
  15. package/dist/infra/provider/OnboardingProvider.d.ts.map +1 -1
  16. package/dist/infra/provider/OnboardingProvider.js +66 -6
  17. package/dist/infra/provider/OnboardingProvider.js.map +1 -1
  18. package/dist/infra/queries/cacheKey.d.ts +41 -3
  19. package/dist/infra/queries/cacheKey.d.ts.map +1 -1
  20. package/dist/infra/queries/cacheKey.js +44 -8
  21. package/dist/infra/queries/cacheKey.js.map +1 -1
  22. package/dist/infra/queries/getOnboarding.query.d.ts.map +1 -1
  23. package/dist/infra/queries/getOnboarding.query.js +6 -1
  24. package/dist/infra/queries/getOnboarding.query.js.map +1 -1
  25. package/dist/paywalls/PaywallProvider.d.ts +52 -4
  26. package/dist/paywalls/PaywallProvider.d.ts.map +1 -1
  27. package/dist/paywalls/PaywallProvider.js +105 -7
  28. package/dist/paywalls/PaywallProvider.js.map +1 -1
  29. package/dist/paywalls/catalogSettleWaiter.d.ts +31 -0
  30. package/dist/paywalls/catalogSettleWaiter.d.ts.map +1 -0
  31. package/dist/paywalls/catalogSettleWaiter.js +58 -0
  32. package/dist/paywalls/catalogSettleWaiter.js.map +1 -0
  33. package/dist/paywalls/getPaywalls.query.d.ts.map +1 -1
  34. package/dist/paywalls/getPaywalls.query.js +6 -1
  35. package/dist/paywalls/getPaywalls.query.js.map +1 -1
  36. package/dist/paywalls/register.d.ts +105 -0
  37. package/dist/paywalls/register.d.ts.map +1 -0
  38. package/dist/paywalls/register.js +112 -0
  39. package/dist/paywalls/register.js.map +1 -0
  40. package/dist/paywalls/usePaywall.d.ts +29 -0
  41. package/dist/paywalls/usePaywall.d.ts.map +1 -1
  42. package/dist/paywalls/usePaywall.js +2 -1
  43. package/dist/paywalls/usePaywall.js.map +1 -1
  44. package/dist/userProperties/applyPatch.d.ts +18 -0
  45. package/dist/userProperties/applyPatch.d.ts.map +1 -0
  46. package/dist/userProperties/applyPatch.js +57 -0
  47. package/dist/userProperties/applyPatch.js.map +1 -0
  48. package/dist/userProperties/effectiveParams.d.ts +29 -0
  49. package/dist/userProperties/effectiveParams.d.ts.map +1 -0
  50. package/dist/userProperties/effectiveParams.js +56 -0
  51. package/dist/userProperties/effectiveParams.js.map +1 -0
  52. package/dist/userProperties/index.d.ts +9 -0
  53. package/dist/userProperties/index.d.ts.map +1 -0
  54. package/dist/userProperties/index.js +21 -0
  55. package/dist/userProperties/index.js.map +1 -0
  56. package/dist/userProperties/reserved.d.ts +33 -0
  57. package/dist/userProperties/reserved.d.ts.map +1 -0
  58. package/dist/userProperties/reserved.js +45 -0
  59. package/dist/userProperties/reserved.js.map +1 -0
  60. package/dist/userProperties/serialize.d.ts +38 -0
  61. package/dist/userProperties/serialize.d.ts.map +1 -0
  62. package/dist/userProperties/serialize.js +67 -0
  63. package/dist/userProperties/serialize.js.map +1 -0
  64. package/dist/userProperties/store.d.ts +65 -0
  65. package/dist/userProperties/store.d.ts.map +1 -0
  66. package/dist/userProperties/store.js +155 -0
  67. package/dist/userProperties/store.js.map +1 -0
  68. package/dist/userProperties/types.d.ts +21 -0
  69. package/dist/userProperties/types.d.ts.map +1 -0
  70. package/dist/userProperties/types.js +3 -0
  71. package/dist/userProperties/types.js.map +1 -0
  72. package/dist/userProperties/useUserProperties.d.ts +20 -0
  73. package/dist/userProperties/useUserProperties.d.ts.map +1 -0
  74. package/dist/userProperties/useUserProperties.js +30 -0
  75. package/dist/userProperties/useUserProperties.js.map +1 -0
  76. package/package.json +5 -1
  77. package/src/OnboardingStudio.ts +147 -0
  78. package/src/OnboardingStudioClient.ts +27 -11
  79. package/src/__tests__/OnboardingDataGate.test.tsx +445 -0
  80. package/src/__tests__/OnboardingStudio.test.ts +208 -0
  81. package/src/__tests__/cacheKey.test.ts +71 -0
  82. package/src/__tests__/getOnboarding.query.test.ts +47 -8
  83. package/src/index.ts +43 -0
  84. package/src/infra/provider/OnboardingProvider.tsx +98 -10
  85. package/src/infra/queries/cacheKey.ts +54 -9
  86. package/src/infra/queries/getOnboarding.query.ts +9 -1
  87. package/src/paywalls/PaywallProvider.tsx +162 -6
  88. package/src/paywalls/__tests__/catalogSettleWaiter.test.ts +134 -0
  89. package/src/paywalls/__tests__/getPaywalls.test.ts +29 -11
  90. package/src/paywalls/__tests__/register.test.ts +266 -0
  91. package/src/paywalls/catalogSettleWaiter.ts +72 -0
  92. package/src/paywalls/getPaywalls.query.ts +9 -1
  93. package/src/paywalls/register.ts +169 -0
  94. package/src/paywalls/usePaywall.ts +40 -2
  95. package/src/userProperties/__tests__/effectiveParams.test.ts +51 -0
  96. package/src/userProperties/__tests__/primitives.test.ts +96 -0
  97. package/src/userProperties/__tests__/store.test.ts +181 -0
  98. package/src/userProperties/applyPatch.ts +68 -0
  99. package/src/userProperties/effectiveParams.ts +60 -0
  100. package/src/userProperties/index.ts +11 -0
  101. package/src/userProperties/reserved.ts +44 -0
  102. package/src/userProperties/serialize.ts +61 -0
  103. package/src/userProperties/store.ts +179 -0
  104. package/src/userProperties/types.ts +22 -0
  105. package/src/userProperties/useUserProperties.ts +26 -0
@@ -0,0 +1,266 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+ import { resolveRegisterDecision, shouldRunFeature, runRegister } from "../register";
3
+ import type { RegisterDeps } from "../register";
4
+ import type { PaywallCatalog } from "../types";
5
+
6
+ const paywall = {
7
+ id: "pw1",
8
+ name: "Main",
9
+ moment: "unlock_stats",
10
+ products: [],
11
+ billing: "store",
12
+ } as any;
13
+ const catalog = { paywalls: { unlock_stats: paywall } } as unknown as PaywallCatalog;
14
+
15
+ beforeEach(() => {
16
+ vi.restoreAllMocks();
17
+ vi.spyOn(console, "warn").mockImplementation(() => {});
18
+ });
19
+
20
+ describe("resolveRegisterDecision", () => {
21
+ it("presents when the catalog holds the moment", () => {
22
+ expect(resolveRegisterDecision(catalog, "ready", "unlock_stats")).toEqual({
23
+ type: "present",
24
+ paywall,
25
+ });
26
+ });
27
+
28
+ it("runs the feature when a resolved catalog has no such moment", () => {
29
+ expect(resolveRegisterDecision(catalog, "ready", "not_authored")).toEqual({
30
+ type: "run",
31
+ reason: "no-paywall",
32
+ });
33
+ });
34
+
35
+ it("waits while the catalog is still loading", () => {
36
+ expect(resolveRegisterDecision(null, "loading", "unlock_stats")).toEqual({ type: "wait" });
37
+ });
38
+
39
+ it("fails open when the catalog failed to load", () => {
40
+ expect(resolveRegisterDecision(null, "error", "unlock_stats")).toEqual({
41
+ type: "run",
42
+ reason: "catalog-unavailable",
43
+ });
44
+ });
45
+
46
+ it("treats a revalidating catalog as usable", () => {
47
+ // Safe only because the disk cache key is now params-scoped: a served
48
+ // catalog always matches the current params.
49
+ expect(resolveRegisterDecision(catalog, "revalidating", "unlock_stats")).toEqual({
50
+ type: "present",
51
+ paywall,
52
+ });
53
+ expect(resolveRegisterDecision(catalog, "revalidating", "not_authored")).toEqual({
54
+ type: "run",
55
+ reason: "no-paywall",
56
+ });
57
+ });
58
+
59
+ it("never returns wait once a catalog exists", () => {
60
+ for (const status of ["loading", "ready", "revalidating", "error"] as const) {
61
+ expect(resolveRegisterDecision(catalog, status, "unlock_stats").type).not.toBe("wait");
62
+ }
63
+ });
64
+ });
65
+
66
+ describe("shouldRunFeature", () => {
67
+ it("runs only on a purchase", () => {
68
+ expect(shouldRunFeature({ status: "purchased" })).toBe(true);
69
+ });
70
+
71
+ it("does not run on anything else", () => {
72
+ // Also the Stripe case: a Payment Link purchase never resolves "purchased"
73
+ // (the entitlement arrives out-of-band through RevenueCat), so the
74
+ // presentation reports "dismissed" via its onPending branch.
75
+ expect(shouldRunFeature({ status: "dismissed" })).toBe(false);
76
+ expect(shouldRunFeature({ status: "cancelled" })).toBe(false);
77
+ expect(shouldRunFeature({ status: "error", reason: "unknown-moment" })).toBe(false);
78
+ expect(
79
+ shouldRunFeature({ status: "error", reason: "already-presenting", activeMoment: "x" }),
80
+ ).toBe(false);
81
+ });
82
+ });
83
+
84
+ const deps = (over: Partial<RegisterDeps> = {}): RegisterDeps => ({
85
+ getCatalog: () => catalog,
86
+ getCatalogStatus: () => "ready",
87
+ waitForCatalogSettled: async () => {},
88
+ present: async () => ({ status: "dismissed" }),
89
+ timeoutMs: 3000,
90
+ ...over,
91
+ });
92
+
93
+ describe("runRegister", () => {
94
+ it("runs the feature and never presents when the moment has no paywall", async () => {
95
+ const present = vi.fn();
96
+ const feature = vi.fn();
97
+ const result = await runRegister(deps({ present }), "not_authored", feature);
98
+ expect(present).not.toHaveBeenCalled();
99
+ expect(feature).toHaveBeenCalledTimes(1);
100
+ expect(result).toEqual({ ran: true, presented: false, reason: "no-paywall" });
101
+ });
102
+
103
+ it("does not warn about a moment that simply is not monetised", async () => {
104
+ await runRegister(deps(), "not_authored", vi.fn());
105
+ expect(console.warn).not.toHaveBeenCalled();
106
+ });
107
+
108
+ it("fails open when there is no catalog and it is not loading", async () => {
109
+ const feature = vi.fn();
110
+ const result = await runRegister(
111
+ deps({ getCatalog: () => null, getCatalogStatus: () => "error" }),
112
+ "unlock_stats",
113
+ feature,
114
+ );
115
+ expect(feature).toHaveBeenCalledTimes(1);
116
+ expect(result).toEqual({ ran: true, presented: false, reason: "catalog-unavailable" });
117
+ expect(console.warn).toHaveBeenCalledWith(expect.stringContaining("unlock_stats"));
118
+ });
119
+
120
+ it("waits once, then decides against the settled catalog", async () => {
121
+ let status: "loading" | "ready" = "loading";
122
+ let current: PaywallCatalog | null = null;
123
+ const waited = vi.fn();
124
+ const present = vi.fn(async () => ({ status: "purchased" }) as const);
125
+ const feature = vi.fn();
126
+
127
+ const result = await runRegister(
128
+ deps({
129
+ getCatalog: () => current,
130
+ getCatalogStatus: () => status,
131
+ waitForCatalogSettled: async () => {
132
+ waited();
133
+ status = "ready";
134
+ current = catalog;
135
+ },
136
+ present,
137
+ }),
138
+ "unlock_stats",
139
+ feature,
140
+ );
141
+
142
+ expect(waited).toHaveBeenCalledTimes(1);
143
+ expect(present).toHaveBeenCalledWith("unlock_stats");
144
+ expect(feature).toHaveBeenCalledTimes(1);
145
+ expect(result).toEqual({
146
+ ran: true,
147
+ presented: true,
148
+ reason: "purchased",
149
+ outcome: { status: "purchased" },
150
+ });
151
+ });
152
+
153
+ it("passes the configured timeout to the waiter", async () => {
154
+ const waitForCatalogSettled = vi.fn(async () => {});
155
+ await runRegister(
156
+ deps({
157
+ getCatalog: () => null,
158
+ getCatalogStatus: () => "loading",
159
+ waitForCatalogSettled,
160
+ timeoutMs: 1234,
161
+ }),
162
+ "unlock_stats",
163
+ );
164
+ expect(waitForCatalogSettled).toHaveBeenCalledWith(1234);
165
+ });
166
+
167
+ it("fails open — and does not wait twice — when the wait times out still loading", async () => {
168
+ const waitForCatalogSettled = vi.fn(async () => {});
169
+ const feature = vi.fn();
170
+ const result = await runRegister(
171
+ deps({ getCatalog: () => null, getCatalogStatus: () => "loading", waitForCatalogSettled }),
172
+ "unlock_stats",
173
+ feature,
174
+ );
175
+ expect(waitForCatalogSettled).toHaveBeenCalledTimes(1);
176
+ expect(feature).toHaveBeenCalledTimes(1);
177
+ expect(result).toEqual({ ran: true, presented: false, reason: "catalog-unavailable" });
178
+ });
179
+
180
+ it("presents and withholds the feature when the user does not buy", async () => {
181
+ const feature = vi.fn();
182
+ const result = await runRegister(
183
+ deps({ present: async () => ({ status: "dismissed" }) }),
184
+ "unlock_stats",
185
+ feature,
186
+ );
187
+ expect(feature).not.toHaveBeenCalled();
188
+ expect(result).toEqual({
189
+ ran: false,
190
+ presented: true,
191
+ reason: "not-purchased",
192
+ outcome: { status: "dismissed" },
193
+ });
194
+ });
195
+
196
+ it("withholds the feature when another paywall is already presenting", async () => {
197
+ const feature = vi.fn();
198
+ const result = await runRegister(
199
+ deps({
200
+ present: async () => ({
201
+ status: "error",
202
+ reason: "already-presenting",
203
+ activeMoment: "other",
204
+ }),
205
+ }),
206
+ "unlock_stats",
207
+ feature,
208
+ );
209
+ expect(feature).not.toHaveBeenCalled();
210
+ expect(result.ran).toBe(false);
211
+ });
212
+
213
+ it("warns before presenting a Stripe paywall, whose purchase never unlocks", async () => {
214
+ const stripeCatalog = {
215
+ paywalls: { unlock_stats: { ...paywall, billing: "stripe" } },
216
+ } as unknown as PaywallCatalog;
217
+ const feature = vi.fn();
218
+ const result = await runRegister(
219
+ deps({
220
+ getCatalog: () => stripeCatalog,
221
+ // A Stripe checkout resolves the PURCHASE as "pending"; the
222
+ // presentation itself closes as "dismissed" through its onPending
223
+ // branch, so the feature is correctly withheld.
224
+ present: async () => ({ status: "dismissed" }),
225
+ }),
226
+ "unlock_stats",
227
+ feature,
228
+ );
229
+ expect(console.warn).toHaveBeenCalledWith(expect.stringContaining("Stripe"));
230
+ expect(feature).not.toHaveBeenCalled();
231
+ expect(result.ran).toBe(false);
232
+ });
233
+
234
+ it("does not warn about Stripe for a store-billed paywall", async () => {
235
+ await runRegister(deps(), "unlock_stats", vi.fn());
236
+ expect(console.warn).not.toHaveBeenCalled();
237
+ });
238
+
239
+ it("awaits an async feature before resolving", async () => {
240
+ const order: string[] = [];
241
+ const result = await runRegister(
242
+ deps({ present: async () => ({ status: "purchased" }) }),
243
+ "unlock_stats",
244
+ async () => {
245
+ await new Promise((r) => setTimeout(r, 0));
246
+ order.push("feature");
247
+ },
248
+ );
249
+ order.push("resolved");
250
+ expect(order).toEqual(["feature", "resolved"]);
251
+ expect(result.ran).toBe(true);
252
+ });
253
+
254
+ it("works with no feature at all — register is also a plain gate check", async () => {
255
+ const result = await runRegister(
256
+ deps({ present: async () => ({ status: "purchased" }) }),
257
+ "unlock_stats",
258
+ );
259
+ expect(result).toEqual({
260
+ ran: true,
261
+ presented: true,
262
+ reason: "purchased",
263
+ outcome: { status: "purchased" },
264
+ });
265
+ });
266
+ });
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Parks `register()` callers while the paywall catalog is still loading, and
3
+ * wakes them when it settles or when their own timeout elapses.
4
+ *
5
+ * Extracted from `PaywallProvider` — rather than written inline over a couple of
6
+ * refs — because it has two invariants that are easy to get wrong and impossible
7
+ * to assert from inside a component without a DOM (this repo's tests run in
8
+ * vitest's default `node` environment):
9
+ *
10
+ * 1. **A waiter resolves exactly once.** A timeout can fire after a real settle
11
+ * already woke the waiter. Resolving a Promise twice is harmless in itself,
12
+ * but the bookkeeping around it is not — a stale entry left in the set would
13
+ * be woken by the NEXT settle, running a continuation that belongs to nobody.
14
+ * 2. **Draining must not skip a re-parked waiter.** A woken caller's continuation
15
+ * may call `register()` again and park immediately; mutating the set while
16
+ * iterating it would either miss that new waiter or loop over it. So the set
17
+ * is swapped out before it is drained.
18
+ *
19
+ * The timer is injected so both invariants are testable without real time.
20
+ */
21
+
22
+ /** Cancels the scheduled callback. */
23
+ export type ScheduleCancel = () => void;
24
+ export type Schedule = (fn: () => void, ms: number) => ScheduleCancel;
25
+
26
+ export type CatalogSettleWaiter = {
27
+ /** Resolves when the catalog stops loading, or after `timeoutMs`. */
28
+ wait: (timeoutMs: number) => Promise<void>;
29
+ /** Wakes every parked waiter. Called when the catalog status leaves "loading". */
30
+ settle: () => void;
31
+ };
32
+
33
+ const defaultSchedule: Schedule = (fn, ms) => {
34
+ const timer = setTimeout(fn, ms);
35
+ return () => clearTimeout(timer);
36
+ };
37
+
38
+ export const createCatalogSettleWaiter = (
39
+ isLoading: () => boolean,
40
+ schedule: Schedule = defaultSchedule
41
+ ): CatalogSettleWaiter => {
42
+ let waiters = new Set<() => void>();
43
+
44
+ return {
45
+ wait: (timeoutMs) =>
46
+ new Promise<void>((resolve) => {
47
+ // Nothing to wait for — do not allocate a timer or an entry.
48
+ if (!isLoading()) return resolve();
49
+
50
+ let settled = false;
51
+ let cancelTimer: ScheduleCancel = () => {};
52
+
53
+ const finish = () => {
54
+ if (settled) return; // invariant 1
55
+ settled = true;
56
+ waiters.delete(finish);
57
+ cancelTimer();
58
+ resolve();
59
+ };
60
+
61
+ waiters.add(finish);
62
+ cancelTimer = schedule(finish, timeoutMs);
63
+ }),
64
+
65
+ settle: () => {
66
+ // Swapped before draining — invariant 2.
67
+ const parked = waiters;
68
+ waiters = new Set();
69
+ for (const wake of parked) wake();
70
+ },
71
+ };
72
+ };
@@ -3,6 +3,7 @@ import type { QueryClient } from "@tanstack/react-query";
3
3
  import { OnboardingStudioClient } from "../OnboardingStudioClient";
4
4
  import { PaywallCatalog } from "./types";
5
5
  import { getPaywallsCacheKey } from "../infra/queries/cacheKey";
6
+ import { paramsHash } from "../userProperties/serialize";
6
7
 
7
8
  /**
8
9
  * Mirrors `getOnboarding.query.ts`'s cache-first / background-revalidate /
@@ -56,7 +57,14 @@ export const getPaywallsQuery = (
56
57
  // with NO background revalidation, so a pinned version survives across
57
58
  // launches. The default key keeps stale-while-revalidate.
58
59
  const hasCustomKey = Boolean(client.options.cacheKey);
59
- const cacheKey = getPaywallsCacheKey(client.options.cacheKey);
60
+ // Scoped by the resolved audience params — see `cacheKey.ts`. This is what
61
+ // makes `catalogStatus: "revalidating"` mean "a genuine freshness refresh"
62
+ // rather than "this catalog may have been resolved under other params",
63
+ // which `register()`'s decision relies on.
64
+ const cacheKey = getPaywallsCacheKey(
65
+ client.options.cacheKey,
66
+ paramsHash(customAudienceParams as Record<string, string>),
67
+ );
60
68
 
61
69
  // Fetches the live catalog, caches it, and pushes it into the query
62
70
  // cache directly — see the module doc above for why that push is
@@ -0,0 +1,169 @@
1
+ import type { Paywall, PaywallCatalog, PresentResult } from "./types";
2
+ import type { CatalogStatus } from "./present";
3
+
4
+ /** The feature `register` gates. May be async; `register` awaits it. */
5
+ export type RegisterFeature = () => void | Promise<void>;
6
+
7
+ /**
8
+ * What `register(moment, feature)` should do, as a pure function of current
9
+ * state — extracted for the same reason `resolvePresentDecision` and
10
+ * `shouldAdvanceOnComplete` are: every branch on a monetisation path gets an
11
+ * importable test rather than inspection.
12
+ */
13
+ export type RegisterDecision =
14
+ | { type: "run"; reason: "no-paywall" | "catalog-unavailable" }
15
+ | { type: "present"; paywall: Paywall }
16
+ | { type: "wait" };
17
+
18
+ /**
19
+ * `wait` is a DECISION rather than something the caller infers from
20
+ * `catalogStatus` itself, so "when may register block?" has exactly one answer in
21
+ * one tested place. The caller awaits the catalog settling and calls this again;
22
+ * the second call cannot return `wait`, because the wait resolves only on
23
+ * `"ready"`/`"error"` and a timeout is treated as `catalog-unavailable` without
24
+ * asking again.
25
+ *
26
+ * `"revalidating"` counts as usable. That is safe only because the AsyncStorage
27
+ * cache key is scoped by audience params: before that, a revalidating catalog
28
+ * might have been resolved under DIFFERENT params, so a missing moment could
29
+ * mean "not yet" rather than "absent". Now a served catalog always matches the
30
+ * current params.
31
+ */
32
+ export const resolveRegisterDecision = (
33
+ catalog: PaywallCatalog | null,
34
+ catalogStatus: CatalogStatus,
35
+ moment: string
36
+ ): RegisterDecision => {
37
+ if (!catalog) {
38
+ // Nothing to decide against yet. "loading" is worth waiting for; anything
39
+ // else with no catalog is terminal.
40
+ return catalogStatus === "loading"
41
+ ? { type: "wait" }
42
+ : { type: "run", reason: "catalog-unavailable" };
43
+ }
44
+ const paywall = catalog.paywalls[moment];
45
+ // A moment absent from a RESOLVED catalog is not a failure: it means the moment
46
+ // is not monetised, or is not authored yet. The feature is free.
47
+ if (!paywall) return { type: "run", reason: "no-paywall" };
48
+ return { type: "present", paywall };
49
+ };
50
+
51
+ /**
52
+ * Whether a completed presentation unlocks the feature. Only a purchase does.
53
+ *
54
+ * This one-liner is correct only because `resolvePresentedOutcome` already
55
+ * upgraded the generic `{status:"dismissed"}` that the canonical authoring shape
56
+ * — `{type:"purchase", onSuccess:[{type:"dismiss"}]}` — produces into
57
+ * `"purchased"` when the store actually charged. Without that upgrade this would
58
+ * refuse the feature to every user who bought.
59
+ *
60
+ * **A Stripe paywall never unlocks on the purchase alone.** `PresentResult` has
61
+ * no `"pending"` status — that belongs to `PurchaseResult` — so a Payment Link
62
+ * checkout surfaces here as whatever its action list reported, in practice
63
+ * `"dismissed"` via its `onPending` branch. The entitlement arrives out-of-band
64
+ * through RevenueCat, so grant access from that webhook rather than from
65
+ * `register`. `runRegister` warns when it is about to present one.
66
+ */
67
+ export const shouldRunFeature = (outcome: PresentResult): boolean =>
68
+ outcome.status === "purchased";
69
+
70
+ /**
71
+ * What `register` resolves to.
72
+ *
73
+ * Returned rather than fire-and-forget so a host can measure how often it ran
74
+ * ungated: `reason: "catalog-unavailable"` is the rate at which failing open is
75
+ * giving features away, and a host that cannot see that number cannot decide
76
+ * whether the default is right for it.
77
+ */
78
+ export type RegisterResult =
79
+ | { ran: true; presented: false; reason: "no-paywall" | "catalog-unavailable" }
80
+ | { ran: true; presented: true; reason: "purchased"; outcome: PresentResult }
81
+ | { ran: false; presented: true; reason: "not-purchased"; outcome: PresentResult };
82
+
83
+ /**
84
+ * Everything `register` reads from its environment, injected.
85
+ *
86
+ * The catalog and its status are read through GETTERS rather than passed by value
87
+ * because `register` may await a wait in the middle: reading them once up front
88
+ * would decide against a catalog that has since arrived, which is the entire
89
+ * point of waiting.
90
+ */
91
+ export type RegisterDeps = {
92
+ getCatalog: () => PaywallCatalog | null;
93
+ getCatalogStatus: () => CatalogStatus;
94
+ /** Resolves when the catalog stops loading, or after `timeoutMs`. */
95
+ waitForCatalogSettled: (timeoutMs: number) => Promise<void>;
96
+ present: (moment: string) => Promise<PresentResult>;
97
+ timeoutMs: number;
98
+ };
99
+
100
+ /**
101
+ * `register(moment, feature)`'s whole orchestration.
102
+ *
103
+ * Lives here rather than inside `PaywallProvider` so every branch — both
104
+ * fail-open paths, the wait-once rule, the Stripe warning, and the
105
+ * withhold-on-dismiss case — is covered by a plain async test. This repo has no
106
+ * vitest config, so tests run without a DOM; a provider-rendering test would mean
107
+ * adding jsdom to assert control flow that has nothing to do with rendering.
108
+ *
109
+ * It delegates presentation to the injected `present`, which in the provider is
110
+ * the real one — so the wedge recovery, the purchase-generation race guard and
111
+ * outcome reconciliation all apply unchanged.
112
+ */
113
+ export const runRegister = async (
114
+ deps: RegisterDeps,
115
+ moment: string,
116
+ feature?: RegisterFeature
117
+ ): Promise<RegisterResult> => {
118
+ let decision = resolveRegisterDecision(deps.getCatalog(), deps.getCatalogStatus(), moment);
119
+
120
+ if (decision.type === "wait") {
121
+ // Called on a user tap, so it cannot simply fail because the catalog has not
122
+ // landed. In practice a returning user's catalog is already on disk and this
123
+ // resolves immediately.
124
+ await deps.waitForCatalogSettled(deps.timeoutMs);
125
+ decision = resolveRegisterDecision(deps.getCatalog(), deps.getCatalogStatus(), moment);
126
+ // The wait timed out with the catalog still loading. Decide — never wait a
127
+ // second time, or a permanently-loading catalog would park the caller
128
+ // forever in `timeoutMs` increments.
129
+ if (decision.type === "wait") decision = { type: "run", reason: "catalog-unavailable" };
130
+ }
131
+
132
+ if (decision.type === "run") {
133
+ if (decision.reason === "catalog-unavailable") {
134
+ // Failing OPEN. The alternative locks every gated feature behind a network
135
+ // call: an offline launch would make the app's features silently dead with
136
+ // no paywall to explain why, which is indistinguishable from a broken app.
137
+ // The cost is real — some sessions get a paid feature free — so it is
138
+ // logged, and the returned `reason` lets a host measure the rate.
139
+ console.warn(
140
+ `[paywalls] register("${moment}") could not reach a verdict (no paywall catalog) ` +
141
+ "and ran the feature ungated. The catalog failed to load, or is still loading " +
142
+ "after the register timeout."
143
+ );
144
+ }
145
+ await feature?.();
146
+ return { ran: true, presented: false, reason: decision.reason };
147
+ }
148
+
149
+ if (decision.paywall.billing === "stripe") {
150
+ // See `shouldRunFeature`: a Payment Link checkout never produces a
151
+ // "purchased" PresentResult, so the gated feature cannot unlock from it.
152
+ console.warn(
153
+ `[paywalls] register("${moment}") will present a Stripe-billed paywall. A Payment ` +
154
+ 'Link checkout never resolves as "purchased" — the entitlement arrives out-of-band ' +
155
+ "through RevenueCat — so the gated feature will NOT run on a successful checkout. " +
156
+ "Grant access from your RevenueCat entitlement webhook instead."
157
+ );
158
+ }
159
+
160
+ const outcome = await deps.present(moment);
161
+ if (shouldRunFeature(outcome)) {
162
+ await feature?.();
163
+ return { ran: true, presented: true, reason: "purchased", outcome };
164
+ }
165
+ // Covers dismissed, cancelled and every `present()` error — including
166
+ // "already-presenting", which needs no branch of its own: the feature does not
167
+ // run and the in-flight paywall is untouched.
168
+ return { ran: false, presented: true, reason: "not-purchased", outcome };
169
+ };
@@ -4,6 +4,7 @@ import { PaywallCatalog, PresentResult } from "./types";
4
4
  import type { CatalogStatus } from "./present";
5
5
  import type { ProductStatus } from "../products/types";
6
6
  import type { CustomPaywallScreens } from "./customScreens";
7
+ import type { RegisterFeature, RegisterResult } from "./register";
7
8
 
8
9
  export type UsePaywallResult = {
9
10
  /**
@@ -17,6 +18,34 @@ export type UsePaywallResult = {
17
18
  * presented. See `resolvePresentDecision` in `present.ts`.
18
19
  */
19
20
  present: (moment: string) => Promise<PresentResult>;
21
+ /**
22
+ * Gate a feature on a moment — Superwall's `registerPlacement`, in this SDK's
23
+ * vocabulary:
24
+ *
25
+ * ```ts
26
+ * await register("unlock_stats", () => router.push("/stats"));
27
+ * ```
28
+ *
29
+ * - The moment has **no paywall** (not monetised, or not authored yet) → runs
30
+ * the feature immediately.
31
+ * - The moment **has** a paywall → presents it, and runs the feature **only**
32
+ * on a purchase. A dismiss or a cancel withholds it.
33
+ * - **No catalog is reachable** → fails OPEN: runs the feature and warns. An
34
+ * offline launch must not silently disable the app's features. Read
35
+ * `reason: "catalog-unavailable"` off the result to measure how often this
36
+ * happens.
37
+ *
38
+ * Gates on the moment **alone** — there is no entitlement check. Exclude
39
+ * paying users by setting a user property
40
+ * (`OnboardingStudio.setUserProperty("plan", "pro")`)
41
+ * and authoring an audience filter on it.
42
+ *
43
+ * **A Stripe-billed paywall never runs the feature**, even on a successful
44
+ * checkout: a Payment Link resolves out-of-band through RevenueCat, so the
45
+ * presentation never reports `"purchased"`. Grant access from your RevenueCat
46
+ * entitlement webhook. `register` warns when it presents one.
47
+ */
48
+ register: (moment: string, feature?: RegisterFeature) => Promise<RegisterResult>;
20
49
  /**
21
50
  * `true` once BOTH the catalog and its products have resolved — the one
22
51
  * flag meaning "calling `present()` now will not show a spinner".
@@ -59,10 +88,19 @@ export type UsePaywallResult = {
59
88
  * `useProductRuntime()` degrades to `null` with no ancestor.
60
89
  */
61
90
  export const usePaywall = (): UsePaywallResult => {
62
- const { present, isReady, catalog, catalogStatus, productsStatus, isProviderMounted, customScreens } =
63
- useContext(PaywallContext);
91
+ const {
92
+ present,
93
+ register,
94
+ isReady,
95
+ catalog,
96
+ catalogStatus,
97
+ productsStatus,
98
+ isProviderMounted,
99
+ customScreens,
100
+ } = useContext(PaywallContext);
64
101
  return {
65
102
  present,
103
+ register,
66
104
  isReady,
67
105
  catalog,
68
106
  catalogStatus,
@@ -0,0 +1,51 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+ import { resolveEffectiveParams } from "../effectiveParams";
3
+
4
+ beforeEach(() => {
5
+ vi.restoreAllMocks();
6
+ });
7
+
8
+ describe("resolveEffectiveParams", () => {
9
+ it("merges the store over the prop", () => {
10
+ expect(resolveEffectiveParams({ onboardingId: "abc", plan: "stale" }, { plan: "free" })).toEqual({
11
+ onboardingId: "abc",
12
+ plan: "free",
13
+ });
14
+ });
15
+
16
+ it("serializes both sides to strings", () => {
17
+ expect(resolveEffectiveParams({ build: 42 }, { days: 3, trial: true })).toEqual({
18
+ build: "42",
19
+ days: "3",
20
+ trial: "true",
21
+ });
22
+ });
23
+
24
+ it('drops a null or undefined baseline value rather than sending "null"', () => {
25
+ expect(resolveEffectiveParams({ a: null, b: undefined, c: "keep" }, {})).toEqual({ c: "keep" });
26
+ });
27
+
28
+ it("drops a reserved key present in the baseline prop, warning once", () => {
29
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
30
+ expect(resolveEffectiveParams({ projectId: "sneaky", plan: "free" }, {})).toEqual({
31
+ plan: "free",
32
+ });
33
+ expect(warn).toHaveBeenCalledTimes(1);
34
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining("projectId"));
35
+ });
36
+
37
+ it("returns an empty map for empty inputs", () => {
38
+ expect(resolveEffectiveParams({}, {})).toEqual({});
39
+ });
40
+
41
+ it("tolerates a missing baseline", () => {
42
+ expect(resolveEffectiveParams(undefined as any, { plan: "free" })).toEqual({ plan: "free" });
43
+ });
44
+
45
+ it("stringifies an unsupported baseline value rather than dropping it", () => {
46
+ // `customAudienceParams` is typed `Record<string, any>` and predates this
47
+ // module, so an existing host may already be passing something exotic. It
48
+ // must keep reaching the server exactly as it did before.
49
+ expect(resolveEffectiveParams({ ids: [1, 2] }, {})).toEqual({ ids: "1,2" });
50
+ });
51
+ });