@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
@@ -0,0 +1,245 @@
1
+ import { formatCurrency } from "../derive";
2
+ import type {
3
+ ProductPeriod,
4
+ ProductProvider,
5
+ ProductRef,
6
+ ResolvedProduct,
7
+ RestoreResult,
8
+ } from "../types";
9
+
10
+ /**
11
+ * Stripe Payment Link provider.
12
+ *
13
+ * Deliberately NOT a store adapter. It makes no network call and holds no
14
+ * Stripe key: the price is authored in Onboarding Studio and travels inline on
15
+ * the `ProductRef` (`ProductRef.stripe`), so `getProducts` is a synchronous
16
+ * synthesis and `purchase` is a link-out.
17
+ *
18
+ * What it does NOT do, on purpose:
19
+ * - grant or verify anything. `purchase()` resolves `{ status: "pending" }`
20
+ * because the browser leaves the app — on web the JS context is destroyed.
21
+ * The entitlement arrives later through RevenueCat's Stripe integration,
22
+ * which is why `clientReferenceId` MUST return the RevenueCat App User ID:
23
+ * it is the key RevenueCat's webhook matches on, and the only thing tying
24
+ * the payment to the user. Return the wrong id and the money is taken with
25
+ * no entitlement granted. An ABSENT id (null/undefined/empty) is handled
26
+ * differently: `purchase()` refuses before opening anything, unless
27
+ * `allowAnonymous` opts in — see `StripeLinkProviderConfig.allowAnonymous`.
28
+ * - import `react-native` at module scope, so this file is safe to load on
29
+ * web. URL opening is injected (`openUrl`) for the same reason, and so the
30
+ * provider is testable under Node.
31
+ */
32
+ export type StripeLinkProviderConfig = {
33
+ /**
34
+ * The RevenueCat App User ID, as a getter — it changes on login/logout, and
35
+ * a value captured at provider construction would go stale.
36
+ */
37
+ clientReferenceId: () => string | null | undefined;
38
+ /** Optional email prefill for the Checkout page. */
39
+ prefilledEmail?: () => string | null | undefined;
40
+ /**
41
+ * How to leave the app. Defaults to `react-native`'s `Linking.openURL`,
42
+ * required lazily so this module stays importable where react-native is not.
43
+ */
44
+ openUrl?: (url: string) => void | Promise<void>;
45
+ /**
46
+ * Restoring is a store-account operation Stripe links cannot perform. Supply
47
+ * the host's real implementation (usually the RevenueCat adapter's
48
+ * `restore`) to make a Restore button work on a Stripe paywall.
49
+ */
50
+ restore?: ProductProvider["restore"];
51
+ /** Passed to `Intl.NumberFormat` when formatting the authored price. */
52
+ locale?: string;
53
+ /**
54
+ * Opt-in for checkout with no `clientReferenceId()`. Default `false`:
55
+ * `purchase()` refuses (fails closed) rather than open a Payment Link it
56
+ * cannot attribute to a RevenueCat user, because a payment that opens
57
+ * anyway is taken with NO way to grant the entitlement afterwards — see
58
+ * `purchase()` below. Set `true` only if you genuinely want anonymous
59
+ * checkout; entitlements from those purchases cannot be attributed
60
+ * automatically and must be reconciled out of band.
61
+ */
62
+ allowAnonymous?: boolean;
63
+ };
64
+
65
+ const PERIOD_FROM_UNIT: Record<string, ProductPeriod> = {
66
+ D: "week",
67
+ W: "week",
68
+ M: "month",
69
+ Y: "year",
70
+ };
71
+
72
+ /** Same shape the store adapters parse, for one consistent notion of period. */
73
+ const toPeriod = (iso: string | null | undefined): { period: ProductPeriod | null; count: number } => {
74
+ if (!iso) return { period: null, count: 0 };
75
+ const m = /^P(\d+)([DWMY])$/.exec(iso);
76
+ if (!m) return { period: null, count: 0 };
77
+ return { period: PERIOD_FROM_UNIT[m[2]] ?? null, count: Number(m[1]) };
78
+ };
79
+
80
+ const lazyLinking = (url: string): void | Promise<void> => {
81
+ // Required lazily and defensively: this provider's whole point is running on
82
+ // web, where react-native may be absent entirely.
83
+ try {
84
+ const RN = require("react-native");
85
+ return RN.Linking.openURL(url);
86
+ } catch {
87
+ if (typeof globalThis !== "undefined" && (globalThis as any).location) {
88
+ (globalThis as any).location.assign(url);
89
+ return;
90
+ }
91
+ throw new Error(
92
+ "stripeLinkProductProvider: no way to open a URL. Pass `openUrl` in the provider config.",
93
+ );
94
+ }
95
+ };
96
+
97
+ const withParams = (
98
+ link: string,
99
+ params: Record<string, string | null | undefined>,
100
+ ): string => {
101
+ // Parsed rather than string-concatenated so a link that already carries
102
+ // query parameters (`?locale=fr`) keeps them and does not gain a second `?`.
103
+ const url = new URL(link);
104
+ for (const [name, value] of Object.entries(params)) {
105
+ // Omit rather than emit — Stripe would receive the literal string "null".
106
+ if (value === null || value === undefined || value === "") continue;
107
+ url.searchParams.set(name, value);
108
+ }
109
+ return url.toString();
110
+ };
111
+
112
+ export const stripeLinkProductProvider = (config: StripeLinkProviderConfig): ProductProvider => {
113
+ const { clientReferenceId, prefilledEmail, openUrl = lazyLinking, restore, locale, allowAnonymous = false } =
114
+ config;
115
+
116
+ // `ResolvedProduct` has no field for the payment link and widening it would
117
+ // put a Stripe concern on every store product, so the link is remembered
118
+ // here, populated by `getProducts` — the same call that produced the
119
+ // `ResolvedProduct` `purchase` is later handed.
120
+ const linkByKey = new Map<string, string>();
121
+
122
+ return {
123
+ async getProducts(refs: ProductRef[]): Promise<ResolvedProduct[]> {
124
+ // Cleared, not merged: this call's `refs` is the full current catalog, so
125
+ // it defines the resolvable set on its own. A key that carried a stripe
126
+ // block last call but not this one (re-authored off Stripe billing) must
127
+ // stop resolving — an accumulating map would keep `purchase()` opening
128
+ // that stale link indefinitely instead of taking the "no link" error path.
129
+ linkByKey.clear();
130
+ const out: ResolvedProduct[] = [];
131
+ for (const ref of refs) {
132
+ const s = ref.stripe;
133
+ // A ref with no stripe block is not an error — the catalog union spans
134
+ // every paywall, including `billing: "store"` ones. Dropping it is the
135
+ // same contract the store adapters have for a missing platform id.
136
+ if (!s || !s.paymentLink) continue;
137
+ linkByKey.set(ref.key, s.paymentLink);
138
+ const { period, count } = toPeriod(s.periodIso);
139
+ const trialDays = s.trialDays ?? 0;
140
+ out.push({
141
+ key: ref.key,
142
+ productId: s.priceId ?? s.paymentLink,
143
+ store: "stripe",
144
+ title: "",
145
+ description: "",
146
+ price: formatCurrency(s.amount, s.currency, locale),
147
+ priceAmount: s.amount,
148
+ currencyCode: s.currency,
149
+ period,
150
+ periodCount: count,
151
+ periodIso: s.periodIso ?? null,
152
+ // Expressed in days, which is what `deriveProductFields` reads via
153
+ // `trial.days`; the period/count pair is filled in consistently so
154
+ // nothing downstream sees a half-populated trial.
155
+ ...(trialDays > 0
156
+ ? {
157
+ trial: {
158
+ period: "week" as ProductPeriod,
159
+ periodCount: Math.max(1, Math.round(trialDays / 7)),
160
+ days: trialDays,
161
+ },
162
+ }
163
+ : {}),
164
+ });
165
+ }
166
+ return out;
167
+ },
168
+
169
+ async purchase(product) {
170
+ const link = linkByKey.get(product.key);
171
+ if (!link) {
172
+ return {
173
+ status: "error",
174
+ error: new Error(
175
+ `stripeLinkProductProvider: no payment link for "${product.key}". ` +
176
+ "getProducts() never resolved this key, so the ref carries no `stripe.paymentLink`.",
177
+ ),
178
+ };
179
+ }
180
+ // Resolved and checked BEFORE the link opens — once it opens, the
181
+ // browser has left the app and the payment cannot be stopped. A
182
+ // null/undefined/empty id is not exotic: a getter wired to
183
+ // RevenueCat's `appUserID` before `Purchases.configure()` resolves, or
184
+ // read while the user is logged out, returns null. Without this check
185
+ // the link would still open, `purchase()` would still resolve
186
+ // "pending", the user would pay, and RevenueCat would have nothing to
187
+ // match the payment to — nothing fails loudly at any layer. See this
188
+ // file's top comment: "Return the wrong id and the money is taken with
189
+ // no entitlement granted" — this is that, for the ABSENT case.
190
+ const refId = clientReferenceId();
191
+ const hasRefId = refId !== null && refId !== undefined && refId !== "";
192
+ if (!hasRefId && !allowAnonymous) {
193
+ return {
194
+ status: "error",
195
+ error: new Error(
196
+ "stripeLinkProductProvider: clientReferenceId() returned no id — refusing to open the " +
197
+ "Payment Link. Opening it anyway would take payment with no way to attribute the " +
198
+ "entitlement RevenueCat grants afterwards. Wire `clientReferenceId` to the RevenueCat App " +
199
+ "User ID and make sure it resolves AFTER `Purchases.configure()` completes (reading it " +
200
+ "before configure() finishes, or while the user is logged out, is what returns null). " +
201
+ "Pass `allowAnonymous: true` in the provider config if anonymous checkout — with no " +
202
+ "automatic entitlement attribution — is genuinely what you want.",
203
+ ),
204
+ };
205
+ }
206
+ // `withParams` throws synchronously on a malformed link (`new URL`) —
207
+ // a plausible failure mode for an author-pasted Stripe URL. That throw
208
+ // happens before any `await`, so left unguarded it would make
209
+ // `purchase()` return a REJECTED promise instead of the resolved
210
+ // `{ status: "error", error }` every other failure path in this file
211
+ // uses. Callers awaiting `purchase()` should only ever see it resolve.
212
+ try {
213
+ await openUrl(
214
+ withParams(link, {
215
+ client_reference_id: refId,
216
+ prefilled_email: prefilledEmail?.(),
217
+ }),
218
+ );
219
+ } catch (e) {
220
+ // Always renamed to name the offending link — a bare `Invalid URL`
221
+ // (what `new URL` throws) gives an author nothing to act on.
222
+ const reason = e instanceof Error ? e.message : String(e);
223
+ return {
224
+ status: "error",
225
+ error: new Error(`stripeLinkProductProvider: failed to open payment link "${link}": ${reason}`),
226
+ };
227
+ }
228
+ // Never "purchased": the browser has taken over and, on web, this JS
229
+ // context is about to be destroyed. RevenueCat reports the entitlement.
230
+ return { status: "pending" };
231
+ },
232
+
233
+ async restore(): Promise<RestoreResult> {
234
+ if (restore) return restore();
235
+ return {
236
+ status: "error",
237
+ error: new Error(
238
+ "stripeLinkProductProvider: restore is not configured. A Stripe Payment Link cannot " +
239
+ "enumerate past purchases; pass `restore` (usually your RevenueCat adapter's) in the " +
240
+ "provider config so a Restore button does something.",
241
+ ),
242
+ };
243
+ },
244
+ };
245
+ };
@@ -1,5 +1,6 @@
1
1
  export type {
2
2
  ProductRef,
3
+ StripeProductRef,
3
4
  ProductPeriod,
4
5
  ResolvedProduct,
5
6
  DerivedProductFields,
@@ -13,8 +14,11 @@ export type {
13
14
  export { parseIsoDuration } from "./duration";
14
15
  export { formatCurrency, deriveProductFields, deriveAll } from "./derive";
15
16
  export { productVariables } from "./toVariables";
17
+ export { productRefIdentity } from "./refIdentity";
16
18
  export { useProducts } from "./useProducts";
17
19
  export { ProductRuntimeContext, useProductRuntime } from "./ProductRuntimeContext";
18
20
  export { stubProductProvider } from "./adapters/stub";
19
21
  export { revenueCatProductProvider } from "./adapters/revenueCat";
20
22
  export { expoIapProductProvider } from "./adapters/expoIap";
23
+ export { stripeLinkProductProvider } from "./adapters/stripeLink";
24
+ export type { StripeLinkProviderConfig } from "./adapters/stripeLink";
@@ -0,0 +1,33 @@
1
+ import type { ProductRef } from "./types";
2
+
3
+ /**
4
+ * The content identity of a `ProductRef` — the ONE place its fields are
5
+ * enumerated.
6
+ *
7
+ * Two callers depend on this and neither fails loudly when it is wrong:
8
+ * `useProducts`'s `refsKey` (a stale identity means a changed ref never
9
+ * refetches) and `collectProductRefs`'s dedup (a colliding identity means two
10
+ * distinct refs collapse into one and the second is never resolved). Both used
11
+ * to hand-roll the same template string, so adding a field to `ProductRef`
12
+ * meant remembering two places. Add new fields HERE and both callers follow.
13
+ *
14
+ * A unit separator (U+001F) rather than a printable one: a Play id is
15
+ * `productId:basePlanId` and a Payment Link is a URL, both of which can
16
+ * contain almost any printable character, so a printable separator risks
17
+ * `{ios:"a",android:"b"}` and `{ios:"a|b"}` hashing alike.
18
+ */
19
+ const SEP = "\u001F";
20
+
21
+ export const productRefIdentity = (ref: ProductRef): string =>
22
+ [
23
+ ref.key,
24
+ ref.ios ?? "",
25
+ ref.android ?? "",
26
+ ref.compareTo ?? "",
27
+ ref.stripe?.paymentLink ?? "",
28
+ ref.stripe?.priceId ?? "",
29
+ ref.stripe?.amount ?? "",
30
+ ref.stripe?.currency ?? "",
31
+ ref.stripe?.periodIso ?? "",
32
+ ref.stripe?.trialDays ?? "",
33
+ ].join(SEP);
@@ -1,3 +1,30 @@
1
+ /**
2
+ * A Stripe Payment Link and the price to render beside it.
3
+ *
4
+ * Unlike `ios`/`android` — which are ids a store resolves at runtime — this
5
+ * block is the RESOLVED product. There is no Stripe runtime to ask: listing a
6
+ * price needs a secret key, and by design nobody in this system holds one
7
+ * (not the host, not Onboarding Studio). So the studio copies the authored
8
+ * price onto the ref, and `stripeLinkProductProvider` synthesises a
9
+ * `ResolvedProduct` from it without any network call.
10
+ *
11
+ * Consequence the author owns: this price can DRIFT from Stripe. Nothing
12
+ * reconciles them.
13
+ */
14
+ export type StripeProductRef = {
15
+ /** `https://buy.stripe.com/...`, pre-created in Stripe. Required — nothing to open without it. */
16
+ paymentLink: string;
17
+ /** `price_...`. Informational in this version; kept for reconciliation and a future proxy mode. */
18
+ priceId?: string;
19
+ /** Major units (79, not 7900), matching `project_products.stripe_price.amount`. */
20
+ amount: number;
21
+ /** ISO-4217, e.g. "USD". */
22
+ currency: string;
23
+ /** ISO-8601, e.g. "P1Y". Drives `pricePerWeek` and friends via `deriveProductFields`. */
24
+ periodIso?: string | null;
25
+ trialDays?: number;
26
+ };
27
+
1
28
  /** A product slot declared by the author: a stable key plus per-store ids. */
2
29
  export type ProductRef = {
3
30
  /** Author-chosen slot name used in variables, e.g. "yearly" → product.yearly.price */
@@ -6,6 +33,8 @@ export type ProductRef = {
6
33
  ios?: string;
7
34
  /** Play product identifier. `productId:basePlanId` — RevenueCat's convention. */
8
35
  android?: string;
36
+ /** Stripe Payment Link + authored price. Present only on a `billing: "stripe"` paywall's refs. */
37
+ stripe?: StripeProductRef;
9
38
  /** Another slot's key; savingsPct is computed against it. */
10
39
  compareTo?: string;
11
40
  };
@@ -17,7 +46,7 @@ export type ResolvedProduct = {
17
46
  key: string;
18
47
  /** The identifier resolved for THIS platform. */
19
48
  productId: string;
20
- store: "app_store" | "play_store";
49
+ store: "app_store" | "play_store" | "stripe";
21
50
  title: string;
22
51
  description: string;
23
52
  /** Store-localized, pre-formatted, e.g. "$59.99". Display this. */
@@ -1,5 +1,6 @@
1
1
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
2
  import { deriveAll } from "./derive";
3
+ import { productRefIdentity } from "./refIdentity";
3
4
  import type {
4
5
  ProductProvider,
5
6
  ProductRef,
@@ -39,10 +40,12 @@ export const useProducts = (
39
40
 
40
41
  // Key the effect on the refs' identity CONTENT, not the array identity — a
41
42
  // host passing an inline array literal would otherwise refetch every render.
42
- const refsKey = useMemo(
43
- () => (refs ?? []).map((r) => `${r.key}|${r.ios ?? ""}|${r.android ?? ""}|${r.compareTo ?? ""}`).join(","),
44
- [refs]
45
- );
43
+ // `productRefIdentity` owns the field list; see its doc for why it is shared
44
+ // with `collectProductRefs` rather than duplicated here.
45
+ // "\u001E" (record separator) BETWEEN refs, distinct from the "\u001F"
46
+ // `productRefIdentity` puts between FIELDS — one separator for each nesting
47
+ // level, so no arrangement of ids can produce two identical keys.
48
+ const refsKey = useMemo(() => (refs ?? []).map(productRefIdentity).join("\u001E"), [refs]);
46
49
  const refsRef = useRef(refs);
47
50
  refsRef.current = refs;
48
51