@rocapine/react-native-onboarding 1.68.2 → 1.70.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 (54) hide show
  1. package/dist/OnboardingStudioClient.d.ts +4 -4
  2. package/dist/OnboardingStudioClient.js +7 -7
  3. package/dist/OnboardingStudioClient.js.map +1 -1
  4. package/dist/index.d.ts +1 -0
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/paywalls/PaywallProvider.d.ts +38 -7
  7. package/dist/paywalls/PaywallProvider.d.ts.map +1 -1
  8. package/dist/paywalls/PaywallProvider.js +101 -44
  9. package/dist/paywalls/PaywallProvider.js.map +1 -1
  10. package/dist/paywalls/present.d.ts +91 -12
  11. package/dist/paywalls/present.d.ts.map +1 -1
  12. package/dist/paywalls/present.js +75 -18
  13. package/dist/paywalls/present.js.map +1 -1
  14. package/dist/paywalls/types.d.ts +48 -23
  15. package/dist/paywalls/types.d.ts.map +1 -1
  16. package/dist/paywalls/types.js +0 -7
  17. package/dist/paywalls/types.js.map +1 -1
  18. package/dist/paywalls/usePaywall.d.ts +19 -4
  19. package/dist/paywalls/usePaywall.d.ts.map +1 -1
  20. package/dist/paywalls/usePaywall.js +2 -2
  21. package/dist/paywalls/usePaywall.js.map +1 -1
  22. package/dist/products/adapters/stripeLink.d.ts +57 -0
  23. package/dist/products/adapters/stripeLink.d.ts.map +1 -0
  24. package/dist/products/adapters/stripeLink.js +158 -0
  25. package/dist/products/adapters/stripeLink.js.map +1 -0
  26. package/dist/products/index.d.ts +4 -1
  27. package/dist/products/index.d.ts.map +1 -1
  28. package/dist/products/index.js +5 -1
  29. package/dist/products/index.js.map +1 -1
  30. package/dist/products/refIdentity.d.ts +3 -0
  31. package/dist/products/refIdentity.d.ts.map +1 -0
  32. package/dist/products/refIdentity.js +37 -0
  33. package/dist/products/refIdentity.js.map +1 -0
  34. package/dist/products/types.d.ts +29 -1
  35. package/dist/products/types.d.ts.map +1 -1
  36. package/dist/products/useProducts.d.ts.map +1 -1
  37. package/dist/products/useProducts.js +7 -1
  38. package/dist/products/useProducts.js.map +1 -1
  39. package/package.json +1 -1
  40. package/src/OnboardingStudioClient.ts +7 -7
  41. package/src/index.ts +3 -0
  42. package/src/paywalls/PaywallProvider.tsx +145 -48
  43. package/src/paywalls/__tests__/getPaywalls.test.ts +15 -12
  44. package/src/paywalls/__tests__/present.test.ts +192 -26
  45. package/src/paywalls/present.ts +115 -19
  46. package/src/paywalls/types.ts +49 -23
  47. package/src/paywalls/usePaywall.ts +22 -6
  48. package/src/products/__tests__/refIdentity.test.ts +44 -0
  49. package/src/products/adapters/__tests__/stripeLink.test.ts +179 -0
  50. package/src/products/adapters/stripeLink.ts +245 -0
  51. package/src/products/index.ts +4 -0
  52. package/src/products/refIdentity.ts +33 -0
  53. package/src/products/types.ts +30 -1
  54. package/src/products/useProducts.ts +7 -4
@@ -1,27 +1,32 @@
1
1
  import { describe, it, expect } from "vitest";
2
2
  import {
3
3
  collectProductRefs,
4
+ computeCatalogStatus,
4
5
  computeIsReady,
5
6
  purchaseOutcomeFromResult,
6
7
  resolvePresentDecision,
7
8
  resolvePresentedOutcome,
9
+ selectActiveProductRuntime,
8
10
  shouldBreakPresentationWedge,
9
11
  shouldRecordPurchaseOutcome,
10
12
  } from "../present";
11
13
  import type { Paywall, PaywallCatalog } from "../types";
12
- import type { PurchaseResult } from "../../products/types";
14
+ import type { ProductRuntime, PurchaseResult } from "../../products/types";
13
15
 
14
- const makePaywall = (overrides: Partial<Paywall> & Pick<Paywall, "id" | "placement">): Paywall => ({
16
+ const makePaywall = (overrides: Partial<Paywall> & Pick<Paywall, "id" | "moment">): Paywall => ({
15
17
  name: overrides.name ?? "Paywall",
18
+ audienceId: overrides.audienceId ?? null,
19
+ audienceName: overrides.audienceName ?? null,
16
20
  elements: overrides.elements ?? [],
21
+ billing: overrides.billing ?? "store",
17
22
  products: overrides.products ?? [],
18
23
  configuration: overrides.configuration ?? null,
19
24
  ...overrides,
20
25
  });
21
26
 
22
27
  const makeCatalog = (paywalls: Paywall[]): PaywallCatalog => ({
23
- metadata: { audienceId: null, audienceName: null, locale: "en", draft: false },
24
- paywalls: Object.fromEntries(paywalls.map((p) => [p.placement, p])),
28
+ metadata: { locale: "en", draft: false },
29
+ paywalls: Object.fromEntries(paywalls.map((p) => [p.moment, p])),
25
30
  fonts: null,
26
31
  });
27
32
 
@@ -31,14 +36,14 @@ describe("collectProductRefs", () => {
31
36
  });
32
37
 
33
38
  it("returns an empty array when no paywall declares any products", () => {
34
- const catalog = makeCatalog([makePaywall({ id: "1", placement: "a", products: [] })]);
39
+ const catalog = makeCatalog([makePaywall({ id: "1", moment: "a", products: [] })]);
35
40
  expect(collectProductRefs(catalog)).toEqual([]);
36
41
  });
37
42
 
38
- it("flattens products from every placement into one array", () => {
43
+ it("flattens products from every moment into one array", () => {
39
44
  const catalog = makeCatalog([
40
- makePaywall({ id: "1", placement: "a", products: [{ key: "yearly", ios: "com.app.yr" }] }),
41
- makePaywall({ id: "2", placement: "b", products: [{ key: "monthly", ios: "com.app.mo" }] }),
45
+ makePaywall({ id: "1", moment: "a", products: [{ key: "yearly", ios: "com.app.yr" }] }),
46
+ makePaywall({ id: "2", moment: "b", products: [{ key: "monthly", ios: "com.app.mo" }] }),
42
47
  ]);
43
48
  expect(collectProductRefs(catalog)).toEqual([
44
49
  { key: "yearly", ios: "com.app.yr" },
@@ -46,11 +51,11 @@ describe("collectProductRefs", () => {
46
51
  ]);
47
52
  });
48
53
 
49
- it("dedupes identical refs (same key + ios + android + compareTo) across placements", () => {
54
+ it("dedupes identical refs (same key + ios + android + compareTo) across moments", () => {
50
55
  const shared = { key: "yearly", ios: "com.app.yr", android: "com.app.yr:p1y" };
51
56
  const catalog = makeCatalog([
52
- makePaywall({ id: "1", placement: "a", products: [shared] }),
53
- makePaywall({ id: "2", placement: "b", products: [shared, { key: "monthly", ios: "com.app.mo" }] }),
57
+ makePaywall({ id: "1", moment: "a", products: [shared] }),
58
+ makePaywall({ id: "2", moment: "b", products: [shared, { key: "monthly", ios: "com.app.mo" }] }),
54
59
  ]);
55
60
  expect(collectProductRefs(catalog)).toEqual([
56
61
  shared,
@@ -62,7 +67,7 @@ describe("collectProductRefs", () => {
62
67
  const catalog = makeCatalog([
63
68
  makePaywall({
64
69
  id: "1",
65
- placement: "a",
70
+ moment: "a",
66
71
  products: [
67
72
  { key: "yearly", ios: "com.app.yr" },
68
73
  { key: "yearly", ios: "com.app.yr", compareTo: "monthly" },
@@ -74,10 +79,10 @@ describe("collectProductRefs", () => {
74
79
  });
75
80
 
76
81
  describe("resolvePresentDecision", () => {
77
- const paywall = makePaywall({ id: "1", placement: "hard_paywall", products: [] });
82
+ const paywall = makePaywall({ id: "1", moment: "hard_paywall", products: [] });
78
83
  const catalog = makeCatalog([paywall]);
79
84
 
80
- it("starts when the placement exists and nothing is currently showing", () => {
85
+ it("starts when the moment exists and nothing is currently showing", () => {
81
86
  const decision = resolvePresentDecision(catalog, null, "hard_paywall");
82
87
  expect(decision).toEqual({ type: "start", paywall });
83
88
  });
@@ -86,24 +91,32 @@ describe("resolvePresentDecision", () => {
86
91
  // used to assert is what made two conditions with OPPOSITE correct responses
87
92
  // — "retry later, the catalog may still arrive" vs "do not retry, something
88
93
  // is stuck" — indistinguishable to the caller.
89
- it("resolves 'unknown-placement' when the placement is absent from the catalog", () => {
94
+ it("resolves 'unknown-moment' when the moment is absent from the catalog", () => {
90
95
  const decision = resolvePresentDecision(catalog, null, "does_not_exist");
91
96
  expect(decision).toEqual({
92
97
  type: "immediate",
93
- result: { status: "error", reason: "unknown-placement" },
98
+ result: { status: "error", reason: "unknown-moment" },
94
99
  });
95
100
  });
96
101
 
97
- it("resolves 'unknown-placement' when the catalog has not resolved yet (null)", () => {
102
+ it("resolves 'unknown-moment' when the catalog has not resolved yet (null)", () => {
98
103
  const decision = resolvePresentDecision(null, null, "hard_paywall");
99
104
  expect(decision).toEqual({
100
105
  type: "immediate",
101
- result: { status: "error", reason: "unknown-placement" },
106
+ result: { status: "error", reason: "unknown-moment" },
102
107
  });
103
108
  });
104
109
 
105
- it("resolves 'already-presenting' AND names the placement that is showing", () => {
106
- // The placement is the difference between "I double-called for the same
110
+ it("reports unknown-moment when the key is absent from the catalog", () => {
111
+ const decision = resolvePresentDecision(catalog, null, "not_a_moment");
112
+ expect(decision).toEqual({
113
+ type: "immediate",
114
+ result: { status: "error", reason: "unknown-moment" },
115
+ });
116
+ });
117
+
118
+ it("resolves 'already-presenting' AND names the moment that is showing", () => {
119
+ // The moment is the difference between "I double-called for the same
107
120
  // one" (caller adds a guard) and "something else is stuck" (caller cannot
108
121
  // fix it) — different diagnoses, so the bare status could serve neither.
109
122
  const decision = resolvePresentDecision(catalog, "already_showing", "hard_paywall");
@@ -112,24 +125,24 @@ describe("resolvePresentDecision", () => {
112
125
  result: {
113
126
  status: "error",
114
127
  reason: "already-presenting",
115
- activePlacement: "already_showing",
128
+ activeMoment: "already_showing",
116
129
  },
117
130
  });
118
131
  });
119
132
 
120
- it("reports 'already-presenting' when the caller re-presents the SAME placement", () => {
133
+ it("reports 'already-presenting' when the caller re-presents the SAME moment", () => {
121
134
  const decision = resolvePresentDecision(catalog, "hard_paywall", "hard_paywall");
122
135
  expect(decision).toEqual({
123
136
  type: "immediate",
124
137
  result: {
125
138
  status: "error",
126
139
  reason: "already-presenting",
127
- activePlacement: "hard_paywall",
140
+ activeMoment: "hard_paywall",
128
141
  },
129
142
  });
130
143
  });
131
144
 
132
- it("the concurrent-present check takes priority over the unknown-placement check", () => {
145
+ it("the concurrent-present check takes priority over the unknown-moment check", () => {
133
146
  // Both conditions are true at once: prove the function still resolves
134
147
  // rather than e.g. throwing on the first branch it happens to hit, and
135
148
  // that the reason reflects the branch actually taken.
@@ -139,7 +152,7 @@ describe("resolvePresentDecision", () => {
139
152
  result: {
140
153
  status: "error",
141
154
  reason: "already-presenting",
142
- activePlacement: "already_showing",
155
+ activeMoment: "already_showing",
143
156
  },
144
157
  });
145
158
  });
@@ -235,7 +248,7 @@ describe("resolvePresentedOutcome", () => {
235
248
  });
236
249
 
237
250
  it("never upgrades a status other than 'dismissed', even if a purchase occurred", () => {
238
- // "error" here means "unknown placement / already showing" (resolvePresentDecision) —
251
+ // "error" here means "unknown moment / already showing" (resolvePresentDecision) —
239
252
  // a purchase outcome must never be allowed to clobber that different meaning.
240
253
  expect(resolvePresentedOutcome({ status: "error" }, "purchased")).toEqual({ status: "error" });
241
254
  });
@@ -257,3 +270,156 @@ describe("shouldRecordPurchaseOutcome", () => {
257
270
  expect(shouldRecordPurchaseOutcome(1, 5)).toBe(false);
258
271
  });
259
272
  });
273
+
274
+ describe("computeCatalogStatus", () => {
275
+ const catalog = makeCatalog([makePaywall({ id: "1", moment: "hard_paywall" })]);
276
+
277
+ it("is 'loading' before anything arrives", () => {
278
+ expect(computeCatalogStatus(null, null, true)).toBe("loading");
279
+ expect(computeCatalogStatus(null, null, false)).toBe("loading");
280
+ });
281
+
282
+ it("is 'error' only when there is no catalog to fall back on", () => {
283
+ expect(computeCatalogStatus(null, new Error("network"), false)).toBe("error");
284
+ });
285
+
286
+ it("is 'ready' for a settled catalog", () => {
287
+ expect(computeCatalogStatus(catalog, null, false)).toBe("ready");
288
+ });
289
+
290
+ it("is 'revalidating' when a catalog is on hand AND a fetch is in flight", () => {
291
+ // The state this type exists for. In production the catalog is served
292
+ // cache-first from a disk key that is NOT scoped by customAudienceParams,
293
+ // so this catalog may have been resolved under DIFFERENT params and be
294
+ // superseded in a moment. A host must be able to tell that a moment
295
+ // missing HERE might simply not have arrived yet.
296
+ expect(computeCatalogStatus(catalog, null, true)).toBe("revalidating");
297
+ });
298
+
299
+ it("prefers a usable catalog over reporting a failed revalidation", () => {
300
+ // react-query keeps cached `data` and sets `error` when a background
301
+ // refetch fails. Reporting "error" there would make a host discard a
302
+ // perfectly serviceable catalog.
303
+ expect(computeCatalogStatus(catalog, new Error("revalidation failed"), false)).toBe("ready");
304
+ expect(computeCatalogStatus(catalog, new Error("revalidation failed"), true)).toBe("revalidating");
305
+ });
306
+
307
+ it("distinguishes every state `isReady` collapses", () => {
308
+ // isReady is false for all three of these; catalogStatus separates them,
309
+ // which is the whole point.
310
+ const loading = computeCatalogStatus(null, null, true);
311
+ const errored = computeCatalogStatus(null, new Error("x"), false);
312
+ const productsPending = computeCatalogStatus(catalog, null, false);
313
+ expect(computeIsReady(null, [], "idle")).toBe(false);
314
+ expect(new Set([loading, errored, productsPending]).size).toBe(3);
315
+ });
316
+ });
317
+
318
+ const runtime = (over: Partial<ProductRuntime> = {}): ProductRuntime => ({
319
+ products: {},
320
+ status: "ready",
321
+ purchasing: false,
322
+ purchase: async () => ({ status: "cancelled" }),
323
+ restore: async () => ({ status: "nothing_to_restore" }),
324
+ ...over,
325
+ });
326
+
327
+ describe("selectActiveProductRuntime", () => {
328
+ const storeRuntime = runtime({ status: "ready" });
329
+ const stripeRuntime = runtime({ status: "loading" });
330
+
331
+ it("publishes the store runtime when billing is 'store'", () => {
332
+ expect(
333
+ selectActiveProductRuntime({
334
+ storeRuntime,
335
+ stripeRuntime,
336
+ billing: "store",
337
+ hasStripeProvider: true,
338
+ hasStoreProvider: true,
339
+ }),
340
+ ).toBe(storeRuntime);
341
+ });
342
+
343
+ it("publishes the store runtime when no paywall is active and both providers exist", () => {
344
+ // Neither is more likely to be "the" right one just because nothing is
345
+ // active yet, so this keeps the pre-existing store-first default.
346
+ expect(
347
+ selectActiveProductRuntime({
348
+ storeRuntime,
349
+ stripeRuntime,
350
+ billing: undefined,
351
+ hasStripeProvider: true,
352
+ hasStoreProvider: true,
353
+ }),
354
+ ).toBe(storeRuntime);
355
+ });
356
+
357
+ it("publishes the store runtime when no paywall is active and neither provider exists", () => {
358
+ expect(
359
+ selectActiveProductRuntime({
360
+ storeRuntime,
361
+ stripeRuntime,
362
+ billing: undefined,
363
+ hasStripeProvider: false,
364
+ hasStoreProvider: false,
365
+ }),
366
+ ).toBe(storeRuntime);
367
+ });
368
+
369
+ it("publishes the stripe runtime when no paywall is active and only a stripe provider was passed", () => {
370
+ // A stripe-only host (no `productProvider` at all) must not sit on an
371
+ // "idle" store runtime forever — see this function's doc for why that
372
+ // used to keep `products.loaded` at "false" for every screen before the
373
+ // first paywall presents.
374
+ expect(
375
+ selectActiveProductRuntime({
376
+ storeRuntime,
377
+ stripeRuntime,
378
+ billing: undefined,
379
+ hasStripeProvider: true,
380
+ hasStoreProvider: false,
381
+ }),
382
+ ).toBe(stripeRuntime);
383
+ });
384
+
385
+ it("publishes the stripe runtime when billing is 'stripe'", () => {
386
+ expect(
387
+ selectActiveProductRuntime({
388
+ storeRuntime,
389
+ stripeRuntime,
390
+ billing: "stripe",
391
+ hasStripeProvider: true,
392
+ hasStoreProvider: true,
393
+ }),
394
+ ).toBe(stripeRuntime);
395
+ });
396
+
397
+ it("falls back to the store runtime when billing is 'stripe' but no stripe provider was passed", () => {
398
+ // Without this, `useProducts` leaves the stripe runtime at "idle" forever
399
+ // (it bails before calling a provider it does not have), `computeIsReady`
400
+ // never turns true, and every paywall silently stops presenting — the same
401
+ // trap `mergeProductRuntimes` documents for its own status merge.
402
+ const idleStripe = runtime({ status: "idle" });
403
+ expect(
404
+ selectActiveProductRuntime({
405
+ storeRuntime,
406
+ stripeRuntime: idleStripe,
407
+ billing: "stripe",
408
+ hasStripeProvider: false,
409
+ hasStoreProvider: true,
410
+ }),
411
+ ).toBe(storeRuntime);
412
+ });
413
+
414
+ it("never merges the two statuses", () => {
415
+ // A store paywall must not be held un-ready by the stripe pass.
416
+ const selected = selectActiveProductRuntime({
417
+ storeRuntime: runtime({ status: "ready" }),
418
+ stripeRuntime: runtime({ status: "loading" }),
419
+ billing: "store",
420
+ hasStripeProvider: true,
421
+ hasStoreProvider: true,
422
+ });
423
+ expect(selected.status).toBe("ready");
424
+ });
425
+ });
@@ -1,12 +1,13 @@
1
1
  import type { Paywall, PaywallCatalog, PresentResult } from "./types";
2
- import type { ProductRef, ProductStatus, PurchaseResult } from "../products/types";
2
+ import type { ProductRef, ProductRuntime, ProductStatus, PurchaseResult } from "../products/types";
3
+ import { productRefIdentity } from "../products/refIdentity";
3
4
 
4
5
  /**
5
6
  * Union of every `paywall.products[]` across the WHOLE catalog, deduplicated
6
7
  * 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.
8
+ * (`products/refIdentity.ts`: keyed on ref CONTENT, not array identity), so
9
+ * this array is exactly as cheap to pass as a hand-written one: `useProducts`
10
+ * resolves it once and does not refetch on every render.
10
11
  *
11
12
  * Resolving the whole catalog's union ONCE at load — rather than re-keying
12
13
  * `useProducts` per presented paywall — is the deliberate design decision:
@@ -20,7 +21,7 @@ export const collectProductRefs = (catalog: PaywallCatalog | null): ProductRef[]
20
21
  const refs: ProductRef[] = [];
21
22
  for (const paywall of Object.values(catalog.paywalls)) {
22
23
  for (const ref of paywall.products) {
23
- const identity = `${ref.key}|${ref.ios ?? ""}|${ref.android ?? ""}|${ref.compareTo ?? ""}`;
24
+ const identity = productRefIdentity(ref);
24
25
  if (seen.has(identity)) continue;
25
26
  seen.add(identity);
26
27
  refs.push(ref);
@@ -35,13 +36,13 @@ export type PresentDecision =
35
36
  | { type: "immediate"; result: PresentResult };
36
37
 
37
38
  /**
38
- * `present(placement)`'s edge-case decision, extracted so both documented
39
+ * `present(moment)`'s edge-case decision, extracted so both documented
39
40
  * edge cases are covered by an importable test rather than only inspection:
40
41
  *
41
- * - **Unknown placement** (absent from the catalog, or the catalog hasn't
42
- * resolved yet — both look identical here: `catalog?.paywalls[placement]`
42
+ * - **Unknown moment** (absent from the catalog, or the catalog hasn't
43
+ * resolved yet — both look identical here: `catalog?.paywalls[moment]`
43
44
  * is `undefined` either way) → resolves `"error"`, never throws. A missing
44
- * placement must not crash a host app mid-flow.
45
+ * moment must not crash a host app mid-flow.
45
46
  * - **`present()` called while another paywall is already showing** → also
46
47
  * resolves `"error"` immediately, leaving the in-progress presentation
47
48
  * untouched. This SDK shows one paywall at a time. Silently replacing the
@@ -49,23 +50,23 @@ export type PresentDecision =
49
50
  * resolved — that caller hangs forever); queueing the new request would
50
51
  * need its own cancellation/timeout story that nothing here asks for.
51
52
  * Resolving the new call immediately applies the same "resolve, don't
52
- * throw" contract as the unknown-placement case, consistently.
53
+ * throw" contract as the unknown-moment case, consistently.
53
54
  */
54
55
  export const resolvePresentDecision = (
55
56
  catalog: PaywallCatalog | null,
56
- activePlacement: string | null,
57
- placement: string
57
+ activeMoment: string | null,
58
+ moment: string
58
59
  ): PresentDecision => {
59
- if (activePlacement !== null) {
60
- // `activePlacement` is echoed back deliberately — see PresentErrorReason.
60
+ if (activeMoment !== null) {
61
+ // `activeMoment` is echoed back deliberately — see PresentErrorReason.
61
62
  return {
62
63
  type: "immediate",
63
- result: { status: "error", reason: "already-presenting", activePlacement },
64
+ result: { status: "error", reason: "already-presenting", activeMoment },
64
65
  };
65
66
  }
66
- const paywall = catalog?.paywalls[placement];
67
+ const paywall = catalog?.paywalls[moment];
67
68
  if (!paywall) {
68
- return { type: "immediate", result: { status: "error", reason: "unknown-placement" } };
69
+ return { type: "immediate", result: { status: "error", reason: "unknown-moment" } };
69
70
  }
70
71
  return { type: "start", paywall };
71
72
  };
@@ -99,6 +100,49 @@ export const shouldBreakPresentationWedge = (
99
100
  timedOut: boolean
100
101
  ): boolean => activePlacement !== null && !hostAcknowledged && timedOut;
101
102
 
103
+ /**
104
+ * What the catalog is doing right now — the states `isReady` collapses.
105
+ *
106
+ * `isReady` is a single boolean over at least three distinct situations (no
107
+ * catalog yet, a catalog whose products are still resolving, and a failed query
108
+ * — which also presents as `catalog === null`). A host deciding "wait for the
109
+ * catalog" versus "fall back to another paywall engine" cannot tell those apart
110
+ * from one boolean, and every host that needs the distinction ends up building
111
+ * its own multi-input gate.
112
+ *
113
+ * `"revalidating"` is the state that motivated this, and it is not cosmetic.
114
+ * In production the catalog is served CACHE-FIRST from AsyncStorage under a key
115
+ * that is NOT scoped by `customAudienceParams` (`getPaywalls.query.ts` — the
116
+ * react-query key is param-scoped, the disk key is a bare constant). So a host
117
+ * sending volatile params gets an instantly-available catalog that was resolved
118
+ * under DIFFERENT params, with a fresh fetch in flight behind it. That catalog
119
+ * is present and non-null, so it reads as ready — and a host gating on
120
+ * `catalog.paywalls[moment]` can conclude the moment does not exist and
121
+ * route away, milliseconds before the correct catalog arrives.
122
+ *
123
+ * Observed consequence, reported from a production pilot: for an audience gated
124
+ * on a threshold (`hoursSinceOnboardingPaywall >= 44`), the launch where a user
125
+ * first becomes eligible is served the PRE-threshold catalog, so the arm under
126
+ * test loses exactly the launch that matters. `"revalidating"` is how a host
127
+ * distinguishes "this catalog is final" from "this catalog may be superseded in
128
+ * a moment", and therefore whether a missing moment means absent or not-yet.
129
+ *
130
+ * A present catalog outranks an error deliberately: if a background
131
+ * revalidation fails, react-query keeps the cached `data` AND sets `error`, and
132
+ * a usable catalog should not be reported as a failure.
133
+ */
134
+ export type CatalogStatus = "loading" | "ready" | "revalidating" | "error";
135
+
136
+ export const computeCatalogStatus = (
137
+ catalog: PaywallCatalog | null,
138
+ error: unknown,
139
+ isFetching: boolean
140
+ ): CatalogStatus => {
141
+ if (catalog !== null) return isFetching ? "revalidating" : "ready";
142
+ if (error) return "error";
143
+ return "loading";
144
+ };
145
+
102
146
  /**
103
147
  * `isReady` = catalog resolved AND products resolved — the one flag a caller
104
148
  * needs to know "presenting now will not show a spinner".
@@ -123,7 +167,7 @@ export const computeIsReady = (
123
167
  * `"error"` are not: they don't describe what happened to the STORE PURCHASE
124
168
  * in a way that should override how the paywall itself reports closing (an
125
169
  * `"error"` here would collide with `PresentResult`'s existing `"error"`,
126
- * which means something structurally different — an unknown placement or a
170
+ * which means something structurally different — an unknown moment or a
127
171
  * mistimed `present()` call, not a failed purchase attempt).
128
172
  */
129
173
  export type PurchaseOutcomeDuringPresentation = "purchased" | "cancelled" | null;
@@ -164,7 +208,7 @@ export const resolvePresentedOutcome = (
164
208
  * generation again after — only an unchanged generation means the write is
165
209
  * still for the presentation that started it.
166
210
  *
167
- * A monotonic counter, not the placement string: the same placement can
211
+ * A monotonic counter, not the moment string: the same moment can
168
212
  * legitimately be presented twice in a row, and a string comparison would
169
213
  * let a stale write from the FIRST of those two land in the second.
170
214
  */
@@ -172,3 +216,55 @@ export const shouldRecordPurchaseOutcome = (
172
216
  startedInGeneration: number,
173
217
  currentGeneration: number
174
218
  ): boolean => startedInGeneration === currentGeneration;
219
+
220
+ /**
221
+ * Which of the two resolved product runtimes to publish.
222
+ *
223
+ * `PaywallProvider` resolves the catalog's product union TWICE — once through
224
+ * the host's store adapter, once through its Stripe adapter — because the
225
+ * runtime is published as one map keyed by product key, and a `store` paywall
226
+ * and a `stripe` paywall declaring the same key would otherwise fight over
227
+ * `product.<key>.price`. Only one paywall is ever presented at a time
228
+ * (`activeMoment`), so "the active one" is unambiguous.
229
+ *
230
+ * This is cheap rather than wasteful because the Stripe pass performs no
231
+ * network call (`stripeLinkProductProvider`) and each provider silently drops
232
+ * refs it cannot resolve, so neither pass does work for the other's paywalls.
233
+ *
234
+ * The statuses are deliberately NOT merged. Merging is the trap
235
+ * `mergeProductRuntimes` documents from the other direction: an `"idle"`
236
+ * runtime with nothing to wait for drags a `"ready"` one down and closes every
237
+ * `products.loaded` gate for the life of the process.
238
+ *
239
+ * `hasStripeProvider` is the guard for a misconfigured host: a `stripe`
240
+ * paywall with no `stripeProductProvider` passed leaves `useProducts` at
241
+ * `"idle"` forever (it bails before calling a provider it does not have), so
242
+ * `computeIsReady` would never turn true and paywalls would stop appearing
243
+ * with no error. Falling back to the store runtime keeps the app alive; the
244
+ * caller warns.
245
+ *
246
+ * `billing` is `undefined` whenever no paywall is active (`activePaywall` is
247
+ * null before the first `present()`, and after every `complete()`) — there is
248
+ * no `.billing` to read yet. That USED to fall through to the store runtime
249
+ * unconditionally, which meant a host that passes ONLY
250
+ * `stripeProductProvider` (no `productProvider` at all) sat on an `"idle"`
251
+ * `storeRuntime` — forever, for every screen before a paywall first presents,
252
+ * since nothing ever calls a `present()` to select the stripe runtime instead
253
+ * — so `products.loaded` read `"false"` everywhere and `isReady` never turned
254
+ * true. `hasStoreProvider` closes that gap: with no active paywall, prefer
255
+ * whichever provider was actually SUPPLIED. When both or neither exist there
256
+ * is no asymmetry to correct, so this keeps the pre-existing store-first
257
+ * default — unchanged for every host that already worked.
258
+ */
259
+ export const selectActiveProductRuntime = (args: {
260
+ storeRuntime: ProductRuntime;
261
+ stripeRuntime: ProductRuntime;
262
+ billing: "store" | "stripe" | undefined;
263
+ hasStripeProvider: boolean;
264
+ hasStoreProvider: boolean;
265
+ }): ProductRuntime => {
266
+ if (args.billing === "stripe" && args.hasStripeProvider) return args.stripeRuntime;
267
+ if (args.billing !== undefined) return args.storeRuntime;
268
+ if (args.hasStripeProvider && !args.hasStoreProvider) return args.stripeRuntime;
269
+ return args.storeRuntime;
270
+ };