@rocapine/react-native-onboarding 1.61.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 +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -1
- package/dist/index.js.map +1 -1
- package/dist/infra/provider/OnboardingProvider.d.ts +25 -0
- package/dist/infra/provider/OnboardingProvider.d.ts.map +1 -1
- package/dist/infra/provider/OnboardingProvider.js +63 -3
- 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/index.d.ts +1 -0
- package/dist/products/index.d.ts.map +1 -1
- package/dist/products/index.js +4 -1
- package/dist/products/index.js.map +1 -1
- 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/steps/common.types.d.ts +22 -1
- package/dist/steps/common.types.d.ts.map +1 -1
- package/dist/steps/common.types.js +10 -1
- 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__/resolveLocalProductArgs.test.ts +41 -0
- package/src/index.ts +12 -0
- package/src/infra/provider/OnboardingProvider.tsx +73 -3
- 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/index.ts +1 -0
- package/src/products/mergeProductRuntimes.ts +78 -0
- package/src/steps/common.types.ts +34 -1
|
@@ -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
|
+
};
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import type { Paywall, PaywallCatalog, PresentResult } from "./types";
|
|
2
|
+
import type { ProductRef, ProductStatus, PurchaseResult } from "../products/types";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Union of every `paywall.products[]` across the WHOLE catalog, deduplicated
|
|
6
|
+
* by content — the same identity notion `useProducts`' `refsKey` uses
|
|
7
|
+
* (`products/useProducts.ts:41-45`: keyed on ref CONTENT, not array
|
|
8
|
+
* identity), so this array is exactly as cheap to pass as a hand-written one:
|
|
9
|
+
* `useProducts` resolves it once and does not refetch on every render.
|
|
10
|
+
*
|
|
11
|
+
* Resolving the whole catalog's union ONCE at load — rather than re-keying
|
|
12
|
+
* `useProducts` per presented paywall — is the deliberate design decision:
|
|
13
|
+
* a paywall must render the instant the user taps upgrade (spec §6.1), and a
|
|
14
|
+
* store round-trip at that moment is exactly the latency this avoids. Cost
|
|
15
|
+
* accepted: an app resolves products for paywalls it may never show.
|
|
16
|
+
*/
|
|
17
|
+
export const collectProductRefs = (catalog: PaywallCatalog | null): ProductRef[] => {
|
|
18
|
+
if (!catalog) return [];
|
|
19
|
+
const seen = new Set<string>();
|
|
20
|
+
const refs: ProductRef[] = [];
|
|
21
|
+
for (const paywall of Object.values(catalog.paywalls)) {
|
|
22
|
+
for (const ref of paywall.products) {
|
|
23
|
+
const identity = `${ref.key}|${ref.ios ?? ""}|${ref.android ?? ""}|${ref.compareTo ?? ""}`;
|
|
24
|
+
if (seen.has(identity)) continue;
|
|
25
|
+
seen.add(identity);
|
|
26
|
+
refs.push(ref);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return refs;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** What `present()` should do, decided as a pure function of current state. */
|
|
33
|
+
export type PresentDecision =
|
|
34
|
+
| { type: "start"; paywall: Paywall }
|
|
35
|
+
| { type: "immediate"; result: PresentResult };
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* `present(placement)`'s edge-case decision, extracted so both documented
|
|
39
|
+
* edge cases are covered by an importable test rather than only inspection:
|
|
40
|
+
*
|
|
41
|
+
* - **Unknown placement** (absent from the catalog, or the catalog hasn't
|
|
42
|
+
* resolved yet — both look identical here: `catalog?.paywalls[placement]`
|
|
43
|
+
* is `undefined` either way) → resolves `"error"`, never throws. A missing
|
|
44
|
+
* placement must not crash a host app mid-flow.
|
|
45
|
+
* - **`present()` called while another paywall is already showing** → also
|
|
46
|
+
* resolves `"error"` immediately, leaving the in-progress presentation
|
|
47
|
+
* untouched. This SDK shows one paywall at a time. Silently replacing the
|
|
48
|
+
* active paywall would orphan its pending `present()` promise (never
|
|
49
|
+
* resolved — that caller hangs forever); queueing the new request would
|
|
50
|
+
* need its own cancellation/timeout story that nothing here asks for.
|
|
51
|
+
* Resolving the new call immediately applies the same "resolve, don't
|
|
52
|
+
* throw" contract as the unknown-placement case, consistently.
|
|
53
|
+
*/
|
|
54
|
+
export const resolvePresentDecision = (
|
|
55
|
+
catalog: PaywallCatalog | null,
|
|
56
|
+
activePlacement: string | null,
|
|
57
|
+
placement: string
|
|
58
|
+
): PresentDecision => {
|
|
59
|
+
if (activePlacement !== null) {
|
|
60
|
+
return { type: "immediate", result: { status: "error" } };
|
|
61
|
+
}
|
|
62
|
+
const paywall = catalog?.paywalls[placement];
|
|
63
|
+
if (!paywall) {
|
|
64
|
+
return { type: "immediate", result: { status: "error" } };
|
|
65
|
+
}
|
|
66
|
+
return { type: "start", paywall };
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* `isReady` = catalog resolved AND products resolved — the one flag a caller
|
|
71
|
+
* needs to know "presenting now will not show a spinner".
|
|
72
|
+
*
|
|
73
|
+
* The `productRefs.length === 0` branch handles a real edge case:
|
|
74
|
+
* `useProducts` never leaves status `"idle"` when its ref set is empty
|
|
75
|
+
* (`products/useProducts.ts:49-54` bails out before ever calling the
|
|
76
|
+
* provider) — a catalog whose paywalls declare no products at all would
|
|
77
|
+
* otherwise report `isReady: false` forever, with nothing to actually wait
|
|
78
|
+
* for.
|
|
79
|
+
*/
|
|
80
|
+
export const computeIsReady = (
|
|
81
|
+
catalog: PaywallCatalog | null,
|
|
82
|
+
productRefs: ProductRef[],
|
|
83
|
+
productsStatus: ProductStatus
|
|
84
|
+
): boolean => catalog !== null && (productRefs.length === 0 || productsStatus === "ready");
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* What a purchase attempt resolved to during the current presentation, or
|
|
88
|
+
* `null` if none did. Only the two `PurchaseResult` statuses that describe a
|
|
89
|
+
* completed store interaction are tracked — `"pending"` (e.g. Ask-to-Buy) and
|
|
90
|
+
* `"error"` are not: they don't describe what happened to the STORE PURCHASE
|
|
91
|
+
* in a way that should override how the paywall itself reports closing (an
|
|
92
|
+
* `"error"` here would collide with `PresentResult`'s existing `"error"`,
|
|
93
|
+
* which means something structurally different — an unknown placement or a
|
|
94
|
+
* mistimed `present()` call, not a failed purchase attempt).
|
|
95
|
+
*/
|
|
96
|
+
export type PurchaseOutcomeDuringPresentation = "purchased" | "cancelled" | null;
|
|
97
|
+
|
|
98
|
+
/** Narrows a `PurchaseResult` to the subset `PurchaseOutcomeDuringPresentation` tracks. */
|
|
99
|
+
export const purchaseOutcomeFromResult = (result: PurchaseResult): PurchaseOutcomeDuringPresentation =>
|
|
100
|
+
result.status === "purchased" || result.status === "cancelled" ? result.status : null;
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Reconciles what the closing action REPORTED with what actually happened at
|
|
104
|
+
* the store during this presentation. `dismiss` (spec §4.5) always reports
|
|
105
|
+
* `{status:"dismissed"}` — it is the generic "this screen is done" signal and
|
|
106
|
+
* knows nothing about purchases, which is exactly the gap spec §4.6's own
|
|
107
|
+
* canonical authoring shape falls into: `{type:"purchase", onSuccess:
|
|
108
|
+
* [{type:"dismiss"}]}` closes a successful purchase through the SAME generic
|
|
109
|
+
* signal a user backing out would produce. So a bare `"dismissed"` is treated
|
|
110
|
+
* as "the caller didn't have anything more specific to say" and gets upgraded
|
|
111
|
+
* to whatever the store actually did (if anything). Any other reported
|
|
112
|
+
* status is assumed to mean something deliberate and passes through
|
|
113
|
+
* unchanged — this only fills in the generic default, never overrides a
|
|
114
|
+
* caller that already said something more specific.
|
|
115
|
+
*/
|
|
116
|
+
export const resolvePresentedOutcome = (
|
|
117
|
+
reported: PresentResult,
|
|
118
|
+
purchaseOutcome: PurchaseOutcomeDuringPresentation
|
|
119
|
+
): PresentResult =>
|
|
120
|
+
reported.status === "dismissed" && purchaseOutcome ? { status: purchaseOutcome } : reported;
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Guards the purchase-outcome WRITE against a race that resetting the ref at
|
|
124
|
+
* `present()`'s start does not, by itself, prevent: paywall A is showing,
|
|
125
|
+
* `purchase()` is in flight; the user dismisses A (nothing tracked yet, so A
|
|
126
|
+
* correctly resolves `"dismissed"`); paywall B is presented, resetting the
|
|
127
|
+
* tracked outcome; THEN A's stale promise finally settles and would write
|
|
128
|
+
* `"purchased"` into what is now B's tracker — B later reports a purchase
|
|
129
|
+
* the user never made on it. `purchase()` must capture the current
|
|
130
|
+
* generation BEFORE awaiting the store and compare it against the current
|
|
131
|
+
* generation again after — only an unchanged generation means the write is
|
|
132
|
+
* still for the presentation that started it.
|
|
133
|
+
*
|
|
134
|
+
* A monotonic counter, not the placement string: the same placement can
|
|
135
|
+
* legitimately be presented twice in a row, and a string comparison would
|
|
136
|
+
* let a stale write from the FIRST of those two land in the second.
|
|
137
|
+
*/
|
|
138
|
+
export const shouldRecordPurchaseOutcome = (
|
|
139
|
+
startedInGeneration: number,
|
|
140
|
+
currentGeneration: number
|
|
141
|
+
): boolean => startedInGeneration === currentGeneration;
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Response types for `OnboardingStudioClient.getPaywalls()` (spec §6.1). The
|
|
3
|
+
* endpoint returns every placement for the project/audience/locale in one
|
|
4
|
+
* payload — a paywall must render the instant the user taps upgrade, and a
|
|
5
|
+
* network round-trip at that moment is a conversion bug, so there is no
|
|
6
|
+
* per-placement fetch in the common path (see `PaywallOptions.placement`).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** A single studio-authored paywall, keyed by `placement` in `PaywallCatalog.paywalls`. */
|
|
10
|
+
export type Paywall = {
|
|
11
|
+
id: string;
|
|
12
|
+
name: string;
|
|
13
|
+
placement: string;
|
|
14
|
+
/** UIElement[] — parsed by the UI adapter (Task 7's `ScreenElementsSchema`), not here. */
|
|
15
|
+
elements: unknown[];
|
|
16
|
+
products: Array<{
|
|
17
|
+
key: string;
|
|
18
|
+
ios?: string;
|
|
19
|
+
android?: string;
|
|
20
|
+
compareTo?: string;
|
|
21
|
+
}>;
|
|
22
|
+
configuration: Record<string, unknown> | null;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** Full response body of `GET get-paywalls`. */
|
|
26
|
+
export type PaywallCatalog = {
|
|
27
|
+
metadata: {
|
|
28
|
+
audienceId: number | null;
|
|
29
|
+
audienceName: string | null;
|
|
30
|
+
locale: string | null;
|
|
31
|
+
draft: boolean;
|
|
32
|
+
};
|
|
33
|
+
/** Keyed by placement, not by paywall id. */
|
|
34
|
+
paywalls: Record<string, Paywall>;
|
|
35
|
+
fonts: Record<string, unknown> | null;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Options for `OnboardingStudioClient.getPaywalls()`.
|
|
40
|
+
*
|
|
41
|
+
* `placement` narrows the response to a single paywall — the exception, not
|
|
42
|
+
* the default. Omit it to get every placement in one round-trip, which is
|
|
43
|
+
* what lets a paywall render instantly at buy-tap time (see the module doc
|
|
44
|
+
* above).
|
|
45
|
+
*/
|
|
46
|
+
export type PaywallOptions = {
|
|
47
|
+
locale?: string;
|
|
48
|
+
placement?: string;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Response headers for `get-paywalls`. Deliberately **not** the onboarding
|
|
53
|
+
* trio (`ONBS-Onboarding-Id` / `ONBS-Audience-Id` / `ONBS-Onboarding-Name`) —
|
|
54
|
+
* the paywall endpoint has no single onboarding/audience-name concept and
|
|
55
|
+
* instead reports which paywall ids came back.
|
|
56
|
+
*/
|
|
57
|
+
export interface GetPaywallsResponseHeaders {
|
|
58
|
+
"ONBS-Audience-Id": string | null;
|
|
59
|
+
"ONBS-Paywall-Ids": string | null;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Resolved outcome of a `usePaywall().present(placement)` call (spec §7).
|
|
64
|
+
* Closed union, not the open-ended `ScreenHost.CompleteOutcome` — a
|
|
65
|
+
* presentation ends in exactly one of these four ways, and `present()`'s
|
|
66
|
+
* caller (typically an `await`) should be able to switch over it exhaustively.
|
|
67
|
+
*
|
|
68
|
+
* `"error"` covers both: (a) `placement` is absent from the catalog (or the
|
|
69
|
+
* catalog hasn't resolved yet), and (b) `present()` was called while another
|
|
70
|
+
* paywall is already being presented. Both resolve rather than throw — a
|
|
71
|
+
* missing placement or a mistimed call must not crash a host app mid-flow.
|
|
72
|
+
* See `resolvePresentDecision` in `present.ts` for the exact decision logic.
|
|
73
|
+
*
|
|
74
|
+
* `"purchased"` / `"cancelled"` are NOT produced by any ButtonAction directly
|
|
75
|
+
* — `dismiss` (the only in-content closing action) always reports
|
|
76
|
+
* `{status:"dismissed"}`, on purpose, since it doesn't know anything about
|
|
77
|
+
* purchase state. `PaywallProvider` instead tracks what the store actually
|
|
78
|
+
* did during the active presentation (`purchaseOutcomeFromResult` in
|
|
79
|
+
* `present.ts`) and `resolvePresentedOutcome` upgrades a bare `"dismissed"`
|
|
80
|
+
* to whichever of these occurred, if any — so spec §4.6's canonical authoring
|
|
81
|
+
* shape (`{type:"purchase", onSuccess:[{type:"dismiss"}]}`) resolves
|
|
82
|
+
* `"purchased"` even though `dismiss` itself never says so.
|
|
83
|
+
*/
|
|
84
|
+
/**
|
|
85
|
+
* How a presentation ENDED — not what the user is entitled to.
|
|
86
|
+
*
|
|
87
|
+
* `"purchased"` means a purchase succeeded while this paywall was showing, and
|
|
88
|
+
* is the honest report in the common case. But it is deliberately not an
|
|
89
|
+
* entitlement signal: a purchase followed by a render crash resolves `"error"`
|
|
90
|
+
* (the boundary settles the promise so the user is not trapped), so a host that
|
|
91
|
+
* keys entitlement off `status === "purchased"` would under-grant a user who
|
|
92
|
+
* genuinely paid.
|
|
93
|
+
*
|
|
94
|
+
* Entitlement belongs to the store — read it from the `ProductProvider` /
|
|
95
|
+
* billing SDK, and use this only to decide what the UI does next.
|
|
96
|
+
*/
|
|
97
|
+
export type PresentResult = {
|
|
98
|
+
status: "purchased" | "dismissed" | "cancelled" | "error";
|
|
99
|
+
};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { useContext } from "react";
|
|
2
|
+
import { PaywallContext } from "./PaywallProvider";
|
|
3
|
+
import { PaywallCatalog, PresentResult } from "./types";
|
|
4
|
+
|
|
5
|
+
export type UsePaywallResult = {
|
|
6
|
+
/**
|
|
7
|
+
* Present a paywall by placement. Never fetches — the catalog and its
|
|
8
|
+
* products are already resolved (or resolving) from `PaywallProvider`
|
|
9
|
+
* mount, which is the whole point: a paywall must render the instant the
|
|
10
|
+
* user taps upgrade.
|
|
11
|
+
*
|
|
12
|
+
* Resolves `{ status: "error" }` — never throws — when `placement` is
|
|
13
|
+
* absent from the catalog, or when another paywall is already being
|
|
14
|
+
* presented. See `resolvePresentDecision` in `present.ts`.
|
|
15
|
+
*/
|
|
16
|
+
present: (placement: string) => Promise<PresentResult>;
|
|
17
|
+
/**
|
|
18
|
+
* `true` once BOTH the catalog and its products have resolved — the one
|
|
19
|
+
* flag meaning "calling `present()` now will not show a spinner".
|
|
20
|
+
*/
|
|
21
|
+
isReady: boolean;
|
|
22
|
+
/** The full resolved catalog (every placement), or `null` before it loads. */
|
|
23
|
+
catalog: PaywallCatalog | null;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Read the paywall runtime published by an ancestor `PaywallProvider`.
|
|
28
|
+
* Outside one, returns inert defaults (`present` resolves `"error"`,
|
|
29
|
+
* `isReady: false`, `catalog: null`) rather than throwing — mirrors how
|
|
30
|
+
* `useProductRuntime()` degrades to `null` with no ancestor.
|
|
31
|
+
*/
|
|
32
|
+
export const usePaywall = (): UsePaywallResult => {
|
|
33
|
+
const { present, isReady, catalog } = useContext(PaywallContext);
|
|
34
|
+
return { present, isReady, catalog };
|
|
35
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { createContext, useContext } from "react";
|
|
2
|
+
import type { ProductRuntime } from "./types";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Publishes one `ProductRuntime` above both `PaywallProvider` and
|
|
6
|
+
* `OnboardingProvider`, so a `PaywallProvider` mounted around an
|
|
7
|
+
* `OnboardingProvider` (Phase 5's `presentPaywall` arrangement) gives them one
|
|
8
|
+
* shared product catalog instead of each mounting its own `useProducts` — one
|
|
9
|
+
* store round-trip, one `purchasing` flag, for both.
|
|
10
|
+
*
|
|
11
|
+
* `null` by default: nothing above publishes a runtime, which is the normal
|
|
12
|
+
* case for an app that mounts only `OnboardingProvider`.
|
|
13
|
+
*/
|
|
14
|
+
export const ProductRuntimeContext = createContext<ProductRuntime | null>(null);
|
|
15
|
+
|
|
16
|
+
/** The ancestor `ProductRuntime`, or `null` when no provider publishes one. */
|
|
17
|
+
export const useProductRuntime = (): ProductRuntime | null => useContext(ProductRuntimeContext);
|
package/src/products/index.ts
CHANGED
|
@@ -14,6 +14,7 @@ export { parseIsoDuration } from "./duration";
|
|
|
14
14
|
export { formatCurrency, deriveProductFields, deriveAll } from "./derive";
|
|
15
15
|
export { productVariables } from "./toVariables";
|
|
16
16
|
export { useProducts } from "./useProducts";
|
|
17
|
+
export { ProductRuntimeContext, useProductRuntime } from "./ProductRuntimeContext";
|
|
17
18
|
export { stubProductProvider } from "./adapters/stub";
|
|
18
19
|
export { revenueCatProductProvider } from "./adapters/revenueCat";
|
|
19
20
|
export { expoIapProductProvider } from "./adapters/expoIap";
|