@rocapine/react-native-onboarding 1.61.0 → 1.63.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 (173) hide show
  1. package/dist/OnboardingStudioClient.d.ts +23 -5
  2. package/dist/OnboardingStudioClient.d.ts.map +1 -1
  3. package/dist/OnboardingStudioClient.js +82 -6
  4. package/dist/OnboardingStudioClient.js.map +1 -1
  5. package/dist/index.d.ts +7 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +12 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/infra/hooks/index.d.ts +1 -0
  10. package/dist/infra/hooks/index.d.ts.map +1 -1
  11. package/dist/infra/hooks/index.js +3 -1
  12. package/dist/infra/hooks/index.js.map +1 -1
  13. package/dist/infra/hooks/useProgressHeaderConfig.d.ts +14 -0
  14. package/dist/infra/hooks/useProgressHeaderConfig.d.ts.map +1 -0
  15. package/dist/infra/hooks/useProgressHeaderConfig.js +24 -0
  16. package/dist/infra/hooks/useProgressHeaderConfig.js.map +1 -0
  17. package/dist/infra/preload/extractAssetUrls.d.ts.map +1 -1
  18. package/dist/infra/preload/extractAssetUrls.js +67 -0
  19. package/dist/infra/preload/extractAssetUrls.js.map +1 -1
  20. package/dist/infra/provider/OnboardingProvider.d.ts +25 -0
  21. package/dist/infra/provider/OnboardingProvider.d.ts.map +1 -1
  22. package/dist/infra/provider/OnboardingProvider.js +74 -3
  23. package/dist/infra/provider/OnboardingProvider.js.map +1 -1
  24. package/dist/infra/queries/cacheKey.d.ts +22 -4
  25. package/dist/infra/queries/cacheKey.d.ts.map +1 -1
  26. package/dist/infra/queries/cacheKey.js +26 -5
  27. package/dist/infra/queries/cacheKey.js.map +1 -1
  28. package/dist/onboarding-example.d.ts +1063 -60
  29. package/dist/onboarding-example.d.ts.map +1 -1
  30. package/dist/onboarding-example.js +140 -0
  31. package/dist/onboarding-example.js.map +1 -1
  32. package/dist/paywalls/PaywallProvider.d.ts +66 -0
  33. package/dist/paywalls/PaywallProvider.d.ts.map +1 -0
  34. package/dist/paywalls/PaywallProvider.js +227 -0
  35. package/dist/paywalls/PaywallProvider.js.map +1 -0
  36. package/dist/paywalls/getPaywalls.query.d.ts +37 -0
  37. package/dist/paywalls/getPaywalls.query.d.ts.map +1 -0
  38. package/dist/paywalls/getPaywalls.query.js +114 -0
  39. package/dist/paywalls/getPaywalls.query.js.map +1 -0
  40. package/dist/paywalls/present.d.ts +100 -0
  41. package/dist/paywalls/present.d.ts.map +1 -0
  42. package/dist/paywalls/present.js +113 -0
  43. package/dist/paywalls/present.js.map +1 -0
  44. package/dist/paywalls/types.d.ts +95 -0
  45. package/dist/paywalls/types.d.ts.map +1 -0
  46. package/dist/paywalls/types.js +10 -0
  47. package/dist/paywalls/types.js.map +1 -0
  48. package/dist/paywalls/usePaywall.d.ts +29 -0
  49. package/dist/paywalls/usePaywall.d.ts.map +1 -0
  50. package/dist/paywalls/usePaywall.js +17 -0
  51. package/dist/paywalls/usePaywall.js.map +1 -0
  52. package/dist/products/ProductRuntimeContext.d.ts +15 -0
  53. package/dist/products/ProductRuntimeContext.d.ts.map +1 -0
  54. package/dist/products/ProductRuntimeContext.js +19 -0
  55. package/dist/products/ProductRuntimeContext.js.map +1 -0
  56. package/dist/products/index.d.ts +1 -0
  57. package/dist/products/index.d.ts.map +1 -1
  58. package/dist/products/index.js +4 -1
  59. package/dist/products/index.js.map +1 -1
  60. package/dist/products/mergeProductRuntimes.d.ts +55 -0
  61. package/dist/products/mergeProductRuntimes.d.ts.map +1 -0
  62. package/dist/products/mergeProductRuntimes.js +79 -0
  63. package/dist/products/mergeProductRuntimes.js.map +1 -0
  64. package/dist/screens/elements/AnimatedTextElement.d.ts +7 -0
  65. package/dist/screens/elements/AnimatedTextElement.d.ts.map +1 -1
  66. package/dist/screens/elements/BaseBoxProps.d.ts +39 -0
  67. package/dist/screens/elements/BaseBoxProps.d.ts.map +1 -1
  68. package/dist/screens/elements/BaseBoxProps.js +9 -0
  69. package/dist/screens/elements/BaseBoxProps.js.map +1 -1
  70. package/dist/screens/elements/ButtonElement.d.ts +28 -0
  71. package/dist/screens/elements/ButtonElement.d.ts.map +1 -1
  72. package/dist/screens/elements/CarouselElement.d.ts +38 -0
  73. package/dist/screens/elements/CarouselElement.d.ts.map +1 -1
  74. package/dist/screens/elements/CarouselElement.js +1 -0
  75. package/dist/screens/elements/CarouselElement.js.map +1 -1
  76. package/dist/screens/elements/CheckboxGroupElement.d.ts +7 -0
  77. package/dist/screens/elements/CheckboxGroupElement.d.ts.map +1 -1
  78. package/dist/screens/elements/DatePickerElement.d.ts +7 -0
  79. package/dist/screens/elements/DatePickerElement.d.ts.map +1 -1
  80. package/dist/screens/elements/DrawingPadElement.d.ts +7 -0
  81. package/dist/screens/elements/DrawingPadElement.d.ts.map +1 -1
  82. package/dist/screens/elements/IconElement.d.ts +7 -0
  83. package/dist/screens/elements/IconElement.d.ts.map +1 -1
  84. package/dist/screens/elements/ImageElement.d.ts +26 -0
  85. package/dist/screens/elements/ImageElement.d.ts.map +1 -1
  86. package/dist/screens/elements/ImageElement.js +1 -0
  87. package/dist/screens/elements/ImageElement.js.map +1 -1
  88. package/dist/screens/elements/InputElement.d.ts +7 -0
  89. package/dist/screens/elements/InputElement.d.ts.map +1 -1
  90. package/dist/screens/elements/KeyboardAvoidingViewElement.d.ts +7 -0
  91. package/dist/screens/elements/KeyboardAvoidingViewElement.d.ts.map +1 -1
  92. package/dist/screens/elements/LottieElement.d.ts +7 -0
  93. package/dist/screens/elements/LottieElement.d.ts.map +1 -1
  94. package/dist/screens/elements/ProgressIndicatorElement.d.ts +7 -0
  95. package/dist/screens/elements/ProgressIndicatorElement.d.ts.map +1 -1
  96. package/dist/screens/elements/ProgressiveBlurImageElement.d.ts +7 -0
  97. package/dist/screens/elements/ProgressiveBlurImageElement.d.ts.map +1 -1
  98. package/dist/screens/elements/RadioGroupElement.d.ts +7 -0
  99. package/dist/screens/elements/RadioGroupElement.d.ts.map +1 -1
  100. package/dist/screens/elements/RepeatElement.d.ts +79 -0
  101. package/dist/screens/elements/RepeatElement.d.ts.map +1 -0
  102. package/dist/screens/elements/RepeatElement.js +10 -0
  103. package/dist/screens/elements/RepeatElement.js.map +1 -0
  104. package/dist/screens/elements/RichTextElement.d.ts +7 -0
  105. package/dist/screens/elements/RichTextElement.d.ts.map +1 -1
  106. package/dist/screens/elements/RiveElement.d.ts +7 -0
  107. package/dist/screens/elements/RiveElement.d.ts.map +1 -1
  108. package/dist/screens/elements/SafeAreaViewElement.d.ts +7 -0
  109. package/dist/screens/elements/SafeAreaViewElement.d.ts.map +1 -1
  110. package/dist/screens/elements/ScrollViewElement.d.ts +7 -0
  111. package/dist/screens/elements/ScrollViewElement.d.ts.map +1 -1
  112. package/dist/screens/elements/SliderElement.d.ts +7 -0
  113. package/dist/screens/elements/SliderElement.d.ts.map +1 -1
  114. package/dist/screens/elements/StackElement.d.ts +7 -0
  115. package/dist/screens/elements/StackElement.d.ts.map +1 -1
  116. package/dist/screens/elements/TextElement.d.ts +7 -0
  117. package/dist/screens/elements/TextElement.d.ts.map +1 -1
  118. package/dist/screens/elements/TypewriterTextElement.d.ts +26 -0
  119. package/dist/screens/elements/TypewriterTextElement.d.ts.map +1 -1
  120. package/dist/screens/elements/TypewriterTextElement.js +1 -0
  121. package/dist/screens/elements/TypewriterTextElement.js.map +1 -1
  122. package/dist/screens/elements/VideoElement.d.ts +7 -0
  123. package/dist/screens/elements/VideoElement.d.ts.map +1 -1
  124. package/dist/screens/elements/WheelPickerElement.d.ts +7 -0
  125. package/dist/screens/elements/WheelPickerElement.d.ts.map +1 -1
  126. package/dist/screens/elements/ZStackElement.d.ts +7 -0
  127. package/dist/screens/elements/ZStackElement.d.ts.map +1 -1
  128. package/dist/screens/types.d.ts +9 -0
  129. package/dist/screens/types.d.ts.map +1 -1
  130. package/dist/screens/types.js +9 -0
  131. package/dist/screens/types.js.map +1 -1
  132. package/dist/screens/unknownKeys.d.ts +67 -0
  133. package/dist/screens/unknownKeys.d.ts.map +1 -0
  134. package/dist/screens/unknownKeys.js +160 -0
  135. package/dist/screens/unknownKeys.js.map +1 -0
  136. package/dist/steps/common.types.d.ts +22 -1
  137. package/dist/steps/common.types.d.ts.map +1 -1
  138. package/dist/steps/common.types.js +10 -1
  139. package/dist/steps/common.types.js.map +1 -1
  140. package/dist/types.d.ts +73 -0
  141. package/dist/types.d.ts.map +1 -1
  142. package/package.json +1 -1
  143. package/src/OnboardingStudioClient.ts +110 -7
  144. package/src/__tests__/extractAssetUrls.test.ts +104 -0
  145. package/src/__tests__/mergeProductRuntimes.test.ts +172 -0
  146. package/src/__tests__/resolveLocalProductArgs.test.ts +41 -0
  147. package/src/__tests__/unknownKeys.test.ts +234 -0
  148. package/src/index.ts +20 -0
  149. package/src/infra/hooks/index.ts +1 -0
  150. package/src/infra/hooks/useProgressHeaderConfig.ts +21 -0
  151. package/src/infra/preload/extractAssetUrls.ts +72 -0
  152. package/src/infra/provider/OnboardingProvider.tsx +87 -3
  153. package/src/infra/queries/cacheKey.ts +27 -4
  154. package/src/onboarding-example.ts +140 -0
  155. package/src/paywalls/PaywallProvider.tsx +342 -0
  156. package/src/paywalls/__tests__/getPaywalls.test.ts +334 -0
  157. package/src/paywalls/__tests__/present.test.ts +190 -0
  158. package/src/paywalls/getPaywalls.query.ts +123 -0
  159. package/src/paywalls/present.ts +141 -0
  160. package/src/paywalls/types.ts +99 -0
  161. package/src/paywalls/usePaywall.ts +35 -0
  162. package/src/products/ProductRuntimeContext.tsx +17 -0
  163. package/src/products/index.ts +1 -0
  164. package/src/products/mergeProductRuntimes.ts +78 -0
  165. package/src/screens/elements/BaseBoxProps.ts +56 -0
  166. package/src/screens/elements/CarouselElement.ts +31 -0
  167. package/src/screens/elements/ImageElement.ts +16 -0
  168. package/src/screens/elements/RepeatElement.ts +80 -0
  169. package/src/screens/elements/TypewriterTextElement.ts +19 -0
  170. package/src/screens/types.ts +18 -0
  171. package/src/screens/unknownKeys.ts +211 -0
  172. package/src/steps/common.types.ts +34 -1
  173. package/src/types.ts +86 -0
@@ -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
+ });
@@ -0,0 +1,190 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import {
3
+ collectProductRefs,
4
+ computeIsReady,
5
+ purchaseOutcomeFromResult,
6
+ resolvePresentDecision,
7
+ resolvePresentedOutcome,
8
+ shouldRecordPurchaseOutcome,
9
+ } from "../present";
10
+ import type { Paywall, PaywallCatalog } from "../types";
11
+ import type { PurchaseResult } from "../../products/types";
12
+
13
+ const makePaywall = (overrides: Partial<Paywall> & Pick<Paywall, "id" | "placement">): Paywall => ({
14
+ name: overrides.name ?? "Paywall",
15
+ elements: overrides.elements ?? [],
16
+ products: overrides.products ?? [],
17
+ configuration: overrides.configuration ?? null,
18
+ ...overrides,
19
+ });
20
+
21
+ const makeCatalog = (paywalls: Paywall[]): PaywallCatalog => ({
22
+ metadata: { audienceId: null, audienceName: null, locale: "en", draft: false },
23
+ paywalls: Object.fromEntries(paywalls.map((p) => [p.placement, p])),
24
+ fonts: null,
25
+ });
26
+
27
+ describe("collectProductRefs", () => {
28
+ it("returns an empty array for a null catalog", () => {
29
+ expect(collectProductRefs(null)).toEqual([]);
30
+ });
31
+
32
+ it("returns an empty array when no paywall declares any products", () => {
33
+ const catalog = makeCatalog([makePaywall({ id: "1", placement: "a", products: [] })]);
34
+ expect(collectProductRefs(catalog)).toEqual([]);
35
+ });
36
+
37
+ it("flattens products from every placement into one array", () => {
38
+ const catalog = makeCatalog([
39
+ makePaywall({ id: "1", placement: "a", products: [{ key: "yearly", ios: "com.app.yr" }] }),
40
+ makePaywall({ id: "2", placement: "b", products: [{ key: "monthly", ios: "com.app.mo" }] }),
41
+ ]);
42
+ expect(collectProductRefs(catalog)).toEqual([
43
+ { key: "yearly", ios: "com.app.yr" },
44
+ { key: "monthly", ios: "com.app.mo" },
45
+ ]);
46
+ });
47
+
48
+ it("dedupes identical refs (same key + ios + android + compareTo) across placements", () => {
49
+ const shared = { key: "yearly", ios: "com.app.yr", android: "com.app.yr:p1y" };
50
+ const catalog = makeCatalog([
51
+ makePaywall({ id: "1", placement: "a", products: [shared] }),
52
+ makePaywall({ id: "2", placement: "b", products: [shared, { key: "monthly", ios: "com.app.mo" }] }),
53
+ ]);
54
+ expect(collectProductRefs(catalog)).toEqual([
55
+ shared,
56
+ { key: "monthly", ios: "com.app.mo" },
57
+ ]);
58
+ });
59
+
60
+ it("does NOT dedupe refs that share a key but differ in ios/android/compareTo", () => {
61
+ const catalog = makeCatalog([
62
+ makePaywall({
63
+ id: "1",
64
+ placement: "a",
65
+ products: [
66
+ { key: "yearly", ios: "com.app.yr" },
67
+ { key: "yearly", ios: "com.app.yr", compareTo: "monthly" },
68
+ ],
69
+ }),
70
+ ]);
71
+ expect(collectProductRefs(catalog)).toHaveLength(2);
72
+ });
73
+ });
74
+
75
+ describe("resolvePresentDecision", () => {
76
+ const paywall = makePaywall({ id: "1", placement: "hard_paywall", products: [] });
77
+ const catalog = makeCatalog([paywall]);
78
+
79
+ it("starts when the placement exists and nothing is currently showing", () => {
80
+ const decision = resolvePresentDecision(catalog, null, "hard_paywall");
81
+ expect(decision).toEqual({ type: "start", paywall });
82
+ });
83
+
84
+ it("resolves 'error' immediately when the placement is absent from the catalog", () => {
85
+ const decision = resolvePresentDecision(catalog, null, "does_not_exist");
86
+ expect(decision).toEqual({ type: "immediate", result: { status: "error" } });
87
+ });
88
+
89
+ it("resolves 'error' immediately when the catalog has not resolved yet (null)", () => {
90
+ const decision = resolvePresentDecision(null, null, "hard_paywall");
91
+ expect(decision).toEqual({ type: "immediate", result: { status: "error" } });
92
+ });
93
+
94
+ it("resolves 'error' immediately when another paywall is already showing, even for a valid placement", () => {
95
+ const decision = resolvePresentDecision(catalog, "already_showing", "hard_paywall");
96
+ expect(decision).toEqual({ type: "immediate", result: { status: "error" } });
97
+ });
98
+
99
+ it("the concurrent-present check takes priority over the unknown-placement check", () => {
100
+ // Both conditions are true at once: prove the function still resolves
101
+ // rather than e.g. throwing on the first branch it happens to hit.
102
+ const decision = resolvePresentDecision(catalog, "already_showing", "does_not_exist");
103
+ expect(decision).toEqual({ type: "immediate", result: { status: "error" } });
104
+ });
105
+ });
106
+
107
+ describe("computeIsReady", () => {
108
+ const refs = [{ key: "yearly", ios: "com.app.yr" }];
109
+
110
+ it("is false while the catalog has not resolved", () => {
111
+ expect(computeIsReady(null, refs, "idle")).toBe(false);
112
+ expect(computeIsReady(null, refs, "ready")).toBe(false);
113
+ });
114
+
115
+ it("is false when the catalog resolved but products have not (loading/idle/error)", () => {
116
+ const catalog = makeCatalog([]);
117
+ expect(computeIsReady(catalog, refs, "idle")).toBe(false);
118
+ expect(computeIsReady(catalog, refs, "loading")).toBe(false);
119
+ expect(computeIsReady(catalog, refs, "error")).toBe(false);
120
+ });
121
+
122
+ it("is true once both the catalog and products resolved", () => {
123
+ const catalog = makeCatalog([]);
124
+ expect(computeIsReady(catalog, refs, "ready")).toBe(true);
125
+ });
126
+
127
+ it("is true as soon as the catalog resolves when NO paywall declares any products — useProducts would otherwise stay 'idle' forever", () => {
128
+ const catalog = makeCatalog([]);
129
+ expect(computeIsReady(catalog, [], "idle")).toBe(true);
130
+ });
131
+ });
132
+
133
+ describe("purchaseOutcomeFromResult", () => {
134
+ it("tracks 'purchased'", () => {
135
+ const result: PurchaseResult = { status: "purchased", productKey: "yearly" };
136
+ expect(purchaseOutcomeFromResult(result)).toBe("purchased");
137
+ });
138
+
139
+ it("tracks 'cancelled'", () => {
140
+ const result: PurchaseResult = { status: "cancelled" };
141
+ expect(purchaseOutcomeFromResult(result)).toBe("cancelled");
142
+ });
143
+
144
+ it("does not track 'pending' — not a completed store interaction", () => {
145
+ const result: PurchaseResult = { status: "pending" };
146
+ expect(purchaseOutcomeFromResult(result)).toBeNull();
147
+ });
148
+
149
+ it("does not track 'error' — would collide with PresentResult's own, differently-meaning 'error'", () => {
150
+ const result: PurchaseResult = { status: "error", error: new Error("boom") };
151
+ expect(purchaseOutcomeFromResult(result)).toBeNull();
152
+ });
153
+ });
154
+
155
+ describe("resolvePresentedOutcome", () => {
156
+ it("upgrades a bare 'dismissed' to 'purchased' when a purchase succeeded during the presentation", () => {
157
+ expect(resolvePresentedOutcome({ status: "dismissed" }, "purchased")).toEqual({ status: "purchased" });
158
+ });
159
+
160
+ it("upgrades a bare 'dismissed' to 'cancelled' when the store purchase was cancelled during the presentation", () => {
161
+ expect(resolvePresentedOutcome({ status: "dismissed" }, "cancelled")).toEqual({ status: "cancelled" });
162
+ });
163
+
164
+ it("leaves 'dismissed' alone when nothing happened at the store", () => {
165
+ expect(resolvePresentedOutcome({ status: "dismissed" }, null)).toEqual({ status: "dismissed" });
166
+ });
167
+
168
+ it("never upgrades a status other than 'dismissed', even if a purchase occurred", () => {
169
+ // "error" here means "unknown placement / already showing" (resolvePresentDecision) —
170
+ // a purchase outcome must never be allowed to clobber that different meaning.
171
+ expect(resolvePresentedOutcome({ status: "error" }, "purchased")).toEqual({ status: "error" });
172
+ });
173
+ });
174
+
175
+ describe("shouldRecordPurchaseOutcome", () => {
176
+ it("records when the presentation is still the one the purchase started in", () => {
177
+ expect(shouldRecordPurchaseOutcome(1, 1)).toBe(true);
178
+ });
179
+
180
+ it("does NOT record when a newer presentation has started since the purchase began — the race this guards against", () => {
181
+ // Paywall A's purchase() captured generation 1; the user dismissed A and
182
+ // paywall B was presented (generation bumped to 2) before A's promise
183
+ // settled. A's write must not land in B's tracker.
184
+ expect(shouldRecordPurchaseOutcome(1, 2)).toBe(false);
185
+ });
186
+
187
+ it("does NOT record for a generation older than the current one by more than one step either", () => {
188
+ expect(shouldRecordPurchaseOutcome(1, 5)).toBe(false);
189
+ });
190
+ });
@@ -0,0 +1,123 @@
1
+ import AsyncStorage from "@react-native-async-storage/async-storage";
2
+ import type { QueryClient } from "@tanstack/react-query";
3
+ import { OnboardingStudioClient } from "../OnboardingStudioClient";
4
+ import { PaywallCatalog } from "./types";
5
+ import { getPaywallsCacheKey } from "../infra/queries/cacheKey";
6
+
7
+ /**
8
+ * Mirrors `getOnboarding.query.ts`'s cache-first / background-revalidate /
9
+ * custom-key behaviour exactly (same `staleTime: Infinity`, same
10
+ * production-vs-sandbox split, same "no background refetch under a custom
11
+ * key" rule) so a paywall does not revalidate differently from an
12
+ * onboarding.
13
+ *
14
+ * Deliberate difference: `getOnboardingQuery`'s `fetchAndCache` special-cases
15
+ * the client's offline-fallback payload (`ONBS-Onboarding-Id === "fallback"`)
16
+ * and skips caching it. `OnboardingStudioClient.getPaywalls` has no fallback
17
+ * option — it always throws on a network/response error instead of returning
18
+ * a stand-in payload — so there is no fallback case to special-case here:
19
+ * every resolved catalog is a real one and is always cached.
20
+ *
21
+ * `catalog` consumption used to be a `setCatalog` callback mirrored into a
22
+ * component `useState` — but `queryFn` only re-runs on a cache MISS
23
+ * (`staleTime: Infinity`), so that mirror went stale on a provider remount
24
+ * (module-scope `QueryClient`, cache outlives the provider) and on a
25
+ * query-key round-trip (`locale` switched away and back) — Finding 1, 2026-
26
+ * 08-17 final review. The fix: `PaywallProviderInner` now reads `data`
27
+ * straight off `useQuery` as the single source of truth — react-query's own
28
+ * cache already gets this right on both a remount and a key round-trip. The
29
+ * ONE case `data` alone can't cover is the BACKGROUND revalidation below:
30
+ * `fetchAndCache()` there runs detached from the pending query call (its
31
+ * return value is discarded, not observed by react-query), so it must push
32
+ * the fresh payload into the query cache directly via `queryClient.
33
+ * setQueryData` — there is no mirrored component state left to keep in sync.
34
+ */
35
+ export const getPaywallsQuery = (
36
+ client: OnboardingStudioClient,
37
+ locale: string,
38
+ customAudienceParams: Record<string, any>,
39
+ queryClient?: QueryClient
40
+ ) => {
41
+ const queryKey = [
42
+ "paywallCatalog",
43
+ client.projectId,
44
+ client.options.isSandbox,
45
+ client.options.baseUrl,
46
+ client.options.cacheKey,
47
+ locale,
48
+ JSON.stringify(customAudienceParams),
49
+ ];
50
+
51
+ return {
52
+ queryKey,
53
+ queryFn: async (): Promise<PaywallCatalog> => {
54
+ const isProduction = !(client?.options?.isSandbox || false);
55
+ // A custom key opts into app-controlled caching: persist cache-first
56
+ // with NO background revalidation, so a pinned version survives across
57
+ // launches. The default key keeps stale-while-revalidate.
58
+ const hasCustomKey = Boolean(client.options.cacheKey);
59
+ const cacheKey = getPaywallsCacheKey(client.options.cacheKey);
60
+
61
+ // Fetches the live catalog, caches it, and pushes it into the query
62
+ // cache directly — see the module doc above for why that push is
63
+ // needed even though `queryFn`'s own return value already becomes
64
+ // `data` for a LIVE call: this same function also runs detached, as a
65
+ // background revalidation, whose return value nothing observes.
66
+ // Unlike `getOnboardingQuery`, there is no fallback payload to exclude
67
+ // from caching — a rejection here propagates as-is (error-surfacing,
68
+ // not a resolved fallback).
69
+ const fetchAndCache = async (): Promise<PaywallCatalog> => {
70
+ const { data } = await client.getPaywalls(
71
+ { locale },
72
+ customAudienceParams
73
+ );
74
+
75
+ queryClient?.setQueryData<PaywallCatalog>(queryKey, data);
76
+
77
+ try {
78
+ await AsyncStorage.setItem(cacheKey, JSON.stringify(data));
79
+ } catch (error) {
80
+ console.warn("Failed to cache paywalls:", error);
81
+ }
82
+
83
+ return data;
84
+ };
85
+
86
+ // Sandbox / draft: always fetch fresh, no caching.
87
+ if (!isProduction) {
88
+ return fetchAndCache();
89
+ }
90
+
91
+ // Production: serve the cached catalog instantly (fast first paint,
92
+ // offline-resilient). With the default key this is stale-while-revalidate
93
+ // (also refresh in the background so studio re-deploys propagate and a
94
+ // stale cache heals). With a custom key it's persist-only — no background
95
+ // refetch — so a pinned version is never swapped out from under the host.
96
+ let cached: PaywallCatalog | null = null;
97
+ try {
98
+ const cachedData = await AsyncStorage.getItem(cacheKey);
99
+ if (cachedData) cached = JSON.parse(cachedData) as PaywallCatalog;
100
+ } catch (error) {
101
+ console.warn("Failed to load cached paywalls:", error);
102
+ }
103
+
104
+ if (cached) {
105
+ if (!hasCustomKey) {
106
+ // Background revalidation — updates the cache + query state when a
107
+ // fresh real payload arrives via `queryClient.setQueryData` above.
108
+ // Errors are swallowed: the cache already painted, so an offline
109
+ // revalidation must not surface as a query error.
110
+ void fetchAndCache().catch((error) => {
111
+ console.warn("Background paywalls revalidation failed:", error);
112
+ });
113
+ }
114
+ return cached;
115
+ }
116
+
117
+ // No cache yet: await the network. A rejection here surfaces as the
118
+ // query's error (there is no fallback to fall back to).
119
+ return fetchAndCache();
120
+ },
121
+ staleTime: Infinity,
122
+ };
123
+ };