@solvapay/react 1.0.8-preview.6 → 1.0.8-preview.7
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/README.md +12 -95
- package/dist/CancelPlanButton-Bb7cvym9.d.cts +1105 -0
- package/dist/CancelPlanButton-CieT9swn.d.cts +1102 -0
- package/dist/CancelPlanButton-Cq117t7h.d.ts +1105 -0
- package/dist/CancelPlanButton-f56UlQN-.d.ts +1102 -0
- package/dist/PaymentForm-B5dw0i1X.d.ts +934 -0
- package/dist/PaymentForm-CesoRQWu.d.cts +934 -0
- package/dist/chunk-C7SKOENW.js +1889 -0
- package/dist/chunk-ISYAH4ZL.js +1889 -0
- package/dist/chunk-MOP3ZBGC.js +4749 -0
- package/dist/chunk-Q7GPX6X4.js +4748 -0
- package/dist/chunk-TP4JPKE2.js +3126 -0
- package/dist/chunk-VTGIXJQU.js +4755 -0
- package/dist/chunk-XMQ4GBWQ.js +4752 -0
- package/dist/index-DLl3UwO3.d.ts +798 -0
- package/dist/index-Sj2lHLl8.d.cts +798 -0
- package/dist/index.cjs +11 -25
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/primitives/index.cjs +4 -21
- package/dist/primitives/index.d.cts +2 -2
- package/dist/primitives/index.d.ts +2 -2
- package/dist/primitives/index.js +1 -1
- package/dist/src/PaymentForm.d.ts +56 -0
- package/dist/src/PaymentForm.d.ts.map +1 -0
- package/dist/src/PaymentForm.js +212 -0
- package/dist/src/PaymentForm.js.map +1 -0
- package/dist/src/SolvaPayProvider.d.ts +84 -0
- package/dist/src/SolvaPayProvider.d.ts.map +1 -0
- package/dist/src/SolvaPayProvider.js +537 -0
- package/dist/src/SolvaPayProvider.js.map +1 -0
- package/dist/src/adapters/auth.d.ts +43 -0
- package/dist/src/adapters/auth.d.ts.map +1 -0
- package/dist/src/adapters/auth.js +38 -0
- package/dist/src/adapters/auth.js.map +1 -0
- package/dist/src/components/PlanBadge.d.ts +31 -0
- package/dist/src/components/PlanBadge.d.ts.map +1 -0
- package/dist/src/components/PlanBadge.js +119 -0
- package/dist/src/components/PlanBadge.js.map +1 -0
- package/dist/src/components/PlanSelector.d.ts +49 -0
- package/dist/src/components/PlanSelector.d.ts.map +1 -0
- package/dist/src/components/PlanSelector.js +82 -0
- package/dist/src/components/PlanSelector.js.map +1 -0
- package/dist/src/components/Spinner.d.ts +10 -0
- package/dist/src/components/Spinner.d.ts.map +1 -0
- package/dist/src/components/Spinner.js +14 -0
- package/dist/src/components/Spinner.js.map +1 -0
- package/dist/src/components/StripePaymentFormWrapper.d.ts +17 -0
- package/dist/src/components/StripePaymentFormWrapper.d.ts.map +1 -0
- package/dist/src/components/StripePaymentFormWrapper.js +158 -0
- package/dist/src/components/StripePaymentFormWrapper.js.map +1 -0
- package/dist/src/components/SubscriptionGate.d.ts +21 -0
- package/dist/src/components/SubscriptionGate.d.ts.map +1 -0
- package/dist/src/components/SubscriptionGate.js +32 -0
- package/dist/src/components/SubscriptionGate.js.map +1 -0
- package/dist/src/hooks/__tests__/useSubscription.test.d.ts +2 -0
- package/dist/src/hooks/__tests__/useSubscription.test.d.ts.map +1 -0
- package/dist/src/hooks/__tests__/useSubscription.test.js +554 -0
- package/dist/src/hooks/__tests__/useSubscription.test.js.map +1 -0
- package/dist/src/hooks/__tests__/useSubscriptionStatus.test.d.ts +2 -0
- package/dist/src/hooks/__tests__/useSubscriptionStatus.test.d.ts.map +1 -0
- package/dist/src/hooks/__tests__/useSubscriptionStatus.test.js +719 -0
- package/dist/src/hooks/__tests__/useSubscriptionStatus.test.js.map +1 -0
- package/dist/src/hooks/useCheckout.d.ts +59 -0
- package/dist/src/hooks/useCheckout.d.ts.map +1 -0
- package/dist/src/hooks/useCheckout.js +138 -0
- package/dist/src/hooks/useCheckout.js.map +1 -0
- package/dist/src/hooks/useCustomer.d.ts +43 -0
- package/dist/src/hooks/useCustomer.d.ts.map +1 -0
- package/dist/src/hooks/useCustomer.js +31 -0
- package/dist/src/hooks/useCustomer.js.map +1 -0
- package/dist/src/hooks/usePlans.d.ts +28 -0
- package/dist/src/hooks/usePlans.d.ts.map +1 -0
- package/dist/src/hooks/usePlans.js +181 -0
- package/dist/src/hooks/usePlans.js.map +1 -0
- package/dist/src/hooks/useSolvaPay.d.ts +44 -0
- package/dist/src/hooks/useSolvaPay.d.ts.map +1 -0
- package/dist/src/hooks/useSolvaPay.js +52 -0
- package/dist/src/hooks/useSolvaPay.js.map +1 -0
- package/dist/src/hooks/useSubscription.d.ts +46 -0
- package/dist/src/hooks/useSubscription.d.ts.map +1 -0
- package/dist/src/hooks/useSubscription.js +50 -0
- package/dist/src/hooks/useSubscription.js.map +1 -0
- package/dist/src/hooks/useSubscriptionStatus.d.ts +19 -0
- package/dist/src/hooks/useSubscriptionStatus.d.ts.map +1 -0
- package/dist/src/hooks/useSubscriptionStatus.js +68 -0
- package/dist/src/hooks/useSubscriptionStatus.js.map +1 -0
- package/dist/src/index.d.ts +24 -0
- package/dist/src/index.d.ts.map +1 -0
- package/dist/src/index.js +26 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/types/index.d.ts +339 -0
- package/dist/src/types/index.d.ts.map +1 -0
- package/dist/src/types/index.js +5 -0
- package/dist/src/types/index.js.map +1 -0
- package/dist/src/utils/__tests__/subscriptions.test.d.ts +2 -0
- package/dist/src/utils/__tests__/subscriptions.test.d.ts.map +1 -0
- package/dist/src/utils/__tests__/subscriptions.test.js +121 -0
- package/dist/src/utils/__tests__/subscriptions.test.js.map +1 -0
- package/dist/src/utils/subscriptions.d.ts +57 -0
- package/dist/src/utils/subscriptions.d.ts.map +1 -0
- package/dist/src/utils/subscriptions.js +85 -0
- package/dist/src/utils/subscriptions.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/package.json +2 -2
|
@@ -0,0 +1,3126 @@
|
|
|
1
|
+
import {
|
|
2
|
+
defaultAuthAdapter
|
|
3
|
+
} from "./chunk-OUSEQRCT.js";
|
|
4
|
+
|
|
5
|
+
// src/utils/purchases.ts
|
|
6
|
+
function filterPurchases(purchases) {
|
|
7
|
+
return purchases.filter((purchase) => purchase.status === "active");
|
|
8
|
+
}
|
|
9
|
+
function getActivePurchases(purchases) {
|
|
10
|
+
return purchases.filter((purchase) => purchase.status === "active");
|
|
11
|
+
}
|
|
12
|
+
function getCancelledPurchasesWithEndDate(purchases) {
|
|
13
|
+
const now = /* @__PURE__ */ new Date();
|
|
14
|
+
return purchases.filter((purchase) => {
|
|
15
|
+
return purchase.status === "active" && purchase.cancelledAt && purchase.endDate && new Date(purchase.endDate) > now;
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
function getMostRecentPurchase(purchases) {
|
|
19
|
+
if (purchases.length === 0) return null;
|
|
20
|
+
return purchases.reduce((latest, current) => {
|
|
21
|
+
return new Date(current.startDate) > new Date(latest.startDate) ? current : latest;
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
function getPrimaryPurchase(purchases) {
|
|
25
|
+
const filtered = filterPurchases(purchases);
|
|
26
|
+
if (filtered.length > 0) {
|
|
27
|
+
return getMostRecentPurchase(filtered);
|
|
28
|
+
}
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
function isPaidPurchase(purchase) {
|
|
32
|
+
return (purchase.amount ?? 0) > 0;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// src/i18n/en.ts
|
|
36
|
+
function intervalPhrase(ctx) {
|
|
37
|
+
const interval = ctx.plan?.interval;
|
|
38
|
+
const count = ctx.plan?.intervalCount ?? 1;
|
|
39
|
+
if (!interval) return "";
|
|
40
|
+
return count > 1 ? `${count} ${interval}s` : interval;
|
|
41
|
+
}
|
|
42
|
+
function trialPhrase(ctx) {
|
|
43
|
+
const trialDays = ctx.plan?.trialDays ?? ctx.trialDays;
|
|
44
|
+
return trialDays ? ` after your ${trialDays}-day free trial` : "";
|
|
45
|
+
}
|
|
46
|
+
function termsSentence(ctx) {
|
|
47
|
+
const { termsUrl, privacyUrl } = ctx.merchant;
|
|
48
|
+
if (termsUrl && privacyUrl) {
|
|
49
|
+
return ` See ${termsUrl} and ${privacyUrl}.`;
|
|
50
|
+
}
|
|
51
|
+
if (termsUrl) return ` See ${termsUrl}.`;
|
|
52
|
+
if (privacyUrl) return ` See ${privacyUrl}.`;
|
|
53
|
+
return "";
|
|
54
|
+
}
|
|
55
|
+
var enCopy = {
|
|
56
|
+
mandate: {
|
|
57
|
+
recurring: (ctx) => {
|
|
58
|
+
const period = intervalPhrase(ctx);
|
|
59
|
+
const trial = trialPhrase(ctx);
|
|
60
|
+
const every = period ? ` every ${period}` : "";
|
|
61
|
+
return `By subscribing, you authorize ${ctx.merchant.legalName} to charge ${ctx.amountFormatted}${every}${trial} until you cancel. You can cancel any time. Payments are processed by SolvaPay.${termsSentence(ctx)}`;
|
|
62
|
+
},
|
|
63
|
+
oneTime: (ctx) => {
|
|
64
|
+
const product = ctx.product?.name ? ` for ${ctx.product.name}` : "";
|
|
65
|
+
return `By confirming, you authorize ${ctx.merchant.legalName} to charge ${ctx.amountFormatted}${product}. Payments are processed by SolvaPay.${termsSentence(ctx)}`;
|
|
66
|
+
},
|
|
67
|
+
topup: (ctx) => {
|
|
68
|
+
const product = ctx.product?.name ? ` to add credits to your ${ctx.product.name} balance` : " to add credits to your balance";
|
|
69
|
+
return `By confirming, you authorize ${ctx.merchant.legalName} to charge ${ctx.amountFormatted}${product}. Credits are non-refundable once used. Payments are processed by SolvaPay.${termsSentence(ctx)}`;
|
|
70
|
+
},
|
|
71
|
+
usageMetered: (ctx) => {
|
|
72
|
+
const measures = ctx.plan?.measures ?? "unit";
|
|
73
|
+
const cycle = ctx.plan?.billingCycle ?? "monthly";
|
|
74
|
+
const product = ctx.product?.name ?? "the service";
|
|
75
|
+
return `By confirming, you authorize ${ctx.merchant.legalName} to charge your payment method for metered usage of ${product} at ${ctx.amountFormatted} per ${measures}, billed ${cycle}. You can cancel any time. Payments are processed by SolvaPay.${termsSentence(ctx)}`;
|
|
76
|
+
},
|
|
77
|
+
freeTier: (ctx) => {
|
|
78
|
+
const product = ctx.product?.name ?? "this plan";
|
|
79
|
+
const planPhrase = ctx.plan?.name ? ` on ${ctx.plan.name}` : "";
|
|
80
|
+
return `By confirming, you activate ${product}${planPhrase}. Payments are processed by SolvaPay.${termsSentence(ctx)}`;
|
|
81
|
+
}
|
|
82
|
+
},
|
|
83
|
+
cta: {
|
|
84
|
+
payNow: "Pay Now",
|
|
85
|
+
topUp: "Top Up",
|
|
86
|
+
subscribe: "Subscribe",
|
|
87
|
+
trialStart: "Start {trialDays}-day free trial",
|
|
88
|
+
payAmount: "Pay {amount}",
|
|
89
|
+
addAmount: "Add {amount}",
|
|
90
|
+
startUsing: "Start using {product}",
|
|
91
|
+
processing: "Processing..."
|
|
92
|
+
},
|
|
93
|
+
interval: {
|
|
94
|
+
day: "day",
|
|
95
|
+
week: "week",
|
|
96
|
+
month: "month",
|
|
97
|
+
year: "year",
|
|
98
|
+
every: "every {n} {unit}",
|
|
99
|
+
free: "Free",
|
|
100
|
+
trial: "{trialDays}-day free trial"
|
|
101
|
+
},
|
|
102
|
+
terms: {
|
|
103
|
+
checkboxLabel: "I agree to the terms and privacy policy"
|
|
104
|
+
},
|
|
105
|
+
customer: {
|
|
106
|
+
chargingTo: "Charging to {email}",
|
|
107
|
+
emailLabel: "Email",
|
|
108
|
+
nameLabel: "Name"
|
|
109
|
+
},
|
|
110
|
+
balance: {
|
|
111
|
+
credits: " credits",
|
|
112
|
+
currencyEquivalent: " (~{amount})"
|
|
113
|
+
},
|
|
114
|
+
product: {
|
|
115
|
+
currentProductLabel: "Current product: {name}"
|
|
116
|
+
},
|
|
117
|
+
topup: {
|
|
118
|
+
selectOrEnterAmount: "Please select or enter an amount",
|
|
119
|
+
minAmount: "Minimum amount is {amount}",
|
|
120
|
+
maxAmount: "Maximum amount is {amount}"
|
|
121
|
+
},
|
|
122
|
+
activation: {
|
|
123
|
+
paymentRequired: "This plan requires payment. Please select a different plan.",
|
|
124
|
+
invalidConfiguration: "Invalid plan configuration.",
|
|
125
|
+
unexpectedResponse: "Unexpected response from server.",
|
|
126
|
+
failed: "Activation failed"
|
|
127
|
+
},
|
|
128
|
+
planSelector: {
|
|
129
|
+
heading: "Choose your pricing",
|
|
130
|
+
currentBadge: "Current",
|
|
131
|
+
popularBadge: "Popular",
|
|
132
|
+
freeBadge: "Free",
|
|
133
|
+
perIntervalShort: "/{interval}",
|
|
134
|
+
continueButton: "Continue",
|
|
135
|
+
backButton: "\u2190 Back to plans",
|
|
136
|
+
trialBadge: "{trialDays}-day free trial"
|
|
137
|
+
},
|
|
138
|
+
amountPicker: {
|
|
139
|
+
selectAmountLabel: "Select an amount",
|
|
140
|
+
customAmountLabel: "Or enter a custom amount",
|
|
141
|
+
creditEstimateExact: "= {credits} credits",
|
|
142
|
+
creditEstimateApprox: "~ {credits} credits"
|
|
143
|
+
},
|
|
144
|
+
activationFlow: {
|
|
145
|
+
heading: "Confirm your plan",
|
|
146
|
+
activateButton: "Activate",
|
|
147
|
+
activatingLabel: "Activating...",
|
|
148
|
+
topupHeading: "Add credits",
|
|
149
|
+
topupSubheading: "Top up your credits to activate this plan.",
|
|
150
|
+
continueToPayment: "Continue to payment",
|
|
151
|
+
changeAmountButton: "Change amount",
|
|
152
|
+
retryingHeading: "Activating your plan...",
|
|
153
|
+
retryingSubheading: "Payment received. Setting up your plan.",
|
|
154
|
+
activatedHeading: "Plan selected",
|
|
155
|
+
activatedSubheading: "Your plan is now active.",
|
|
156
|
+
tryAgainButton: "Try Again",
|
|
157
|
+
backButton: "\u2190 Back to plan selection"
|
|
158
|
+
},
|
|
159
|
+
cancelPlan: {
|
|
160
|
+
button: "Cancel plan",
|
|
161
|
+
buttonLoading: "Cancelling...",
|
|
162
|
+
confirmRecurring: "Are you sure you want to cancel your subscription?",
|
|
163
|
+
confirmUsageBased: "Are you sure you want to deactivate your plan? This will take effect immediately."
|
|
164
|
+
},
|
|
165
|
+
cancelledNotice: {
|
|
166
|
+
heading: "Your purchase has been cancelled",
|
|
167
|
+
expiresLabel: "Purchase Expires: {date}",
|
|
168
|
+
daysRemaining: "{days} days remaining",
|
|
169
|
+
dayRemaining: "1 day remaining",
|
|
170
|
+
accessUntil: "You'll continue to have access to {product} features until this date",
|
|
171
|
+
accessEnded: "Your purchase access has ended",
|
|
172
|
+
cancelledOn: "Cancelled on {date}",
|
|
173
|
+
reactivateButton: "Undo Cancellation",
|
|
174
|
+
reactivateButtonLoading: "Reactivating..."
|
|
175
|
+
},
|
|
176
|
+
creditGate: {
|
|
177
|
+
lowBalanceHeading: "You're out of credits",
|
|
178
|
+
lowBalanceSubheading: "Top up to continue using {product}",
|
|
179
|
+
topUpCta: "Top up now"
|
|
180
|
+
},
|
|
181
|
+
errors: {
|
|
182
|
+
paymentInitFailed: "Payment initialization failed",
|
|
183
|
+
topupInitFailed: "Top-up initialization failed",
|
|
184
|
+
configMissingPlanOrProduct: "PaymentForm: either planRef or productRef is required",
|
|
185
|
+
configMissingAmount: "TopupForm: amount must be a positive number",
|
|
186
|
+
unknownError: "Unknown error",
|
|
187
|
+
stripeUnavailable: "Stripe is not available. Please refresh the page.",
|
|
188
|
+
paymentIntentUnavailable: "Payment intent not available. Please refresh the page.",
|
|
189
|
+
cardElementMissing: "Card element not found",
|
|
190
|
+
paymentUnexpected: "An unexpected error occurred.",
|
|
191
|
+
paymentProcessingFailed: "Payment processing failed. Please try again or contact support.",
|
|
192
|
+
paymentRequires3ds: "Payment requires additional authentication. Please complete the verification.",
|
|
193
|
+
paymentProcessingTimeout: "Payment processing timed out \u2014 webhooks may not be configured",
|
|
194
|
+
paymentStatusPrefix: "Payment status: {status}"
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
// src/i18n/merge.ts
|
|
199
|
+
function mergeCopy(defaults, overrides) {
|
|
200
|
+
if (!overrides) return defaults;
|
|
201
|
+
const merged = { ...defaults };
|
|
202
|
+
for (const sectionKey of Object.keys(overrides)) {
|
|
203
|
+
const defaultSection = defaults[sectionKey];
|
|
204
|
+
const overrideSection = overrides[sectionKey];
|
|
205
|
+
if (!overrideSection) continue;
|
|
206
|
+
const combined = { ...defaultSection, ...overrideSection };
|
|
207
|
+
merged[sectionKey] = combined;
|
|
208
|
+
}
|
|
209
|
+
return merged;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// src/i18n/context.tsx
|
|
213
|
+
import { createContext, useContext, useMemo } from "react";
|
|
214
|
+
import { jsx } from "react/jsx-runtime";
|
|
215
|
+
var CopyContext = createContext({
|
|
216
|
+
locale: void 0,
|
|
217
|
+
copy: enCopy
|
|
218
|
+
});
|
|
219
|
+
var CopyProvider = ({
|
|
220
|
+
locale,
|
|
221
|
+
copy: overrides,
|
|
222
|
+
children
|
|
223
|
+
}) => {
|
|
224
|
+
const value = useMemo(
|
|
225
|
+
() => ({
|
|
226
|
+
locale,
|
|
227
|
+
copy: mergeCopy(enCopy, overrides)
|
|
228
|
+
}),
|
|
229
|
+
[locale, overrides]
|
|
230
|
+
);
|
|
231
|
+
return /* @__PURE__ */ jsx(CopyContext.Provider, { value, children });
|
|
232
|
+
};
|
|
233
|
+
function useCopyContext() {
|
|
234
|
+
return useContext(CopyContext);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// src/SolvaPayProvider.tsx
|
|
238
|
+
import { createContext as createContext2, useState, useEffect, useCallback, useMemo as useMemo2, useRef } from "react";
|
|
239
|
+
|
|
240
|
+
// src/utils/headers.ts
|
|
241
|
+
var CUSTOMER_REF_KEY = "solvapay_customerRef";
|
|
242
|
+
var CUSTOMER_REF_EXPIRY = "solvapay_customerRef_expiry";
|
|
243
|
+
var CUSTOMER_REF_USER_ID_KEY = "solvapay_customerRef_userId";
|
|
244
|
+
function getAuthAdapter(config) {
|
|
245
|
+
if (config?.auth?.adapter) {
|
|
246
|
+
return config.auth.adapter;
|
|
247
|
+
}
|
|
248
|
+
if (config?.auth?.getToken || config?.auth?.getUserId) {
|
|
249
|
+
return {
|
|
250
|
+
async getToken() {
|
|
251
|
+
return config?.auth?.getToken?.() || null;
|
|
252
|
+
},
|
|
253
|
+
async getUserId() {
|
|
254
|
+
return config?.auth?.getUserId?.() || null;
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
return defaultAuthAdapter;
|
|
259
|
+
}
|
|
260
|
+
function getCachedCustomerRef(userId) {
|
|
261
|
+
if (typeof window === "undefined") return null;
|
|
262
|
+
const cached = localStorage.getItem(CUSTOMER_REF_KEY);
|
|
263
|
+
const expiry = localStorage.getItem(CUSTOMER_REF_EXPIRY);
|
|
264
|
+
const cachedUserId = localStorage.getItem(CUSTOMER_REF_USER_ID_KEY);
|
|
265
|
+
if (!cached || !expiry) return null;
|
|
266
|
+
if (Date.now() > parseInt(expiry)) {
|
|
267
|
+
localStorage.removeItem(CUSTOMER_REF_KEY);
|
|
268
|
+
localStorage.removeItem(CUSTOMER_REF_EXPIRY);
|
|
269
|
+
localStorage.removeItem(CUSTOMER_REF_USER_ID_KEY);
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
if (userId !== void 0 && userId !== null) {
|
|
273
|
+
if (cachedUserId !== userId) {
|
|
274
|
+
clearCachedCustomerRef();
|
|
275
|
+
return null;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
return cached;
|
|
279
|
+
}
|
|
280
|
+
var CACHE_DURATION = 24 * 60 * 60 * 1e3;
|
|
281
|
+
function setCachedCustomerRef(customerRef, userId) {
|
|
282
|
+
if (typeof window === "undefined") return;
|
|
283
|
+
if (userId === void 0 || userId === null) {
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
localStorage.setItem(CUSTOMER_REF_KEY, customerRef);
|
|
287
|
+
localStorage.setItem(CUSTOMER_REF_EXPIRY, String(Date.now() + CACHE_DURATION));
|
|
288
|
+
localStorage.setItem(CUSTOMER_REF_USER_ID_KEY, userId);
|
|
289
|
+
}
|
|
290
|
+
function clearCachedCustomerRef() {
|
|
291
|
+
if (typeof window === "undefined") return;
|
|
292
|
+
localStorage.removeItem(CUSTOMER_REF_KEY);
|
|
293
|
+
localStorage.removeItem(CUSTOMER_REF_EXPIRY);
|
|
294
|
+
localStorage.removeItem(CUSTOMER_REF_USER_ID_KEY);
|
|
295
|
+
}
|
|
296
|
+
async function buildRequestHeaders(config) {
|
|
297
|
+
const adapter = getAuthAdapter(config);
|
|
298
|
+
const token = await adapter.getToken();
|
|
299
|
+
const userId = await adapter.getUserId();
|
|
300
|
+
const cachedRef = getCachedCustomerRef(userId);
|
|
301
|
+
const headers = {
|
|
302
|
+
"Content-Type": "application/json"
|
|
303
|
+
};
|
|
304
|
+
if (token) {
|
|
305
|
+
headers["Authorization"] = `Bearer ${token}`;
|
|
306
|
+
}
|
|
307
|
+
if (cachedRef) {
|
|
308
|
+
headers["x-solvapay-customer-ref"] = cachedRef;
|
|
309
|
+
}
|
|
310
|
+
if (config?.headers) {
|
|
311
|
+
const custom = typeof config.headers === "function" ? await config.headers() : config.headers;
|
|
312
|
+
Object.assign(headers, custom);
|
|
313
|
+
}
|
|
314
|
+
return { headers, userId };
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// src/SolvaPayProvider.tsx
|
|
318
|
+
import { jsx as jsx2 } from "react/jsx-runtime";
|
|
319
|
+
var SolvaPayContext = createContext2(null);
|
|
320
|
+
var SolvaPayProvider = ({
|
|
321
|
+
config,
|
|
322
|
+
createPayment: customCreatePayment,
|
|
323
|
+
checkPurchase: customCheckPurchase,
|
|
324
|
+
processPayment: customProcessPayment,
|
|
325
|
+
createTopupPayment: customCreateTopupPayment,
|
|
326
|
+
children
|
|
327
|
+
}) => {
|
|
328
|
+
const [purchaseData, setPurchaseData] = useState({
|
|
329
|
+
purchases: []
|
|
330
|
+
});
|
|
331
|
+
const [loading, setLoading] = useState(false);
|
|
332
|
+
const [isRefetching, setIsRefetching] = useState(false);
|
|
333
|
+
const [purchaseError, setPurchaseError] = useState(null);
|
|
334
|
+
const [internalCustomerRef, setInternalCustomerRef] = useState(void 0);
|
|
335
|
+
const [userId, setUserId] = useState(null);
|
|
336
|
+
const [isAuthenticated, setIsAuthenticated] = useState(false);
|
|
337
|
+
const [creditsValue, setCreditsValue] = useState(null);
|
|
338
|
+
const [displayCurrencyValue, setDisplayCurrencyValue] = useState(null);
|
|
339
|
+
const [creditsPerMinorUnitValue, setCreditsPerMinorUnitValue] = useState(null);
|
|
340
|
+
const [displayExchangeRateValue, setDisplayExchangeRateValue] = useState(null);
|
|
341
|
+
const [balanceLoading, setBalanceLoading] = useState(false);
|
|
342
|
+
const balanceInFlightRef = useRef(false);
|
|
343
|
+
const balanceLoadedRef = useRef(false);
|
|
344
|
+
const optimisticUntilRef = useRef(0);
|
|
345
|
+
const optimisticTimerRef = useRef(null);
|
|
346
|
+
const fetchBalanceRef = useRef(null);
|
|
347
|
+
const inFlightRef = useRef(null);
|
|
348
|
+
const checkPurchaseRef = useRef(null);
|
|
349
|
+
const createPaymentRef = useRef(null);
|
|
350
|
+
const processPaymentRef = useRef(null);
|
|
351
|
+
const createTopupPaymentRef = useRef(null);
|
|
352
|
+
const configRef = useRef(config);
|
|
353
|
+
const buildDefaultCheckPurchaseRef = useRef(
|
|
354
|
+
null
|
|
355
|
+
);
|
|
356
|
+
useEffect(() => {
|
|
357
|
+
configRef.current = config;
|
|
358
|
+
}, [config]);
|
|
359
|
+
useEffect(() => {
|
|
360
|
+
checkPurchaseRef.current = customCheckPurchase || null;
|
|
361
|
+
}, [customCheckPurchase]);
|
|
362
|
+
useEffect(() => {
|
|
363
|
+
createPaymentRef.current = customCreatePayment || null;
|
|
364
|
+
}, [customCreatePayment]);
|
|
365
|
+
useEffect(() => {
|
|
366
|
+
processPaymentRef.current = customProcessPayment || null;
|
|
367
|
+
}, [customProcessPayment]);
|
|
368
|
+
useEffect(() => {
|
|
369
|
+
createTopupPaymentRef.current = customCreateTopupPayment || null;
|
|
370
|
+
}, [customCreateTopupPayment]);
|
|
371
|
+
const buildDefaultCheckPurchase = useCallback(async () => {
|
|
372
|
+
const currentConfig = configRef.current;
|
|
373
|
+
const { headers } = await buildRequestHeaders(currentConfig);
|
|
374
|
+
const route = currentConfig?.api?.checkPurchase || "/api/check-purchase";
|
|
375
|
+
const fetchFn = currentConfig?.fetch || fetch;
|
|
376
|
+
const res = await fetchFn(route, { method: "GET", headers });
|
|
377
|
+
if (!res.ok) {
|
|
378
|
+
const error = new Error(`Failed to check purchase: ${res.statusText}`);
|
|
379
|
+
currentConfig?.onError?.(error, "checkPurchase");
|
|
380
|
+
throw error;
|
|
381
|
+
}
|
|
382
|
+
return res.json();
|
|
383
|
+
}, []);
|
|
384
|
+
useEffect(() => {
|
|
385
|
+
buildDefaultCheckPurchaseRef.current = buildDefaultCheckPurchase;
|
|
386
|
+
}, [buildDefaultCheckPurchase]);
|
|
387
|
+
const buildDefaultCreatePayment = useCallback(
|
|
388
|
+
async (params) => {
|
|
389
|
+
const currentConfig = configRef.current;
|
|
390
|
+
const { headers } = await buildRequestHeaders(currentConfig);
|
|
391
|
+
const route = currentConfig?.api?.createPayment || "/api/create-payment-intent";
|
|
392
|
+
const fetchFn = currentConfig?.fetch || fetch;
|
|
393
|
+
const body = {};
|
|
394
|
+
if (params.planRef) {
|
|
395
|
+
body.planRef = params.planRef;
|
|
396
|
+
}
|
|
397
|
+
if (params.productRef) {
|
|
398
|
+
body.productRef = params.productRef;
|
|
399
|
+
}
|
|
400
|
+
if (params.customer && (params.customer.name || params.customer.email)) {
|
|
401
|
+
body.customer = params.customer;
|
|
402
|
+
}
|
|
403
|
+
const res = await fetchFn(route, {
|
|
404
|
+
method: "POST",
|
|
405
|
+
headers,
|
|
406
|
+
body: JSON.stringify(body)
|
|
407
|
+
});
|
|
408
|
+
if (!res.ok) {
|
|
409
|
+
const error = new Error(`Failed to create payment: ${res.statusText}`);
|
|
410
|
+
currentConfig?.onError?.(error, "createPayment");
|
|
411
|
+
throw error;
|
|
412
|
+
}
|
|
413
|
+
return res.json();
|
|
414
|
+
},
|
|
415
|
+
[]
|
|
416
|
+
);
|
|
417
|
+
const buildDefaultProcessPayment = useCallback(
|
|
418
|
+
async (params) => {
|
|
419
|
+
const currentConfig = configRef.current;
|
|
420
|
+
const { headers } = await buildRequestHeaders(currentConfig);
|
|
421
|
+
const route = currentConfig?.api?.processPayment || "/api/process-payment";
|
|
422
|
+
const fetchFn = currentConfig?.fetch || fetch;
|
|
423
|
+
const res = await fetchFn(route, {
|
|
424
|
+
method: "POST",
|
|
425
|
+
headers,
|
|
426
|
+
body: JSON.stringify(params)
|
|
427
|
+
});
|
|
428
|
+
if (!res.ok) {
|
|
429
|
+
const error = new Error(`Failed to process payment: ${res.statusText}`);
|
|
430
|
+
currentConfig?.onError?.(error, "processPayment");
|
|
431
|
+
throw error;
|
|
432
|
+
}
|
|
433
|
+
return res.json();
|
|
434
|
+
},
|
|
435
|
+
[]
|
|
436
|
+
);
|
|
437
|
+
const buildDefaultCreateTopupPayment = useCallback(
|
|
438
|
+
async (params) => {
|
|
439
|
+
const currentConfig = configRef.current;
|
|
440
|
+
const { headers } = await buildRequestHeaders(currentConfig);
|
|
441
|
+
const route = currentConfig?.api?.createTopupPayment || "/api/create-topup-payment-intent";
|
|
442
|
+
const fetchFn = currentConfig?.fetch || fetch;
|
|
443
|
+
const res = await fetchFn(route, {
|
|
444
|
+
method: "POST",
|
|
445
|
+
headers,
|
|
446
|
+
body: JSON.stringify({
|
|
447
|
+
amount: params.amount,
|
|
448
|
+
currency: params.currency
|
|
449
|
+
})
|
|
450
|
+
});
|
|
451
|
+
if (!res.ok) {
|
|
452
|
+
const error = new Error(`Failed to create topup payment: ${res.statusText}`);
|
|
453
|
+
currentConfig?.onError?.(error, "createTopupPayment");
|
|
454
|
+
throw error;
|
|
455
|
+
}
|
|
456
|
+
return res.json();
|
|
457
|
+
},
|
|
458
|
+
[]
|
|
459
|
+
);
|
|
460
|
+
const fetchBalanceImpl = useCallback(async () => {
|
|
461
|
+
if (optimisticUntilRef.current > Date.now()) return;
|
|
462
|
+
if (!isAuthenticated && !internalCustomerRef) {
|
|
463
|
+
setCreditsValue(null);
|
|
464
|
+
setDisplayCurrencyValue(null);
|
|
465
|
+
setCreditsPerMinorUnitValue(null);
|
|
466
|
+
setDisplayExchangeRateValue(null);
|
|
467
|
+
setBalanceLoading(false);
|
|
468
|
+
balanceLoadedRef.current = false;
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
if (balanceInFlightRef.current) return;
|
|
472
|
+
balanceInFlightRef.current = true;
|
|
473
|
+
if (!balanceLoadedRef.current) {
|
|
474
|
+
setBalanceLoading(true);
|
|
475
|
+
}
|
|
476
|
+
try {
|
|
477
|
+
const currentConfig = configRef.current;
|
|
478
|
+
const { headers } = await buildRequestHeaders(currentConfig);
|
|
479
|
+
const route = currentConfig?.api?.customerBalance || "/api/customer-balance";
|
|
480
|
+
const fetchFn = currentConfig?.fetch || fetch;
|
|
481
|
+
const res = await fetchFn(route, { method: "GET", headers });
|
|
482
|
+
if (!res.ok) {
|
|
483
|
+
console.error("[SolvaPayProvider] Failed to fetch balance:", res.statusText);
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
const data = await res.json();
|
|
487
|
+
setCreditsValue(data.credits ?? null);
|
|
488
|
+
setDisplayCurrencyValue(data.displayCurrency ?? null);
|
|
489
|
+
setCreditsPerMinorUnitValue(data.creditsPerMinorUnit ?? null);
|
|
490
|
+
setDisplayExchangeRateValue(data.displayExchangeRate ?? null);
|
|
491
|
+
balanceLoadedRef.current = true;
|
|
492
|
+
} catch (error) {
|
|
493
|
+
console.error("[SolvaPayProvider] Failed to fetch balance:", error);
|
|
494
|
+
} finally {
|
|
495
|
+
setBalanceLoading(false);
|
|
496
|
+
balanceInFlightRef.current = false;
|
|
497
|
+
}
|
|
498
|
+
}, [isAuthenticated, internalCustomerRef]);
|
|
499
|
+
useEffect(() => {
|
|
500
|
+
fetchBalanceRef.current = fetchBalanceImpl;
|
|
501
|
+
}, [fetchBalanceImpl]);
|
|
502
|
+
useEffect(() => {
|
|
503
|
+
return () => {
|
|
504
|
+
if (optimisticTimerRef.current) clearTimeout(optimisticTimerRef.current);
|
|
505
|
+
};
|
|
506
|
+
}, []);
|
|
507
|
+
const OPTIMISTIC_GRACE_MS = 8e3;
|
|
508
|
+
const adjustBalanceImpl = useCallback((credits) => {
|
|
509
|
+
setCreditsValue((prev) => (prev ?? 0) + credits);
|
|
510
|
+
optimisticUntilRef.current = Date.now() + OPTIMISTIC_GRACE_MS;
|
|
511
|
+
if (optimisticTimerRef.current) clearTimeout(optimisticTimerRef.current);
|
|
512
|
+
optimisticTimerRef.current = setTimeout(() => {
|
|
513
|
+
optimisticUntilRef.current = 0;
|
|
514
|
+
fetchBalanceRef.current?.();
|
|
515
|
+
}, OPTIMISTIC_GRACE_MS);
|
|
516
|
+
}, []);
|
|
517
|
+
const _checkPurchase = useCallback(async () => {
|
|
518
|
+
if (checkPurchaseRef.current) {
|
|
519
|
+
return checkPurchaseRef.current();
|
|
520
|
+
}
|
|
521
|
+
if (buildDefaultCheckPurchaseRef.current) {
|
|
522
|
+
return buildDefaultCheckPurchaseRef.current();
|
|
523
|
+
}
|
|
524
|
+
return buildDefaultCheckPurchase();
|
|
525
|
+
}, [buildDefaultCheckPurchase]);
|
|
526
|
+
const createPayment = useCallback(
|
|
527
|
+
async (params) => {
|
|
528
|
+
if (createPaymentRef.current) {
|
|
529
|
+
return createPaymentRef.current(params);
|
|
530
|
+
}
|
|
531
|
+
return buildDefaultCreatePayment(params);
|
|
532
|
+
},
|
|
533
|
+
[buildDefaultCreatePayment]
|
|
534
|
+
);
|
|
535
|
+
const processPayment = useCallback(
|
|
536
|
+
async (params) => {
|
|
537
|
+
if (processPaymentRef.current) {
|
|
538
|
+
return processPaymentRef.current(params);
|
|
539
|
+
}
|
|
540
|
+
return buildDefaultProcessPayment(params);
|
|
541
|
+
},
|
|
542
|
+
[buildDefaultProcessPayment]
|
|
543
|
+
);
|
|
544
|
+
const createTopupPayment = useCallback(
|
|
545
|
+
async (params) => {
|
|
546
|
+
if (createTopupPaymentRef.current) {
|
|
547
|
+
return createTopupPaymentRef.current(params);
|
|
548
|
+
}
|
|
549
|
+
return buildDefaultCreateTopupPayment(params);
|
|
550
|
+
},
|
|
551
|
+
[buildDefaultCreateTopupPayment]
|
|
552
|
+
);
|
|
553
|
+
useEffect(() => {
|
|
554
|
+
const detectAuth = async () => {
|
|
555
|
+
const currentConfig = configRef.current;
|
|
556
|
+
const adapter = getAuthAdapter(currentConfig);
|
|
557
|
+
const token = await adapter.getToken();
|
|
558
|
+
const detectedUserId = await adapter.getUserId();
|
|
559
|
+
const prevUserId = userId;
|
|
560
|
+
setIsAuthenticated(!!token);
|
|
561
|
+
setUserId(detectedUserId);
|
|
562
|
+
if (prevUserId !== null && detectedUserId !== prevUserId) {
|
|
563
|
+
clearCachedCustomerRef();
|
|
564
|
+
setInternalCustomerRef(void 0);
|
|
565
|
+
return;
|
|
566
|
+
}
|
|
567
|
+
const cachedRef = getCachedCustomerRef(detectedUserId);
|
|
568
|
+
if (cachedRef && token) {
|
|
569
|
+
setInternalCustomerRef(cachedRef);
|
|
570
|
+
} else if (!token) {
|
|
571
|
+
clearCachedCustomerRef();
|
|
572
|
+
setInternalCustomerRef(void 0);
|
|
573
|
+
} else if (token && !cachedRef) {
|
|
574
|
+
setInternalCustomerRef(void 0);
|
|
575
|
+
}
|
|
576
|
+
};
|
|
577
|
+
detectAuth();
|
|
578
|
+
const interval = setInterval(detectAuth, 3e4);
|
|
579
|
+
return () => clearInterval(interval);
|
|
580
|
+
}, [userId]);
|
|
581
|
+
const fetchPurchase = useCallback(
|
|
582
|
+
async (force = false) => {
|
|
583
|
+
if (!isAuthenticated && !internalCustomerRef) {
|
|
584
|
+
setPurchaseData({ purchases: [] });
|
|
585
|
+
setPurchaseError(null);
|
|
586
|
+
setLoading(false);
|
|
587
|
+
setIsRefetching(false);
|
|
588
|
+
inFlightRef.current = null;
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
const cacheKey = internalCustomerRef || userId || "anonymous";
|
|
592
|
+
if (inFlightRef.current === cacheKey && !force) {
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
inFlightRef.current = cacheKey;
|
|
596
|
+
const hasExistingData = purchaseData.purchases.length > 0;
|
|
597
|
+
if (hasExistingData) {
|
|
598
|
+
setIsRefetching(true);
|
|
599
|
+
} else {
|
|
600
|
+
setLoading(true);
|
|
601
|
+
}
|
|
602
|
+
try {
|
|
603
|
+
const checkFn = checkPurchaseRef.current || buildDefaultCheckPurchaseRef.current;
|
|
604
|
+
if (!checkFn) {
|
|
605
|
+
throw new Error("checkPurchase function not available");
|
|
606
|
+
}
|
|
607
|
+
const data = await checkFn();
|
|
608
|
+
if (data.customerRef) {
|
|
609
|
+
setInternalCustomerRef(data.customerRef);
|
|
610
|
+
const currentAdapter = getAuthAdapter(configRef.current);
|
|
611
|
+
const currentUserId = await currentAdapter.getUserId();
|
|
612
|
+
setCachedCustomerRef(data.customerRef, currentUserId);
|
|
613
|
+
}
|
|
614
|
+
if (inFlightRef.current === cacheKey) {
|
|
615
|
+
const filteredData = {
|
|
616
|
+
...data,
|
|
617
|
+
purchases: filterPurchases(data.purchases || [])
|
|
618
|
+
};
|
|
619
|
+
setPurchaseData(filteredData);
|
|
620
|
+
setPurchaseError(null);
|
|
621
|
+
}
|
|
622
|
+
} catch (err) {
|
|
623
|
+
console.error("[SolvaPayProvider] Failed to fetch purchase:", err);
|
|
624
|
+
if (inFlightRef.current === cacheKey) {
|
|
625
|
+
setPurchaseError(err instanceof Error ? err : new Error(String(err)));
|
|
626
|
+
}
|
|
627
|
+
} finally {
|
|
628
|
+
if (inFlightRef.current === cacheKey) {
|
|
629
|
+
setLoading(false);
|
|
630
|
+
setIsRefetching(false);
|
|
631
|
+
inFlightRef.current = null;
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
},
|
|
635
|
+
[isAuthenticated, internalCustomerRef, userId, purchaseData.purchases.length]
|
|
636
|
+
);
|
|
637
|
+
const fetchPurchaseRef = useRef(fetchPurchase);
|
|
638
|
+
useEffect(() => {
|
|
639
|
+
fetchPurchaseRef.current = fetchPurchase;
|
|
640
|
+
}, [fetchPurchase]);
|
|
641
|
+
const refetchPurchase = useCallback(async () => {
|
|
642
|
+
inFlightRef.current = null;
|
|
643
|
+
await fetchPurchaseRef.current(true);
|
|
644
|
+
}, []);
|
|
645
|
+
const cancelRenewal = useCallback(
|
|
646
|
+
async (params) => {
|
|
647
|
+
const currentConfig = configRef.current;
|
|
648
|
+
const { headers } = await buildRequestHeaders(currentConfig);
|
|
649
|
+
const route = currentConfig?.api?.cancelRenewal || "/api/cancel-renewal";
|
|
650
|
+
const fetchFn = currentConfig?.fetch || fetch;
|
|
651
|
+
const res = await fetchFn(route, {
|
|
652
|
+
method: "POST",
|
|
653
|
+
headers,
|
|
654
|
+
body: JSON.stringify(params)
|
|
655
|
+
});
|
|
656
|
+
if (!res.ok) {
|
|
657
|
+
const data = await res.json().catch(() => ({}));
|
|
658
|
+
const error = new Error(data.error || `Failed to cancel renewal: ${res.statusText}`);
|
|
659
|
+
currentConfig?.onError?.(error, "cancelRenewal");
|
|
660
|
+
throw error;
|
|
661
|
+
}
|
|
662
|
+
const result = await res.json();
|
|
663
|
+
await refetchPurchase();
|
|
664
|
+
return result;
|
|
665
|
+
},
|
|
666
|
+
[refetchPurchase]
|
|
667
|
+
);
|
|
668
|
+
const reactivateRenewal = useCallback(
|
|
669
|
+
async (params) => {
|
|
670
|
+
const currentConfig = configRef.current;
|
|
671
|
+
const { headers } = await buildRequestHeaders(currentConfig);
|
|
672
|
+
const route = currentConfig?.api?.reactivateRenewal || "/api/reactivate-renewal";
|
|
673
|
+
const fetchFn = currentConfig?.fetch || fetch;
|
|
674
|
+
const res = await fetchFn(route, {
|
|
675
|
+
method: "POST",
|
|
676
|
+
headers,
|
|
677
|
+
body: JSON.stringify(params)
|
|
678
|
+
});
|
|
679
|
+
if (!res.ok) {
|
|
680
|
+
const data = await res.json().catch(() => ({}));
|
|
681
|
+
const error = new Error(data.error || `Failed to reactivate renewal: ${res.statusText}`);
|
|
682
|
+
currentConfig?.onError?.(error, "reactivateRenewal");
|
|
683
|
+
throw error;
|
|
684
|
+
}
|
|
685
|
+
const result = await res.json();
|
|
686
|
+
await refetchPurchase();
|
|
687
|
+
return result;
|
|
688
|
+
},
|
|
689
|
+
[refetchPurchase]
|
|
690
|
+
);
|
|
691
|
+
const activatePlan = useCallback(
|
|
692
|
+
async (params) => {
|
|
693
|
+
const currentConfig = configRef.current;
|
|
694
|
+
const { headers } = await buildRequestHeaders(currentConfig);
|
|
695
|
+
const route = currentConfig?.api?.activatePlan || "/api/activate-plan";
|
|
696
|
+
const fetchFn = currentConfig?.fetch || fetch;
|
|
697
|
+
const res = await fetchFn(route, {
|
|
698
|
+
method: "POST",
|
|
699
|
+
headers,
|
|
700
|
+
body: JSON.stringify(params)
|
|
701
|
+
});
|
|
702
|
+
if (!res.ok) {
|
|
703
|
+
const data = await res.json().catch(() => ({}));
|
|
704
|
+
const error = new Error(data.error || `Failed to activate plan: ${res.statusText}`);
|
|
705
|
+
currentConfig?.onError?.(error, "activatePlan");
|
|
706
|
+
throw error;
|
|
707
|
+
}
|
|
708
|
+
const result = await res.json();
|
|
709
|
+
if (result.status === "activated" || result.status === "already_active") {
|
|
710
|
+
await refetchPurchase();
|
|
711
|
+
}
|
|
712
|
+
return result;
|
|
713
|
+
},
|
|
714
|
+
[refetchPurchase]
|
|
715
|
+
);
|
|
716
|
+
useEffect(() => {
|
|
717
|
+
inFlightRef.current = null;
|
|
718
|
+
if (isAuthenticated || internalCustomerRef) {
|
|
719
|
+
fetchPurchase();
|
|
720
|
+
} else {
|
|
721
|
+
setPurchaseData({ purchases: [] });
|
|
722
|
+
setPurchaseError(null);
|
|
723
|
+
setLoading(false);
|
|
724
|
+
setIsRefetching(false);
|
|
725
|
+
}
|
|
726
|
+
}, [isAuthenticated, internalCustomerRef, userId]);
|
|
727
|
+
const updateCustomerRef = useCallback(
|
|
728
|
+
(newCustomerRef) => {
|
|
729
|
+
setInternalCustomerRef(newCustomerRef);
|
|
730
|
+
setCachedCustomerRef(newCustomerRef, userId);
|
|
731
|
+
fetchPurchase(true);
|
|
732
|
+
},
|
|
733
|
+
[fetchPurchase, userId]
|
|
734
|
+
);
|
|
735
|
+
const purchase = useMemo2(() => {
|
|
736
|
+
const activePurchase = getPrimaryPurchase(purchaseData.purchases);
|
|
737
|
+
const activePaidPurchases = purchaseData.purchases.filter(
|
|
738
|
+
(p) => p.status === "active" && isPaidPurchase(p)
|
|
739
|
+
);
|
|
740
|
+
const activePaidPurchase = activePaidPurchases.sort(
|
|
741
|
+
(a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime()
|
|
742
|
+
)[0] || null;
|
|
743
|
+
return {
|
|
744
|
+
loading,
|
|
745
|
+
isRefetching,
|
|
746
|
+
error: purchaseError,
|
|
747
|
+
customerRef: purchaseData.customerRef || internalCustomerRef,
|
|
748
|
+
email: purchaseData.email,
|
|
749
|
+
name: purchaseData.name,
|
|
750
|
+
purchases: purchaseData.purchases,
|
|
751
|
+
hasProduct: (productName) => {
|
|
752
|
+
return purchaseData.purchases.some(
|
|
753
|
+
(p) => p.productName.toLowerCase() === productName.toLowerCase() && p.status === "active"
|
|
754
|
+
);
|
|
755
|
+
},
|
|
756
|
+
hasPlan: (productName) => {
|
|
757
|
+
return purchaseData.purchases.some(
|
|
758
|
+
(p) => p.productName.toLowerCase() === productName.toLowerCase() && p.status === "active"
|
|
759
|
+
);
|
|
760
|
+
},
|
|
761
|
+
activePurchase,
|
|
762
|
+
hasPaidPurchase: activePaidPurchases.length > 0,
|
|
763
|
+
activePaidPurchase
|
|
764
|
+
};
|
|
765
|
+
}, [loading, isRefetching, purchaseError, purchaseData, internalCustomerRef]);
|
|
766
|
+
const balance = useMemo2(
|
|
767
|
+
() => ({
|
|
768
|
+
loading: balanceLoading,
|
|
769
|
+
credits: creditsValue,
|
|
770
|
+
displayCurrency: displayCurrencyValue,
|
|
771
|
+
creditsPerMinorUnit: creditsPerMinorUnitValue,
|
|
772
|
+
displayExchangeRate: displayExchangeRateValue,
|
|
773
|
+
refetch: fetchBalanceImpl,
|
|
774
|
+
adjustBalance: adjustBalanceImpl
|
|
775
|
+
}),
|
|
776
|
+
[balanceLoading, creditsValue, displayCurrencyValue, creditsPerMinorUnitValue, displayExchangeRateValue, fetchBalanceImpl, adjustBalanceImpl]
|
|
777
|
+
);
|
|
778
|
+
const contextValue = useMemo2(
|
|
779
|
+
() => ({
|
|
780
|
+
purchase,
|
|
781
|
+
refetchPurchase,
|
|
782
|
+
createPayment,
|
|
783
|
+
processPayment,
|
|
784
|
+
createTopupPayment,
|
|
785
|
+
cancelRenewal,
|
|
786
|
+
reactivateRenewal,
|
|
787
|
+
activatePlan,
|
|
788
|
+
customerRef: purchaseData.customerRef || internalCustomerRef,
|
|
789
|
+
updateCustomerRef,
|
|
790
|
+
balance,
|
|
791
|
+
_config: configRef.current
|
|
792
|
+
}),
|
|
793
|
+
[
|
|
794
|
+
purchase,
|
|
795
|
+
refetchPurchase,
|
|
796
|
+
createPayment,
|
|
797
|
+
processPayment,
|
|
798
|
+
createTopupPayment,
|
|
799
|
+
cancelRenewal,
|
|
800
|
+
reactivateRenewal,
|
|
801
|
+
activatePlan,
|
|
802
|
+
purchaseData.customerRef,
|
|
803
|
+
internalCustomerRef,
|
|
804
|
+
updateCustomerRef,
|
|
805
|
+
balance
|
|
806
|
+
]
|
|
807
|
+
);
|
|
808
|
+
return /* @__PURE__ */ jsx2(SolvaPayContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsx2(CopyProvider, { locale: config?.locale, copy: config?.copy, children }) });
|
|
809
|
+
};
|
|
810
|
+
|
|
811
|
+
// src/primitives/composeRefs.ts
|
|
812
|
+
function setRef(ref, value) {
|
|
813
|
+
if (typeof ref === "function") {
|
|
814
|
+
ref(value);
|
|
815
|
+
} else if (ref !== null && ref !== void 0) {
|
|
816
|
+
;
|
|
817
|
+
ref.current = value;
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
function composeRefs(...refs) {
|
|
821
|
+
return (node) => {
|
|
822
|
+
for (const ref of refs) {
|
|
823
|
+
setRef(ref, node);
|
|
824
|
+
}
|
|
825
|
+
};
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
// src/primitives/slot.tsx
|
|
829
|
+
import React3 from "react";
|
|
830
|
+
import { Fragment, jsx as jsx3 } from "react/jsx-runtime";
|
|
831
|
+
var Slot = React3.forwardRef((props, forwardedRef) => {
|
|
832
|
+
const { children, ...slotProps } = props;
|
|
833
|
+
const childrenArray = React3.Children.toArray(children);
|
|
834
|
+
const slottable = childrenArray.find(isSlottable);
|
|
835
|
+
if (slottable) {
|
|
836
|
+
const newElement = slottable.props.children;
|
|
837
|
+
const newChildren = childrenArray.map((child) => {
|
|
838
|
+
if (child === slottable) {
|
|
839
|
+
if (React3.Children.count(newElement) > 1) return React3.Children.only(null);
|
|
840
|
+
return React3.isValidElement(newElement) ? newElement.props.children : null;
|
|
841
|
+
}
|
|
842
|
+
return child;
|
|
843
|
+
});
|
|
844
|
+
return /* @__PURE__ */ jsx3(SlotClone, { ...slotProps, ref: forwardedRef, children: React3.isValidElement(newElement) ? React3.cloneElement(newElement, void 0, newChildren) : null });
|
|
845
|
+
}
|
|
846
|
+
return /* @__PURE__ */ jsx3(SlotClone, { ...slotProps, ref: forwardedRef, children });
|
|
847
|
+
});
|
|
848
|
+
Slot.displayName = "Slot";
|
|
849
|
+
var SlotClone = React3.forwardRef(
|
|
850
|
+
(props, forwardedRef) => {
|
|
851
|
+
const { children, ...slotProps } = props;
|
|
852
|
+
if (React3.isValidElement(children)) {
|
|
853
|
+
const childProps = children.props ?? {};
|
|
854
|
+
const childRef = getElementRef(children);
|
|
855
|
+
const props2 = mergeProps(slotProps, childProps);
|
|
856
|
+
const cloneProps = { ...props2 };
|
|
857
|
+
if (forwardedRef) {
|
|
858
|
+
cloneProps.ref = childRef ? composeRefs(forwardedRef, childRef) : forwardedRef;
|
|
859
|
+
} else {
|
|
860
|
+
cloneProps.ref = childRef;
|
|
861
|
+
}
|
|
862
|
+
return React3.cloneElement(children, cloneProps);
|
|
863
|
+
}
|
|
864
|
+
return React3.Children.count(children) > 1 ? React3.Children.only(null) : null;
|
|
865
|
+
}
|
|
866
|
+
);
|
|
867
|
+
SlotClone.displayName = "SlotClone";
|
|
868
|
+
var Slottable = ({ children }) => {
|
|
869
|
+
return /* @__PURE__ */ jsx3(Fragment, { children });
|
|
870
|
+
};
|
|
871
|
+
function isSlottable(child) {
|
|
872
|
+
return React3.isValidElement(child) && child.type === Slottable;
|
|
873
|
+
}
|
|
874
|
+
function mergeProps(slotProps, childProps) {
|
|
875
|
+
const overrideProps = { ...childProps };
|
|
876
|
+
for (const propName in slotProps) {
|
|
877
|
+
const slotPropValue = slotProps[propName];
|
|
878
|
+
const childPropValue = childProps[propName];
|
|
879
|
+
const isHandler = /^on[A-Z]/.test(propName);
|
|
880
|
+
if (isHandler) {
|
|
881
|
+
if (slotPropValue && childPropValue) {
|
|
882
|
+
overrideProps[propName] = (...args) => {
|
|
883
|
+
;
|
|
884
|
+
childPropValue(...args);
|
|
885
|
+
const first = args[0];
|
|
886
|
+
if (!first?.defaultPrevented) {
|
|
887
|
+
;
|
|
888
|
+
slotPropValue(...args);
|
|
889
|
+
}
|
|
890
|
+
};
|
|
891
|
+
} else if (slotPropValue) {
|
|
892
|
+
overrideProps[propName] = slotPropValue;
|
|
893
|
+
}
|
|
894
|
+
} else if (propName === "style") {
|
|
895
|
+
overrideProps[propName] = {
|
|
896
|
+
...slotPropValue,
|
|
897
|
+
...childPropValue
|
|
898
|
+
};
|
|
899
|
+
} else if (propName === "className") {
|
|
900
|
+
overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
|
|
901
|
+
} else if (propName === "ref") {
|
|
902
|
+
} else if (childPropValue === void 0) {
|
|
903
|
+
overrideProps[propName] = slotPropValue;
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
return overrideProps;
|
|
907
|
+
}
|
|
908
|
+
function getElementRef(element) {
|
|
909
|
+
const el = element;
|
|
910
|
+
return el.props?.ref ?? el.ref ?? null;
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
// src/primitives/composeEventHandlers.ts
|
|
914
|
+
function composeEventHandlers(originalEventHandler, ourEventHandler, { checkForDefaultPrevented = true } = {}) {
|
|
915
|
+
return function handleEvent(event) {
|
|
916
|
+
originalEventHandler?.(event);
|
|
917
|
+
if (checkForDefaultPrevented === false || !event.defaultPrevented) {
|
|
918
|
+
ourEventHandler?.(event);
|
|
919
|
+
}
|
|
920
|
+
};
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
// src/hooks/useSolvaPay.ts
|
|
924
|
+
import { useContext as useContext2 } from "react";
|
|
925
|
+
function useSolvaPay() {
|
|
926
|
+
const context = useContext2(SolvaPayContext);
|
|
927
|
+
if (!context) {
|
|
928
|
+
throw new Error(
|
|
929
|
+
"useSolvaPay must be used within a SolvaPayProvider. Wrap your component tree with <SolvaPayProvider> to use this hook."
|
|
930
|
+
);
|
|
931
|
+
}
|
|
932
|
+
return context;
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
// src/hooks/useCheckout.ts
|
|
936
|
+
import { useState as useState2, useCallback as useCallback2, useRef as useRef2 } from "react";
|
|
937
|
+
import { loadStripe } from "@stripe/stripe-js";
|
|
938
|
+
var stripePromiseCache = /* @__PURE__ */ new Map();
|
|
939
|
+
function getStripeCacheKey(publishableKey, accountId) {
|
|
940
|
+
return accountId ? `${publishableKey}:${accountId}` : publishableKey;
|
|
941
|
+
}
|
|
942
|
+
async function resolvePlanRef(productRef, fetchFn, headers, listPlansRoute) {
|
|
943
|
+
const url = `${listPlansRoute}?productRef=${encodeURIComponent(productRef)}`;
|
|
944
|
+
const res = await fetchFn(url, { method: "GET", headers });
|
|
945
|
+
if (!res.ok) {
|
|
946
|
+
throw new Error(`Failed to fetch plans for product "${productRef}": ${res.statusText}`);
|
|
947
|
+
}
|
|
948
|
+
const data = await res.json();
|
|
949
|
+
const allPlans = data.plans ?? [];
|
|
950
|
+
const activePlans = allPlans.filter((p) => p.isActive !== false && p.status !== "inactive");
|
|
951
|
+
if (activePlans.length === 0) {
|
|
952
|
+
throw new Error(
|
|
953
|
+
`No active plans found for product "${productRef}". Configure at least one plan in the SolvaPay Console.`
|
|
954
|
+
);
|
|
955
|
+
}
|
|
956
|
+
if (activePlans.length === 1) {
|
|
957
|
+
return activePlans[0].reference;
|
|
958
|
+
}
|
|
959
|
+
const defaultPlan = activePlans.find((p) => p.default === true);
|
|
960
|
+
if (defaultPlan) {
|
|
961
|
+
return defaultPlan.reference;
|
|
962
|
+
}
|
|
963
|
+
throw new Error(
|
|
964
|
+
`Product "${productRef}" has ${activePlans.length} active plans but none is marked as default. Either pass planRef explicitly, use <PricingSelector> for user selection, or mark one plan as default in the SolvaPay Console.`
|
|
965
|
+
);
|
|
966
|
+
}
|
|
967
|
+
function useCheckout(options) {
|
|
968
|
+
const { planRef, productRef, customer } = options;
|
|
969
|
+
const { createPayment, customerRef, updateCustomerRef, _config } = useSolvaPay();
|
|
970
|
+
const [loading, setLoading] = useState2(false);
|
|
971
|
+
const [error, setError] = useState2(null);
|
|
972
|
+
const [stripePromise, setStripePromise] = useState2(null);
|
|
973
|
+
const [clientSecret, setClientSecret] = useState2(null);
|
|
974
|
+
const [resolvedPlanRef, setResolvedPlanRef] = useState2(planRef || null);
|
|
975
|
+
const isStartingRef = useRef2(false);
|
|
976
|
+
const startCheckout = useCallback2(async () => {
|
|
977
|
+
if (isStartingRef.current || loading) {
|
|
978
|
+
return;
|
|
979
|
+
}
|
|
980
|
+
if (!planRef && !productRef) {
|
|
981
|
+
setError(
|
|
982
|
+
new Error(
|
|
983
|
+
"useCheckout: either planRef or productRef is required. Pass planRef directly, or pass productRef to auto-resolve the plan."
|
|
984
|
+
)
|
|
985
|
+
);
|
|
986
|
+
return;
|
|
987
|
+
}
|
|
988
|
+
isStartingRef.current = true;
|
|
989
|
+
setLoading(true);
|
|
990
|
+
setError(null);
|
|
991
|
+
try {
|
|
992
|
+
let effectivePlanRef = planRef;
|
|
993
|
+
if (!effectivePlanRef && productRef) {
|
|
994
|
+
const listPlansRoute = _config?.api?.listPlans || "/api/list-plans";
|
|
995
|
+
effectivePlanRef = await resolvePlanRef(productRef, fetch, {}, listPlansRoute);
|
|
996
|
+
setResolvedPlanRef(effectivePlanRef);
|
|
997
|
+
}
|
|
998
|
+
if (!effectivePlanRef) {
|
|
999
|
+
throw new Error("Could not determine plan reference for checkout");
|
|
1000
|
+
}
|
|
1001
|
+
const result = await createPayment({
|
|
1002
|
+
planRef: effectivePlanRef,
|
|
1003
|
+
productRef,
|
|
1004
|
+
customer
|
|
1005
|
+
});
|
|
1006
|
+
if (!result || typeof result !== "object") {
|
|
1007
|
+
throw new Error("Invalid payment intent response from server");
|
|
1008
|
+
}
|
|
1009
|
+
if (!result.clientSecret || typeof result.clientSecret !== "string") {
|
|
1010
|
+
throw new Error("Invalid client secret in payment intent response");
|
|
1011
|
+
}
|
|
1012
|
+
if (!result.publishableKey || typeof result.publishableKey !== "string") {
|
|
1013
|
+
throw new Error("Invalid publishable key in payment intent response");
|
|
1014
|
+
}
|
|
1015
|
+
if (result.customerRef && result.customerRef !== customerRef && updateCustomerRef) {
|
|
1016
|
+
updateCustomerRef(result.customerRef);
|
|
1017
|
+
}
|
|
1018
|
+
const stripeOptions = result.accountId ? { stripeAccount: result.accountId } : {};
|
|
1019
|
+
const cacheKey = getStripeCacheKey(result.publishableKey, result.accountId);
|
|
1020
|
+
let stripe = stripePromiseCache.get(cacheKey);
|
|
1021
|
+
if (!stripe) {
|
|
1022
|
+
stripe = loadStripe(result.publishableKey, stripeOptions);
|
|
1023
|
+
stripePromiseCache.set(cacheKey, stripe);
|
|
1024
|
+
}
|
|
1025
|
+
setStripePromise(stripe);
|
|
1026
|
+
setClientSecret(result.clientSecret);
|
|
1027
|
+
} catch (err) {
|
|
1028
|
+
const error2 = err instanceof Error ? err : new Error("Failed to start checkout");
|
|
1029
|
+
setError(error2);
|
|
1030
|
+
} finally {
|
|
1031
|
+
setLoading(false);
|
|
1032
|
+
isStartingRef.current = false;
|
|
1033
|
+
}
|
|
1034
|
+
}, [planRef, productRef, customer, createPayment, updateCustomerRef, loading, _config]);
|
|
1035
|
+
const reset = useCallback2(() => {
|
|
1036
|
+
isStartingRef.current = false;
|
|
1037
|
+
setLoading(false);
|
|
1038
|
+
setError(null);
|
|
1039
|
+
setStripePromise(null);
|
|
1040
|
+
setClientSecret(null);
|
|
1041
|
+
setResolvedPlanRef(planRef || null);
|
|
1042
|
+
}, [planRef]);
|
|
1043
|
+
return {
|
|
1044
|
+
loading,
|
|
1045
|
+
error,
|
|
1046
|
+
stripePromise,
|
|
1047
|
+
clientSecret,
|
|
1048
|
+
resolvedPlanRef,
|
|
1049
|
+
startCheckout,
|
|
1050
|
+
reset
|
|
1051
|
+
};
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
// src/hooks/usePurchase.ts
|
|
1055
|
+
function usePurchase() {
|
|
1056
|
+
const { purchase, refetchPurchase } = useSolvaPay();
|
|
1057
|
+
return {
|
|
1058
|
+
...purchase,
|
|
1059
|
+
refetch: refetchPurchase
|
|
1060
|
+
};
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
// src/hooks/useCustomer.ts
|
|
1064
|
+
function useCustomer() {
|
|
1065
|
+
const { purchase, customerRef } = useSolvaPay();
|
|
1066
|
+
return {
|
|
1067
|
+
customerRef: purchase.customerRef || customerRef,
|
|
1068
|
+
email: purchase.email,
|
|
1069
|
+
name: purchase.name,
|
|
1070
|
+
loading: purchase.loading
|
|
1071
|
+
};
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
// src/hooks/useCopy.ts
|
|
1075
|
+
function useCopy() {
|
|
1076
|
+
return useCopyContext().copy;
|
|
1077
|
+
}
|
|
1078
|
+
function useLocale() {
|
|
1079
|
+
return useCopyContext().locale;
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
// src/hooks/usePlans.ts
|
|
1083
|
+
import { useState as useState3, useEffect as useEffect2, useCallback as useCallback3, useMemo as useMemo3, useRef as useRef3 } from "react";
|
|
1084
|
+
var plansCache = /* @__PURE__ */ new Map();
|
|
1085
|
+
var CACHE_DURATION2 = 5 * 60 * 1e3;
|
|
1086
|
+
function processPlans(raw, filter, sortBy) {
|
|
1087
|
+
let result = sortBy ? [...raw].sort(sortBy) : raw;
|
|
1088
|
+
if (filter) result = result.filter(filter);
|
|
1089
|
+
return result;
|
|
1090
|
+
}
|
|
1091
|
+
function computeInitialIndex(plans, initialPlanRef, autoSelectFirstPaid) {
|
|
1092
|
+
if (plans.length === 0) return 0;
|
|
1093
|
+
if (initialPlanRef) {
|
|
1094
|
+
const idx = plans.findIndex((p) => p.reference === initialPlanRef);
|
|
1095
|
+
if (idx >= 0) return idx;
|
|
1096
|
+
}
|
|
1097
|
+
if (autoSelectFirstPaid) {
|
|
1098
|
+
const idx = plans.findIndex((p) => p.requiresPayment !== false);
|
|
1099
|
+
return idx >= 0 ? idx : 0;
|
|
1100
|
+
}
|
|
1101
|
+
return 0;
|
|
1102
|
+
}
|
|
1103
|
+
function usePlans(options) {
|
|
1104
|
+
const {
|
|
1105
|
+
fetcher,
|
|
1106
|
+
productRef,
|
|
1107
|
+
filter,
|
|
1108
|
+
sortBy,
|
|
1109
|
+
autoSelectFirstPaid = false,
|
|
1110
|
+
initialPlanRef,
|
|
1111
|
+
selectionReady = true
|
|
1112
|
+
} = options;
|
|
1113
|
+
const fetcherRef = useRef3(fetcher);
|
|
1114
|
+
const filterRef = useRef3(filter);
|
|
1115
|
+
const sortByRef = useRef3(sortBy);
|
|
1116
|
+
const autoSelectFirstPaidRef = useRef3(autoSelectFirstPaid);
|
|
1117
|
+
const initialPlanRefRef = useRef3(initialPlanRef);
|
|
1118
|
+
const selectionReadyRef = useRef3(selectionReady);
|
|
1119
|
+
const hasAppliedInitialRef = useRef3(false);
|
|
1120
|
+
const userHasSelectedRef = useRef3(false);
|
|
1121
|
+
const [selectedPlanIndex, setSelectedPlanIndexState] = useState3(() => {
|
|
1122
|
+
if (!selectionReady || !productRef) return 0;
|
|
1123
|
+
const cached = plansCache.get(productRef);
|
|
1124
|
+
if (!cached || Date.now() - cached.timestamp >= CACHE_DURATION2 || cached.plans.length === 0) {
|
|
1125
|
+
return 0;
|
|
1126
|
+
}
|
|
1127
|
+
const processed = processPlans(cached.plans, filter, sortBy);
|
|
1128
|
+
if (processed.length === 0) return 0;
|
|
1129
|
+
const idx = computeInitialIndex(processed, initialPlanRef, autoSelectFirstPaid);
|
|
1130
|
+
hasAppliedInitialRef.current = true;
|
|
1131
|
+
return idx;
|
|
1132
|
+
});
|
|
1133
|
+
const [plans, setPlans] = useState3(() => {
|
|
1134
|
+
if (!productRef) return [];
|
|
1135
|
+
const cached = plansCache.get(productRef);
|
|
1136
|
+
if (!cached || Date.now() - cached.timestamp >= CACHE_DURATION2 || cached.plans.length === 0) {
|
|
1137
|
+
return [];
|
|
1138
|
+
}
|
|
1139
|
+
return processPlans(cached.plans, filter, sortBy);
|
|
1140
|
+
});
|
|
1141
|
+
const [loading, setLoading] = useState3(() => plans.length === 0);
|
|
1142
|
+
const [error, setError] = useState3(null);
|
|
1143
|
+
useEffect2(() => {
|
|
1144
|
+
fetcherRef.current = fetcher;
|
|
1145
|
+
}, [fetcher]);
|
|
1146
|
+
useEffect2(() => {
|
|
1147
|
+
filterRef.current = filter;
|
|
1148
|
+
}, [filter]);
|
|
1149
|
+
useEffect2(() => {
|
|
1150
|
+
sortByRef.current = sortBy;
|
|
1151
|
+
}, [sortBy]);
|
|
1152
|
+
useEffect2(() => {
|
|
1153
|
+
autoSelectFirstPaidRef.current = autoSelectFirstPaid;
|
|
1154
|
+
}, [autoSelectFirstPaid]);
|
|
1155
|
+
useEffect2(() => {
|
|
1156
|
+
initialPlanRefRef.current = initialPlanRef;
|
|
1157
|
+
}, [initialPlanRef]);
|
|
1158
|
+
useEffect2(() => {
|
|
1159
|
+
selectionReadyRef.current = selectionReady;
|
|
1160
|
+
}, [selectionReady]);
|
|
1161
|
+
const setSelectedPlanIndex = useCallback3((index) => {
|
|
1162
|
+
userHasSelectedRef.current = true;
|
|
1163
|
+
setSelectedPlanIndexState(index);
|
|
1164
|
+
}, []);
|
|
1165
|
+
const applyInitialSelection = useCallback3((processedPlans) => {
|
|
1166
|
+
if (hasAppliedInitialRef.current || userHasSelectedRef.current) return;
|
|
1167
|
+
if (!selectionReadyRef.current || processedPlans.length === 0) return;
|
|
1168
|
+
hasAppliedInitialRef.current = true;
|
|
1169
|
+
const idx = computeInitialIndex(
|
|
1170
|
+
processedPlans,
|
|
1171
|
+
initialPlanRefRef.current,
|
|
1172
|
+
autoSelectFirstPaidRef.current
|
|
1173
|
+
);
|
|
1174
|
+
setSelectedPlanIndexState(idx);
|
|
1175
|
+
}, []);
|
|
1176
|
+
const fetchPlans = useCallback3(
|
|
1177
|
+
async (force = false) => {
|
|
1178
|
+
if (!productRef) {
|
|
1179
|
+
setError(new Error("Product reference not configured"));
|
|
1180
|
+
setLoading(false);
|
|
1181
|
+
return;
|
|
1182
|
+
}
|
|
1183
|
+
const cached = plansCache.get(productRef);
|
|
1184
|
+
const now = Date.now();
|
|
1185
|
+
if (!force && cached && now - cached.timestamp < CACHE_DURATION2) {
|
|
1186
|
+
const processedPlans = processPlans(
|
|
1187
|
+
cached.plans,
|
|
1188
|
+
filterRef.current,
|
|
1189
|
+
sortByRef.current
|
|
1190
|
+
);
|
|
1191
|
+
setPlans(processedPlans);
|
|
1192
|
+
setLoading(false);
|
|
1193
|
+
setError(null);
|
|
1194
|
+
applyInitialSelection(processedPlans);
|
|
1195
|
+
return;
|
|
1196
|
+
}
|
|
1197
|
+
if (cached?.promise) {
|
|
1198
|
+
try {
|
|
1199
|
+
setLoading(true);
|
|
1200
|
+
const fetchedPlans = await cached.promise;
|
|
1201
|
+
const processedPlans = processPlans(
|
|
1202
|
+
fetchedPlans,
|
|
1203
|
+
filterRef.current,
|
|
1204
|
+
sortByRef.current
|
|
1205
|
+
);
|
|
1206
|
+
setPlans(processedPlans);
|
|
1207
|
+
setError(null);
|
|
1208
|
+
applyInitialSelection(processedPlans);
|
|
1209
|
+
} catch (err) {
|
|
1210
|
+
setError(err instanceof Error ? err : new Error("Failed to load plans"));
|
|
1211
|
+
} finally {
|
|
1212
|
+
setLoading(false);
|
|
1213
|
+
}
|
|
1214
|
+
return;
|
|
1215
|
+
}
|
|
1216
|
+
try {
|
|
1217
|
+
setLoading(true);
|
|
1218
|
+
setError(null);
|
|
1219
|
+
const fetchPromise = fetcherRef.current(productRef);
|
|
1220
|
+
plansCache.set(productRef, { plans: [], timestamp: now, promise: fetchPromise });
|
|
1221
|
+
const fetchedPlans = await fetchPromise;
|
|
1222
|
+
plansCache.set(productRef, { plans: fetchedPlans, timestamp: now, promise: null });
|
|
1223
|
+
const processedPlans = processPlans(
|
|
1224
|
+
fetchedPlans,
|
|
1225
|
+
filterRef.current,
|
|
1226
|
+
sortByRef.current
|
|
1227
|
+
);
|
|
1228
|
+
setPlans(processedPlans);
|
|
1229
|
+
applyInitialSelection(processedPlans);
|
|
1230
|
+
} catch (err) {
|
|
1231
|
+
plansCache.delete(productRef);
|
|
1232
|
+
setError(err instanceof Error ? err : new Error("Failed to load plans"));
|
|
1233
|
+
} finally {
|
|
1234
|
+
setLoading(false);
|
|
1235
|
+
}
|
|
1236
|
+
},
|
|
1237
|
+
[productRef, applyInitialSelection]
|
|
1238
|
+
);
|
|
1239
|
+
useEffect2(() => {
|
|
1240
|
+
fetchPlans();
|
|
1241
|
+
}, [fetchPlans]);
|
|
1242
|
+
useEffect2(() => {
|
|
1243
|
+
if (hasAppliedInitialRef.current || userHasSelectedRef.current) return;
|
|
1244
|
+
if (!selectionReady || plans.length === 0) return;
|
|
1245
|
+
applyInitialSelection(plans);
|
|
1246
|
+
}, [selectionReady, plans, applyInitialSelection]);
|
|
1247
|
+
const selectedPlan = useMemo3(() => plans[selectedPlanIndex] || null, [plans, selectedPlanIndex]);
|
|
1248
|
+
const selectPlan = useCallback3(
|
|
1249
|
+
(planRef) => {
|
|
1250
|
+
const index = plans.findIndex((p) => p.reference === planRef);
|
|
1251
|
+
if (index >= 0) {
|
|
1252
|
+
setSelectedPlanIndex(index);
|
|
1253
|
+
}
|
|
1254
|
+
},
|
|
1255
|
+
[plans, setSelectedPlanIndex]
|
|
1256
|
+
);
|
|
1257
|
+
return {
|
|
1258
|
+
plans,
|
|
1259
|
+
loading,
|
|
1260
|
+
error,
|
|
1261
|
+
selectedPlanIndex,
|
|
1262
|
+
selectedPlan,
|
|
1263
|
+
setSelectedPlanIndex,
|
|
1264
|
+
selectPlan,
|
|
1265
|
+
refetch: () => fetchPlans(true),
|
|
1266
|
+
isSelectionReady: hasAppliedInitialRef.current
|
|
1267
|
+
};
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
// src/hooks/usePlan.ts
|
|
1271
|
+
import { useCallback as useCallback4, useEffect as useEffect3, useState as useState4 } from "react";
|
|
1272
|
+
async function listPlans(productRef, config) {
|
|
1273
|
+
const base = config?.api?.listPlans || "/api/list-plans";
|
|
1274
|
+
const url = `${base}?productRef=${encodeURIComponent(productRef)}`;
|
|
1275
|
+
const fetchFn = config?.fetch || fetch;
|
|
1276
|
+
const { headers } = await buildRequestHeaders(config);
|
|
1277
|
+
const res = await fetchFn(url, { method: "GET", headers });
|
|
1278
|
+
if (!res.ok) {
|
|
1279
|
+
const error = new Error(`Failed to fetch plans: ${res.statusText || res.status}`);
|
|
1280
|
+
config?.onError?.(error, "listPlans");
|
|
1281
|
+
throw error;
|
|
1282
|
+
}
|
|
1283
|
+
const data = await res.json();
|
|
1284
|
+
return data.plans ?? [];
|
|
1285
|
+
}
|
|
1286
|
+
function usePlan(options) {
|
|
1287
|
+
const { planRef, productRef } = options;
|
|
1288
|
+
const { _config } = useSolvaPay();
|
|
1289
|
+
const findPlan = useCallback4(
|
|
1290
|
+
(plans) => {
|
|
1291
|
+
if (!planRef) return null;
|
|
1292
|
+
return plans.find((p) => p.reference === planRef) || null;
|
|
1293
|
+
},
|
|
1294
|
+
[planRef]
|
|
1295
|
+
);
|
|
1296
|
+
const [plan, setPlan] = useState4(() => {
|
|
1297
|
+
if (!planRef || !productRef) return null;
|
|
1298
|
+
const cached = plansCache.get(productRef);
|
|
1299
|
+
if (!cached || Date.now() - cached.timestamp >= CACHE_DURATION2) return null;
|
|
1300
|
+
return findPlan(cached.plans);
|
|
1301
|
+
});
|
|
1302
|
+
const [loading, setLoading] = useState4(() => !!(planRef && !plan));
|
|
1303
|
+
const [error, setError] = useState4(null);
|
|
1304
|
+
const load = useCallback4(
|
|
1305
|
+
async (force = false) => {
|
|
1306
|
+
if (!planRef) {
|
|
1307
|
+
setPlan(null);
|
|
1308
|
+
setLoading(false);
|
|
1309
|
+
setError(null);
|
|
1310
|
+
return;
|
|
1311
|
+
}
|
|
1312
|
+
if (!productRef) {
|
|
1313
|
+
setLoading(false);
|
|
1314
|
+
setError(
|
|
1315
|
+
new Error("usePlan: productRef is required to resolve a plan reference")
|
|
1316
|
+
);
|
|
1317
|
+
return;
|
|
1318
|
+
}
|
|
1319
|
+
const cached = plansCache.get(productRef);
|
|
1320
|
+
const now = Date.now();
|
|
1321
|
+
if (!force && cached?.plans.length && now - cached.timestamp < CACHE_DURATION2) {
|
|
1322
|
+
const p = findPlan(cached.plans);
|
|
1323
|
+
setPlan(p);
|
|
1324
|
+
setLoading(false);
|
|
1325
|
+
setError(
|
|
1326
|
+
p ? null : new Error(
|
|
1327
|
+
`Plan "${planRef}" not found in product "${productRef}"`
|
|
1328
|
+
)
|
|
1329
|
+
);
|
|
1330
|
+
return;
|
|
1331
|
+
}
|
|
1332
|
+
if (!force && cached?.promise) {
|
|
1333
|
+
try {
|
|
1334
|
+
setLoading(true);
|
|
1335
|
+
const plans = await cached.promise;
|
|
1336
|
+
const p = findPlan(plans);
|
|
1337
|
+
setPlan(p);
|
|
1338
|
+
setError(
|
|
1339
|
+
p ? null : new Error(
|
|
1340
|
+
`Plan "${planRef}" not found in product "${productRef}"`
|
|
1341
|
+
)
|
|
1342
|
+
);
|
|
1343
|
+
} catch (err) {
|
|
1344
|
+
setError(err instanceof Error ? err : new Error("Failed to load plan"));
|
|
1345
|
+
} finally {
|
|
1346
|
+
setLoading(false);
|
|
1347
|
+
}
|
|
1348
|
+
return;
|
|
1349
|
+
}
|
|
1350
|
+
try {
|
|
1351
|
+
setLoading(true);
|
|
1352
|
+
setError(null);
|
|
1353
|
+
const promise = listPlans(productRef, _config);
|
|
1354
|
+
plansCache.set(productRef, { plans: [], timestamp: now, promise });
|
|
1355
|
+
const plans = await promise;
|
|
1356
|
+
plansCache.set(productRef, { plans, timestamp: now, promise: null });
|
|
1357
|
+
const p = findPlan(plans);
|
|
1358
|
+
setPlan(p);
|
|
1359
|
+
if (!p) {
|
|
1360
|
+
setError(new Error(`Plan "${planRef}" not found in product "${productRef}"`));
|
|
1361
|
+
}
|
|
1362
|
+
} catch (err) {
|
|
1363
|
+
plansCache.delete(productRef);
|
|
1364
|
+
setError(err instanceof Error ? err : new Error("Failed to load plan"));
|
|
1365
|
+
} finally {
|
|
1366
|
+
setLoading(false);
|
|
1367
|
+
}
|
|
1368
|
+
},
|
|
1369
|
+
[planRef, productRef, _config, findPlan]
|
|
1370
|
+
);
|
|
1371
|
+
useEffect3(() => {
|
|
1372
|
+
load();
|
|
1373
|
+
}, [load]);
|
|
1374
|
+
return {
|
|
1375
|
+
plan,
|
|
1376
|
+
loading,
|
|
1377
|
+
error,
|
|
1378
|
+
refetch: () => load(true)
|
|
1379
|
+
};
|
|
1380
|
+
}
|
|
1381
|
+
|
|
1382
|
+
// src/hooks/useProduct.ts
|
|
1383
|
+
import { useCallback as useCallback5, useEffect as useEffect4, useState as useState5 } from "react";
|
|
1384
|
+
var productCache = /* @__PURE__ */ new Map();
|
|
1385
|
+
var CACHE_DURATION3 = 5 * 60 * 1e3;
|
|
1386
|
+
function routeFor(config) {
|
|
1387
|
+
return config?.api?.getProduct || "/api/get-product";
|
|
1388
|
+
}
|
|
1389
|
+
async function fetchProduct(productRef, config) {
|
|
1390
|
+
const base = routeFor(config);
|
|
1391
|
+
const url = `${base}?productRef=${encodeURIComponent(productRef)}`;
|
|
1392
|
+
const fetchFn = config?.fetch || fetch;
|
|
1393
|
+
const { headers } = await buildRequestHeaders(config);
|
|
1394
|
+
const res = await fetchFn(url, { method: "GET", headers });
|
|
1395
|
+
if (!res.ok) {
|
|
1396
|
+
const error = new Error(`Failed to fetch product: ${res.statusText || res.status}`);
|
|
1397
|
+
config?.onError?.(error, "getProduct");
|
|
1398
|
+
throw error;
|
|
1399
|
+
}
|
|
1400
|
+
return await res.json();
|
|
1401
|
+
}
|
|
1402
|
+
function useProduct(productRef) {
|
|
1403
|
+
const { _config } = useSolvaPay();
|
|
1404
|
+
const cacheKey = productRef || "";
|
|
1405
|
+
const [product, setProduct] = useState5(
|
|
1406
|
+
() => productRef ? productCache.get(cacheKey)?.product ?? null : null
|
|
1407
|
+
);
|
|
1408
|
+
const [loading, setLoading] = useState5(() => {
|
|
1409
|
+
if (!productRef) return false;
|
|
1410
|
+
const cached = productCache.get(cacheKey);
|
|
1411
|
+
return !cached || !cached.product && !cached.promise;
|
|
1412
|
+
});
|
|
1413
|
+
const [error, setError] = useState5(null);
|
|
1414
|
+
const load = useCallback5(
|
|
1415
|
+
async (force = false) => {
|
|
1416
|
+
if (!productRef) {
|
|
1417
|
+
setProduct(null);
|
|
1418
|
+
setLoading(false);
|
|
1419
|
+
setError(null);
|
|
1420
|
+
return;
|
|
1421
|
+
}
|
|
1422
|
+
const cached = productCache.get(productRef);
|
|
1423
|
+
const now = Date.now();
|
|
1424
|
+
if (!force && cached?.product && now - cached.timestamp < CACHE_DURATION3) {
|
|
1425
|
+
setProduct(cached.product);
|
|
1426
|
+
setLoading(false);
|
|
1427
|
+
setError(null);
|
|
1428
|
+
return;
|
|
1429
|
+
}
|
|
1430
|
+
if (!force && cached?.promise) {
|
|
1431
|
+
try {
|
|
1432
|
+
setLoading(true);
|
|
1433
|
+
const p = await cached.promise;
|
|
1434
|
+
setProduct(p);
|
|
1435
|
+
setError(null);
|
|
1436
|
+
} catch (err) {
|
|
1437
|
+
setError(err instanceof Error ? err : new Error("Failed to load product"));
|
|
1438
|
+
} finally {
|
|
1439
|
+
setLoading(false);
|
|
1440
|
+
}
|
|
1441
|
+
return;
|
|
1442
|
+
}
|
|
1443
|
+
try {
|
|
1444
|
+
setLoading(true);
|
|
1445
|
+
setError(null);
|
|
1446
|
+
const promise = fetchProduct(productRef, _config);
|
|
1447
|
+
productCache.set(productRef, { product: null, promise, timestamp: now });
|
|
1448
|
+
const p = await promise;
|
|
1449
|
+
productCache.set(productRef, { product: p, promise: null, timestamp: now });
|
|
1450
|
+
setProduct(p);
|
|
1451
|
+
} catch (err) {
|
|
1452
|
+
productCache.delete(productRef);
|
|
1453
|
+
setError(err instanceof Error ? err : new Error("Failed to load product"));
|
|
1454
|
+
} finally {
|
|
1455
|
+
setLoading(false);
|
|
1456
|
+
}
|
|
1457
|
+
},
|
|
1458
|
+
[productRef, _config]
|
|
1459
|
+
);
|
|
1460
|
+
useEffect4(() => {
|
|
1461
|
+
load();
|
|
1462
|
+
}, [load]);
|
|
1463
|
+
return {
|
|
1464
|
+
product,
|
|
1465
|
+
loading,
|
|
1466
|
+
error,
|
|
1467
|
+
refetch: () => load(true)
|
|
1468
|
+
};
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1471
|
+
// src/hooks/useActivation.ts
|
|
1472
|
+
import { useState as useState6, useCallback as useCallback6 } from "react";
|
|
1473
|
+
function useActivation() {
|
|
1474
|
+
const { activatePlan } = useSolvaPay();
|
|
1475
|
+
const copy = useCopy();
|
|
1476
|
+
const [state, setState] = useState6("idle");
|
|
1477
|
+
const [error, setError] = useState6(null);
|
|
1478
|
+
const [result, setResult] = useState6(null);
|
|
1479
|
+
const activate = useCallback6(
|
|
1480
|
+
async (params) => {
|
|
1481
|
+
setState("activating");
|
|
1482
|
+
setError(null);
|
|
1483
|
+
setResult(null);
|
|
1484
|
+
try {
|
|
1485
|
+
const data = await activatePlan(params);
|
|
1486
|
+
setResult(data);
|
|
1487
|
+
switch (data.status) {
|
|
1488
|
+
case "activated":
|
|
1489
|
+
case "already_active":
|
|
1490
|
+
setState("activated");
|
|
1491
|
+
break;
|
|
1492
|
+
case "topup_required":
|
|
1493
|
+
setState("topup_required");
|
|
1494
|
+
break;
|
|
1495
|
+
case "payment_required":
|
|
1496
|
+
setError(copy.activation.paymentRequired);
|
|
1497
|
+
setState("payment_required");
|
|
1498
|
+
break;
|
|
1499
|
+
case "invalid":
|
|
1500
|
+
setError(data.message || copy.activation.invalidConfiguration);
|
|
1501
|
+
setState("error");
|
|
1502
|
+
break;
|
|
1503
|
+
default:
|
|
1504
|
+
setError(copy.activation.unexpectedResponse);
|
|
1505
|
+
setState("error");
|
|
1506
|
+
}
|
|
1507
|
+
} catch (err) {
|
|
1508
|
+
setError(err instanceof Error ? err.message : copy.activation.failed);
|
|
1509
|
+
setState("error");
|
|
1510
|
+
}
|
|
1511
|
+
},
|
|
1512
|
+
[activatePlan, copy]
|
|
1513
|
+
);
|
|
1514
|
+
const reset = useCallback6(() => {
|
|
1515
|
+
setState("idle");
|
|
1516
|
+
setError(null);
|
|
1517
|
+
setResult(null);
|
|
1518
|
+
}, []);
|
|
1519
|
+
return { activate, state, error, result, reset };
|
|
1520
|
+
}
|
|
1521
|
+
|
|
1522
|
+
// src/components/PaymentFormContext.tsx
|
|
1523
|
+
import { createContext as createContext3, useContext as useContext3 } from "react";
|
|
1524
|
+
import { jsx as jsx4 } from "react/jsx-runtime";
|
|
1525
|
+
var PaymentFormContext = createContext3(null);
|
|
1526
|
+
function usePaymentForm() {
|
|
1527
|
+
const ctx = useContext3(PaymentFormContext);
|
|
1528
|
+
if (!ctx) {
|
|
1529
|
+
throw new Error(
|
|
1530
|
+
"PaymentForm subcomponents must be used inside a <PaymentForm>. Wrap the slots with <PaymentForm planRef=... productRef=...>."
|
|
1531
|
+
);
|
|
1532
|
+
}
|
|
1533
|
+
return ctx;
|
|
1534
|
+
}
|
|
1535
|
+
var PaymentFormProvider = ({ value, children }) => /* @__PURE__ */ jsx4(PaymentFormContext.Provider, { value, children });
|
|
1536
|
+
|
|
1537
|
+
// src/utils/format.ts
|
|
1538
|
+
var ZERO_DECIMAL_CURRENCIES = /* @__PURE__ */ new Set([
|
|
1539
|
+
"bif",
|
|
1540
|
+
"clp",
|
|
1541
|
+
"djf",
|
|
1542
|
+
"gnf",
|
|
1543
|
+
"jpy",
|
|
1544
|
+
"kmf",
|
|
1545
|
+
"krw",
|
|
1546
|
+
"mga",
|
|
1547
|
+
"pyg",
|
|
1548
|
+
"rwf",
|
|
1549
|
+
"ugx",
|
|
1550
|
+
"vnd",
|
|
1551
|
+
"vuv",
|
|
1552
|
+
"xaf",
|
|
1553
|
+
"xof",
|
|
1554
|
+
"xpf"
|
|
1555
|
+
]);
|
|
1556
|
+
function getFractionDigits(currency) {
|
|
1557
|
+
return ZERO_DECIMAL_CURRENCIES.has(currency.toLowerCase()) ? 0 : 2;
|
|
1558
|
+
}
|
|
1559
|
+
function toMajorUnits(amountMinor, currency) {
|
|
1560
|
+
const fractionDigits = getFractionDigits(currency);
|
|
1561
|
+
return fractionDigits === 0 ? amountMinor : amountMinor / 100;
|
|
1562
|
+
}
|
|
1563
|
+
function formatPrice(amountMinor, currency, opts = {}) {
|
|
1564
|
+
const { locale, interval, intervalCount = 1, free = "Free" } = opts;
|
|
1565
|
+
if (amountMinor === 0 && free !== "") {
|
|
1566
|
+
return free;
|
|
1567
|
+
}
|
|
1568
|
+
const fractionDigits = getFractionDigits(currency);
|
|
1569
|
+
const major = toMajorUnits(amountMinor, currency);
|
|
1570
|
+
const formatter = new Intl.NumberFormat(locale, {
|
|
1571
|
+
style: "currency",
|
|
1572
|
+
currency: currency.toUpperCase(),
|
|
1573
|
+
minimumFractionDigits: fractionDigits,
|
|
1574
|
+
maximumFractionDigits: fractionDigits
|
|
1575
|
+
});
|
|
1576
|
+
const formatted = formatter.format(major);
|
|
1577
|
+
if (!interval) return formatted;
|
|
1578
|
+
const suffix = intervalCount > 1 ? `${intervalCount} ${interval}s` : interval;
|
|
1579
|
+
return `${formatted} / ${suffix}`;
|
|
1580
|
+
}
|
|
1581
|
+
|
|
1582
|
+
// src/i18n/interpolate.ts
|
|
1583
|
+
function interpolate(template, vars) {
|
|
1584
|
+
return template.replace(/\{(\w+)\}/g, (match, key) => {
|
|
1585
|
+
const value = vars[key];
|
|
1586
|
+
if (value === void 0 || value === null) return match;
|
|
1587
|
+
return String(value);
|
|
1588
|
+
});
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
// src/primitives/CheckoutSummary.tsx
|
|
1592
|
+
import { createContext as createContext5, forwardRef, useContext as useContext5, useMemo as useMemo4 } from "react";
|
|
1593
|
+
|
|
1594
|
+
// src/components/PlanSelectionContext.tsx
|
|
1595
|
+
import { createContext as createContext4, useContext as useContext4 } from "react";
|
|
1596
|
+
import { jsx as jsx5 } from "react/jsx-runtime";
|
|
1597
|
+
var PlanSelectionContext = createContext4(null);
|
|
1598
|
+
var PlanSelectionProvider = ({
|
|
1599
|
+
value,
|
|
1600
|
+
children
|
|
1601
|
+
}) => /* @__PURE__ */ jsx5(PlanSelectionContext.Provider, { value, children });
|
|
1602
|
+
function usePlanSelection() {
|
|
1603
|
+
return useContext4(PlanSelectionContext);
|
|
1604
|
+
}
|
|
1605
|
+
|
|
1606
|
+
// src/utils/errors.ts
|
|
1607
|
+
var DOCS_BASE_URL = "https://solvapay.com/docs";
|
|
1608
|
+
var SolvaPayError = class extends Error {
|
|
1609
|
+
code;
|
|
1610
|
+
docsUrl;
|
|
1611
|
+
constructor(code, message, docsUrl) {
|
|
1612
|
+
super(message);
|
|
1613
|
+
this.name = "SolvaPayError";
|
|
1614
|
+
this.code = code;
|
|
1615
|
+
this.docsUrl = docsUrl;
|
|
1616
|
+
}
|
|
1617
|
+
};
|
|
1618
|
+
var MissingProviderError = class extends SolvaPayError {
|
|
1619
|
+
constructor(primitiveName) {
|
|
1620
|
+
const docsUrl = `${DOCS_BASE_URL}/troubleshooting/missing-provider`;
|
|
1621
|
+
super(
|
|
1622
|
+
"MISSING_PROVIDER",
|
|
1623
|
+
`${primitiveName} must be rendered inside <SolvaPayProvider>. Wrap your app (or the section using ${primitiveName}) with <SolvaPayProvider config={{ ... }}>. See ${docsUrl}`,
|
|
1624
|
+
docsUrl
|
|
1625
|
+
);
|
|
1626
|
+
this.name = "MissingProviderError";
|
|
1627
|
+
}
|
|
1628
|
+
};
|
|
1629
|
+
var MissingProductRefError = class extends SolvaPayError {
|
|
1630
|
+
constructor(primitiveName) {
|
|
1631
|
+
const docsUrl = `${DOCS_BASE_URL}/primitives/product-ref`;
|
|
1632
|
+
super(
|
|
1633
|
+
"MISSING_PRODUCT_REF",
|
|
1634
|
+
`${primitiveName} requires a productRef. Pass the \`productRef\` prop (or set NEXT_PUBLIC_SOLVAPAY_PRODUCT_REF). See ${docsUrl}`,
|
|
1635
|
+
docsUrl
|
|
1636
|
+
);
|
|
1637
|
+
this.name = "MissingProductRefError";
|
|
1638
|
+
}
|
|
1639
|
+
};
|
|
1640
|
+
|
|
1641
|
+
// src/primitives/CheckoutSummary.tsx
|
|
1642
|
+
import { jsx as jsx6 } from "react/jsx-runtime";
|
|
1643
|
+
var CheckoutSummaryContext = createContext5(null);
|
|
1644
|
+
function useCheckoutSummaryContext(part) {
|
|
1645
|
+
const ctx = useContext5(CheckoutSummaryContext);
|
|
1646
|
+
if (!ctx) {
|
|
1647
|
+
throw new Error(
|
|
1648
|
+
`CheckoutSummary.${part} must be rendered inside <CheckoutSummary.Root>.`
|
|
1649
|
+
);
|
|
1650
|
+
}
|
|
1651
|
+
return ctx;
|
|
1652
|
+
}
|
|
1653
|
+
var Root = forwardRef(function CheckoutSummaryRoot({ planRef, productRef, asChild, children, ...rest }, forwardedRef) {
|
|
1654
|
+
const solva = useContext5(SolvaPayContext);
|
|
1655
|
+
if (!solva) throw new MissingProviderError("CheckoutSummary");
|
|
1656
|
+
const locale = useLocale();
|
|
1657
|
+
const copy = useCopy();
|
|
1658
|
+
const planSelection = usePlanSelection();
|
|
1659
|
+
const resolvedPlanRef = planRef ?? planSelection?.selectedPlanRef ?? void 0;
|
|
1660
|
+
const resolvedProductRef = productRef ?? planSelection?.productRef;
|
|
1661
|
+
const { plan, loading: planLoading } = usePlan({
|
|
1662
|
+
planRef: resolvedPlanRef,
|
|
1663
|
+
productRef: resolvedProductRef
|
|
1664
|
+
});
|
|
1665
|
+
const { product, loading: productLoading } = useProduct(resolvedProductRef);
|
|
1666
|
+
const loading = planLoading || productLoading;
|
|
1667
|
+
const priceFormatted = useMemo4(() => {
|
|
1668
|
+
const price = plan?.price ?? 0;
|
|
1669
|
+
const currency = plan?.currency ?? "usd";
|
|
1670
|
+
return formatPrice(price, currency, {
|
|
1671
|
+
locale,
|
|
1672
|
+
interval: plan?.interval,
|
|
1673
|
+
intervalCount: 1,
|
|
1674
|
+
free: copy.interval.free
|
|
1675
|
+
});
|
|
1676
|
+
}, [plan, locale, copy.interval.free]);
|
|
1677
|
+
const trialBanner = useMemo4(() => {
|
|
1678
|
+
const trialDays = plan?.trialDays;
|
|
1679
|
+
if (!trialDays || trialDays <= 0) return null;
|
|
1680
|
+
return interpolate(copy.interval.trial, { trialDays });
|
|
1681
|
+
}, [plan?.trialDays, copy.interval.trial]);
|
|
1682
|
+
const ctx = useMemo4(
|
|
1683
|
+
() => ({ plan, product, priceFormatted, trialBanner, loading }),
|
|
1684
|
+
[plan, product, priceFormatted, trialBanner, loading]
|
|
1685
|
+
);
|
|
1686
|
+
const Comp = asChild ? Slot : "div";
|
|
1687
|
+
return /* @__PURE__ */ jsx6(Comp, { ref: forwardedRef, "data-solvapay-checkout-summary": "", ...rest, children: /* @__PURE__ */ jsx6(CheckoutSummaryContext.Provider, { value: ctx, children }) });
|
|
1688
|
+
});
|
|
1689
|
+
var ProductSlot = forwardRef(function CheckoutSummaryProduct({ asChild, children, ...rest }, forwardedRef) {
|
|
1690
|
+
const ctx = useCheckoutSummaryContext("Product");
|
|
1691
|
+
const name = ctx.product?.name;
|
|
1692
|
+
if (!name) return null;
|
|
1693
|
+
const Comp = asChild ? Slot : "span";
|
|
1694
|
+
return /* @__PURE__ */ jsx6(Comp, { ref: forwardedRef, "data-solvapay-checkout-summary-product": "", ...rest, children: children ?? name });
|
|
1695
|
+
});
|
|
1696
|
+
var PlanSlot = forwardRef(function CheckoutSummaryPlan({ asChild, children, ...rest }, forwardedRef) {
|
|
1697
|
+
const ctx = useCheckoutSummaryContext("Plan");
|
|
1698
|
+
const name = ctx.plan?.name;
|
|
1699
|
+
if (!name) return null;
|
|
1700
|
+
const Comp = asChild ? Slot : "span";
|
|
1701
|
+
return /* @__PURE__ */ jsx6(Comp, { ref: forwardedRef, "data-solvapay-checkout-summary-plan": "", ...rest, children: children ?? name });
|
|
1702
|
+
});
|
|
1703
|
+
var PriceSlot = forwardRef(function CheckoutSummaryPrice({ asChild, children, ...rest }, forwardedRef) {
|
|
1704
|
+
const ctx = useCheckoutSummaryContext("Price");
|
|
1705
|
+
const Comp = asChild ? Slot : "span";
|
|
1706
|
+
return /* @__PURE__ */ jsx6(Comp, { ref: forwardedRef, "data-solvapay-checkout-summary-price": "", ...rest, children: children ?? ctx.priceFormatted });
|
|
1707
|
+
});
|
|
1708
|
+
var TrialSlot = forwardRef(function CheckoutSummaryTrial({ asChild, children, ...rest }, forwardedRef) {
|
|
1709
|
+
const ctx = useCheckoutSummaryContext("Trial");
|
|
1710
|
+
if (!ctx.trialBanner) return null;
|
|
1711
|
+
const Comp = asChild ? Slot : "span";
|
|
1712
|
+
return /* @__PURE__ */ jsx6(Comp, { ref: forwardedRef, "data-solvapay-checkout-summary-trial": "", ...rest, children: children ?? ctx.trialBanner });
|
|
1713
|
+
});
|
|
1714
|
+
var TaxNoteSlot = forwardRef(function CheckoutSummaryTaxNote({ asChild, children, ...rest }, forwardedRef) {
|
|
1715
|
+
useCheckoutSummaryContext("TaxNote");
|
|
1716
|
+
const Comp = asChild ? Slot : "span";
|
|
1717
|
+
return /* @__PURE__ */ jsx6(Comp, { ref: forwardedRef, "data-solvapay-checkout-summary-tax-note": "", ...rest, children: children ?? "Taxes calculated at checkout" });
|
|
1718
|
+
});
|
|
1719
|
+
var CheckoutSummaryRoot2 = Root;
|
|
1720
|
+
var CheckoutSummaryProduct2 = ProductSlot;
|
|
1721
|
+
var CheckoutSummaryPlan2 = PlanSlot;
|
|
1722
|
+
var CheckoutSummaryPrice2 = PriceSlot;
|
|
1723
|
+
var CheckoutSummaryTrial2 = TrialSlot;
|
|
1724
|
+
var CheckoutSummaryTaxNote2 = TaxNoteSlot;
|
|
1725
|
+
var CheckoutSummary = {
|
|
1726
|
+
Root,
|
|
1727
|
+
Product: ProductSlot,
|
|
1728
|
+
Plan: PlanSlot,
|
|
1729
|
+
Price: PriceSlot,
|
|
1730
|
+
Trial: TrialSlot,
|
|
1731
|
+
TaxNote: TaxNoteSlot
|
|
1732
|
+
};
|
|
1733
|
+
function useCheckoutSummary() {
|
|
1734
|
+
return useCheckoutSummaryContext("useCheckoutSummary");
|
|
1735
|
+
}
|
|
1736
|
+
|
|
1737
|
+
// src/components/CheckoutSummary.tsx
|
|
1738
|
+
import { jsx as jsx7, jsxs } from "react/jsx-runtime";
|
|
1739
|
+
var CheckoutSummary2 = ({
|
|
1740
|
+
planRef,
|
|
1741
|
+
productRef,
|
|
1742
|
+
showTrial = true,
|
|
1743
|
+
showTaxNote = false,
|
|
1744
|
+
className
|
|
1745
|
+
}) => {
|
|
1746
|
+
const rootClass = ["solvapay-checkout-summary", className].filter(Boolean).join(" ");
|
|
1747
|
+
return /* @__PURE__ */ jsxs(CheckoutSummary.Root, { planRef, productRef, className: rootClass, children: [
|
|
1748
|
+
/* @__PURE__ */ jsx7(CheckoutSummary.Product, { className: "solvapay-checkout-summary-product" }),
|
|
1749
|
+
/* @__PURE__ */ jsxs("div", { className: "solvapay-checkout-summary-row", children: [
|
|
1750
|
+
/* @__PURE__ */ jsx7(CheckoutSummary.Plan, { className: "solvapay-checkout-summary-plan" }),
|
|
1751
|
+
/* @__PURE__ */ jsx7(CheckoutSummary.Price, { className: "solvapay-checkout-summary-price" })
|
|
1752
|
+
] }),
|
|
1753
|
+
showTrial && /* @__PURE__ */ jsx7(CheckoutSummary.Trial, { className: "solvapay-checkout-summary-trial" }),
|
|
1754
|
+
showTaxNote && /* @__PURE__ */ jsx7(CheckoutSummary.TaxNote, { className: "solvapay-checkout-summary-tax-note" })
|
|
1755
|
+
] });
|
|
1756
|
+
};
|
|
1757
|
+
|
|
1758
|
+
// src/hooks/useMerchant.ts
|
|
1759
|
+
import { useCallback as useCallback7, useEffect as useEffect5, useState as useState7 } from "react";
|
|
1760
|
+
var merchantCache = /* @__PURE__ */ new Map();
|
|
1761
|
+
var CACHE_DURATION4 = 5 * 60 * 1e3;
|
|
1762
|
+
function cacheKeyFor(config) {
|
|
1763
|
+
return config?.api?.getMerchant || "/api/merchant";
|
|
1764
|
+
}
|
|
1765
|
+
async function fetchMerchant(config) {
|
|
1766
|
+
const route = cacheKeyFor(config);
|
|
1767
|
+
const fetchFn = config?.fetch || fetch;
|
|
1768
|
+
const { headers } = await buildRequestHeaders(config);
|
|
1769
|
+
const res = await fetchFn(route, { method: "GET", headers });
|
|
1770
|
+
if (!res.ok) {
|
|
1771
|
+
const error = new Error(`Failed to fetch merchant: ${res.statusText || res.status}`);
|
|
1772
|
+
config?.onError?.(error, "getMerchant");
|
|
1773
|
+
throw error;
|
|
1774
|
+
}
|
|
1775
|
+
return await res.json();
|
|
1776
|
+
}
|
|
1777
|
+
function useMerchant() {
|
|
1778
|
+
const { _config } = useSolvaPay();
|
|
1779
|
+
const key = cacheKeyFor(_config);
|
|
1780
|
+
const [merchant, setMerchant] = useState7(
|
|
1781
|
+
() => merchantCache.get(key)?.merchant ?? null
|
|
1782
|
+
);
|
|
1783
|
+
const [loading, setLoading] = useState7(() => {
|
|
1784
|
+
const cached = merchantCache.get(key);
|
|
1785
|
+
return !cached || !cached.merchant && !cached.promise;
|
|
1786
|
+
});
|
|
1787
|
+
const [error, setError] = useState7(null);
|
|
1788
|
+
const load = useCallback7(
|
|
1789
|
+
async (force = false) => {
|
|
1790
|
+
const cached = merchantCache.get(key);
|
|
1791
|
+
const now = Date.now();
|
|
1792
|
+
if (!force && cached?.merchant && now - cached.timestamp < CACHE_DURATION4) {
|
|
1793
|
+
setMerchant(cached.merchant);
|
|
1794
|
+
setLoading(false);
|
|
1795
|
+
setError(null);
|
|
1796
|
+
return;
|
|
1797
|
+
}
|
|
1798
|
+
if (!force && cached?.promise) {
|
|
1799
|
+
try {
|
|
1800
|
+
setLoading(true);
|
|
1801
|
+
const m = await cached.promise;
|
|
1802
|
+
setMerchant(m);
|
|
1803
|
+
setError(null);
|
|
1804
|
+
} catch (err) {
|
|
1805
|
+
setError(err instanceof Error ? err : new Error("Failed to load merchant"));
|
|
1806
|
+
} finally {
|
|
1807
|
+
setLoading(false);
|
|
1808
|
+
}
|
|
1809
|
+
return;
|
|
1810
|
+
}
|
|
1811
|
+
try {
|
|
1812
|
+
setLoading(true);
|
|
1813
|
+
setError(null);
|
|
1814
|
+
const promise = fetchMerchant(_config);
|
|
1815
|
+
merchantCache.set(key, { merchant: null, promise, timestamp: now });
|
|
1816
|
+
const m = await promise;
|
|
1817
|
+
merchantCache.set(key, { merchant: m, promise: null, timestamp: now });
|
|
1818
|
+
setMerchant(m);
|
|
1819
|
+
} catch (err) {
|
|
1820
|
+
merchantCache.delete(key);
|
|
1821
|
+
setError(err instanceof Error ? err : new Error("Failed to load merchant"));
|
|
1822
|
+
} finally {
|
|
1823
|
+
setLoading(false);
|
|
1824
|
+
}
|
|
1825
|
+
},
|
|
1826
|
+
[_config, key]
|
|
1827
|
+
);
|
|
1828
|
+
useEffect5(() => {
|
|
1829
|
+
load();
|
|
1830
|
+
}, [load]);
|
|
1831
|
+
return {
|
|
1832
|
+
merchant,
|
|
1833
|
+
loading,
|
|
1834
|
+
error,
|
|
1835
|
+
refetch: () => load(true)
|
|
1836
|
+
};
|
|
1837
|
+
}
|
|
1838
|
+
|
|
1839
|
+
// src/utils/checkoutVariant.ts
|
|
1840
|
+
function deriveVariant(plan, mode) {
|
|
1841
|
+
if (mode === "topup") return "topup";
|
|
1842
|
+
if (!plan?.type) return "oneTime";
|
|
1843
|
+
if (plan.type === "usage-based") {
|
|
1844
|
+
return plan.billingModel === "post-paid" ? "usageMetered" : "topup";
|
|
1845
|
+
}
|
|
1846
|
+
if (plan.requiresPayment === false) return "freeTier";
|
|
1847
|
+
switch (plan.type) {
|
|
1848
|
+
case "recurring":
|
|
1849
|
+
return "recurring";
|
|
1850
|
+
case "one-time":
|
|
1851
|
+
default:
|
|
1852
|
+
return "oneTime";
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
|
|
1856
|
+
// src/components/MandateText.tsx
|
|
1857
|
+
import { useMemo as useMemo5 } from "react";
|
|
1858
|
+
import { jsx as jsx8 } from "react/jsx-runtime";
|
|
1859
|
+
var MandateText = ({
|
|
1860
|
+
planRef,
|
|
1861
|
+
productRef,
|
|
1862
|
+
variant,
|
|
1863
|
+
mode,
|
|
1864
|
+
amountMinor,
|
|
1865
|
+
currency,
|
|
1866
|
+
className
|
|
1867
|
+
}) => {
|
|
1868
|
+
const locale = useLocale();
|
|
1869
|
+
const copy = useCopy();
|
|
1870
|
+
const planSelection = usePlanSelection();
|
|
1871
|
+
const resolvedPlanRef = planRef ?? planSelection?.selectedPlanRef ?? void 0;
|
|
1872
|
+
const resolvedProductRef = productRef ?? planSelection?.productRef;
|
|
1873
|
+
const { plan } = usePlan({ planRef: resolvedPlanRef, productRef: resolvedProductRef });
|
|
1874
|
+
const { product } = useProduct(resolvedProductRef);
|
|
1875
|
+
const { merchant } = useMerchant();
|
|
1876
|
+
const resolvedVariant = variant || deriveVariant(plan, mode);
|
|
1877
|
+
const effectiveAmount = amountMinor ?? plan?.price ?? 0;
|
|
1878
|
+
const effectiveCurrency = currency ?? plan?.currency ?? merchant?.defaultCurrency ?? "usd";
|
|
1879
|
+
const amountFormatted = formatPrice(effectiveAmount, effectiveCurrency, {
|
|
1880
|
+
locale,
|
|
1881
|
+
free: copy.interval.free
|
|
1882
|
+
});
|
|
1883
|
+
const ctx = useMemo5(
|
|
1884
|
+
() => ({
|
|
1885
|
+
merchant: {
|
|
1886
|
+
legalName: merchant?.legalName ?? merchant?.displayName ?? "",
|
|
1887
|
+
displayName: merchant?.displayName,
|
|
1888
|
+
supportEmail: merchant?.supportEmail,
|
|
1889
|
+
termsUrl: merchant?.termsUrl,
|
|
1890
|
+
privacyUrl: merchant?.privacyUrl
|
|
1891
|
+
},
|
|
1892
|
+
plan: plan ? {
|
|
1893
|
+
name: plan.name,
|
|
1894
|
+
interval: plan.interval,
|
|
1895
|
+
intervalCount: 1,
|
|
1896
|
+
trialDays: plan.trialDays,
|
|
1897
|
+
measures: plan.measures,
|
|
1898
|
+
billingCycle: plan.billingCycle
|
|
1899
|
+
} : void 0,
|
|
1900
|
+
product: product ? { name: product.name } : void 0,
|
|
1901
|
+
amountFormatted,
|
|
1902
|
+
trialDays: plan?.trialDays
|
|
1903
|
+
}),
|
|
1904
|
+
[merchant, plan, product, amountFormatted]
|
|
1905
|
+
);
|
|
1906
|
+
const template = copy.mandate[resolvedVariant];
|
|
1907
|
+
const text = typeof template === "function" ? template(ctx) : template;
|
|
1908
|
+
if (!text) return null;
|
|
1909
|
+
return /* @__PURE__ */ jsx8(
|
|
1910
|
+
"p",
|
|
1911
|
+
{
|
|
1912
|
+
className,
|
|
1913
|
+
"data-solvapay-mandate-text": "",
|
|
1914
|
+
style: {
|
|
1915
|
+
fontSize: 12,
|
|
1916
|
+
lineHeight: 1.5,
|
|
1917
|
+
color: "rgba(0,0,0,0.6)",
|
|
1918
|
+
margin: 0
|
|
1919
|
+
},
|
|
1920
|
+
children: text
|
|
1921
|
+
}
|
|
1922
|
+
);
|
|
1923
|
+
};
|
|
1924
|
+
|
|
1925
|
+
// src/components/Spinner.tsx
|
|
1926
|
+
import { jsx as jsx9, jsxs as jsxs2 } from "react/jsx-runtime";
|
|
1927
|
+
var Spinner = ({
|
|
1928
|
+
className = "",
|
|
1929
|
+
size = "md"
|
|
1930
|
+
}) => {
|
|
1931
|
+
const sizeClasses = {
|
|
1932
|
+
sm: "h-4 w-4",
|
|
1933
|
+
md: "h-5 w-5",
|
|
1934
|
+
lg: "h-6 w-6"
|
|
1935
|
+
};
|
|
1936
|
+
return /* @__PURE__ */ jsxs2(
|
|
1937
|
+
"svg",
|
|
1938
|
+
{
|
|
1939
|
+
className: `animate-spin ${sizeClasses[size]} ${className}`,
|
|
1940
|
+
xmlns: "http://www.w3.org/2000/svg",
|
|
1941
|
+
fill: "none",
|
|
1942
|
+
viewBox: "0 0 24 24",
|
|
1943
|
+
role: "status",
|
|
1944
|
+
"aria-busy": "true",
|
|
1945
|
+
children: [
|
|
1946
|
+
/* @__PURE__ */ jsx9("circle", { className: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "4" }),
|
|
1947
|
+
/* @__PURE__ */ jsx9(
|
|
1948
|
+
"path",
|
|
1949
|
+
{
|
|
1950
|
+
className: "opacity-75",
|
|
1951
|
+
fill: "currentColor",
|
|
1952
|
+
d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
|
|
1953
|
+
}
|
|
1954
|
+
)
|
|
1955
|
+
]
|
|
1956
|
+
}
|
|
1957
|
+
);
|
|
1958
|
+
};
|
|
1959
|
+
|
|
1960
|
+
// src/utils/confirmPayment.ts
|
|
1961
|
+
async function confirmPayment(input) {
|
|
1962
|
+
const { stripe, elements, clientSecret, mode, returnUrl, billingDetails, copy } = input;
|
|
1963
|
+
try {
|
|
1964
|
+
if (mode === "payment-element") {
|
|
1965
|
+
const paymentElement = elements.getElement("payment");
|
|
1966
|
+
if (!paymentElement) {
|
|
1967
|
+
return { status: "error", message: copy.errors.cardElementMissing };
|
|
1968
|
+
}
|
|
1969
|
+
const { error: error2, paymentIntent: paymentIntent2 } = await stripe.confirmPayment({
|
|
1970
|
+
elements,
|
|
1971
|
+
clientSecret,
|
|
1972
|
+
confirmParams: {
|
|
1973
|
+
return_url: returnUrl,
|
|
1974
|
+
payment_method_data: billingDetails ? { billing_details: billingDetails } : void 0
|
|
1975
|
+
},
|
|
1976
|
+
redirect: "if_required"
|
|
1977
|
+
});
|
|
1978
|
+
if (error2) {
|
|
1979
|
+
return { status: "error", message: error2.message || copy.errors.paymentUnexpected };
|
|
1980
|
+
}
|
|
1981
|
+
return mapIntent(paymentIntent2, copy);
|
|
1982
|
+
}
|
|
1983
|
+
const cardElement = elements.getElement("card");
|
|
1984
|
+
if (!cardElement) {
|
|
1985
|
+
return { status: "error", message: copy.errors.cardElementMissing };
|
|
1986
|
+
}
|
|
1987
|
+
const { error, paymentIntent } = await stripe.confirmCardPayment(clientSecret, {
|
|
1988
|
+
payment_method: {
|
|
1989
|
+
card: cardElement,
|
|
1990
|
+
billing_details: billingDetails
|
|
1991
|
+
}
|
|
1992
|
+
});
|
|
1993
|
+
if (error) {
|
|
1994
|
+
return { status: "error", message: error.message || copy.errors.paymentUnexpected };
|
|
1995
|
+
}
|
|
1996
|
+
return mapIntent(paymentIntent, copy);
|
|
1997
|
+
} catch (err) {
|
|
1998
|
+
return {
|
|
1999
|
+
status: "error",
|
|
2000
|
+
message: err instanceof Error ? err.message : copy.errors.paymentUnexpected
|
|
2001
|
+
};
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
function mapIntent(paymentIntent, copy) {
|
|
2005
|
+
if (!paymentIntent) {
|
|
2006
|
+
return { status: "error", message: copy.errors.paymentUnexpected };
|
|
2007
|
+
}
|
|
2008
|
+
if (paymentIntent.status === "succeeded") {
|
|
2009
|
+
return { status: "succeeded", paymentIntent };
|
|
2010
|
+
}
|
|
2011
|
+
if (paymentIntent.status === "requires_action") {
|
|
2012
|
+
return { status: "requires_action", message: copy.errors.paymentRequires3ds };
|
|
2013
|
+
}
|
|
2014
|
+
return {
|
|
2015
|
+
status: "other",
|
|
2016
|
+
message: interpolate(copy.errors.paymentStatusPrefix, {
|
|
2017
|
+
status: paymentIntent.status || "processing"
|
|
2018
|
+
}),
|
|
2019
|
+
paymentIntent
|
|
2020
|
+
};
|
|
2021
|
+
}
|
|
2022
|
+
|
|
2023
|
+
// src/utils/checkoutCta.ts
|
|
2024
|
+
function resolveCta(input) {
|
|
2025
|
+
if (input.override) return input.override;
|
|
2026
|
+
const { variant, plan, product, amountFormatted, copy } = input;
|
|
2027
|
+
if (variant === "recurring") {
|
|
2028
|
+
if (plan?.trialDays && plan.trialDays > 0) {
|
|
2029
|
+
return interpolate(copy.cta.trialStart, { trialDays: plan.trialDays });
|
|
2030
|
+
}
|
|
2031
|
+
return copy.cta.subscribe;
|
|
2032
|
+
}
|
|
2033
|
+
if (variant === "oneTime") {
|
|
2034
|
+
return interpolate(copy.cta.payAmount, { amount: amountFormatted });
|
|
2035
|
+
}
|
|
2036
|
+
if (variant === "topup") {
|
|
2037
|
+
return interpolate(copy.cta.addAmount, { amount: amountFormatted });
|
|
2038
|
+
}
|
|
2039
|
+
if (variant === "usageMetered" || variant === "freeTier") {
|
|
2040
|
+
const productName = product?.name ?? (typeof plan?.metadata?.productName === "string" ? plan.metadata.productName : plan?.name ?? "service");
|
|
2041
|
+
return interpolate(copy.cta.startUsing, { product: productName });
|
|
2042
|
+
}
|
|
2043
|
+
return copy.cta.payNow;
|
|
2044
|
+
}
|
|
2045
|
+
|
|
2046
|
+
// src/primitives/PaymentForm.tsx
|
|
2047
|
+
import {
|
|
2048
|
+
forwardRef as forwardRef2,
|
|
2049
|
+
useCallback as useCallback8,
|
|
2050
|
+
useContext as useContext6,
|
|
2051
|
+
useEffect as useEffect6,
|
|
2052
|
+
useMemo as useMemo6,
|
|
2053
|
+
useRef as useRef4,
|
|
2054
|
+
useState as useState8
|
|
2055
|
+
} from "react";
|
|
2056
|
+
import {
|
|
2057
|
+
Elements,
|
|
2058
|
+
useStripe,
|
|
2059
|
+
useElements,
|
|
2060
|
+
PaymentElement as StripePaymentElement,
|
|
2061
|
+
CardElement as StripeCardElement
|
|
2062
|
+
} from "@stripe/react-stripe-js";
|
|
2063
|
+
|
|
2064
|
+
// src/utils/processPaymentResult.ts
|
|
2065
|
+
async function reconcilePayment(input) {
|
|
2066
|
+
const { paymentIntentId, productRef, planRef, processPayment, refetchPurchase, copy } = input;
|
|
2067
|
+
if (!processPayment || !productRef) {
|
|
2068
|
+
try {
|
|
2069
|
+
await refetchPurchase();
|
|
2070
|
+
return { status: "success" };
|
|
2071
|
+
} catch (err) {
|
|
2072
|
+
return {
|
|
2073
|
+
status: "error",
|
|
2074
|
+
error: err instanceof Error ? err : new Error(String(err))
|
|
2075
|
+
};
|
|
2076
|
+
}
|
|
2077
|
+
}
|
|
2078
|
+
try {
|
|
2079
|
+
const result = await processPayment({ paymentIntentId, productRef, planRef });
|
|
2080
|
+
const isTimeout = result?.status === "timeout";
|
|
2081
|
+
if (isTimeout) {
|
|
2082
|
+
for (let attempt = 1; attempt <= 5; attempt++) {
|
|
2083
|
+
await new Promise((resolve) => setTimeout(resolve, attempt * 1e3));
|
|
2084
|
+
await refetchPurchase();
|
|
2085
|
+
}
|
|
2086
|
+
return {
|
|
2087
|
+
status: "timeout",
|
|
2088
|
+
error: new Error(copy.errors.paymentProcessingTimeout)
|
|
2089
|
+
};
|
|
2090
|
+
}
|
|
2091
|
+
await refetchPurchase();
|
|
2092
|
+
return { status: "success" };
|
|
2093
|
+
} catch (err) {
|
|
2094
|
+
return {
|
|
2095
|
+
status: "error",
|
|
2096
|
+
error: err instanceof Error ? err : new Error(String(err))
|
|
2097
|
+
};
|
|
2098
|
+
}
|
|
2099
|
+
}
|
|
2100
|
+
|
|
2101
|
+
// src/primitives/PaymentForm.tsx
|
|
2102
|
+
import { Fragment as Fragment2, jsx as jsx10, jsxs as jsxs3 } from "react/jsx-runtime";
|
|
2103
|
+
function toSubmitVariant(variant) {
|
|
2104
|
+
switch (variant) {
|
|
2105
|
+
case "freeTier":
|
|
2106
|
+
return "free";
|
|
2107
|
+
case "topup":
|
|
2108
|
+
return "topup";
|
|
2109
|
+
case "usageMetered":
|
|
2110
|
+
return "activate";
|
|
2111
|
+
default:
|
|
2112
|
+
return "paid";
|
|
2113
|
+
}
|
|
2114
|
+
}
|
|
2115
|
+
var Root2 = forwardRef2(function PaymentFormRoot(props, forwardedRef) {
|
|
2116
|
+
const {
|
|
2117
|
+
planRef,
|
|
2118
|
+
productRef,
|
|
2119
|
+
onSuccess,
|
|
2120
|
+
onResult,
|
|
2121
|
+
onFreePlan,
|
|
2122
|
+
onError,
|
|
2123
|
+
returnUrl,
|
|
2124
|
+
submitButtonText,
|
|
2125
|
+
className,
|
|
2126
|
+
buttonClassName,
|
|
2127
|
+
prefillCustomer,
|
|
2128
|
+
requireTermsAcceptance = false,
|
|
2129
|
+
children
|
|
2130
|
+
} = props;
|
|
2131
|
+
const solva = useContext6(SolvaPayContext);
|
|
2132
|
+
if (!solva) throw new MissingProviderError("PaymentForm");
|
|
2133
|
+
const copy = useCopy();
|
|
2134
|
+
const locale = useLocale();
|
|
2135
|
+
const planSelection = usePlanSelection();
|
|
2136
|
+
const effectivePlanRef = planRef ?? planSelection?.selectedPlanRef ?? void 0;
|
|
2137
|
+
const effectiveProductRef = productRef ?? planSelection?.productRef;
|
|
2138
|
+
const { plan: resolvedPlan } = usePlan({
|
|
2139
|
+
planRef: effectivePlanRef,
|
|
2140
|
+
productRef: effectiveProductRef
|
|
2141
|
+
});
|
|
2142
|
+
const isFreePlan = resolvedPlan?.requiresPayment === false;
|
|
2143
|
+
const {
|
|
2144
|
+
loading: checkoutLoading,
|
|
2145
|
+
error: checkoutError,
|
|
2146
|
+
clientSecret,
|
|
2147
|
+
startCheckout,
|
|
2148
|
+
stripePromise,
|
|
2149
|
+
resolvedPlanRef
|
|
2150
|
+
} = useCheckout({
|
|
2151
|
+
planRef: effectivePlanRef,
|
|
2152
|
+
productRef: effectiveProductRef,
|
|
2153
|
+
customer: prefillCustomer
|
|
2154
|
+
});
|
|
2155
|
+
const hasInitializedRef = useRef4(false);
|
|
2156
|
+
const hasPlanOrProduct = !!(effectivePlanRef || effectiveProductRef);
|
|
2157
|
+
useEffect6(() => {
|
|
2158
|
+
if (isFreePlan) return;
|
|
2159
|
+
if (!hasInitializedRef.current && hasPlanOrProduct && !checkoutLoading && !checkoutError && !clientSecret) {
|
|
2160
|
+
hasInitializedRef.current = true;
|
|
2161
|
+
startCheckout().catch(() => {
|
|
2162
|
+
hasInitializedRef.current = false;
|
|
2163
|
+
});
|
|
2164
|
+
}
|
|
2165
|
+
if (hasPlanOrProduct && clientSecret) {
|
|
2166
|
+
hasInitializedRef.current = true;
|
|
2167
|
+
}
|
|
2168
|
+
}, [
|
|
2169
|
+
hasPlanOrProduct,
|
|
2170
|
+
checkoutLoading,
|
|
2171
|
+
checkoutError,
|
|
2172
|
+
clientSecret,
|
|
2173
|
+
startCheckout,
|
|
2174
|
+
isFreePlan
|
|
2175
|
+
]);
|
|
2176
|
+
const finalReturnUrl = returnUrl || (typeof window !== "undefined" ? window.location.href : "/");
|
|
2177
|
+
const elementsOptions = useMemo6(() => {
|
|
2178
|
+
if (!clientSecret) return void 0;
|
|
2179
|
+
return { clientSecret, locale };
|
|
2180
|
+
}, [clientSecret, locale]);
|
|
2181
|
+
const shouldRenderElements = !!(stripePromise && clientSecret);
|
|
2182
|
+
if (!hasPlanOrProduct) {
|
|
2183
|
+
return /* @__PURE__ */ jsx10(
|
|
2184
|
+
"div",
|
|
2185
|
+
{
|
|
2186
|
+
ref: forwardedRef,
|
|
2187
|
+
className,
|
|
2188
|
+
"data-solvapay-payment-form": "",
|
|
2189
|
+
"data-state": "error",
|
|
2190
|
+
children: /* @__PURE__ */ jsx10("div", { "data-solvapay-payment-form-error": "", children: copy.errors.configMissingPlanOrProduct })
|
|
2191
|
+
}
|
|
2192
|
+
);
|
|
2193
|
+
}
|
|
2194
|
+
if (checkoutError) {
|
|
2195
|
+
return /* @__PURE__ */ jsx10(
|
|
2196
|
+
"div",
|
|
2197
|
+
{
|
|
2198
|
+
ref: forwardedRef,
|
|
2199
|
+
className,
|
|
2200
|
+
"data-solvapay-payment-form": "",
|
|
2201
|
+
"data-state": "error",
|
|
2202
|
+
children: /* @__PURE__ */ jsxs3("div", { "data-solvapay-payment-form-error": "", children: [
|
|
2203
|
+
copy.errors.paymentInitFailed,
|
|
2204
|
+
" ",
|
|
2205
|
+
checkoutError.message || copy.errors.unknownError
|
|
2206
|
+
] })
|
|
2207
|
+
}
|
|
2208
|
+
);
|
|
2209
|
+
}
|
|
2210
|
+
if (isFreePlan && resolvedPlan) {
|
|
2211
|
+
return /* @__PURE__ */ jsx10(
|
|
2212
|
+
"div",
|
|
2213
|
+
{
|
|
2214
|
+
ref: forwardedRef,
|
|
2215
|
+
className,
|
|
2216
|
+
"data-solvapay-payment-form": "",
|
|
2217
|
+
"data-state": "ready",
|
|
2218
|
+
"data-variant": "free",
|
|
2219
|
+
children: /* @__PURE__ */ jsx10(
|
|
2220
|
+
FreeInner,
|
|
2221
|
+
{
|
|
2222
|
+
planRef: effectivePlanRef,
|
|
2223
|
+
productRef: effectiveProductRef,
|
|
2224
|
+
plan: resolvedPlan,
|
|
2225
|
+
resolvedPlanRef,
|
|
2226
|
+
requireTermsAcceptance,
|
|
2227
|
+
submitButtonText,
|
|
2228
|
+
buttonClassName,
|
|
2229
|
+
onFreePlan,
|
|
2230
|
+
onResult,
|
|
2231
|
+
onError,
|
|
2232
|
+
children
|
|
2233
|
+
}
|
|
2234
|
+
)
|
|
2235
|
+
}
|
|
2236
|
+
);
|
|
2237
|
+
}
|
|
2238
|
+
if (shouldRenderElements && elementsOptions) {
|
|
2239
|
+
return /* @__PURE__ */ jsx10(
|
|
2240
|
+
"div",
|
|
2241
|
+
{
|
|
2242
|
+
ref: forwardedRef,
|
|
2243
|
+
className,
|
|
2244
|
+
"data-solvapay-payment-form": "",
|
|
2245
|
+
"data-state": "ready",
|
|
2246
|
+
"data-variant": "paid",
|
|
2247
|
+
children: /* @__PURE__ */ jsx10(Elements, { stripe: stripePromise, options: elementsOptions, children: /* @__PURE__ */ jsx10(
|
|
2248
|
+
PaidInner,
|
|
2249
|
+
{
|
|
2250
|
+
planRef: effectivePlanRef,
|
|
2251
|
+
productRef: effectiveProductRef,
|
|
2252
|
+
prefillCustomer,
|
|
2253
|
+
resolvedPlanRef,
|
|
2254
|
+
plan: resolvedPlan ?? null,
|
|
2255
|
+
clientSecret,
|
|
2256
|
+
returnUrl: finalReturnUrl,
|
|
2257
|
+
submitButtonText,
|
|
2258
|
+
buttonClassName,
|
|
2259
|
+
requireTermsAcceptance,
|
|
2260
|
+
onSuccess,
|
|
2261
|
+
onResult,
|
|
2262
|
+
onError,
|
|
2263
|
+
children
|
|
2264
|
+
}
|
|
2265
|
+
) }, clientSecret)
|
|
2266
|
+
}
|
|
2267
|
+
);
|
|
2268
|
+
}
|
|
2269
|
+
return /* @__PURE__ */ jsx10(
|
|
2270
|
+
"div",
|
|
2271
|
+
{
|
|
2272
|
+
ref: forwardedRef,
|
|
2273
|
+
className,
|
|
2274
|
+
"data-solvapay-payment-form": "",
|
|
2275
|
+
"data-state": "loading",
|
|
2276
|
+
children: /* @__PURE__ */ jsx10("div", { "data-solvapay-payment-form-loading": "", children: /* @__PURE__ */ jsx10(Spinner, { size: "md" }) })
|
|
2277
|
+
}
|
|
2278
|
+
);
|
|
2279
|
+
});
|
|
2280
|
+
var PaidInner = ({
|
|
2281
|
+
planRef,
|
|
2282
|
+
productRef,
|
|
2283
|
+
prefillCustomer,
|
|
2284
|
+
resolvedPlanRef,
|
|
2285
|
+
plan,
|
|
2286
|
+
clientSecret,
|
|
2287
|
+
returnUrl,
|
|
2288
|
+
submitButtonText,
|
|
2289
|
+
buttonClassName,
|
|
2290
|
+
requireTermsAcceptance,
|
|
2291
|
+
onSuccess,
|
|
2292
|
+
onResult,
|
|
2293
|
+
onError,
|
|
2294
|
+
children
|
|
2295
|
+
}) => {
|
|
2296
|
+
const stripe = useStripe();
|
|
2297
|
+
const elements = useElements();
|
|
2298
|
+
const copy = useCopy();
|
|
2299
|
+
const customer = useCustomer();
|
|
2300
|
+
const { processPayment } = useSolvaPay();
|
|
2301
|
+
const { refetch } = usePurchase();
|
|
2302
|
+
const [elementKind, setElementKind] = useState8(
|
|
2303
|
+
children ? null : "payment-element"
|
|
2304
|
+
);
|
|
2305
|
+
const [paymentInputComplete, setPaymentInputComplete] = useState8(false);
|
|
2306
|
+
const [termsAccepted, setTermsAccepted] = useState8(false);
|
|
2307
|
+
const [isProcessing, setIsProcessing] = useState8(false);
|
|
2308
|
+
const [error, setError] = useState8(null);
|
|
2309
|
+
const isReady = !!(stripe && elements);
|
|
2310
|
+
const canSubmit = isReady && !!clientSecret && !!elementKind && paymentInputComplete && (!requireTermsAcceptance || termsAccepted) && !isProcessing;
|
|
2311
|
+
const submit = useCallback8(async () => {
|
|
2312
|
+
if (!stripe || !elements || !clientSecret || !elementKind) {
|
|
2313
|
+
const msg2 = !stripe || !elements ? copy.errors.stripeUnavailable : copy.errors.paymentIntentUnavailable;
|
|
2314
|
+
setError(msg2);
|
|
2315
|
+
onError?.(new Error(msg2));
|
|
2316
|
+
return;
|
|
2317
|
+
}
|
|
2318
|
+
setError(null);
|
|
2319
|
+
setIsProcessing(true);
|
|
2320
|
+
const result = await confirmPayment({
|
|
2321
|
+
stripe,
|
|
2322
|
+
elements,
|
|
2323
|
+
clientSecret,
|
|
2324
|
+
mode: elementKind,
|
|
2325
|
+
returnUrl,
|
|
2326
|
+
billingDetails: {
|
|
2327
|
+
name: customer.name ?? prefillCustomer?.name,
|
|
2328
|
+
email: customer.email ?? prefillCustomer?.email
|
|
2329
|
+
},
|
|
2330
|
+
copy
|
|
2331
|
+
});
|
|
2332
|
+
if (result.status === "error") {
|
|
2333
|
+
setError(result.message);
|
|
2334
|
+
setIsProcessing(false);
|
|
2335
|
+
onError?.(new Error(result.message));
|
|
2336
|
+
return;
|
|
2337
|
+
}
|
|
2338
|
+
if (result.status === "requires_action" || result.status === "other") {
|
|
2339
|
+
setError(result.message);
|
|
2340
|
+
setIsProcessing(false);
|
|
2341
|
+
return;
|
|
2342
|
+
}
|
|
2343
|
+
const paymentIntent = result.paymentIntent;
|
|
2344
|
+
const reconcileResult = await reconcilePayment({
|
|
2345
|
+
paymentIntentId: paymentIntent.id,
|
|
2346
|
+
productRef,
|
|
2347
|
+
planRef: planRef || resolvedPlanRef || void 0,
|
|
2348
|
+
processPayment,
|
|
2349
|
+
refetchPurchase: refetch,
|
|
2350
|
+
copy
|
|
2351
|
+
});
|
|
2352
|
+
setIsProcessing(false);
|
|
2353
|
+
if (reconcileResult.status === "success") {
|
|
2354
|
+
const pi = paymentIntent;
|
|
2355
|
+
onSuccess?.(pi);
|
|
2356
|
+
const paid = { kind: "paid", paymentIntent: pi };
|
|
2357
|
+
onResult?.(paid);
|
|
2358
|
+
return;
|
|
2359
|
+
}
|
|
2360
|
+
const msg = reconcileResult.status === "timeout" ? reconcileResult.error.message : copy.errors.paymentProcessingFailed;
|
|
2361
|
+
setError(msg);
|
|
2362
|
+
onError?.(reconcileResult.error);
|
|
2363
|
+
}, [
|
|
2364
|
+
stripe,
|
|
2365
|
+
elements,
|
|
2366
|
+
clientSecret,
|
|
2367
|
+
elementKind,
|
|
2368
|
+
returnUrl,
|
|
2369
|
+
customer,
|
|
2370
|
+
prefillCustomer,
|
|
2371
|
+
copy,
|
|
2372
|
+
processPayment,
|
|
2373
|
+
productRef,
|
|
2374
|
+
planRef,
|
|
2375
|
+
resolvedPlanRef,
|
|
2376
|
+
refetch,
|
|
2377
|
+
onSuccess,
|
|
2378
|
+
onResult,
|
|
2379
|
+
onError
|
|
2380
|
+
]);
|
|
2381
|
+
const contextValue = useMemo6(
|
|
2382
|
+
() => ({
|
|
2383
|
+
planRef,
|
|
2384
|
+
productRef,
|
|
2385
|
+
prefillCustomer,
|
|
2386
|
+
resolvedPlanRef,
|
|
2387
|
+
plan,
|
|
2388
|
+
clientSecret,
|
|
2389
|
+
stripe: stripe ?? null,
|
|
2390
|
+
elements: elements ?? null,
|
|
2391
|
+
isProcessing,
|
|
2392
|
+
isReady,
|
|
2393
|
+
paymentInputComplete,
|
|
2394
|
+
termsAccepted,
|
|
2395
|
+
requireTermsAcceptance,
|
|
2396
|
+
canSubmit,
|
|
2397
|
+
error,
|
|
2398
|
+
elementKind,
|
|
2399
|
+
returnUrl,
|
|
2400
|
+
submitButtonText,
|
|
2401
|
+
buttonClassName,
|
|
2402
|
+
setElementKind,
|
|
2403
|
+
setPaymentInputComplete,
|
|
2404
|
+
setTermsAccepted,
|
|
2405
|
+
submit
|
|
2406
|
+
}),
|
|
2407
|
+
[
|
|
2408
|
+
planRef,
|
|
2409
|
+
productRef,
|
|
2410
|
+
prefillCustomer,
|
|
2411
|
+
resolvedPlanRef,
|
|
2412
|
+
plan,
|
|
2413
|
+
clientSecret,
|
|
2414
|
+
stripe,
|
|
2415
|
+
elements,
|
|
2416
|
+
isProcessing,
|
|
2417
|
+
isReady,
|
|
2418
|
+
paymentInputComplete,
|
|
2419
|
+
termsAccepted,
|
|
2420
|
+
requireTermsAcceptance,
|
|
2421
|
+
canSubmit,
|
|
2422
|
+
error,
|
|
2423
|
+
elementKind,
|
|
2424
|
+
returnUrl,
|
|
2425
|
+
submitButtonText,
|
|
2426
|
+
buttonClassName,
|
|
2427
|
+
submit
|
|
2428
|
+
]
|
|
2429
|
+
);
|
|
2430
|
+
return /* @__PURE__ */ jsx10(PaymentFormProvider, { value: contextValue, children });
|
|
2431
|
+
};
|
|
2432
|
+
var FreeInner = ({
|
|
2433
|
+
planRef,
|
|
2434
|
+
productRef,
|
|
2435
|
+
plan,
|
|
2436
|
+
resolvedPlanRef,
|
|
2437
|
+
requireTermsAcceptance,
|
|
2438
|
+
submitButtonText,
|
|
2439
|
+
buttonClassName,
|
|
2440
|
+
onFreePlan,
|
|
2441
|
+
onResult,
|
|
2442
|
+
onError,
|
|
2443
|
+
children
|
|
2444
|
+
}) => {
|
|
2445
|
+
const copy = useCopy();
|
|
2446
|
+
const { refetch } = usePurchase();
|
|
2447
|
+
const { activate, state, error: activationError, result: activationResult } = useActivation();
|
|
2448
|
+
const [termsAccepted, setTermsAccepted] = useState8(false);
|
|
2449
|
+
const [localError, setLocalError] = useState8(null);
|
|
2450
|
+
const resultFiredRef = useRef4(false);
|
|
2451
|
+
useEffect6(() => {
|
|
2452
|
+
if (state === "activated" && activationResult && !resultFiredRef.current) {
|
|
2453
|
+
resultFiredRef.current = true;
|
|
2454
|
+
const res = { kind: "activated", result: activationResult };
|
|
2455
|
+
onResult?.(res);
|
|
2456
|
+
refetch().catch(() => {
|
|
2457
|
+
});
|
|
2458
|
+
}
|
|
2459
|
+
}, [state, activationResult, onResult, refetch]);
|
|
2460
|
+
const isProcessing = state === "activating";
|
|
2461
|
+
const canSubmit = !isProcessing && (!requireTermsAcceptance || termsAccepted) && !!productRef;
|
|
2462
|
+
const submit = useCallback8(async () => {
|
|
2463
|
+
if (!productRef) {
|
|
2464
|
+
const msg = copy.errors.configMissingPlanOrProduct;
|
|
2465
|
+
setLocalError(msg);
|
|
2466
|
+
onError?.(new Error(msg));
|
|
2467
|
+
return;
|
|
2468
|
+
}
|
|
2469
|
+
setLocalError(null);
|
|
2470
|
+
try {
|
|
2471
|
+
if (onFreePlan) {
|
|
2472
|
+
await onFreePlan(plan);
|
|
2473
|
+
onResult?.({
|
|
2474
|
+
kind: "activated",
|
|
2475
|
+
result: {
|
|
2476
|
+
status: "activated",
|
|
2477
|
+
productRef,
|
|
2478
|
+
planRef: plan.reference
|
|
2479
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
2480
|
+
}
|
|
2481
|
+
});
|
|
2482
|
+
return;
|
|
2483
|
+
}
|
|
2484
|
+
await activate({ productRef, planRef: plan.reference });
|
|
2485
|
+
} catch (err) {
|
|
2486
|
+
const msg = err instanceof Error ? err.message : copy.activation.failed;
|
|
2487
|
+
setLocalError(msg);
|
|
2488
|
+
onError?.(err instanceof Error ? err : new Error(msg));
|
|
2489
|
+
}
|
|
2490
|
+
}, [productRef, plan, onFreePlan, activate, onResult, onError, copy]);
|
|
2491
|
+
const error = localError ?? activationError;
|
|
2492
|
+
const contextValue = useMemo6(
|
|
2493
|
+
() => ({
|
|
2494
|
+
planRef,
|
|
2495
|
+
productRef,
|
|
2496
|
+
prefillCustomer: void 0,
|
|
2497
|
+
resolvedPlanRef,
|
|
2498
|
+
plan,
|
|
2499
|
+
clientSecret: null,
|
|
2500
|
+
stripe: null,
|
|
2501
|
+
elements: null,
|
|
2502
|
+
isProcessing,
|
|
2503
|
+
isReady: true,
|
|
2504
|
+
paymentInputComplete: true,
|
|
2505
|
+
termsAccepted,
|
|
2506
|
+
requireTermsAcceptance,
|
|
2507
|
+
canSubmit,
|
|
2508
|
+
error,
|
|
2509
|
+
elementKind: null,
|
|
2510
|
+
returnUrl: "",
|
|
2511
|
+
submitButtonText,
|
|
2512
|
+
buttonClassName,
|
|
2513
|
+
setElementKind: () => {
|
|
2514
|
+
},
|
|
2515
|
+
setPaymentInputComplete: () => {
|
|
2516
|
+
},
|
|
2517
|
+
setTermsAccepted,
|
|
2518
|
+
submit
|
|
2519
|
+
}),
|
|
2520
|
+
[
|
|
2521
|
+
planRef,
|
|
2522
|
+
productRef,
|
|
2523
|
+
resolvedPlanRef,
|
|
2524
|
+
plan,
|
|
2525
|
+
isProcessing,
|
|
2526
|
+
termsAccepted,
|
|
2527
|
+
requireTermsAcceptance,
|
|
2528
|
+
canSubmit,
|
|
2529
|
+
error,
|
|
2530
|
+
submitButtonText,
|
|
2531
|
+
buttonClassName,
|
|
2532
|
+
submit
|
|
2533
|
+
]
|
|
2534
|
+
);
|
|
2535
|
+
return /* @__PURE__ */ jsx10(PaymentFormProvider, { value: contextValue, children });
|
|
2536
|
+
};
|
|
2537
|
+
var Summary = (props) => {
|
|
2538
|
+
const ctx = usePaymentForm();
|
|
2539
|
+
return /* @__PURE__ */ jsx10(
|
|
2540
|
+
CheckoutSummary2,
|
|
2541
|
+
{
|
|
2542
|
+
...props,
|
|
2543
|
+
planRef: ctx.planRef || ctx.resolvedPlanRef || void 0,
|
|
2544
|
+
productRef: ctx.productRef
|
|
2545
|
+
}
|
|
2546
|
+
);
|
|
2547
|
+
};
|
|
2548
|
+
var MandateTextPrimitive = (props) => {
|
|
2549
|
+
const ctx = usePaymentForm();
|
|
2550
|
+
return /* @__PURE__ */ jsx10(
|
|
2551
|
+
MandateText,
|
|
2552
|
+
{
|
|
2553
|
+
...props,
|
|
2554
|
+
planRef: ctx.planRef || ctx.resolvedPlanRef || void 0,
|
|
2555
|
+
productRef: ctx.productRef
|
|
2556
|
+
}
|
|
2557
|
+
);
|
|
2558
|
+
};
|
|
2559
|
+
var CustomerFields = forwardRef2(
|
|
2560
|
+
function PaymentFormCustomerFields({ asChild, readOnly: _readOnly = true, children, ...rest }, ref) {
|
|
2561
|
+
const copy = useCopy();
|
|
2562
|
+
const customer = useCustomer();
|
|
2563
|
+
const { prefillCustomer } = usePaymentForm();
|
|
2564
|
+
const email = customer.email ?? prefillCustomer?.email;
|
|
2565
|
+
const name = customer.name ?? prefillCustomer?.name;
|
|
2566
|
+
if (!email && !name) return null;
|
|
2567
|
+
const Comp = asChild ? Slot : "div";
|
|
2568
|
+
return /* @__PURE__ */ jsx10(Comp, { ref, "data-solvapay-payment-form-customer-fields": "", ...rest, children: children ?? /* @__PURE__ */ jsxs3(Fragment2, { children: [
|
|
2569
|
+
email && /* @__PURE__ */ jsxs3("div", { "data-solvapay-payment-form-customer-email": "", children: [
|
|
2570
|
+
/* @__PURE__ */ jsxs3("span", { children: [
|
|
2571
|
+
copy.customer.emailLabel,
|
|
2572
|
+
": "
|
|
2573
|
+
] }),
|
|
2574
|
+
/* @__PURE__ */ jsx10("span", { children: email })
|
|
2575
|
+
] }),
|
|
2576
|
+
name && /* @__PURE__ */ jsxs3("div", { "data-solvapay-payment-form-customer-name": "", children: [
|
|
2577
|
+
/* @__PURE__ */ jsxs3("span", { children: [
|
|
2578
|
+
copy.customer.nameLabel,
|
|
2579
|
+
": "
|
|
2580
|
+
] }),
|
|
2581
|
+
/* @__PURE__ */ jsx10("span", { children: name })
|
|
2582
|
+
] })
|
|
2583
|
+
] }) });
|
|
2584
|
+
}
|
|
2585
|
+
);
|
|
2586
|
+
var PaymentElementSlot = ({ options }) => {
|
|
2587
|
+
const { setElementKind, setPaymentInputComplete, isReady, stripe, elements } = usePaymentForm();
|
|
2588
|
+
const locale = useLocale();
|
|
2589
|
+
useEffect6(() => {
|
|
2590
|
+
if (stripe && elements) setElementKind("payment-element");
|
|
2591
|
+
}, [setElementKind, stripe, elements]);
|
|
2592
|
+
if (!stripe || !elements) return null;
|
|
2593
|
+
if (!isReady) {
|
|
2594
|
+
return /* @__PURE__ */ jsx10("div", { "data-solvapay-payment-form-loading": "", children: /* @__PURE__ */ jsx10(Spinner, { size: "sm" }) });
|
|
2595
|
+
}
|
|
2596
|
+
return /* @__PURE__ */ jsx10("div", { "data-solvapay-payment-form-payment-element": "", children: /* @__PURE__ */ jsx10(
|
|
2597
|
+
StripePaymentElement,
|
|
2598
|
+
{
|
|
2599
|
+
options,
|
|
2600
|
+
onChange: (e) => setPaymentInputComplete(e.complete)
|
|
2601
|
+
},
|
|
2602
|
+
locale || "default"
|
|
2603
|
+
) });
|
|
2604
|
+
};
|
|
2605
|
+
var CardElementSlot = ({ options }) => {
|
|
2606
|
+
const { setElementKind, setPaymentInputComplete, isReady, stripe, elements } = usePaymentForm();
|
|
2607
|
+
useEffect6(() => {
|
|
2608
|
+
if (stripe && elements) setElementKind("card-element");
|
|
2609
|
+
}, [setElementKind, stripe, elements]);
|
|
2610
|
+
if (!stripe || !elements) return null;
|
|
2611
|
+
if (!isReady) {
|
|
2612
|
+
return /* @__PURE__ */ jsx10("div", { "data-solvapay-payment-form-loading": "", children: /* @__PURE__ */ jsx10(Spinner, { size: "sm" }) });
|
|
2613
|
+
}
|
|
2614
|
+
return /* @__PURE__ */ jsx10("div", { "data-solvapay-payment-form-card-element": "", children: /* @__PURE__ */ jsx10(
|
|
2615
|
+
StripeCardElement,
|
|
2616
|
+
{
|
|
2617
|
+
options,
|
|
2618
|
+
onChange: (e) => setPaymentInputComplete(e.complete)
|
|
2619
|
+
}
|
|
2620
|
+
) });
|
|
2621
|
+
};
|
|
2622
|
+
var TermsCheckbox = forwardRef2(
|
|
2623
|
+
function PaymentFormTermsCheckbox({ asChild, label, children, ...rest }, ref) {
|
|
2624
|
+
const { termsAccepted, setTermsAccepted } = usePaymentForm();
|
|
2625
|
+
const copy = useCopy();
|
|
2626
|
+
const id = "solvapay-terms-checkbox";
|
|
2627
|
+
if (asChild) {
|
|
2628
|
+
return /* @__PURE__ */ jsx10(Slot, { ref, "data-solvapay-payment-form-terms": "", ...rest, children });
|
|
2629
|
+
}
|
|
2630
|
+
return /* @__PURE__ */ jsxs3(
|
|
2631
|
+
"label",
|
|
2632
|
+
{
|
|
2633
|
+
ref,
|
|
2634
|
+
htmlFor: id,
|
|
2635
|
+
"data-solvapay-payment-form-terms": "",
|
|
2636
|
+
...rest,
|
|
2637
|
+
children: [
|
|
2638
|
+
/* @__PURE__ */ jsx10(
|
|
2639
|
+
"input",
|
|
2640
|
+
{
|
|
2641
|
+
id,
|
|
2642
|
+
type: "checkbox",
|
|
2643
|
+
checked: termsAccepted,
|
|
2644
|
+
onChange: (e) => setTermsAccepted(e.target.checked)
|
|
2645
|
+
}
|
|
2646
|
+
),
|
|
2647
|
+
/* @__PURE__ */ jsx10("span", { children: label ?? copy.terms.checkboxLabel })
|
|
2648
|
+
]
|
|
2649
|
+
}
|
|
2650
|
+
);
|
|
2651
|
+
}
|
|
2652
|
+
);
|
|
2653
|
+
var SubmitButton = forwardRef2(
|
|
2654
|
+
function PaymentFormSubmitButton({ asChild, onClick, children, ...rest }, ref) {
|
|
2655
|
+
const ctx = usePaymentForm();
|
|
2656
|
+
const copy = useCopy();
|
|
2657
|
+
const locale = useLocale();
|
|
2658
|
+
const { plan } = usePlan({
|
|
2659
|
+
planRef: ctx.planRef || ctx.resolvedPlanRef || void 0,
|
|
2660
|
+
productRef: ctx.productRef
|
|
2661
|
+
});
|
|
2662
|
+
const { product } = useProduct(ctx.productRef);
|
|
2663
|
+
const variant = deriveVariant(plan ?? ctx.plan ?? void 0);
|
|
2664
|
+
const dataVariant = toSubmitVariant(variant);
|
|
2665
|
+
const dataState = ctx.isProcessing ? "processing" : !ctx.canSubmit ? "disabled" : "idle";
|
|
2666
|
+
const amountFormatted = formatPrice(
|
|
2667
|
+
plan?.price ?? ctx.plan?.price ?? 0,
|
|
2668
|
+
plan?.currency ?? ctx.plan?.currency ?? "usd",
|
|
2669
|
+
{ locale, free: copy.interval.free }
|
|
2670
|
+
);
|
|
2671
|
+
const label = resolveCta({
|
|
2672
|
+
variant,
|
|
2673
|
+
plan: plan ?? ctx.plan,
|
|
2674
|
+
product,
|
|
2675
|
+
amountFormatted,
|
|
2676
|
+
copy,
|
|
2677
|
+
override: typeof children === "string" ? children : ctx.submitButtonText
|
|
2678
|
+
});
|
|
2679
|
+
const content = ctx.isProcessing ? /* @__PURE__ */ jsxs3(Fragment2, { children: [
|
|
2680
|
+
/* @__PURE__ */ jsx10(Spinner, { size: "sm" }),
|
|
2681
|
+
/* @__PURE__ */ jsx10("span", { children: copy.cta.processing })
|
|
2682
|
+
] }) : children && typeof children !== "string" ? children : label;
|
|
2683
|
+
const buttonProps = {
|
|
2684
|
+
"data-solvapay-payment-form-submit": "",
|
|
2685
|
+
"data-state": dataState,
|
|
2686
|
+
"data-variant": dataVariant,
|
|
2687
|
+
"aria-busy": ctx.isProcessing,
|
|
2688
|
+
"aria-disabled": !ctx.canSubmit,
|
|
2689
|
+
"aria-label": label,
|
|
2690
|
+
disabled: !ctx.canSubmit,
|
|
2691
|
+
className: rest.className ?? ctx.buttonClassName,
|
|
2692
|
+
onClick: composeEventHandlers(onClick, (e) => {
|
|
2693
|
+
e.preventDefault();
|
|
2694
|
+
ctx.submit();
|
|
2695
|
+
}),
|
|
2696
|
+
...rest
|
|
2697
|
+
};
|
|
2698
|
+
if (asChild) {
|
|
2699
|
+
return (
|
|
2700
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
2701
|
+
/* @__PURE__ */ jsx10(Slot, { ref, ...buttonProps, children: content })
|
|
2702
|
+
);
|
|
2703
|
+
}
|
|
2704
|
+
return /* @__PURE__ */ jsx10("button", { ref, type: "submit", ...buttonProps, children: content });
|
|
2705
|
+
}
|
|
2706
|
+
);
|
|
2707
|
+
var Loading = forwardRef2(function PaymentFormLoading({ asChild, children, ...rest }, ref) {
|
|
2708
|
+
const ctx = usePaymentForm();
|
|
2709
|
+
if (ctx.isReady && ctx.clientSecret) return null;
|
|
2710
|
+
const Comp = asChild ? Slot : "div";
|
|
2711
|
+
return /* @__PURE__ */ jsx10(Comp, { ref, "data-solvapay-payment-form-loading": "", ...rest, children: children ?? /* @__PURE__ */ jsx10(Spinner, { size: "sm" }) });
|
|
2712
|
+
});
|
|
2713
|
+
var ErrorSlot = forwardRef2(function PaymentFormError({ asChild, children, ...rest }, ref) {
|
|
2714
|
+
const ctx = usePaymentForm();
|
|
2715
|
+
if (!ctx.error) return null;
|
|
2716
|
+
const Comp = asChild ? Slot : "div";
|
|
2717
|
+
return /* @__PURE__ */ jsx10(
|
|
2718
|
+
Comp,
|
|
2719
|
+
{
|
|
2720
|
+
ref,
|
|
2721
|
+
role: "alert",
|
|
2722
|
+
"aria-live": "assertive",
|
|
2723
|
+
"aria-atomic": "true",
|
|
2724
|
+
"data-solvapay-payment-form-error": "",
|
|
2725
|
+
...rest,
|
|
2726
|
+
children: children ?? ctx.error
|
|
2727
|
+
}
|
|
2728
|
+
);
|
|
2729
|
+
});
|
|
2730
|
+
var PaymentFormRoot2 = Root2;
|
|
2731
|
+
var PaymentFormSummary = Summary;
|
|
2732
|
+
var PaymentFormCustomerFields2 = CustomerFields;
|
|
2733
|
+
var PaymentFormPaymentElement = PaymentElementSlot;
|
|
2734
|
+
var PaymentFormCardElement = CardElementSlot;
|
|
2735
|
+
var PaymentFormMandateText = MandateTextPrimitive;
|
|
2736
|
+
var PaymentFormTermsCheckbox2 = TermsCheckbox;
|
|
2737
|
+
var PaymentFormSubmitButton2 = SubmitButton;
|
|
2738
|
+
var PaymentFormLoading2 = Loading;
|
|
2739
|
+
var PaymentFormError2 = ErrorSlot;
|
|
2740
|
+
var PaymentForm = {
|
|
2741
|
+
Root: Root2,
|
|
2742
|
+
Summary,
|
|
2743
|
+
CustomerFields,
|
|
2744
|
+
PaymentElement: PaymentElementSlot,
|
|
2745
|
+
CardElement: CardElementSlot,
|
|
2746
|
+
MandateText: MandateTextPrimitive,
|
|
2747
|
+
TermsCheckbox,
|
|
2748
|
+
SubmitButton,
|
|
2749
|
+
Loading,
|
|
2750
|
+
Error: ErrorSlot
|
|
2751
|
+
};
|
|
2752
|
+
|
|
2753
|
+
// src/primitives/PlanSelector.tsx
|
|
2754
|
+
import {
|
|
2755
|
+
createContext as createContext6,
|
|
2756
|
+
forwardRef as forwardRef3,
|
|
2757
|
+
useCallback as useCallback9,
|
|
2758
|
+
useContext as useContext7,
|
|
2759
|
+
useMemo as useMemo7
|
|
2760
|
+
} from "react";
|
|
2761
|
+
import { jsx as jsx11 } from "react/jsx-runtime";
|
|
2762
|
+
var PlanSelectorContext = createContext6(null);
|
|
2763
|
+
function usePlanSelectorContext(part) {
|
|
2764
|
+
const ctx = useContext7(PlanSelectorContext);
|
|
2765
|
+
if (!ctx) {
|
|
2766
|
+
throw new Error(`PlanSelector.${part} must be rendered inside <PlanSelector.Root>.`);
|
|
2767
|
+
}
|
|
2768
|
+
return ctx;
|
|
2769
|
+
}
|
|
2770
|
+
var CardContext = createContext6(null);
|
|
2771
|
+
function useCardContext(part) {
|
|
2772
|
+
const ctx = useContext7(CardContext);
|
|
2773
|
+
if (!ctx) {
|
|
2774
|
+
throw new Error(`PlanSelector.${part} must be rendered inside <PlanSelector.Card>.`);
|
|
2775
|
+
}
|
|
2776
|
+
return ctx;
|
|
2777
|
+
}
|
|
2778
|
+
async function defaultListPlans(productRef, config) {
|
|
2779
|
+
const base = config?.api?.listPlans || "/api/list-plans";
|
|
2780
|
+
const url = `${base}?productRef=${encodeURIComponent(productRef)}`;
|
|
2781
|
+
const fetchFn = config?.fetch || fetch;
|
|
2782
|
+
const { headers } = await buildRequestHeaders(config);
|
|
2783
|
+
const res = await fetchFn(url, { method: "GET", headers });
|
|
2784
|
+
if (!res.ok) {
|
|
2785
|
+
const error = new Error(`Failed to fetch plans: ${res.statusText || res.status}`);
|
|
2786
|
+
config?.onError?.(error, "listPlans");
|
|
2787
|
+
throw error;
|
|
2788
|
+
}
|
|
2789
|
+
const data = await res.json();
|
|
2790
|
+
return data.plans ?? [];
|
|
2791
|
+
}
|
|
2792
|
+
var Root3 = forwardRef3(function PlanSelectorRoot(props, forwardedRef) {
|
|
2793
|
+
const {
|
|
2794
|
+
productRef,
|
|
2795
|
+
fetcher,
|
|
2796
|
+
filter,
|
|
2797
|
+
sortBy,
|
|
2798
|
+
autoSelectFirstPaid = true,
|
|
2799
|
+
initialPlanRef,
|
|
2800
|
+
currentPlanRef,
|
|
2801
|
+
popularPlanRef,
|
|
2802
|
+
onSelect,
|
|
2803
|
+
children,
|
|
2804
|
+
...rest
|
|
2805
|
+
} = props;
|
|
2806
|
+
const solva = useContext7(SolvaPayContext);
|
|
2807
|
+
if (!solva) throw new MissingProviderError("PlanSelector");
|
|
2808
|
+
if (!productRef) throw new MissingProductRefError("PlanSelector");
|
|
2809
|
+
const { _config } = solva;
|
|
2810
|
+
const { purchases } = usePurchase();
|
|
2811
|
+
const effectiveFetcher = useMemo7(
|
|
2812
|
+
() => fetcher ?? ((ref) => defaultListPlans(ref, _config)),
|
|
2813
|
+
[fetcher, _config]
|
|
2814
|
+
);
|
|
2815
|
+
const { plans, selectedPlan, selectPlan, loading, error } = usePlans({
|
|
2816
|
+
productRef,
|
|
2817
|
+
fetcher: effectiveFetcher,
|
|
2818
|
+
filter,
|
|
2819
|
+
sortBy,
|
|
2820
|
+
autoSelectFirstPaid,
|
|
2821
|
+
initialPlanRef
|
|
2822
|
+
});
|
|
2823
|
+
const autoCurrentPlanRef = useMemo7(() => {
|
|
2824
|
+
const active = purchases.filter((p) => p.status === "active").sort((a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime())[0];
|
|
2825
|
+
return active?.planSnapshot?.reference ?? null;
|
|
2826
|
+
}, [purchases]);
|
|
2827
|
+
const resolvedCurrentPlanRef = currentPlanRef === null ? null : currentPlanRef ?? autoCurrentPlanRef;
|
|
2828
|
+
const isCurrent = useCallback9(
|
|
2829
|
+
(ref) => resolvedCurrentPlanRef === ref,
|
|
2830
|
+
[resolvedCurrentPlanRef]
|
|
2831
|
+
);
|
|
2832
|
+
const isFree = useCallback9(
|
|
2833
|
+
(ref) => plans.find((p) => p.reference === ref)?.requiresPayment === false,
|
|
2834
|
+
[plans]
|
|
2835
|
+
);
|
|
2836
|
+
const isPopular = useCallback9(
|
|
2837
|
+
(ref) => popularPlanRef === ref,
|
|
2838
|
+
[popularPlanRef]
|
|
2839
|
+
);
|
|
2840
|
+
const select = useCallback9(
|
|
2841
|
+
(ref) => {
|
|
2842
|
+
const plan = plans.find((p) => p.reference === ref);
|
|
2843
|
+
if (!plan) return;
|
|
2844
|
+
if (plan.requiresPayment === false) return;
|
|
2845
|
+
selectPlan(ref);
|
|
2846
|
+
onSelect?.(ref, plan);
|
|
2847
|
+
},
|
|
2848
|
+
[plans, selectPlan, onSelect]
|
|
2849
|
+
);
|
|
2850
|
+
const selectedPlanRef = selectedPlan?.reference ?? null;
|
|
2851
|
+
const ctx = useMemo7(
|
|
2852
|
+
() => ({
|
|
2853
|
+
plans,
|
|
2854
|
+
loading,
|
|
2855
|
+
error,
|
|
2856
|
+
selectedPlan: selectedPlan ?? null,
|
|
2857
|
+
selectedPlanRef,
|
|
2858
|
+
popularPlanRef,
|
|
2859
|
+
currentPlanRef: resolvedCurrentPlanRef,
|
|
2860
|
+
isCurrent,
|
|
2861
|
+
isFree,
|
|
2862
|
+
isPopular,
|
|
2863
|
+
select
|
|
2864
|
+
}),
|
|
2865
|
+
[
|
|
2866
|
+
plans,
|
|
2867
|
+
loading,
|
|
2868
|
+
error,
|
|
2869
|
+
selectedPlan,
|
|
2870
|
+
selectedPlanRef,
|
|
2871
|
+
popularPlanRef,
|
|
2872
|
+
resolvedCurrentPlanRef,
|
|
2873
|
+
isCurrent,
|
|
2874
|
+
isFree,
|
|
2875
|
+
isPopular,
|
|
2876
|
+
select
|
|
2877
|
+
]
|
|
2878
|
+
);
|
|
2879
|
+
return /* @__PURE__ */ jsx11(
|
|
2880
|
+
PlanSelectionProvider,
|
|
2881
|
+
{
|
|
2882
|
+
value: {
|
|
2883
|
+
productRef,
|
|
2884
|
+
selectedPlanRef,
|
|
2885
|
+
setSelectedPlanRef: (ref) => {
|
|
2886
|
+
if (ref) select(ref);
|
|
2887
|
+
},
|
|
2888
|
+
plans,
|
|
2889
|
+
loading,
|
|
2890
|
+
error
|
|
2891
|
+
},
|
|
2892
|
+
children: /* @__PURE__ */ jsx11("div", { ref: forwardedRef, "data-solvapay-plan-selector": "", ...rest, children: /* @__PURE__ */ jsx11(PlanSelectorContext.Provider, { value: ctx, children }) })
|
|
2893
|
+
}
|
|
2894
|
+
);
|
|
2895
|
+
});
|
|
2896
|
+
var Heading = forwardRef3(function PlanSelectorHeading({ asChild, children, ...rest }, forwardedRef) {
|
|
2897
|
+
usePlanSelectorContext("Heading");
|
|
2898
|
+
const copy = useCopy();
|
|
2899
|
+
const Comp = asChild ? Slot : "h3";
|
|
2900
|
+
return /* @__PURE__ */ jsx11(Comp, { ref: forwardedRef, "data-solvapay-plan-selector-heading": "", ...rest, children: children ?? copy.planSelector.heading });
|
|
2901
|
+
});
|
|
2902
|
+
var Grid = forwardRef3(function PlanSelectorGrid({ children, ...rest }, forwardedRef) {
|
|
2903
|
+
const ctx = usePlanSelectorContext("Grid");
|
|
2904
|
+
return /* @__PURE__ */ jsx11("div", { ref: forwardedRef, "data-solvapay-plan-selector-grid": "", ...rest, children: ctx.plans.map((plan) => {
|
|
2905
|
+
const isCurrent = ctx.isCurrent(plan.reference);
|
|
2906
|
+
const isFree = ctx.isFree(plan.reference);
|
|
2907
|
+
const isPopular = ctx.isPopular(plan.reference);
|
|
2908
|
+
const selected = ctx.selectedPlanRef === plan.reference;
|
|
2909
|
+
const disabled = isCurrent || isFree;
|
|
2910
|
+
const state = isCurrent ? "current" : isFree ? "disabled" : selected ? "selected" : "idle";
|
|
2911
|
+
const cardCtx = {
|
|
2912
|
+
plan,
|
|
2913
|
+
state,
|
|
2914
|
+
isCurrent,
|
|
2915
|
+
isFree,
|
|
2916
|
+
isPopular,
|
|
2917
|
+
disabled,
|
|
2918
|
+
select: () => ctx.select(plan.reference)
|
|
2919
|
+
};
|
|
2920
|
+
return /* @__PURE__ */ jsx11(CardContext.Provider, { value: cardCtx, children }, plan.reference);
|
|
2921
|
+
}) });
|
|
2922
|
+
});
|
|
2923
|
+
var Card = forwardRef3(function PlanSelectorCard({ asChild, onClick, children, ...rest }, forwardedRef) {
|
|
2924
|
+
const card = useCardContext("Card");
|
|
2925
|
+
const dataTrial = !!(card.plan.trialDays && card.plan.trialDays > 0);
|
|
2926
|
+
const commonProps = {
|
|
2927
|
+
"data-solvapay-plan-selector-card": "",
|
|
2928
|
+
"data-state": card.state,
|
|
2929
|
+
"data-free": card.isFree ? "" : void 0,
|
|
2930
|
+
"data-popular": card.isPopular ? "" : void 0,
|
|
2931
|
+
"data-trial": dataTrial ? "" : void 0,
|
|
2932
|
+
"aria-disabled": card.disabled || void 0,
|
|
2933
|
+
onClick: composeEventHandlers(onClick, () => {
|
|
2934
|
+
if (!card.disabled) card.select();
|
|
2935
|
+
}),
|
|
2936
|
+
...rest
|
|
2937
|
+
};
|
|
2938
|
+
if (asChild) {
|
|
2939
|
+
return (
|
|
2940
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
2941
|
+
/* @__PURE__ */ jsx11(Slot, { ref: forwardedRef, ...commonProps, children })
|
|
2942
|
+
);
|
|
2943
|
+
}
|
|
2944
|
+
return /* @__PURE__ */ jsx11(
|
|
2945
|
+
"button",
|
|
2946
|
+
{
|
|
2947
|
+
ref: forwardedRef,
|
|
2948
|
+
type: "button",
|
|
2949
|
+
disabled: card.disabled,
|
|
2950
|
+
...commonProps,
|
|
2951
|
+
children
|
|
2952
|
+
}
|
|
2953
|
+
);
|
|
2954
|
+
});
|
|
2955
|
+
var CardName = forwardRef3(function PlanSelectorCardName({ asChild, children, ...rest }, forwardedRef) {
|
|
2956
|
+
const card = useCardContext("CardName");
|
|
2957
|
+
if (!card.plan.name) return null;
|
|
2958
|
+
const Comp = asChild ? Slot : "span";
|
|
2959
|
+
return /* @__PURE__ */ jsx11(Comp, { ref: forwardedRef, "data-solvapay-plan-selector-card-name": "", ...rest, children: children ?? card.plan.name });
|
|
2960
|
+
});
|
|
2961
|
+
var CardPrice = forwardRef3(function PlanSelectorCardPrice({ asChild, children, ...rest }, forwardedRef) {
|
|
2962
|
+
const card = useCardContext("CardPrice");
|
|
2963
|
+
const locale = useLocale();
|
|
2964
|
+
const copy = useCopy();
|
|
2965
|
+
const formatted = useMemo7(() => {
|
|
2966
|
+
if (card.isFree) return copy.planSelector.freeBadge;
|
|
2967
|
+
return formatPrice(card.plan.price ?? 0, card.plan.currency ?? "usd", {
|
|
2968
|
+
locale,
|
|
2969
|
+
free: copy.interval.free
|
|
2970
|
+
});
|
|
2971
|
+
}, [
|
|
2972
|
+
card.isFree,
|
|
2973
|
+
card.plan.price,
|
|
2974
|
+
card.plan.currency,
|
|
2975
|
+
locale,
|
|
2976
|
+
copy.planSelector.freeBadge,
|
|
2977
|
+
copy.interval.free
|
|
2978
|
+
]);
|
|
2979
|
+
const Comp = asChild ? Slot : "span";
|
|
2980
|
+
return /* @__PURE__ */ jsx11(Comp, { ref: forwardedRef, "data-solvapay-plan-selector-card-price": "", ...rest, children: children ?? formatted });
|
|
2981
|
+
});
|
|
2982
|
+
var CardInterval = forwardRef3(function PlanSelectorCardInterval({ asChild, children, ...rest }, forwardedRef) {
|
|
2983
|
+
const card = useCardContext("CardInterval");
|
|
2984
|
+
const copy = useCopy();
|
|
2985
|
+
if (card.isFree || !card.plan.interval) return null;
|
|
2986
|
+
const text = interpolate(copy.planSelector.perIntervalShort, { interval: card.plan.interval });
|
|
2987
|
+
const Comp = asChild ? Slot : "span";
|
|
2988
|
+
return /* @__PURE__ */ jsx11(Comp, { ref: forwardedRef, "data-solvapay-plan-selector-card-interval": "", ...rest, children: children ?? text });
|
|
2989
|
+
});
|
|
2990
|
+
var CardBadge = forwardRef3(function PlanSelectorCardBadge({ asChild, children, ...rest }, forwardedRef) {
|
|
2991
|
+
const card = useCardContext("CardBadge");
|
|
2992
|
+
const copy = useCopy();
|
|
2993
|
+
let variant = null;
|
|
2994
|
+
let label = "";
|
|
2995
|
+
if (card.isCurrent) {
|
|
2996
|
+
variant = "current";
|
|
2997
|
+
label = copy.planSelector.currentBadge;
|
|
2998
|
+
} else if (card.isPopular && !card.isFree) {
|
|
2999
|
+
variant = "popular";
|
|
3000
|
+
label = copy.planSelector.popularBadge;
|
|
3001
|
+
}
|
|
3002
|
+
if (!variant) return null;
|
|
3003
|
+
const Comp = asChild ? Slot : "span";
|
|
3004
|
+
return /* @__PURE__ */ jsx11(
|
|
3005
|
+
Comp,
|
|
3006
|
+
{
|
|
3007
|
+
ref: forwardedRef,
|
|
3008
|
+
"data-solvapay-plan-selector-card-badge": "",
|
|
3009
|
+
"data-variant": variant,
|
|
3010
|
+
...rest,
|
|
3011
|
+
children: children ?? label
|
|
3012
|
+
}
|
|
3013
|
+
);
|
|
3014
|
+
});
|
|
3015
|
+
var Loading2 = forwardRef3(function PlanSelectorLoading({ asChild, children, ...rest }, forwardedRef) {
|
|
3016
|
+
const ctx = usePlanSelectorContext("Loading");
|
|
3017
|
+
if (!ctx.loading || ctx.plans.length > 0) return null;
|
|
3018
|
+
const Comp = asChild ? Slot : "div";
|
|
3019
|
+
return /* @__PURE__ */ jsx11(Comp, { ref: forwardedRef, "data-solvapay-plan-selector-loading": "", ...rest, children });
|
|
3020
|
+
});
|
|
3021
|
+
var ErrorSlot2 = forwardRef3(function PlanSelectorError({ asChild, children, ...rest }, forwardedRef) {
|
|
3022
|
+
const ctx = usePlanSelectorContext("Error");
|
|
3023
|
+
if (!ctx.error) return null;
|
|
3024
|
+
const Comp = asChild ? Slot : "div";
|
|
3025
|
+
return /* @__PURE__ */ jsx11(Comp, { ref: forwardedRef, "data-solvapay-plan-selector-error": "", role: "alert", ...rest, children: children ?? ctx.error.message });
|
|
3026
|
+
});
|
|
3027
|
+
var PlanSelectorRoot2 = Root3;
|
|
3028
|
+
var PlanSelectorHeading2 = Heading;
|
|
3029
|
+
var PlanSelectorGrid2 = Grid;
|
|
3030
|
+
var PlanSelectorCard2 = Card;
|
|
3031
|
+
var PlanSelectorCardName2 = CardName;
|
|
3032
|
+
var PlanSelectorCardPrice2 = CardPrice;
|
|
3033
|
+
var PlanSelectorCardInterval2 = CardInterval;
|
|
3034
|
+
var PlanSelectorCardBadge2 = CardBadge;
|
|
3035
|
+
var PlanSelectorLoading2 = Loading2;
|
|
3036
|
+
var PlanSelectorError2 = ErrorSlot2;
|
|
3037
|
+
var PlanSelector = {
|
|
3038
|
+
Root: Root3,
|
|
3039
|
+
Heading,
|
|
3040
|
+
Grid,
|
|
3041
|
+
Card,
|
|
3042
|
+
CardName,
|
|
3043
|
+
CardPrice,
|
|
3044
|
+
CardInterval,
|
|
3045
|
+
CardBadge,
|
|
3046
|
+
Loading: Loading2,
|
|
3047
|
+
Error: ErrorSlot2
|
|
3048
|
+
};
|
|
3049
|
+
function usePlanSelector() {
|
|
3050
|
+
return usePlanSelectorContext("usePlanSelector");
|
|
3051
|
+
}
|
|
3052
|
+
|
|
3053
|
+
export {
|
|
3054
|
+
filterPurchases,
|
|
3055
|
+
getActivePurchases,
|
|
3056
|
+
getCancelledPurchasesWithEndDate,
|
|
3057
|
+
getMostRecentPurchase,
|
|
3058
|
+
getPrimaryPurchase,
|
|
3059
|
+
isPaidPurchase,
|
|
3060
|
+
buildRequestHeaders,
|
|
3061
|
+
enCopy,
|
|
3062
|
+
mergeCopy,
|
|
3063
|
+
CopyContext,
|
|
3064
|
+
CopyProvider,
|
|
3065
|
+
SolvaPayContext,
|
|
3066
|
+
SolvaPayProvider,
|
|
3067
|
+
setRef,
|
|
3068
|
+
composeRefs,
|
|
3069
|
+
Slot,
|
|
3070
|
+
Slottable,
|
|
3071
|
+
composeEventHandlers,
|
|
3072
|
+
useSolvaPay,
|
|
3073
|
+
useCheckout,
|
|
3074
|
+
usePurchase,
|
|
3075
|
+
useCustomer,
|
|
3076
|
+
useCopy,
|
|
3077
|
+
useLocale,
|
|
3078
|
+
usePlans,
|
|
3079
|
+
usePlan,
|
|
3080
|
+
useProduct,
|
|
3081
|
+
useActivation,
|
|
3082
|
+
usePlanSelection,
|
|
3083
|
+
PaymentFormContext,
|
|
3084
|
+
usePaymentForm,
|
|
3085
|
+
PaymentFormProvider,
|
|
3086
|
+
formatPrice,
|
|
3087
|
+
interpolate,
|
|
3088
|
+
CheckoutSummaryRoot2 as CheckoutSummaryRoot,
|
|
3089
|
+
CheckoutSummaryProduct2 as CheckoutSummaryProduct,
|
|
3090
|
+
CheckoutSummaryPlan2 as CheckoutSummaryPlan,
|
|
3091
|
+
CheckoutSummaryPrice2 as CheckoutSummaryPrice,
|
|
3092
|
+
CheckoutSummaryTrial2 as CheckoutSummaryTrial,
|
|
3093
|
+
CheckoutSummaryTaxNote2 as CheckoutSummaryTaxNote,
|
|
3094
|
+
CheckoutSummary,
|
|
3095
|
+
useCheckoutSummary,
|
|
3096
|
+
CheckoutSummary2,
|
|
3097
|
+
useMerchant,
|
|
3098
|
+
deriveVariant,
|
|
3099
|
+
MandateText,
|
|
3100
|
+
Spinner,
|
|
3101
|
+
confirmPayment,
|
|
3102
|
+
resolveCta,
|
|
3103
|
+
PaymentFormRoot2 as PaymentFormRoot,
|
|
3104
|
+
PaymentFormSummary,
|
|
3105
|
+
PaymentFormCustomerFields2 as PaymentFormCustomerFields,
|
|
3106
|
+
PaymentFormPaymentElement,
|
|
3107
|
+
PaymentFormCardElement,
|
|
3108
|
+
PaymentFormMandateText,
|
|
3109
|
+
PaymentFormTermsCheckbox2 as PaymentFormTermsCheckbox,
|
|
3110
|
+
PaymentFormSubmitButton2 as PaymentFormSubmitButton,
|
|
3111
|
+
PaymentFormLoading2 as PaymentFormLoading,
|
|
3112
|
+
PaymentFormError2 as PaymentFormError,
|
|
3113
|
+
PaymentForm,
|
|
3114
|
+
PlanSelectorRoot2 as PlanSelectorRoot,
|
|
3115
|
+
PlanSelectorHeading2 as PlanSelectorHeading,
|
|
3116
|
+
PlanSelectorGrid2 as PlanSelectorGrid,
|
|
3117
|
+
PlanSelectorCard2 as PlanSelectorCard,
|
|
3118
|
+
PlanSelectorCardName2 as PlanSelectorCardName,
|
|
3119
|
+
PlanSelectorCardPrice2 as PlanSelectorCardPrice,
|
|
3120
|
+
PlanSelectorCardInterval2 as PlanSelectorCardInterval,
|
|
3121
|
+
PlanSelectorCardBadge2 as PlanSelectorCardBadge,
|
|
3122
|
+
PlanSelectorLoading2 as PlanSelectorLoading,
|
|
3123
|
+
PlanSelectorError2 as PlanSelectorError,
|
|
3124
|
+
PlanSelector,
|
|
3125
|
+
usePlanSelector
|
|
3126
|
+
};
|