@rocapine/react-native-onboarding 1.60.0 → 1.62.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.
- package/dist/OnboardingStudioClient.d.ts +23 -5
- package/dist/OnboardingStudioClient.d.ts.map +1 -1
- package/dist/OnboardingStudioClient.js +82 -6
- package/dist/OnboardingStudioClient.js.map +1 -1
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -1
- package/dist/index.js.map +1 -1
- package/dist/infra/provider/OnboardingProvider.d.ts +37 -1
- package/dist/infra/provider/OnboardingProvider.d.ts.map +1 -1
- package/dist/infra/provider/OnboardingProvider.js +76 -2
- package/dist/infra/provider/OnboardingProvider.js.map +1 -1
- package/dist/infra/queries/cacheKey.d.ts +22 -4
- package/dist/infra/queries/cacheKey.d.ts.map +1 -1
- package/dist/infra/queries/cacheKey.js +26 -5
- package/dist/infra/queries/cacheKey.js.map +1 -1
- package/dist/paywalls/PaywallProvider.d.ts +66 -0
- package/dist/paywalls/PaywallProvider.d.ts.map +1 -0
- package/dist/paywalls/PaywallProvider.js +227 -0
- package/dist/paywalls/PaywallProvider.js.map +1 -0
- package/dist/paywalls/getPaywalls.query.d.ts +37 -0
- package/dist/paywalls/getPaywalls.query.d.ts.map +1 -0
- package/dist/paywalls/getPaywalls.query.js +114 -0
- package/dist/paywalls/getPaywalls.query.js.map +1 -0
- package/dist/paywalls/present.d.ts +100 -0
- package/dist/paywalls/present.d.ts.map +1 -0
- package/dist/paywalls/present.js +113 -0
- package/dist/paywalls/present.js.map +1 -0
- package/dist/paywalls/types.d.ts +95 -0
- package/dist/paywalls/types.d.ts.map +1 -0
- package/dist/paywalls/types.js +10 -0
- package/dist/paywalls/types.js.map +1 -0
- package/dist/paywalls/usePaywall.d.ts +29 -0
- package/dist/paywalls/usePaywall.d.ts.map +1 -0
- package/dist/paywalls/usePaywall.js +17 -0
- package/dist/paywalls/usePaywall.js.map +1 -0
- package/dist/products/ProductRuntimeContext.d.ts +15 -0
- package/dist/products/ProductRuntimeContext.d.ts.map +1 -0
- package/dist/products/ProductRuntimeContext.js +19 -0
- package/dist/products/ProductRuntimeContext.js.map +1 -0
- package/dist/products/adapters/expoIap.d.ts +4 -0
- package/dist/products/adapters/expoIap.d.ts.map +1 -0
- package/dist/products/adapters/expoIap.js +95 -0
- package/dist/products/adapters/expoIap.js.map +1 -0
- package/dist/products/adapters/revenueCat.d.ts +7 -0
- package/dist/products/adapters/revenueCat.d.ts.map +1 -0
- package/dist/products/adapters/revenueCat.js +116 -0
- package/dist/products/adapters/revenueCat.js.map +1 -0
- package/dist/products/adapters/stub.d.ts +8 -0
- package/dist/products/adapters/stub.d.ts.map +1 -0
- package/dist/products/adapters/stub.js +21 -0
- package/dist/products/adapters/stub.js.map +1 -0
- package/dist/products/derive.d.ts +19 -0
- package/dist/products/derive.d.ts.map +1 -0
- package/dist/products/derive.js +79 -0
- package/dist/products/derive.js.map +1 -0
- package/dist/products/duration.d.ts +3 -0
- package/dist/products/duration.d.ts.map +1 -0
- package/dist/products/duration.js +25 -0
- package/dist/products/duration.js.map +1 -0
- package/dist/products/index.d.ts +10 -0
- package/dist/products/index.d.ts.map +1 -0
- package/dist/products/index.js +23 -0
- package/dist/products/index.js.map +1 -0
- package/dist/products/mergeProductRuntimes.d.ts +55 -0
- package/dist/products/mergeProductRuntimes.d.ts.map +1 -0
- package/dist/products/mergeProductRuntimes.js +79 -0
- package/dist/products/mergeProductRuntimes.js.map +1 -0
- package/dist/products/toVariables.d.ts +18 -0
- package/dist/products/toVariables.d.ts.map +1 -0
- package/dist/products/toVariables.js +52 -0
- package/dist/products/toVariables.js.map +1 -0
- package/dist/products/types.d.ts +96 -0
- package/dist/products/types.d.ts.map +1 -0
- package/dist/products/types.js +3 -0
- package/dist/products/types.js.map +1 -0
- package/dist/products/useProducts.d.ts +12 -0
- package/dist/products/useProducts.d.ts.map +1 -0
- package/dist/products/useProducts.js +90 -0
- package/dist/products/useProducts.js.map +1 -0
- package/dist/screens/elements/AnimatedTextElement.d.ts +1 -24
- package/dist/screens/elements/AnimatedTextElement.d.ts.map +1 -1
- package/dist/screens/elements/BaseBoxProps.d.ts +1 -24
- package/dist/screens/elements/BaseBoxProps.d.ts.map +1 -1
- package/dist/screens/elements/ButtonElement.d.ts +6 -121
- package/dist/screens/elements/ButtonElement.d.ts.map +1 -1
- package/dist/screens/elements/CarouselElement.d.ts +1 -24
- package/dist/screens/elements/CarouselElement.d.ts.map +1 -1
- package/dist/screens/elements/CheckboxGroupElement.d.ts +1 -24
- package/dist/screens/elements/CheckboxGroupElement.d.ts.map +1 -1
- package/dist/screens/elements/DatePickerElement.d.ts +1 -24
- package/dist/screens/elements/DatePickerElement.d.ts.map +1 -1
- package/dist/screens/elements/DrawingPadElement.d.ts +1 -24
- package/dist/screens/elements/DrawingPadElement.d.ts.map +1 -1
- package/dist/screens/elements/IconElement.d.ts +1 -24
- package/dist/screens/elements/IconElement.d.ts.map +1 -1
- package/dist/screens/elements/ImageElement.d.ts +1 -24
- package/dist/screens/elements/ImageElement.d.ts.map +1 -1
- package/dist/screens/elements/InputElement.d.ts +1 -24
- package/dist/screens/elements/InputElement.d.ts.map +1 -1
- package/dist/screens/elements/KeyboardAvoidingViewElement.d.ts +1 -24
- package/dist/screens/elements/KeyboardAvoidingViewElement.d.ts.map +1 -1
- package/dist/screens/elements/LottieElement.d.ts +1 -24
- package/dist/screens/elements/LottieElement.d.ts.map +1 -1
- package/dist/screens/elements/ProgressIndicatorElement.d.ts +1 -24
- package/dist/screens/elements/ProgressIndicatorElement.d.ts.map +1 -1
- package/dist/screens/elements/ProgressiveBlurImageElement.d.ts +1 -24
- package/dist/screens/elements/ProgressiveBlurImageElement.d.ts.map +1 -1
- package/dist/screens/elements/RadioGroupElement.d.ts +1 -24
- package/dist/screens/elements/RadioGroupElement.d.ts.map +1 -1
- package/dist/screens/elements/RichTextElement.d.ts +1 -24
- package/dist/screens/elements/RichTextElement.d.ts.map +1 -1
- package/dist/screens/elements/RiveElement.d.ts +1 -24
- package/dist/screens/elements/RiveElement.d.ts.map +1 -1
- package/dist/screens/elements/SafeAreaViewElement.d.ts +1 -24
- package/dist/screens/elements/SafeAreaViewElement.d.ts.map +1 -1
- package/dist/screens/elements/ScrollViewElement.d.ts +1 -24
- package/dist/screens/elements/ScrollViewElement.d.ts.map +1 -1
- package/dist/screens/elements/SliderElement.d.ts +1 -24
- package/dist/screens/elements/SliderElement.d.ts.map +1 -1
- package/dist/screens/elements/StackElement.d.ts +1 -24
- package/dist/screens/elements/StackElement.d.ts.map +1 -1
- package/dist/screens/elements/TextElement.d.ts +1 -24
- package/dist/screens/elements/TextElement.d.ts.map +1 -1
- package/dist/screens/elements/TypewriterTextElement.d.ts +1 -24
- package/dist/screens/elements/TypewriterTextElement.d.ts.map +1 -1
- package/dist/screens/elements/VideoElement.d.ts +1 -24
- package/dist/screens/elements/VideoElement.d.ts.map +1 -1
- package/dist/screens/elements/WheelPickerElement.d.ts +1 -24
- package/dist/screens/elements/WheelPickerElement.d.ts.map +1 -1
- package/dist/screens/elements/ZStackElement.d.ts +1 -24
- package/dist/screens/elements/ZStackElement.d.ts.map +1 -1
- package/dist/steps/Carousel/types.d.ts +1 -1
- package/dist/steps/Commitment/types.d.ts +1 -1
- package/dist/steps/ComposableScreen/types.d.ts +1 -1
- package/dist/steps/Loader/types.d.ts +1 -1
- package/dist/steps/MediaContent/types.d.ts +1 -1
- package/dist/steps/Picker/types.d.ts +1 -1
- package/dist/steps/Question/types.d.ts +1 -1
- package/dist/steps/Ratings/types.d.ts +1 -1
- package/dist/steps/common.types.d.ts +44 -30
- package/dist/steps/common.types.d.ts.map +1 -1
- package/dist/steps/common.types.js +27 -3
- package/dist/steps/common.types.js.map +1 -1
- package/package.json +1 -1
- package/src/OnboardingStudioClient.ts +110 -7
- package/src/__tests__/mergeProductRuntimes.test.ts +172 -0
- package/src/__tests__/productAdapters.test.ts +58 -0
- package/src/__tests__/productDerive.test.ts +111 -0
- package/src/__tests__/productVariables.test.ts +109 -0
- package/src/__tests__/resolveLocalProductArgs.test.ts +41 -0
- package/src/index.ts +14 -0
- package/src/infra/provider/OnboardingProvider.tsx +101 -2
- package/src/infra/queries/cacheKey.ts +27 -4
- package/src/paywalls/PaywallProvider.tsx +342 -0
- package/src/paywalls/__tests__/getPaywalls.test.ts +334 -0
- package/src/paywalls/__tests__/present.test.ts +190 -0
- package/src/paywalls/getPaywalls.query.ts +123 -0
- package/src/paywalls/present.ts +141 -0
- package/src/paywalls/types.ts +99 -0
- package/src/paywalls/usePaywall.ts +35 -0
- package/src/products/ProductRuntimeContext.tsx +17 -0
- package/src/products/adapters/expoIap.ts +93 -0
- package/src/products/adapters/revenueCat.ts +108 -0
- package/src/products/adapters/stub.ts +20 -0
- package/src/products/derive.ts +93 -0
- package/src/products/duration.ts +21 -0
- package/src/products/index.ts +20 -0
- package/src/products/mergeProductRuntimes.ts +78 -0
- package/src/products/toVariables.ts +54 -0
- package/src/products/types.ts +88 -0
- package/src/products/useProducts.ts +106 -0
- package/src/steps/common.types.ts +83 -6
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
|
|
2
|
+
import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";
|
|
3
|
+
import { OnboardingStudioClient } from "../OnboardingStudioClient";
|
|
4
|
+
import { getPaywallsQuery } from "./getPaywalls.query";
|
|
5
|
+
import { Paywall, PaywallCatalog, PresentResult } from "./types";
|
|
6
|
+
import {
|
|
7
|
+
collectProductRefs,
|
|
8
|
+
computeIsReady,
|
|
9
|
+
purchaseOutcomeFromResult,
|
|
10
|
+
resolvePresentDecision,
|
|
11
|
+
resolvePresentedOutcome,
|
|
12
|
+
shouldRecordPurchaseOutcome,
|
|
13
|
+
type PurchaseOutcomeDuringPresentation,
|
|
14
|
+
} from "./present";
|
|
15
|
+
import { useProducts } from "../products/useProducts";
|
|
16
|
+
import { ProductProvider } from "../products/types";
|
|
17
|
+
import { ProductRuntimeContext } from "../products/ProductRuntimeContext";
|
|
18
|
+
import type { CustomActions } from "../infra/provider/OnboardingProvider";
|
|
19
|
+
|
|
20
|
+
// Module-scope, private to this file — mirrors `OnboardingProvider.tsx:17-23`.
|
|
21
|
+
// `OnboardingProvider`'s QueryClient is not exported, so it cannot be reused
|
|
22
|
+
// here; a second, independent cache is intentional, not an oversight — the
|
|
23
|
+
// paywall catalog and the onboarding step payload are different resources
|
|
24
|
+
// with different lifetimes and different AsyncStorage namespaces
|
|
25
|
+
// (`rocapine-paywalls-*` vs `rocapine-onboarding-*`, see
|
|
26
|
+
// `infra/queries/cacheKey.ts`).
|
|
27
|
+
const paywallQueryClient = new QueryClient({
|
|
28
|
+
defaultOptions: {
|
|
29
|
+
queries: {
|
|
30
|
+
staleTime: Infinity,
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
// Frozen at module scope, not a default PARAMETER — a default parameter
|
|
36
|
+
// re-allocates on every render, and `customActions` sits in the published
|
|
37
|
+
// context value (read by `usePaywallHost()` to build the presented paywall's
|
|
38
|
+
// `ScreenHost`), so an unstable identity would defeat memoization the same
|
|
39
|
+
// way `EMPTY_CUSTOM_ACTIONS` in `OnboardingProvider.tsx` documents.
|
|
40
|
+
const EMPTY_CUSTOM_ACTIONS: CustomActions = Object.freeze({});
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Everything a paywall consumer or a paywall HOST needs. Deliberately one
|
|
44
|
+
* context carrying both, mirroring how `OnboardingProgressContext` bundles
|
|
45
|
+
* far more than any single hook reads — `usePaywall()` and `usePaywallHost()`
|
|
46
|
+
* each slice out the fields they need, same pattern as the small hooks in
|
|
47
|
+
* `infra/hooks/` slicing `OnboardingProgressContext`.
|
|
48
|
+
*/
|
|
49
|
+
export type PaywallContextValue = {
|
|
50
|
+
present: (placement: string) => Promise<PresentResult>;
|
|
51
|
+
isReady: boolean;
|
|
52
|
+
catalog: PaywallCatalog | null;
|
|
53
|
+
/** The paywall currently being presented, or null. Read by `usePaywallHost()` — not by `usePaywall()`. */
|
|
54
|
+
activePaywall: Paywall | null;
|
|
55
|
+
/**
|
|
56
|
+
* Resolve the pending `present()` call and clear the active placement.
|
|
57
|
+
* Call this from the presented paywall's `ScreenHost.complete` (Task 7's
|
|
58
|
+
* `PaywallHost`) — never from an ordinary consumer.
|
|
59
|
+
*/
|
|
60
|
+
complete: (result: PresentResult) => void;
|
|
61
|
+
/** Forwarded into the presented paywall's `ScreenHost.customActions`. */
|
|
62
|
+
customActions: CustomActions;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
const EMPTY_PAYWALL_CONTEXT: PaywallContextValue = {
|
|
66
|
+
present: async () => ({ status: "error" }),
|
|
67
|
+
isReady: false,
|
|
68
|
+
catalog: null,
|
|
69
|
+
activePaywall: null,
|
|
70
|
+
complete: () => {},
|
|
71
|
+
customActions: EMPTY_CUSTOM_ACTIONS,
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
export const PaywallContext = createContext<PaywallContextValue>(EMPTY_PAYWALL_CONTEXT);
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The seam a paywall HOST (Task 7's `PaywallHost`) reads from — analogous to
|
|
78
|
+
* `ScreenHost` being the seam the rendering engine reads from. Kept out of
|
|
79
|
+
* `usePaywall()`'s return so an ordinary caller never sees presentation
|
|
80
|
+
* internals it has no reason to touch (which paywall is active, how to
|
|
81
|
+
* resolve it).
|
|
82
|
+
*/
|
|
83
|
+
export const usePaywallHost = (): Pick<PaywallContextValue, "activePaywall" | "complete" | "customActions"> => {
|
|
84
|
+
const { activePaywall, complete, customActions } = useContext(PaywallContext);
|
|
85
|
+
return { activePaywall, complete, customActions };
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
interface PaywallProviderProps {
|
|
89
|
+
children: React.ReactNode;
|
|
90
|
+
client: OnboardingStudioClient;
|
|
91
|
+
locale?: string;
|
|
92
|
+
customAudienceParams?: Record<string, any>;
|
|
93
|
+
/**
|
|
94
|
+
* Billing adapter. Products are resolved once, over the union of every
|
|
95
|
+
* `paywall.products[]` in the catalog (deduplicated), and published via
|
|
96
|
+
* `ProductRuntimeContext` — an `OnboardingProvider` mounted anywhere inside
|
|
97
|
+
* this tree picks up the SAME runtime instead of resolving its own, so
|
|
98
|
+
* there is one store round-trip and one `purchasing` flag for both.
|
|
99
|
+
*/
|
|
100
|
+
productProvider?: ProductProvider;
|
|
101
|
+
/** Handlers for `{ type: "custom" }` ButtonActions inside a paywall's elements. */
|
|
102
|
+
customActions?: CustomActions;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
interface PaywallProviderInnerProps {
|
|
106
|
+
children: React.ReactNode;
|
|
107
|
+
client: OnboardingStudioClient;
|
|
108
|
+
locale: string;
|
|
109
|
+
customAudienceParams: Record<string, any>;
|
|
110
|
+
productProvider?: ProductProvider;
|
|
111
|
+
customActions: CustomActions;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const PaywallProviderInner = ({
|
|
115
|
+
children,
|
|
116
|
+
client,
|
|
117
|
+
locale,
|
|
118
|
+
customAudienceParams,
|
|
119
|
+
productProvider,
|
|
120
|
+
customActions,
|
|
121
|
+
}: PaywallProviderInnerProps) => {
|
|
122
|
+
// `data` straight off `useQuery` is the single source of truth (Finding 1,
|
|
123
|
+
// 2026-08-17 final review) — react-query's own cache already gets both a
|
|
124
|
+
// provider remount and a locale/customAudienceParams round-trip right; a
|
|
125
|
+
// mirrored `useState` populated from inside `queryFn` does not (it only
|
|
126
|
+
// gets written on a cache MISS). See `getPaywalls.query.ts`'s module doc
|
|
127
|
+
// for why the query still needs `paywallQueryClient` for the ONE case
|
|
128
|
+
// `data` alone can't cover: a background revalidation pushing a fresh
|
|
129
|
+
// payload while this query call already resolved with the cached one.
|
|
130
|
+
const { data, error } = useQuery<PaywallCatalog>(
|
|
131
|
+
getPaywallsQuery(client, locale, customAudienceParams, paywallQueryClient)
|
|
132
|
+
);
|
|
133
|
+
const catalog = data ?? null;
|
|
134
|
+
|
|
135
|
+
useEffect(() => {
|
|
136
|
+
if (!error) return;
|
|
137
|
+
// Deliberately NOT thrown. `OnboardingProvider` throws its query error so
|
|
138
|
+
// a host `ErrorBoundary` around a single onboarding screen catches it —
|
|
139
|
+
// but `PaywallProvider` wraps the WHOLE app (spec §7:
|
|
140
|
+
// `<PaywallProvider><App/><PaywallHost/></PaywallProvider>`), so throwing
|
|
141
|
+
// here would crash every screen over a paywall-catalog failure alone.
|
|
142
|
+
// Instead: `catalog` simply stays null, `present()` on any placement
|
|
143
|
+
// resolves "error" (see `resolvePresentDecision` — an unresolved catalog
|
|
144
|
+
// looks identical to an unknown placement), and `isReady` stays false.
|
|
145
|
+
console.warn("[paywalls] Failed to load paywall catalog:", error);
|
|
146
|
+
}, [error]);
|
|
147
|
+
|
|
148
|
+
// Union of every placement's products, deduplicated, resolved ONCE — never
|
|
149
|
+
// re-keyed per presented paywall. See `present.ts`'s `collectProductRefs`
|
|
150
|
+
// doc for why (spec §6.1's "render instantly on tap" requirement).
|
|
151
|
+
const productRefs = useMemo(() => collectProductRefs(catalog), [catalog]);
|
|
152
|
+
const productRuntime = useProducts(productRefs, productProvider, locale);
|
|
153
|
+
|
|
154
|
+
// Tracks what a purchase attempt resolved to during the CURRENT
|
|
155
|
+
// presentation — read by `complete()` to upgrade a generic "dismissed"
|
|
156
|
+
// outcome (see `resolvePresentedOutcome`), reset when a new presentation
|
|
157
|
+
// starts (`present()`'s "start" branch) so one presentation's purchase
|
|
158
|
+
// can never leak into the next.
|
|
159
|
+
const lastPurchaseOutcomeRef = useRef<PurchaseOutcomeDuringPresentation>(null);
|
|
160
|
+
|
|
161
|
+
// Monotonic, incremented every time a presentation actually starts (never
|
|
162
|
+
// on the "immediate" no-op branch). Resetting `lastPurchaseOutcomeRef` at
|
|
163
|
+
// that same moment is NOT enough to stop a stale write: paywall A's
|
|
164
|
+
// `purchase()` can still be in flight when the user dismisses A and
|
|
165
|
+
// paywall B is presented (which resets the ref); if A's promise settles
|
|
166
|
+
// AFTER that reset, an unconditional write would land "purchased" in what
|
|
167
|
+
// is now B's tracker. `purchase()` below captures the generation it
|
|
168
|
+
// started in and only writes if that generation is still current — see
|
|
169
|
+
// `shouldRecordPurchaseOutcome`. DO NOT remove the guard because the write
|
|
170
|
+
// "looks" unconditional; that is exactly the race it closes.
|
|
171
|
+
const presentationGenerationRef = useRef(0);
|
|
172
|
+
|
|
173
|
+
// Wraps `productRuntime.purchase` to record the outcome above (race-guarded
|
|
174
|
+
// — see `presentationGenerationRef`); every other field (and — critically —
|
|
175
|
+
// the object's change cadence, since `products.purchasing` flips must
|
|
176
|
+
// still propagate) is untouched. `productRuntime.purchase` is itself
|
|
177
|
+
// `useCallback(…, [])`-stable (`useProducts.ts`), so this wrapper never
|
|
178
|
+
// changes identity either.
|
|
179
|
+
const purchase = useCallback(
|
|
180
|
+
async (key: string) => {
|
|
181
|
+
const startedInGeneration = presentationGenerationRef.current;
|
|
182
|
+
const result = await productRuntime.purchase(key);
|
|
183
|
+
const outcome = purchaseOutcomeFromResult(result);
|
|
184
|
+
if (outcome && shouldRecordPurchaseOutcome(startedInGeneration, presentationGenerationRef.current)) {
|
|
185
|
+
lastPurchaseOutcomeRef.current = outcome;
|
|
186
|
+
}
|
|
187
|
+
return result;
|
|
188
|
+
},
|
|
189
|
+
[productRuntime.purchase]
|
|
190
|
+
);
|
|
191
|
+
const productRuntimeWithPurchaseTracking = useMemo(
|
|
192
|
+
() => ({ ...productRuntime, purchase }),
|
|
193
|
+
[productRuntime, purchase]
|
|
194
|
+
);
|
|
195
|
+
|
|
196
|
+
const [activePlacement, setActivePlacement] = useState<string | null>(null);
|
|
197
|
+
// Refs so `present`/`complete` stay referentially stable (empty deps) while
|
|
198
|
+
// still reading current state — same pattern `useProducts.ts` uses for its
|
|
199
|
+
// `purchase`/`restore` callbacks.
|
|
200
|
+
const catalogRef = useRef(catalog);
|
|
201
|
+
catalogRef.current = catalog;
|
|
202
|
+
// `activePlacementRef` is made AUTHORITATIVE below — assigned inside
|
|
203
|
+
// `present()`'s start branch and inside `complete()`, not just here. Finding
|
|
204
|
+
// 4, 2026-08-17 final review: this line alone only resyncs the ref from
|
|
205
|
+
// state AFTER React commits, so between a `present()` call and the next
|
|
206
|
+
// commit the ref still holds the PREVIOUS value. Two `present()` calls
|
|
207
|
+
// issued in the same tick (`Promise.all([present("a"), present("b")])`, or
|
|
208
|
+
// two `presentPaywall` actions in one action list) both read the stale ref,
|
|
209
|
+
// both take the "start" branch, and the second overwrites
|
|
210
|
+
// `pendingResolveRef` — the first promise then never settles, exactly the
|
|
211
|
+
// orphaning this whole ref/resolver scheme exists to prevent. Assigning
|
|
212
|
+
// synchronously inside `present`/`complete` closes that window; this
|
|
213
|
+
// render-body line stays only as a resync for the (rare) case something
|
|
214
|
+
// external changes `activePlacement` state without going through either
|
|
215
|
+
// callback.
|
|
216
|
+
const activePlacementRef = useRef(activePlacement);
|
|
217
|
+
activePlacementRef.current = activePlacement;
|
|
218
|
+
const pendingResolveRef = useRef<((result: PresentResult) => void) | null>(null);
|
|
219
|
+
|
|
220
|
+
// present() must not fetch anything — the catalog and products are already
|
|
221
|
+
// resolved (or resolving) from mount. It only decides, synchronously,
|
|
222
|
+
// whether to show the Modal.
|
|
223
|
+
const present = useCallback((placement: string): Promise<PresentResult> => {
|
|
224
|
+
const decision = resolvePresentDecision(catalogRef.current, activePlacementRef.current, placement);
|
|
225
|
+
if (decision.type === "immediate") {
|
|
226
|
+
return Promise.resolve(decision.result);
|
|
227
|
+
}
|
|
228
|
+
// Fresh presentation: no purchase has happened under it yet, and any
|
|
229
|
+
// still-in-flight purchase from a PREVIOUS presentation must not be
|
|
230
|
+
// allowed to write into this one — see `presentationGenerationRef`.
|
|
231
|
+
lastPurchaseOutcomeRef.current = null;
|
|
232
|
+
presentationGenerationRef.current += 1;
|
|
233
|
+
// Authoritative NOW, synchronously — see the ref's doc above. A second
|
|
234
|
+
// `present()` call before React commits reads this value, not the stale
|
|
235
|
+
// pre-commit state, and correctly takes the "already showing" branch.
|
|
236
|
+
activePlacementRef.current = placement;
|
|
237
|
+
return new Promise<PresentResult>((resolve) => {
|
|
238
|
+
pendingResolveRef.current = resolve;
|
|
239
|
+
setActivePlacement(placement);
|
|
240
|
+
});
|
|
241
|
+
}, []);
|
|
242
|
+
|
|
243
|
+
// Called by PaywallHost (Task 7) from the presented paywall's
|
|
244
|
+
// `ScreenHost.complete`. Resolves whatever `present()` call is pending and
|
|
245
|
+
// clears the active placement, hiding the Modal and allowing a new
|
|
246
|
+
// `present()` to start. Safe to call with nothing pending (no-ops).
|
|
247
|
+
//
|
|
248
|
+
// `resolvePresentedOutcome` upgrades a bare "dismissed" to "purchased" (or
|
|
249
|
+
// "cancelled") when the store actually did something during this
|
|
250
|
+
// presentation — see its doc for why `dismiss`'s own `{status:"dismissed"}`
|
|
251
|
+
// isn't treated as an unoverridable explicit answer.
|
|
252
|
+
const complete = useCallback((result: PresentResult) => {
|
|
253
|
+
const resolve = pendingResolveRef.current;
|
|
254
|
+
pendingResolveRef.current = null;
|
|
255
|
+
// Authoritative NOW, synchronously — same reasoning as `present()`'s
|
|
256
|
+
// assignment above: a `present()` issued from the resolution continuation
|
|
257
|
+
// (`const r = await present("a"); … present("downsell")` — a downsell
|
|
258
|
+
// opening from the previous paywall's resolution is a canonical pattern,
|
|
259
|
+
// spec §4.5) must see "nothing showing" immediately, not wait for the
|
|
260
|
+
// next commit.
|
|
261
|
+
activePlacementRef.current = null;
|
|
262
|
+
setActivePlacement(null);
|
|
263
|
+
resolve?.(resolvePresentedOutcome(result, lastPurchaseOutcomeRef.current));
|
|
264
|
+
}, []);
|
|
265
|
+
|
|
266
|
+
const activePaywall = activePlacement ? catalog?.paywalls[activePlacement] ?? null : null;
|
|
267
|
+
|
|
268
|
+
// Finding 6, 2026-08-17 final review, widened by N2 (round 2): a background
|
|
269
|
+
// catalog revalidation (see `getPaywalls.query.ts`) can push a fresh catalog
|
|
270
|
+
// that no longer contains the placement currently on screen (a studio
|
|
271
|
+
// publish renamed or removed it mid-session) — OR the query KEY itself can
|
|
272
|
+
// change while a paywall is showing (`locale`/`customAudienceParams`
|
|
273
|
+
// changed as a prop), which makes react-query report `data: undefined`
|
|
274
|
+
// while the new key is fetching (Finding 1's fix reads `catalog` straight
|
|
275
|
+
// from that `data`). Both collapse `activePaywall` to null the same way, so
|
|
276
|
+
// guarding on THAT — not on `catalog` being non-null — catches both: the
|
|
277
|
+
// original guard (`!catalog` check) missed the query-key case entirely,
|
|
278
|
+
// because a null `catalog` made it bail out before ever checking whether
|
|
279
|
+
// the placement was still present.
|
|
280
|
+
//
|
|
281
|
+
// Either way, the Modal closes itself WITHOUT going through `complete()`,
|
|
282
|
+
// so the pending `present()` promise would never settle and
|
|
283
|
+
// `activePlacement` would stay set forever, silently failing every later
|
|
284
|
+
// `present()` call with `"error"` for the rest of the app's life.
|
|
285
|
+
// `complete()` always clears `activePlacement` together with resolving the
|
|
286
|
+
// pending promise, so it cannot race with or double-resolve this branch.
|
|
287
|
+
useEffect(() => {
|
|
288
|
+
if (!activePlacement || activePaywall) return;
|
|
289
|
+
complete({ status: "error" });
|
|
290
|
+
}, [activePlacement, activePaywall, complete]);
|
|
291
|
+
|
|
292
|
+
const isReady = useMemo(
|
|
293
|
+
() => computeIsReady(catalog, productRefs, productRuntime.status),
|
|
294
|
+
[catalog, productRefs, productRuntime.status]
|
|
295
|
+
);
|
|
296
|
+
|
|
297
|
+
const contextValue = useMemo<PaywallContextValue>(
|
|
298
|
+
() => ({ present, isReady, catalog, activePaywall, complete, customActions }),
|
|
299
|
+
[present, isReady, catalog, activePaywall, complete, customActions]
|
|
300
|
+
);
|
|
301
|
+
|
|
302
|
+
return (
|
|
303
|
+
<ProductRuntimeContext.Provider value={productRuntimeWithPurchaseTracking}>
|
|
304
|
+
<PaywallContext.Provider value={contextValue}>{children}</PaywallContext.Provider>
|
|
305
|
+
</ProductRuntimeContext.Provider>
|
|
306
|
+
);
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* App-level ancestor. Renders ABOVE `OnboardingProvider`, not inside it —
|
|
311
|
+
* that is what lets both share one `ProductRuntimeContext` (React context
|
|
312
|
+
* only flows to descendants; two true siblings could not share one runtime).
|
|
313
|
+
*
|
|
314
|
+
* ```tsx
|
|
315
|
+
* <PaywallProvider client={client} productProvider={revenueCatProductProvider(Purchases)}>
|
|
316
|
+
* <App />
|
|
317
|
+
* <PaywallHost /> // Task 7: renders the active paywall in a fullScreen RN Modal
|
|
318
|
+
* </PaywallProvider>
|
|
319
|
+
* ```
|
|
320
|
+
*/
|
|
321
|
+
export const PaywallProvider = ({
|
|
322
|
+
children,
|
|
323
|
+
client,
|
|
324
|
+
locale = "en",
|
|
325
|
+
customAudienceParams = {},
|
|
326
|
+
productProvider,
|
|
327
|
+
customActions = EMPTY_CUSTOM_ACTIONS,
|
|
328
|
+
}: PaywallProviderProps) => {
|
|
329
|
+
return (
|
|
330
|
+
<QueryClientProvider client={paywallQueryClient}>
|
|
331
|
+
<PaywallProviderInner
|
|
332
|
+
client={client}
|
|
333
|
+
locale={locale}
|
|
334
|
+
customAudienceParams={customAudienceParams}
|
|
335
|
+
productProvider={productProvider}
|
|
336
|
+
customActions={customActions}
|
|
337
|
+
>
|
|
338
|
+
{children}
|
|
339
|
+
</PaywallProviderInner>
|
|
340
|
+
</QueryClientProvider>
|
|
341
|
+
);
|
|
342
|
+
};
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
|
2
|
+
|
|
3
|
+
// react-native is mocked so OnboardingStudioClient (which reads `Platform.OS`)
|
|
4
|
+
// loads under Node — same stub `getOnboarding.query.test.ts` uses.
|
|
5
|
+
vi.mock("react-native", () => ({ Platform: { OS: "ios" } }));
|
|
6
|
+
|
|
7
|
+
// AsyncStorage is mocked — the query reads/writes the paywall cache through it.
|
|
8
|
+
const { getItem, setItem, removeItem } = vi.hoisted(() => ({
|
|
9
|
+
getItem: vi.fn<(key: string) => Promise<string | null>>(),
|
|
10
|
+
setItem: vi.fn<(key: string, value: string) => Promise<void>>(),
|
|
11
|
+
removeItem: vi.fn<(key: string) => Promise<void>>(),
|
|
12
|
+
}));
|
|
13
|
+
vi.mock("@react-native-async-storage/async-storage", () => ({
|
|
14
|
+
default: { getItem, setItem, removeItem },
|
|
15
|
+
}));
|
|
16
|
+
|
|
17
|
+
import { OnboardingStudioClient } from "../../OnboardingStudioClient";
|
|
18
|
+
import {
|
|
19
|
+
getOnboardingCacheKey,
|
|
20
|
+
DEFAULT_ONBOARDING_CACHE_KEY,
|
|
21
|
+
getPaywallsCacheKey,
|
|
22
|
+
DEFAULT_PAYWALLS_CACHE_KEY,
|
|
23
|
+
} from "../../infra/queries/cacheKey";
|
|
24
|
+
import { getPaywallsQuery } from "../getPaywalls.query";
|
|
25
|
+
import type { PaywallCatalog } from "../types";
|
|
26
|
+
|
|
27
|
+
const CACHE_KEY = "rocapine-paywalls-studio";
|
|
28
|
+
const CUSTOM_KEY = "v2";
|
|
29
|
+
const CUSTOM_CACHE_KEY = "rocapine-paywalls-sdk-v2";
|
|
30
|
+
|
|
31
|
+
const catalog: PaywallCatalog = {
|
|
32
|
+
metadata: { audienceId: 1, audienceName: "default", locale: "en", draft: false },
|
|
33
|
+
paywalls: {
|
|
34
|
+
onboarding_end: {
|
|
35
|
+
id: "pw1",
|
|
36
|
+
name: "End paywall",
|
|
37
|
+
placement: "onboarding_end",
|
|
38
|
+
elements: [],
|
|
39
|
+
products: [{ key: "monthly", ios: "com.app.monthly" }],
|
|
40
|
+
configuration: null,
|
|
41
|
+
},
|
|
42
|
+
},
|
|
43
|
+
fonts: null,
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
type FakeResponseInit = {
|
|
47
|
+
ok?: boolean;
|
|
48
|
+
status?: number;
|
|
49
|
+
statusText?: string;
|
|
50
|
+
headers?: Record<string, string>;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const fakeResponse = (body: unknown, init: FakeResponseInit = {}) => ({
|
|
54
|
+
ok: init.ok ?? true,
|
|
55
|
+
status: init.status ?? 200,
|
|
56
|
+
statusText: init.statusText ?? "OK",
|
|
57
|
+
json: async () => body,
|
|
58
|
+
headers: { get: (name: string) => init.headers?.[name] ?? null },
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
describe("OnboardingStudioClient.getPaywalls", () => {
|
|
62
|
+
let fetchMock: ReturnType<typeof vi.fn>;
|
|
63
|
+
|
|
64
|
+
beforeEach(() => {
|
|
65
|
+
fetchMock = vi.fn();
|
|
66
|
+
vi.stubGlobal("fetch", fetchMock);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
afterEach(() => {
|
|
70
|
+
vi.unstubAllGlobals();
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it("builds the URL against get-paywalls with projectId/platform/appVersion/locale, and omits placement by default", async () => {
|
|
74
|
+
fetchMock.mockResolvedValue(
|
|
75
|
+
fakeResponse(catalog, {
|
|
76
|
+
headers: { "ONBS-Audience-Id": "42", "ONBS-Paywall-Ids": "pw1" },
|
|
77
|
+
})
|
|
78
|
+
);
|
|
79
|
+
const client = new OnboardingStudioClient("proj-1", { appVersion: "1.2.3" });
|
|
80
|
+
|
|
81
|
+
await client.getPaywalls({ locale: "fr" });
|
|
82
|
+
|
|
83
|
+
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
84
|
+
const requestedUrl = new URL(fetchMock.mock.calls[0][0] as string);
|
|
85
|
+
expect(requestedUrl.pathname.endsWith("/get-paywalls")).toBe(true);
|
|
86
|
+
expect(requestedUrl.searchParams.get("projectId")).toBe("proj-1");
|
|
87
|
+
expect(requestedUrl.searchParams.get("platform")).toBe("ios");
|
|
88
|
+
expect(requestedUrl.searchParams.get("appVersion")).toBe("1.2.3");
|
|
89
|
+
expect(requestedUrl.searchParams.get("locale")).toBe("fr");
|
|
90
|
+
expect(requestedUrl.searchParams.has("placement")).toBe(false);
|
|
91
|
+
expect(requestedUrl.searchParams.has("draft")).toBe(false);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it("includes placement only when explicitly requested (the exception, not the default)", async () => {
|
|
95
|
+
fetchMock.mockResolvedValue(fakeResponse(catalog));
|
|
96
|
+
const client = new OnboardingStudioClient("proj-1", {});
|
|
97
|
+
|
|
98
|
+
await client.getPaywalls({ locale: "en", placement: "onboarding_end" });
|
|
99
|
+
|
|
100
|
+
const requestedUrl = new URL(fetchMock.mock.calls[0][0] as string);
|
|
101
|
+
expect(requestedUrl.searchParams.get("placement")).toBe("onboarding_end");
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it("appends draft=true in sandbox mode, same as getSteps", async () => {
|
|
105
|
+
fetchMock.mockResolvedValue(fakeResponse(catalog));
|
|
106
|
+
const client = new OnboardingStudioClient("proj-1", { isSandbox: true });
|
|
107
|
+
|
|
108
|
+
await client.getPaywalls();
|
|
109
|
+
|
|
110
|
+
const requestedUrl = new URL(fetchMock.mock.calls[0][0] as string);
|
|
111
|
+
expect(requestedUrl.searchParams.get("draft")).toBe("true");
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it("forwards arbitrary audience params onto the querystring", async () => {
|
|
115
|
+
fetchMock.mockResolvedValue(fakeResponse(catalog));
|
|
116
|
+
const client = new OnboardingStudioClient("proj-1", {});
|
|
117
|
+
|
|
118
|
+
await client.getPaywalls(undefined, { experimentGroup: "b" });
|
|
119
|
+
|
|
120
|
+
const requestedUrl = new URL(fetchMock.mock.calls[0][0] as string);
|
|
121
|
+
expect(requestedUrl.searchParams.get("experimentGroup")).toBe("b");
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it("extracts ONBS-Audience-Id and ONBS-Paywall-Ids — not the onboarding header trio", async () => {
|
|
125
|
+
fetchMock.mockResolvedValue(
|
|
126
|
+
fakeResponse(catalog, {
|
|
127
|
+
headers: { "ONBS-Audience-Id": "7", "ONBS-Paywall-Ids": "pw1,pw2" },
|
|
128
|
+
})
|
|
129
|
+
);
|
|
130
|
+
const client = new OnboardingStudioClient("proj-1", {});
|
|
131
|
+
|
|
132
|
+
const { data, headers } = await client.getPaywalls();
|
|
133
|
+
|
|
134
|
+
expect(data).toEqual(catalog);
|
|
135
|
+
expect(headers).toEqual({
|
|
136
|
+
"ONBS-Audience-Id": "7",
|
|
137
|
+
"ONBS-Paywall-Ids": "pw1,pw2",
|
|
138
|
+
});
|
|
139
|
+
expect(headers).not.toHaveProperty("ONBS-Onboarding-Id");
|
|
140
|
+
expect(headers).not.toHaveProperty("ONBS-Onboarding-Name");
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it("surfaces a non-ok response as a rejection instead of resolving (no fallback)", async () => {
|
|
144
|
+
fetchMock.mockResolvedValue(
|
|
145
|
+
fakeResponse(null, { ok: false, status: 500, statusText: "Internal Server Error" })
|
|
146
|
+
);
|
|
147
|
+
const client = new OnboardingStudioClient("proj-1", {});
|
|
148
|
+
|
|
149
|
+
await expect(client.getPaywalls()).rejects.toThrow(/500/);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
it("surfaces a network failure as a rejection instead of resolving", async () => {
|
|
153
|
+
fetchMock.mockRejectedValue(new Error("network down"));
|
|
154
|
+
const client = new OnboardingStudioClient("proj-1", {});
|
|
155
|
+
|
|
156
|
+
await expect(client.getPaywalls()).rejects.toThrow("network down");
|
|
157
|
+
});
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
describe("getPaywallsCacheKey", () => {
|
|
161
|
+
it("returns the default key when no custom key is given", () => {
|
|
162
|
+
expect(getPaywallsCacheKey()).toBe(DEFAULT_PAYWALLS_CACHE_KEY);
|
|
163
|
+
expect(DEFAULT_PAYWALLS_CACHE_KEY).toBe(CACHE_KEY);
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it("namespaces a custom key, distinctly from the onboarding cache key", () => {
|
|
167
|
+
expect(getPaywallsCacheKey(CUSTOM_KEY)).toBe(CUSTOM_CACHE_KEY);
|
|
168
|
+
expect(getPaywallsCacheKey(CUSTOM_KEY)).not.toBe(getOnboardingCacheKey(CUSTOM_KEY));
|
|
169
|
+
expect(DEFAULT_PAYWALLS_CACHE_KEY).not.toBe(DEFAULT_ONBOARDING_CACHE_KEY);
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
// Fake client shape used by `getPaywallsQuery` — mirrors the fake used in
|
|
174
|
+
// `getOnboarding.query.test.ts`, swapping `getSteps` for `getPaywalls`.
|
|
175
|
+
const makeClient = (
|
|
176
|
+
{
|
|
177
|
+
isSandbox,
|
|
178
|
+
cacheKey,
|
|
179
|
+
data,
|
|
180
|
+
}: { isSandbox: boolean; cacheKey?: string; data: PaywallCatalog }
|
|
181
|
+
) => {
|
|
182
|
+
const getPaywalls = vi.fn().mockResolvedValue({
|
|
183
|
+
data,
|
|
184
|
+
headers: {
|
|
185
|
+
"ONBS-Audience-Id": "1",
|
|
186
|
+
"ONBS-Paywall-Ids": Object.keys(data.paywalls).join(","),
|
|
187
|
+
},
|
|
188
|
+
});
|
|
189
|
+
return {
|
|
190
|
+
projectId: "p1",
|
|
191
|
+
options: { isSandbox, baseUrl: undefined, cacheKey },
|
|
192
|
+
getPaywalls,
|
|
193
|
+
} as any;
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
const makeQueryClient = () => ({ setQueryData: vi.fn() }) as any;
|
|
197
|
+
|
|
198
|
+
const run = (client: any, queryClient = makeQueryClient()) =>
|
|
199
|
+
(getPaywallsQuery(client, "en", {}, queryClient) as any).queryFn();
|
|
200
|
+
|
|
201
|
+
const flush = () => new Promise((r) => setTimeout(r, 0));
|
|
202
|
+
|
|
203
|
+
describe("getPaywallsQuery", () => {
|
|
204
|
+
beforeEach(() => {
|
|
205
|
+
getItem.mockReset();
|
|
206
|
+
setItem.mockReset();
|
|
207
|
+
removeItem.mockReset();
|
|
208
|
+
setItem.mockResolvedValue(undefined);
|
|
209
|
+
removeItem.mockResolvedValue(undefined);
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
it("sandbox: always fetches, never touches the cache", async () => {
|
|
213
|
+
const client = makeClient({ isSandbox: true, data: catalog });
|
|
214
|
+
const data = await run(client);
|
|
215
|
+
|
|
216
|
+
expect(client.getPaywalls).toHaveBeenCalledTimes(1);
|
|
217
|
+
expect(getItem).not.toHaveBeenCalled();
|
|
218
|
+
expect(setItem).toHaveBeenCalledWith(CACHE_KEY, JSON.stringify(catalog));
|
|
219
|
+
expect(data).toBe(catalog);
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
it("production cache miss: fetches and caches under the default key", async () => {
|
|
223
|
+
getItem.mockResolvedValue(null);
|
|
224
|
+
const client = makeClient({ isSandbox: false, data: catalog });
|
|
225
|
+
const queryClient = makeQueryClient();
|
|
226
|
+
|
|
227
|
+
const data = await run(client, queryClient);
|
|
228
|
+
|
|
229
|
+
expect(client.getPaywalls).toHaveBeenCalledTimes(1);
|
|
230
|
+
expect(setItem).toHaveBeenCalledWith(CACHE_KEY, JSON.stringify(catalog));
|
|
231
|
+
// A live (non-background) call also pushes through `setQueryData` — a
|
|
232
|
+
// harmless overwrite with the exact value this call is about to return.
|
|
233
|
+
expect(queryClient.setQueryData).toHaveBeenCalledWith(expect.anything(), catalog);
|
|
234
|
+
expect(data).toBe(catalog);
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
it("production cache hit: returns cache immediately and revalidates in the background", async () => {
|
|
238
|
+
const cached = { ...catalog, metadata: { ...catalog.metadata, locale: "cached" } };
|
|
239
|
+
getItem.mockResolvedValue(JSON.stringify(cached));
|
|
240
|
+
const client = makeClient({ isSandbox: false, data: catalog });
|
|
241
|
+
const queryClient = makeQueryClient();
|
|
242
|
+
|
|
243
|
+
const data = await run(client, queryClient);
|
|
244
|
+
|
|
245
|
+
// Served from cache without blocking on the network — this call's own
|
|
246
|
+
// return value is what becomes `data` for a live `useQuery`, with no
|
|
247
|
+
// query-cache write needed for it.
|
|
248
|
+
expect(data).toEqual(cached);
|
|
249
|
+
|
|
250
|
+
// Background revalidation runs after the cache is returned, and pushes
|
|
251
|
+
// the fresh payload into the query cache directly (Finding 1) — this is
|
|
252
|
+
// the ONE case `useQuery`'s own `data` cannot cover on its own, since this
|
|
253
|
+
// call is detached from the pending query invocation.
|
|
254
|
+
await flush();
|
|
255
|
+
expect(client.getPaywalls).toHaveBeenCalledTimes(1);
|
|
256
|
+
expect(setItem).toHaveBeenCalledWith(CACHE_KEY, JSON.stringify(catalog));
|
|
257
|
+
expect(queryClient.setQueryData).toHaveBeenCalledTimes(1);
|
|
258
|
+
expect(queryClient.setQueryData).toHaveBeenCalledWith(expect.anything(), catalog);
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
it("custom key, cache hit: serves cache and does NOT revalidate", async () => {
|
|
262
|
+
const cached = { ...catalog, metadata: { ...catalog.metadata, locale: "cached" } };
|
|
263
|
+
getItem.mockResolvedValue(JSON.stringify(cached));
|
|
264
|
+
const client = makeClient({ isSandbox: false, cacheKey: CUSTOM_KEY, data: catalog });
|
|
265
|
+
const queryClient = makeQueryClient();
|
|
266
|
+
|
|
267
|
+
const data = await run(client, queryClient);
|
|
268
|
+
|
|
269
|
+
expect(getItem).toHaveBeenCalledWith(CUSTOM_CACHE_KEY);
|
|
270
|
+
expect(data).toEqual(cached);
|
|
271
|
+
expect(queryClient.setQueryData).not.toHaveBeenCalled();
|
|
272
|
+
|
|
273
|
+
// No background revalidation — the pinned version is never refetched.
|
|
274
|
+
await flush();
|
|
275
|
+
expect(client.getPaywalls).not.toHaveBeenCalled();
|
|
276
|
+
expect(setItem).not.toHaveBeenCalled();
|
|
277
|
+
expect(queryClient.setQueryData).not.toHaveBeenCalled();
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
it("custom key, cache miss: fetches once and persists under the namespaced key", async () => {
|
|
281
|
+
getItem.mockResolvedValue(null);
|
|
282
|
+
const client = makeClient({ isSandbox: false, cacheKey: CUSTOM_KEY, data: catalog });
|
|
283
|
+
|
|
284
|
+
const data = await run(client);
|
|
285
|
+
|
|
286
|
+
expect(getItem).toHaveBeenCalledWith(CUSTOM_CACHE_KEY);
|
|
287
|
+
expect(client.getPaywalls).toHaveBeenCalledTimes(1);
|
|
288
|
+
expect(setItem).toHaveBeenCalledWith(CUSTOM_CACHE_KEY, JSON.stringify(catalog));
|
|
289
|
+
expect(data).toBe(catalog);
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
it("cache-key namespace is distinct from the onboarding query's queryKey prefix", () => {
|
|
293
|
+
const client = makeClient({ isSandbox: false, data: catalog });
|
|
294
|
+
const { queryKey } = getPaywallsQuery(client, "en", {}) as any;
|
|
295
|
+
|
|
296
|
+
expect(queryKey[0]).toBe("paywallCatalog");
|
|
297
|
+
expect(queryKey[0]).not.toBe("onboardingQuestions");
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
it("a client error surfaces as a rejection on cache miss — it is not swallowed or cached", async () => {
|
|
301
|
+
getItem.mockResolvedValue(null);
|
|
302
|
+
const getPaywalls = vi.fn().mockRejectedValue(new Error("500 boom"));
|
|
303
|
+
const client = {
|
|
304
|
+
projectId: "p1",
|
|
305
|
+
options: { isSandbox: false, baseUrl: undefined, cacheKey: undefined },
|
|
306
|
+
getPaywalls,
|
|
307
|
+
} as any;
|
|
308
|
+
|
|
309
|
+
await expect(run(client)).rejects.toThrow("500 boom");
|
|
310
|
+
expect(setItem).not.toHaveBeenCalled();
|
|
311
|
+
});
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
describe("OnboardingStudioClient.clearCache", () => {
|
|
315
|
+
beforeEach(() => removeItem.mockReset());
|
|
316
|
+
|
|
317
|
+
it("removes both the default onboarding key and the default paywalls key", async () => {
|
|
318
|
+
const client = new OnboardingStudioClient("p1", {});
|
|
319
|
+
await client.clearCache();
|
|
320
|
+
|
|
321
|
+
expect(removeItem).toHaveBeenCalledWith(DEFAULT_ONBOARDING_CACHE_KEY);
|
|
322
|
+
expect(removeItem).toHaveBeenCalledWith(CACHE_KEY);
|
|
323
|
+
expect(removeItem).toHaveBeenCalledTimes(2);
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
it("removes both namespaced keys when a custom key is configured", async () => {
|
|
327
|
+
const client = new OnboardingStudioClient("p1", { cacheKey: CUSTOM_KEY });
|
|
328
|
+
await client.clearCache();
|
|
329
|
+
|
|
330
|
+
expect(removeItem).toHaveBeenCalledWith(`rocapine-onboarding-sdk-${CUSTOM_KEY}`);
|
|
331
|
+
expect(removeItem).toHaveBeenCalledWith(CUSTOM_CACHE_KEY);
|
|
332
|
+
expect(removeItem).toHaveBeenCalledTimes(2);
|
|
333
|
+
});
|
|
334
|
+
});
|