@rocapine/react-native-onboarding 1.72.0 → 1.74.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 (117) hide show
  1. package/README.md +136 -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 +10 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +43 -4
  13. package/dist/index.js.map +1 -1
  14. package/dist/infra/provider/OnboardingProvider.d.ts +11 -2
  15. package/dist/infra/provider/OnboardingProvider.d.ts.map +1 -1
  16. package/dist/infra/provider/OnboardingProvider.js +26 -2
  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 +95 -5
  26. package/dist/paywalls/PaywallProvider.d.ts.map +1 -1
  27. package/dist/paywalls/PaywallProvider.js +121 -9
  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/customScreens.d.ts +83 -0
  34. package/dist/paywalls/customScreens.d.ts.map +1 -0
  35. package/dist/paywalls/customScreens.js +3 -0
  36. package/dist/paywalls/customScreens.js.map +1 -0
  37. package/dist/paywalls/getPaywalls.query.d.ts.map +1 -1
  38. package/dist/paywalls/getPaywalls.query.js +6 -1
  39. package/dist/paywalls/getPaywalls.query.js.map +1 -1
  40. package/dist/paywalls/register.d.ts +105 -0
  41. package/dist/paywalls/register.d.ts.map +1 -0
  42. package/dist/paywalls/register.js +112 -0
  43. package/dist/paywalls/register.js.map +1 -0
  44. package/dist/paywalls/usePaywall.d.ts +43 -0
  45. package/dist/paywalls/usePaywall.d.ts.map +1 -1
  46. package/dist/paywalls/usePaywall.js +11 -2
  47. package/dist/paywalls/usePaywall.js.map +1 -1
  48. package/dist/steps/Paywall/types.d.ts +63 -0
  49. package/dist/steps/Paywall/types.d.ts.map +1 -0
  50. package/dist/steps/Paywall/types.js +29 -0
  51. package/dist/steps/Paywall/types.js.map +1 -0
  52. package/dist/steps/types.d.ts +2 -1
  53. package/dist/steps/types.d.ts.map +1 -1
  54. package/dist/userProperties/applyPatch.d.ts +18 -0
  55. package/dist/userProperties/applyPatch.d.ts.map +1 -0
  56. package/dist/userProperties/applyPatch.js +57 -0
  57. package/dist/userProperties/applyPatch.js.map +1 -0
  58. package/dist/userProperties/effectiveParams.d.ts +29 -0
  59. package/dist/userProperties/effectiveParams.d.ts.map +1 -0
  60. package/dist/userProperties/effectiveParams.js +56 -0
  61. package/dist/userProperties/effectiveParams.js.map +1 -0
  62. package/dist/userProperties/index.d.ts +9 -0
  63. package/dist/userProperties/index.d.ts.map +1 -0
  64. package/dist/userProperties/index.js +21 -0
  65. package/dist/userProperties/index.js.map +1 -0
  66. package/dist/userProperties/reserved.d.ts +33 -0
  67. package/dist/userProperties/reserved.d.ts.map +1 -0
  68. package/dist/userProperties/reserved.js +45 -0
  69. package/dist/userProperties/reserved.js.map +1 -0
  70. package/dist/userProperties/serialize.d.ts +38 -0
  71. package/dist/userProperties/serialize.d.ts.map +1 -0
  72. package/dist/userProperties/serialize.js +67 -0
  73. package/dist/userProperties/serialize.js.map +1 -0
  74. package/dist/userProperties/store.d.ts +63 -0
  75. package/dist/userProperties/store.d.ts.map +1 -0
  76. package/dist/userProperties/store.js +153 -0
  77. package/dist/userProperties/store.js.map +1 -0
  78. package/dist/userProperties/types.d.ts +21 -0
  79. package/dist/userProperties/types.d.ts.map +1 -0
  80. package/dist/userProperties/types.js +3 -0
  81. package/dist/userProperties/types.js.map +1 -0
  82. package/dist/userProperties/useUserProperties.d.ts +20 -0
  83. package/dist/userProperties/useUserProperties.d.ts.map +1 -0
  84. package/dist/userProperties/useUserProperties.js +30 -0
  85. package/dist/userProperties/useUserProperties.js.map +1 -0
  86. package/package.json +1 -1
  87. package/src/OnboardingStudio.ts +147 -0
  88. package/src/OnboardingStudioClient.ts +27 -11
  89. package/src/__tests__/OnboardingStudio.test.ts +208 -0
  90. package/src/__tests__/cacheKey.test.ts +71 -0
  91. package/src/__tests__/getOnboarding.query.test.ts +47 -8
  92. package/src/index.ts +51 -0
  93. package/src/infra/provider/OnboardingProvider.tsx +45 -4
  94. package/src/infra/queries/cacheKey.ts +54 -9
  95. package/src/infra/queries/getOnboarding.query.ts +9 -1
  96. package/src/paywalls/PaywallProvider.tsx +226 -9
  97. package/src/paywalls/__tests__/catalogSettleWaiter.test.ts +134 -0
  98. package/src/paywalls/__tests__/getPaywalls.test.ts +29 -11
  99. package/src/paywalls/__tests__/register.test.ts +266 -0
  100. package/src/paywalls/catalogSettleWaiter.ts +72 -0
  101. package/src/paywalls/customScreens.ts +82 -0
  102. package/src/paywalls/getPaywalls.query.ts +9 -1
  103. package/src/paywalls/register.ts +169 -0
  104. package/src/paywalls/usePaywall.ts +63 -3
  105. package/src/steps/Paywall/types.ts +29 -0
  106. package/src/steps/types.ts +2 -0
  107. package/src/userProperties/__tests__/effectiveParams.test.ts +51 -0
  108. package/src/userProperties/__tests__/primitives.test.ts +96 -0
  109. package/src/userProperties/__tests__/store.test.ts +181 -0
  110. package/src/userProperties/applyPatch.ts +68 -0
  111. package/src/userProperties/effectiveParams.ts +60 -0
  112. package/src/userProperties/index.ts +11 -0
  113. package/src/userProperties/reserved.ts +44 -0
  114. package/src/userProperties/serialize.ts +61 -0
  115. package/src/userProperties/store.ts +177 -0
  116. package/src/userProperties/types.ts +22 -0
  117. package/src/userProperties/useUserProperties.ts +26 -0
@@ -3,6 +3,7 @@ import { OnboardingStudioClient } from "../../OnboardingStudioClient";
3
3
  import { BaseStepType, Onboarding, OnboardingMetadata } from "../../types";
4
4
  import type { UseQueryOptions } from "@tanstack/react-query";
5
5
  import { getOnboardingCacheKey } from "./cacheKey";
6
+ import { paramsHash } from "../../userProperties/serialize";
6
7
 
7
8
  export const getOnboardingQuery = <StepType extends BaseStepType>(
8
9
  client: OnboardingStudioClient,
@@ -26,7 +27,14 @@ export const getOnboardingQuery = <StepType extends BaseStepType>(
26
27
  // with NO background revalidation, so a pinned version survives across
27
28
  // launches. The default key keeps stale-while-revalidate.
28
29
  const hasCustomKey = Boolean(client.options.cacheKey);
29
- const cacheKey = getOnboardingCacheKey(client.options.cacheKey);
30
+ // Scoped by the resolved audience params — see `cacheKey.ts`. The provider
31
+ // hands these over already serialized to strings
32
+ // (`userProperties/effectiveParams.ts`), so the hash sees the same bytes
33
+ // that go on the querystring.
34
+ const cacheKey = getOnboardingCacheKey(
35
+ client.options.cacheKey,
36
+ paramsHash(customAudienceParams as Record<string, string>),
37
+ );
30
38
 
31
39
  // Fetches the live payload, pushes it to the provider, and caches it —
32
40
  // but NEVER caches the offline fallback. Caching the fallback (with
@@ -20,6 +20,19 @@ import { useProducts } from "../products/useProducts";
20
20
  import { ProductProvider, ProductStatus } from "../products/types";
21
21
  import { ProductRuntimeContext } from "../products/ProductRuntimeContext";
22
22
  import type { CustomActions } from "../infra/provider/OnboardingProvider";
23
+ import type { CustomPaywallScreens } from "./customScreens";
24
+ import { useUserProperties } from "../userProperties/useUserProperties";
25
+ import { resolveEffectiveParams } from "../userProperties/effectiveParams";
26
+ import { runRegister, type RegisterFeature, type RegisterResult } from "./register";
27
+ import {
28
+ OnboardingStudio,
29
+ resolveProviderClient,
30
+ MISSING_CLIENT_MESSAGE,
31
+ } from "../OnboardingStudio";
32
+ import {
33
+ createCatalogSettleWaiter,
34
+ type CatalogSettleWaiter,
35
+ } from "./catalogSettleWaiter";
23
36
 
24
37
  // Module-scope, private to this file — mirrors `OnboardingProvider.tsx:17-23`.
25
38
  // `OnboardingProvider`'s QueryClient is not exported, so it cannot be reused
@@ -43,6 +56,12 @@ const paywallQueryClient = new QueryClient({
43
56
  // way `EMPTY_CUSTOM_ACTIONS` in `OnboardingProvider.tsx` documents.
44
57
  const EMPTY_CUSTOM_ACTIONS: CustomActions = Object.freeze({});
45
58
 
59
+ // Frozen at module scope for the same reason as EMPTY_CUSTOM_ACTIONS above: it
60
+ // sits in the published context value, and an unstable identity would defeat
61
+ // memoization in every consumer that lists it as a dependency (the inline
62
+ // `Paywall` step's decision memo does).
63
+ const EMPTY_CUSTOM_SCREENS: CustomPaywallScreens = Object.freeze({});
64
+
46
65
  /**
47
66
  * Everything a paywall consumer or a paywall HOST needs. Deliberately one
48
67
  * context carrying both, mirroring how `OnboardingProgressContext` bundles
@@ -52,6 +71,20 @@ const EMPTY_CUSTOM_ACTIONS: CustomActions = Object.freeze({});
52
71
  */
53
72
  export type PaywallContextValue = {
54
73
  present: (moment: string) => Promise<PresentResult>;
74
+ /**
75
+ * Gate a feature on a moment: `register("unlock_stats", () => go())`.
76
+ *
77
+ * Runs the feature immediately when the moment has no paywall (it is not
78
+ * monetised, or not authored yet), otherwise presents the moment's paywall and
79
+ * runs the feature ONLY on a purchase. Gates on the moment alone — there is no
80
+ * entitlement check; exclude subscribers with an audience filter on a user
81
+ * property.
82
+ *
83
+ * Fails OPEN: when no catalog is reachable it runs the feature and warns, so an
84
+ * offline launch does not silently disable the app's features. The resolved
85
+ * `reason` reports which path was taken, so a host can measure that rate.
86
+ */
87
+ register: (moment: string, feature?: RegisterFeature) => Promise<RegisterResult>;
55
88
  isReady: boolean;
56
89
  catalog: PaywallCatalog | null;
57
90
  /**
@@ -61,6 +94,22 @@ export type PaywallContextValue = {
61
94
  * does not yet mean an absent one.
62
95
  */
63
96
  catalogStatus: CatalogStatus;
97
+ /**
98
+ * Whether a real `PaywallProvider` is above this consumer.
99
+ *
100
+ * Exists because `EMPTY_PAYWALL_CONTEXT` reports `catalogStatus: "loading"` —
101
+ * honest for `present()`'s contract (nothing is loading and nothing will
102
+ * arrive, so `"error"` is the answer) but INDISTINGUISHABLE from a genuine
103
+ * first load. A consumer that renders a spinner while loading would spin
104
+ * forever under no provider, and the inline `Paywall` onboarding step
105
+ * (`UI/Pages/Paywall/Renderer.tsx` in the UI package) is exactly that
106
+ * consumer.
107
+ *
108
+ * Deliberately NOT a new `CatalogStatus` member: widening that union breaks
109
+ * every host switching exhaustively over it, and "no provider" is not a
110
+ * catalog state.
111
+ */
112
+ isProviderMounted: boolean;
64
113
  /**
65
114
  * What the store products are doing. The other half of `isReady`: a host that
66
115
  * sees `catalogStatus: "ready"` but `isReady: false` can tell it is waiting on
@@ -86,21 +135,44 @@ export type PaywallContextValue = {
86
135
  acknowledgePresentation: () => void;
87
136
  /** Forwarded into the presented paywall's `ScreenHost.customActions`. */
88
137
  customActions: CustomActions;
138
+ /**
139
+ * Host-registered screens for `renderMode: "custom"` paywalls, keyed by
140
+ * `customScreenId`.
141
+ *
142
+ * Published HERE — rather than only on `PaywallHost`, where it started in
143
+ * 1.72.0 — because there are now two renderers: that Modal, and the inline
144
+ * `Paywall` onboarding step, which never goes through `PaywallHost` at all.
145
+ * One registration has to serve both, and this is the provider every host
146
+ * already mounts. `PaywallHost`'s own prop still wins for that host.
147
+ */
148
+ customScreens: CustomPaywallScreens;
89
149
  };
90
150
 
91
151
  const EMPTY_PAYWALL_CONTEXT: PaywallContextValue = {
92
152
  // No provider above: there is no catalog at all, which is the same answer
93
153
  // `resolvePresentDecision` gives for an unresolved one.
94
154
  present: async () => ({ status: "error", reason: "unknown-moment" }),
155
+ // No provider above: no verdict is reachable, which is exactly the fail-open
156
+ // case — consistent with how `register` treats an unavailable catalog. A host
157
+ // that forgot the provider gets a working app whose features are ungated,
158
+ // rather than an app whose gated features are all silently dead.
159
+ register: async (_moment, feature) => {
160
+ await feature?.();
161
+ return { ran: true, presented: false, reason: "catalog-unavailable" };
162
+ },
95
163
  isReady: false,
96
164
  catalog: null,
97
165
  // No provider above: nothing is loading and nothing will arrive.
98
166
  catalogStatus: "loading",
167
+ // The one value that distinguishes this object from a real provider's — see
168
+ // the field's doc above for why `catalogStatus` cannot do that job.
169
+ isProviderMounted: false,
99
170
  productsStatus: "idle",
100
171
  activePaywall: null,
101
172
  complete: () => {},
102
173
  acknowledgePresentation: () => {},
103
174
  customActions: EMPTY_CUSTOM_ACTIONS,
175
+ customScreens: EMPTY_CUSTOM_SCREENS,
104
176
  };
105
177
 
106
178
  /**
@@ -111,6 +183,13 @@ const EMPTY_PAYWALL_CONTEXT: PaywallContextValue = {
111
183
  */
112
184
  const DEFAULT_PRESENT_ACK_TIMEOUT_MS = 5000;
113
185
 
186
+ /**
187
+ * How long `register()` waits for the catalog to settle before deciding without
188
+ * it. Generous enough that a cold network fetch usually lands, short enough that
189
+ * a tap does not feel stuck.
190
+ */
191
+ export const DEFAULT_REGISTER_TIMEOUT_MS = 3000;
192
+
114
193
  export const PaywallContext = createContext<PaywallContextValue>(EMPTY_PAYWALL_CONTEXT);
115
194
 
116
195
  /**
@@ -122,16 +201,24 @@ export const PaywallContext = createContext<PaywallContextValue>(EMPTY_PAYWALL_C
122
201
  */
123
202
  export const usePaywallHost = (): Pick<
124
203
  PaywallContextValue,
125
- "activePaywall" | "complete" | "acknowledgePresentation" | "customActions"
204
+ "activePaywall" | "complete" | "acknowledgePresentation" | "customActions" | "customScreens"
126
205
  > => {
127
- const { activePaywall, complete, acknowledgePresentation, customActions } =
206
+ const { activePaywall, complete, acknowledgePresentation, customActions, customScreens } =
128
207
  useContext(PaywallContext);
129
- return { activePaywall, complete, acknowledgePresentation, customActions };
208
+ return { activePaywall, complete, acknowledgePresentation, customActions, customScreens };
130
209
  };
131
210
 
132
211
  interface PaywallProviderProps {
133
212
  children: React.ReactNode;
134
- client: OnboardingStudioClient;
213
+ /**
214
+ * The studio client. Optional: omit it and the provider uses the client
215
+ * `OnboardingStudio.init({ projectId })` built. Passing one explicitly still
216
+ * wins, so an existing host is unaffected.
217
+ *
218
+ * With neither, this provider warns and renders `children` with paywalls inert
219
+ * — it does not throw, because it wraps the whole app.
220
+ */
221
+ client?: OnboardingStudioClient;
135
222
  locale?: string;
136
223
  customAudienceParams?: Record<string, any>;
137
224
  /**
@@ -161,6 +248,20 @@ interface PaywallProviderProps {
161
248
  stripeProductProvider?: ProductProvider;
162
249
  /** Handlers for `{ type: "custom" }` ButtonActions inside a paywall's elements. */
163
250
  customActions?: CustomActions;
251
+ /**
252
+ * Screens for `renderMode: "custom"` paywalls, keyed by the
253
+ * `customScreenId` authored in the studio.
254
+ *
255
+ * THE canonical place to register them: both renderers read from here —
256
+ * `PaywallHost`'s Modal and the inline `Paywall` onboarding step, which never
257
+ * goes through `PaywallHost`. `PaywallHost` still accepts its own
258
+ * `customScreens` prop (1.72.0's API), and that prop overrides this for that
259
+ * host; prefer this one.
260
+ *
261
+ * MUST be referentially stable (module scope, or `useMemo`) — it lands in the
262
+ * context value and in consumers' dependency arrays.
263
+ */
264
+ customScreens?: CustomPaywallScreens;
164
265
  /**
165
266
  * How long to wait for the host to confirm a paywall actually appeared
166
267
  * before abandoning the presentation and resolving
@@ -171,6 +272,15 @@ interface PaywallProviderProps {
171
272
  * rest of the process. Only pass `null` if the host cannot acknowledge.
172
273
  */
173
274
  presentAckTimeoutMs?: number | null;
275
+ /**
276
+ * How long `register()` waits for the paywall catalog to settle before deciding
277
+ * without it. Defaults to 3000 ms.
278
+ *
279
+ * On timeout `register` fails OPEN — it runs the gated feature and warns. Lower
280
+ * it if a tap feels stuck on a slow network; raise it to give the catalog more
281
+ * chance to land before a feature is given away.
282
+ */
283
+ registerTimeoutMs?: number;
174
284
  }
175
285
 
176
286
  interface PaywallProviderInnerProps {
@@ -181,7 +291,9 @@ interface PaywallProviderInnerProps {
181
291
  productProvider?: ProductProvider;
182
292
  stripeProductProvider?: ProductProvider;
183
293
  customActions: CustomActions;
294
+ customScreens: CustomPaywallScreens;
184
295
  presentAckTimeoutMs: number | null;
296
+ registerTimeoutMs: number;
185
297
  }
186
298
 
187
299
  const PaywallProviderInner = ({
@@ -192,7 +304,9 @@ const PaywallProviderInner = ({
192
304
  productProvider,
193
305
  stripeProductProvider,
194
306
  customActions,
307
+ customScreens,
195
308
  presentAckTimeoutMs,
309
+ registerTimeoutMs,
196
310
  }: PaywallProviderInnerProps) => {
197
311
  // `data` straight off `useQuery` is the single source of truth (Finding 1,
198
312
  // 2026-08-17 final review) — react-query's own cache already gets both a
@@ -202,9 +316,28 @@ const PaywallProviderInner = ({
202
316
  // for why the query still needs `paywallQueryClient` for the ONE case
203
317
  // `data` alone can't cover: a background revalidation pushing a fresh
204
318
  // payload while this query call already resolved with the cached one.
205
- const { data, error, isFetching } = useQuery<PaywallCatalog>(
206
- getPaywallsQuery(client, locale, customAudienceParams, paywallQueryClient)
319
+ // The user-property store is the RUNTIME half of audience targeting; the
320
+ // `customAudienceParams` prop is the static half. Merged store-wins and
321
+ // serialized once, so the query key, the disk cache key's hash and the
322
+ // querystring all see the same bytes — see `resolveEffectiveParams`.
323
+ const { properties, status: propertiesStatus } = useUserProperties();
324
+ const params = useMemo(
325
+ () => resolveEffectiveParams(customAudienceParams, properties),
326
+ [customAudienceParams, properties]
207
327
  );
328
+
329
+ const { data, error, isFetching } = useQuery<PaywallCatalog>({
330
+ ...getPaywallsQuery(client, locale, params, paywallQueryClient),
331
+ // Held until the store has hydrated from disk. Without this the first fetch
332
+ // of a cold launch carries an EMPTY property map, matches the catch-all
333
+ // audience, and — because the catalog is cached with `staleTime: Infinity` —
334
+ // that wrong answer is what the whole session uses.
335
+ //
336
+ // A disabled query reports `data: undefined`, `error: null`,
337
+ // `isFetching: false`, which `computeCatalogStatus` reads as "loading" — the
338
+ // honest answer while the store hydrates, and the one `register()` waits on.
339
+ enabled: propertiesStatus === "ready",
340
+ });
208
341
  const catalog = data ?? null;
209
342
  // `isFetching` (not `isLoading`) on purpose: it is also true for a BACKGROUND
210
343
  // revalidation behind an already-served cached catalog, which is precisely the
@@ -334,6 +467,19 @@ const PaywallProviderInner = ({
334
467
  // `purchase`/`restore` callbacks.
335
468
  const catalogRef = useRef(catalog);
336
469
  catalogRef.current = catalog;
470
+ // `catalogStatus` as a ref for the same reason: `register` must read the
471
+ // CURRENT status without being re-created on every status change.
472
+ const catalogStatusRef = useRef(catalogStatus);
473
+ catalogStatusRef.current = catalogStatus;
474
+ // One waiter per provider instance, reading status through the ref above. See
475
+ // `catalogSettleWaiter.ts` for the two invariants that put it in its own
476
+ // module instead of inline here.
477
+ const settleWaiterRef = useRef<CatalogSettleWaiter | null>(null);
478
+ if (settleWaiterRef.current === null) {
479
+ settleWaiterRef.current = createCatalogSettleWaiter(
480
+ () => catalogStatusRef.current === "loading"
481
+ );
482
+ }
337
483
  // `activeMomentRef` is made AUTHORITATIVE below — assigned inside
338
484
  // `present()`'s start branch and inside `complete()`, not just here. Finding
339
485
  // 4, 2026-08-17 final review: this line alone only resyncs the ref from
@@ -379,6 +525,42 @@ const PaywallProviderInner = ({
379
525
  });
380
526
  }, []);
381
527
 
528
+ // Wakes anything parked in `register` as soon as the catalog stops loading.
529
+ useEffect(() => {
530
+ if (catalogStatus === "loading") return;
531
+ settleWaiterRef.current?.settle();
532
+ }, [catalogStatus]);
533
+
534
+ /**
535
+ * Superwall's `registerPlacement`, in this SDK's vocabulary: gate a feature on
536
+ * a moment.
537
+ *
538
+ * Gates on the MOMENT alone — there is deliberately no entitlement check.
539
+ * Exclude subscribers by authoring an audience filter against a user property
540
+ * the host sets (`plan: "pro"`), which is machinery that already exists.
541
+ *
542
+ * All of the decision logic — both fail-open paths, the wait-once rule, the
543
+ * Stripe warning — is `runRegister` in `register.ts`, where it is unit-tested.
544
+ * This callback only supplies the environment.
545
+ */
546
+ const register = useCallback(
547
+ (moment: string, feature?: RegisterFeature): Promise<RegisterResult> =>
548
+ runRegister(
549
+ {
550
+ getCatalog: () => catalogRef.current,
551
+ getCatalogStatus: () => catalogStatusRef.current,
552
+ waitForCatalogSettled: (ms) => settleWaiterRef.current!.wait(ms),
553
+ // The real `present`, so the wedge recovery, the purchase-generation
554
+ // race guard and outcome reconciliation all apply unchanged.
555
+ present,
556
+ timeoutMs: registerTimeoutMs,
557
+ },
558
+ moment,
559
+ feature
560
+ ),
561
+ [present, registerTimeoutMs]
562
+ );
563
+
382
564
  // Called by PaywallHost (Task 7) from the presented paywall's
383
565
  // `ScreenHost.complete`. Resolves whatever `present()` call is pending and
384
566
  // clears the active moment, hiding the Modal and allowing a new
@@ -461,17 +643,23 @@ const PaywallProviderInner = ({
461
643
  const contextValue = useMemo<PaywallContextValue>(
462
644
  () => ({
463
645
  present,
646
+ register,
464
647
  isReady,
465
648
  catalog,
466
649
  catalogStatus,
650
+ // A literal `true` — no dependency-array entry needed, unlike every
651
+ // other member of this object.
652
+ isProviderMounted: true,
467
653
  productsStatus: productRuntime.status,
468
654
  activePaywall,
469
655
  complete,
470
656
  acknowledgePresentation,
471
657
  customActions,
658
+ customScreens,
472
659
  }),
473
660
  [
474
661
  present,
662
+ register,
475
663
  isReady,
476
664
  catalog,
477
665
  catalogStatus,
@@ -480,6 +668,7 @@ const PaywallProviderInner = ({
480
668
  complete,
481
669
  acknowledgePresentation,
482
670
  customActions,
671
+ customScreens,
483
672
  ]
484
673
  );
485
674
 
@@ -496,22 +685,48 @@ const PaywallProviderInner = ({
496
685
  * only flows to descendants; two true siblings could not share one runtime).
497
686
  *
498
687
  * ```tsx
499
- * <PaywallProvider client={client} productProvider={revenueCatProductProvider(Purchases)}>
688
+ * OnboardingStudio.init({ projectId: "…" }); // at module scope
689
+ *
690
+ * <PaywallProvider productProvider={revenueCatProductProvider(Purchases)}>
500
691
  * <App />
501
- * <PaywallHost /> // Task 7: renders the active paywall in a fullScreen RN Modal
692
+ * <PaywallHost /> // renders the active paywall in a fullScreen RN Modal
502
693
  * </PaywallProvider>
503
694
  * ```
695
+ *
696
+ * With no client at all — neither a prop nor an `OnboardingStudio.init()` — this
697
+ * WARNS and renders `children` untouched, so paywalls are inert and the app
698
+ * still runs. It deliberately does not throw the way `OnboardingProvider` does:
699
+ * this provider wraps the whole app (see the query-error effect inside), so
700
+ * throwing would take down every screen over a missing paywall client. Consumers
701
+ * then read the default context, where `isProviderMounted` is `false` and both
702
+ * `present` and `register` resolve their fail-open answers.
504
703
  */
505
704
  export const PaywallProvider = ({
506
705
  children,
507
- client,
706
+ client: clientProp,
508
707
  locale = "en",
509
708
  customAudienceParams = {},
510
709
  productProvider,
511
710
  stripeProductProvider,
512
711
  customActions = EMPTY_CUSTOM_ACTIONS,
712
+ customScreens = EMPTY_CUSTOM_SCREENS,
513
713
  presentAckTimeoutMs = DEFAULT_PRESENT_ACK_TIMEOUT_MS,
714
+ registerTimeoutMs = DEFAULT_REGISTER_TIMEOUT_MS,
514
715
  }: PaywallProviderProps) => {
716
+ // Prop wins, else whatever `OnboardingStudio.init()` built. Read during render,
717
+ // so `init()` must run before the first render — at module scope.
718
+ const client = resolveProviderClient(clientProp, OnboardingStudio.getClient());
719
+
720
+ // Effect, not an inline call, so a re-render does not re-log. Declared above
721
+ // the early return: hooks must run unconditionally.
722
+ useEffect(() => {
723
+ if (client) return;
724
+ console.warn(`${MISSING_CLIENT_MESSAGE} Paywalls are inert until then.`);
725
+ }, [client]);
726
+
727
+ // Degrade rather than throw — see the doc above.
728
+ if (!client) return <>{children}</>;
729
+
515
730
  return (
516
731
  <QueryClientProvider client={paywallQueryClient}>
517
732
  <PaywallProviderInner
@@ -521,7 +736,9 @@ export const PaywallProvider = ({
521
736
  productProvider={productProvider}
522
737
  stripeProductProvider={stripeProductProvider}
523
738
  customActions={customActions}
739
+ customScreens={customScreens}
524
740
  presentAckTimeoutMs={presentAckTimeoutMs}
741
+ registerTimeoutMs={registerTimeoutMs}
525
742
  >
526
743
  {children}
527
744
  </PaywallProviderInner>
@@ -0,0 +1,134 @@
1
+ import { describe, it, expect, vi } from "vitest";
2
+ import { createCatalogSettleWaiter } from "../catalogSettleWaiter";
3
+
4
+ // A controllable stand-in for setTimeout: records pending callbacks so a test can
5
+ // fire them deliberately instead of waiting on real time.
6
+ const makeScheduler = () => {
7
+ const pending: Array<{ fn: () => void; ms: number; cancelled: boolean }> = [];
8
+ const schedule = (fn: () => void, ms: number) => {
9
+ const entry = { fn, ms, cancelled: false };
10
+ pending.push(entry);
11
+ return () => {
12
+ entry.cancelled = true;
13
+ };
14
+ };
15
+ const fire = () => {
16
+ for (const entry of [...pending]) if (!entry.cancelled) entry.fn();
17
+ };
18
+ return { schedule, fire, pending };
19
+ };
20
+
21
+ describe("createCatalogSettleWaiter", () => {
22
+ it("resolves immediately when the catalog is not loading", async () => {
23
+ const { schedule, pending } = makeScheduler();
24
+ const waiter = createCatalogSettleWaiter(() => false, schedule);
25
+ await waiter.wait(1000);
26
+ // Nothing was scheduled: there was nothing to wait for.
27
+ expect(pending).toHaveLength(0);
28
+ });
29
+
30
+ it("parks while loading and resolves on settle()", async () => {
31
+ const { schedule } = makeScheduler();
32
+ let loading = true;
33
+ const waiter = createCatalogSettleWaiter(() => loading, schedule);
34
+
35
+ let resolved = false;
36
+ const promise = waiter.wait(1000).then(() => {
37
+ resolved = true;
38
+ });
39
+
40
+ await Promise.resolve();
41
+ expect(resolved).toBe(false);
42
+
43
+ loading = false;
44
+ waiter.settle();
45
+ await promise;
46
+ expect(resolved).toBe(true);
47
+ });
48
+
49
+ it("resolves on timeout even if settle() never comes", async () => {
50
+ const { schedule, fire } = makeScheduler();
51
+ const waiter = createCatalogSettleWaiter(() => true, schedule);
52
+ const promise = waiter.wait(1000);
53
+ fire();
54
+ await expect(promise).resolves.toBeUndefined();
55
+ });
56
+
57
+ it("passes the requested timeout to the scheduler", async () => {
58
+ const { schedule, pending, fire } = makeScheduler();
59
+ const waiter = createCatalogSettleWaiter(() => true, schedule);
60
+ const promise = waiter.wait(4321);
61
+ expect(pending[0].ms).toBe(4321);
62
+ fire();
63
+ await promise;
64
+ });
65
+
66
+ it("resolves each waiter exactly once when a timeout races a settle", async () => {
67
+ const { schedule, fire } = makeScheduler();
68
+ const waiter = createCatalogSettleWaiter(() => true, schedule);
69
+ const onResolve = vi.fn();
70
+ const promise = waiter.wait(1000).then(onResolve);
71
+
72
+ waiter.settle();
73
+ fire(); // the timeout fires after the settle already resolved it
74
+ await promise;
75
+
76
+ expect(onResolve).toHaveBeenCalledTimes(1);
77
+ });
78
+
79
+ it("cancels a waiter's timer once it has settled, leaving nothing pending", async () => {
80
+ const { schedule, pending } = makeScheduler();
81
+ const waiter = createCatalogSettleWaiter(() => true, schedule);
82
+ const promise = waiter.wait(1000);
83
+ waiter.settle();
84
+ await promise;
85
+ expect(pending.every((entry) => entry.cancelled)).toBe(true);
86
+ });
87
+
88
+ it("settles every parked waiter", async () => {
89
+ const { schedule } = makeScheduler();
90
+ const waiter = createCatalogSettleWaiter(() => true, schedule);
91
+ const results: number[] = [];
92
+ const all = Promise.all([
93
+ waiter.wait(1000).then(() => results.push(1)),
94
+ waiter.wait(1000).then(() => results.push(2)),
95
+ waiter.wait(1000).then(() => results.push(3)),
96
+ ]);
97
+ waiter.settle();
98
+ await all;
99
+ expect(results.sort()).toEqual([1, 2, 3]);
100
+ });
101
+
102
+ it("does not skip a waiter that re-parks from another waiter's continuation", async () => {
103
+ const { schedule } = makeScheduler();
104
+ const waiter = createCatalogSettleWaiter(() => true, schedule);
105
+ const second = vi.fn();
106
+
107
+ // The first waiter's continuation parks a NEW waiter — which must not be
108
+ // dropped by the drain that woke the first one.
109
+ const first = waiter.wait(1000).then(() => {
110
+ void waiter.wait(1000).then(second);
111
+ });
112
+
113
+ waiter.settle();
114
+ await first;
115
+ await Promise.resolve();
116
+ expect(second).not.toHaveBeenCalled(); // still parked, correctly
117
+
118
+ waiter.settle();
119
+ await Promise.resolve();
120
+ await Promise.resolve();
121
+ expect(second).toHaveBeenCalledTimes(1);
122
+ });
123
+
124
+ it("settle() with nothing parked is a no-op", () => {
125
+ const { schedule } = makeScheduler();
126
+ const waiter = createCatalogSettleWaiter(() => true, schedule);
127
+ expect(() => waiter.settle()).not.toThrow();
128
+ });
129
+
130
+ it("defaults to real timers when no scheduler is injected", async () => {
131
+ const waiter = createCatalogSettleWaiter(() => true);
132
+ await expect(waiter.wait(1)).resolves.toBeUndefined();
133
+ });
134
+ });
@@ -5,13 +5,17 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
5
5
  vi.mock("react-native", () => ({ Platform: { OS: "ios" } }));
6
6
 
7
7
  // AsyncStorage is mocked — the query reads/writes the paywall cache through it.
8
- const { getItem, setItem, removeItem } = vi.hoisted(() => ({
8
+ const { getItem, setItem, removeItem, getAllKeys, multiRemove } = vi.hoisted(() => ({
9
9
  getItem: vi.fn<(key: string) => Promise<string | null>>(),
10
10
  setItem: vi.fn<(key: string, value: string) => Promise<void>>(),
11
11
  removeItem: vi.fn<(key: string) => Promise<void>>(),
12
+ // `clearCache` scans by prefix now — the keys are scoped by a hash of the
13
+ // resolved audience params, so it can no longer name them one by one.
14
+ getAllKeys: vi.fn<() => Promise<string[]>>(),
15
+ multiRemove: vi.fn<(keys: string[]) => Promise<void>>(),
12
16
  }));
13
17
  vi.mock("@react-native-async-storage/async-storage", () => ({
14
- default: { getItem, setItem, removeItem },
18
+ default: { getItem, setItem, removeItem, getAllKeys, multiRemove },
15
19
  }));
16
20
 
17
21
  import { OnboardingStudioClient } from "../../OnboardingStudioClient";
@@ -315,23 +319,37 @@ describe("getPaywallsQuery", () => {
315
319
  });
316
320
 
317
321
  describe("OnboardingStudioClient.clearCache", () => {
318
- beforeEach(() => removeItem.mockReset());
322
+ beforeEach(() => {
323
+ multiRemove.mockReset();
324
+ multiRemove.mockResolvedValue(undefined);
325
+ getAllKeys.mockReset();
326
+ });
319
327
 
320
- it("removes both the default onboarding key and the default paywalls key", async () => {
328
+ it("clears both domains' default keys", async () => {
329
+ getAllKeys.mockResolvedValue([DEFAULT_ONBOARDING_CACHE_KEY, CACHE_KEY]);
321
330
  const client = new OnboardingStudioClient("p1", {});
322
331
  await client.clearCache();
323
332
 
324
- expect(removeItem).toHaveBeenCalledWith(DEFAULT_ONBOARDING_CACHE_KEY);
325
- expect(removeItem).toHaveBeenCalledWith(CACHE_KEY);
326
- expect(removeItem).toHaveBeenCalledTimes(2);
333
+ expect(multiRemove).toHaveBeenCalledWith([DEFAULT_ONBOARDING_CACHE_KEY, CACHE_KEY]);
327
334
  });
328
335
 
329
- it("removes both namespaced keys when a custom key is configured", async () => {
336
+ it("clears both namespaced keys when a custom key is configured", async () => {
337
+ getAllKeys.mockResolvedValue([`rocapine-onboarding-sdk-${CUSTOM_KEY}`, CUSTOM_CACHE_KEY]);
330
338
  const client = new OnboardingStudioClient("p1", { cacheKey: CUSTOM_KEY });
331
339
  await client.clearCache();
332
340
 
333
- expect(removeItem).toHaveBeenCalledWith(`rocapine-onboarding-sdk-${CUSTOM_KEY}`);
334
- expect(removeItem).toHaveBeenCalledWith(CUSTOM_CACHE_KEY);
335
- expect(removeItem).toHaveBeenCalledTimes(2);
341
+ expect(multiRemove).toHaveBeenCalledWith([
342
+ `rocapine-onboarding-sdk-${CUSTOM_KEY}`,
343
+ CUSTOM_CACHE_KEY,
344
+ ]);
345
+ });
346
+
347
+ it("clears a params-scoped paywall key it could not have named in advance", async () => {
348
+ const scoped = `${CACHE_KEY}-1b9a2624`;
349
+ getAllKeys.mockResolvedValue([scoped]);
350
+ const client = new OnboardingStudioClient("p1", {});
351
+ await client.clearCache();
352
+
353
+ expect(multiRemove).toHaveBeenCalledWith([scoped]);
336
354
  });
337
355
  });