@solvapay/react 1.0.8-preview.6 → 1.0.8-preview.8
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,4755 @@
|
|
|
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
|
+
hasProductRef: (productRef) => {
|
|
752
|
+
return purchaseData.purchases.some(
|
|
753
|
+
(p) => p.productRef === productRef && p.status === "active"
|
|
754
|
+
);
|
|
755
|
+
},
|
|
756
|
+
hasPlanRef: (planRef) => {
|
|
757
|
+
return purchaseData.purchases.some(
|
|
758
|
+
(p) => p.planRef === planRef && 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/primitives/MandateText.tsx
|
|
1857
|
+
import { forwardRef as forwardRef2, useContext as useContext6, useMemo as useMemo5 } from "react";
|
|
1858
|
+
import { jsx as jsx8 } from "react/jsx-runtime";
|
|
1859
|
+
var MandateText = forwardRef2(
|
|
1860
|
+
function MandateText2({
|
|
1861
|
+
planRef,
|
|
1862
|
+
productRef,
|
|
1863
|
+
variant,
|
|
1864
|
+
mode,
|
|
1865
|
+
amountMinor,
|
|
1866
|
+
currency,
|
|
1867
|
+
asChild,
|
|
1868
|
+
children,
|
|
1869
|
+
...rest
|
|
1870
|
+
}, forwardedRef) {
|
|
1871
|
+
const solva = useContext6(SolvaPayContext);
|
|
1872
|
+
if (!solva) throw new MissingProviderError("MandateText");
|
|
1873
|
+
const locale = useLocale();
|
|
1874
|
+
const copy = useCopy();
|
|
1875
|
+
const planSelection = usePlanSelection();
|
|
1876
|
+
const resolvedPlanRef = planRef ?? planSelection?.selectedPlanRef ?? void 0;
|
|
1877
|
+
const resolvedProductRef = productRef ?? planSelection?.productRef;
|
|
1878
|
+
const { plan } = usePlan({ planRef: resolvedPlanRef, productRef: resolvedProductRef });
|
|
1879
|
+
const { product } = useProduct(resolvedProductRef);
|
|
1880
|
+
const { merchant } = useMerchant();
|
|
1881
|
+
const resolvedVariant = variant || deriveVariant(plan, mode);
|
|
1882
|
+
const effectiveAmount = amountMinor ?? plan?.price ?? 0;
|
|
1883
|
+
const effectiveCurrency = currency ?? plan?.currency ?? merchant?.defaultCurrency ?? "usd";
|
|
1884
|
+
const amountFormatted = formatPrice(effectiveAmount, effectiveCurrency, {
|
|
1885
|
+
locale,
|
|
1886
|
+
free: copy.interval.free
|
|
1887
|
+
});
|
|
1888
|
+
const ctx = useMemo5(
|
|
1889
|
+
() => ({
|
|
1890
|
+
merchant: {
|
|
1891
|
+
legalName: merchant?.legalName ?? merchant?.displayName ?? "",
|
|
1892
|
+
displayName: merchant?.displayName,
|
|
1893
|
+
supportEmail: merchant?.supportEmail,
|
|
1894
|
+
termsUrl: merchant?.termsUrl,
|
|
1895
|
+
privacyUrl: merchant?.privacyUrl
|
|
1896
|
+
},
|
|
1897
|
+
plan: plan ? {
|
|
1898
|
+
name: plan.name,
|
|
1899
|
+
interval: plan.interval,
|
|
1900
|
+
intervalCount: 1,
|
|
1901
|
+
trialDays: plan.trialDays,
|
|
1902
|
+
measures: plan.measures,
|
|
1903
|
+
billingCycle: plan.billingCycle
|
|
1904
|
+
} : void 0,
|
|
1905
|
+
product: product ? { name: product.name } : void 0,
|
|
1906
|
+
amountFormatted,
|
|
1907
|
+
trialDays: plan?.trialDays
|
|
1908
|
+
}),
|
|
1909
|
+
[merchant, plan, product, amountFormatted]
|
|
1910
|
+
);
|
|
1911
|
+
const template = copy.mandate[resolvedVariant];
|
|
1912
|
+
const text = typeof template === "function" ? template(ctx) : template;
|
|
1913
|
+
if (!text) return null;
|
|
1914
|
+
const Comp = asChild ? Slot : "p";
|
|
1915
|
+
return /* @__PURE__ */ jsx8(
|
|
1916
|
+
Comp,
|
|
1917
|
+
{
|
|
1918
|
+
ref: forwardedRef,
|
|
1919
|
+
"data-solvapay-mandate-text": "",
|
|
1920
|
+
"data-variant": resolvedVariant,
|
|
1921
|
+
...rest,
|
|
1922
|
+
children: children ?? text
|
|
1923
|
+
}
|
|
1924
|
+
);
|
|
1925
|
+
}
|
|
1926
|
+
);
|
|
1927
|
+
|
|
1928
|
+
// src/components/Spinner.tsx
|
|
1929
|
+
import { jsx as jsx9, jsxs as jsxs2 } from "react/jsx-runtime";
|
|
1930
|
+
var Spinner = ({
|
|
1931
|
+
className = "",
|
|
1932
|
+
size = "md"
|
|
1933
|
+
}) => {
|
|
1934
|
+
const sizeClasses = {
|
|
1935
|
+
sm: "h-4 w-4",
|
|
1936
|
+
md: "h-5 w-5",
|
|
1937
|
+
lg: "h-6 w-6"
|
|
1938
|
+
};
|
|
1939
|
+
return /* @__PURE__ */ jsxs2(
|
|
1940
|
+
"svg",
|
|
1941
|
+
{
|
|
1942
|
+
className: `animate-spin ${sizeClasses[size]} ${className}`,
|
|
1943
|
+
xmlns: "http://www.w3.org/2000/svg",
|
|
1944
|
+
fill: "none",
|
|
1945
|
+
viewBox: "0 0 24 24",
|
|
1946
|
+
role: "status",
|
|
1947
|
+
"aria-busy": "true",
|
|
1948
|
+
children: [
|
|
1949
|
+
/* @__PURE__ */ jsx9("circle", { className: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "4" }),
|
|
1950
|
+
/* @__PURE__ */ jsx9(
|
|
1951
|
+
"path",
|
|
1952
|
+
{
|
|
1953
|
+
className: "opacity-75",
|
|
1954
|
+
fill: "currentColor",
|
|
1955
|
+
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"
|
|
1956
|
+
}
|
|
1957
|
+
)
|
|
1958
|
+
]
|
|
1959
|
+
}
|
|
1960
|
+
);
|
|
1961
|
+
};
|
|
1962
|
+
|
|
1963
|
+
// src/utils/confirmPayment.ts
|
|
1964
|
+
async function confirmPayment(input) {
|
|
1965
|
+
const { stripe, elements, clientSecret, mode, returnUrl, billingDetails, copy } = input;
|
|
1966
|
+
try {
|
|
1967
|
+
if (mode === "payment-element") {
|
|
1968
|
+
const paymentElement = elements.getElement("payment");
|
|
1969
|
+
if (!paymentElement) {
|
|
1970
|
+
return { status: "error", message: copy.errors.cardElementMissing };
|
|
1971
|
+
}
|
|
1972
|
+
const { error: error2, paymentIntent: paymentIntent2 } = await stripe.confirmPayment({
|
|
1973
|
+
elements,
|
|
1974
|
+
clientSecret,
|
|
1975
|
+
confirmParams: {
|
|
1976
|
+
return_url: returnUrl,
|
|
1977
|
+
payment_method_data: billingDetails ? { billing_details: billingDetails } : void 0
|
|
1978
|
+
},
|
|
1979
|
+
redirect: "if_required"
|
|
1980
|
+
});
|
|
1981
|
+
if (error2) {
|
|
1982
|
+
return { status: "error", message: error2.message || copy.errors.paymentUnexpected };
|
|
1983
|
+
}
|
|
1984
|
+
return mapIntent(paymentIntent2, copy);
|
|
1985
|
+
}
|
|
1986
|
+
const cardElement = elements.getElement("card");
|
|
1987
|
+
if (!cardElement) {
|
|
1988
|
+
return { status: "error", message: copy.errors.cardElementMissing };
|
|
1989
|
+
}
|
|
1990
|
+
const { error, paymentIntent } = await stripe.confirmCardPayment(clientSecret, {
|
|
1991
|
+
payment_method: {
|
|
1992
|
+
card: cardElement,
|
|
1993
|
+
billing_details: billingDetails
|
|
1994
|
+
}
|
|
1995
|
+
});
|
|
1996
|
+
if (error) {
|
|
1997
|
+
return { status: "error", message: error.message || copy.errors.paymentUnexpected };
|
|
1998
|
+
}
|
|
1999
|
+
return mapIntent(paymentIntent, copy);
|
|
2000
|
+
} catch (err) {
|
|
2001
|
+
return {
|
|
2002
|
+
status: "error",
|
|
2003
|
+
message: err instanceof Error ? err.message : copy.errors.paymentUnexpected
|
|
2004
|
+
};
|
|
2005
|
+
}
|
|
2006
|
+
}
|
|
2007
|
+
function mapIntent(paymentIntent, copy) {
|
|
2008
|
+
if (!paymentIntent) {
|
|
2009
|
+
return { status: "error", message: copy.errors.paymentUnexpected };
|
|
2010
|
+
}
|
|
2011
|
+
if (paymentIntent.status === "succeeded") {
|
|
2012
|
+
return { status: "succeeded", paymentIntent };
|
|
2013
|
+
}
|
|
2014
|
+
if (paymentIntent.status === "requires_action") {
|
|
2015
|
+
return { status: "requires_action", message: copy.errors.paymentRequires3ds };
|
|
2016
|
+
}
|
|
2017
|
+
return {
|
|
2018
|
+
status: "other",
|
|
2019
|
+
message: interpolate(copy.errors.paymentStatusPrefix, {
|
|
2020
|
+
status: paymentIntent.status || "processing"
|
|
2021
|
+
}),
|
|
2022
|
+
paymentIntent
|
|
2023
|
+
};
|
|
2024
|
+
}
|
|
2025
|
+
|
|
2026
|
+
// src/utils/checkoutCta.ts
|
|
2027
|
+
function resolveCta(input) {
|
|
2028
|
+
if (input.override) return input.override;
|
|
2029
|
+
const { variant, plan, product, amountFormatted, copy } = input;
|
|
2030
|
+
if (variant === "recurring") {
|
|
2031
|
+
if (plan?.trialDays && plan.trialDays > 0) {
|
|
2032
|
+
return interpolate(copy.cta.trialStart, { trialDays: plan.trialDays });
|
|
2033
|
+
}
|
|
2034
|
+
return copy.cta.subscribe;
|
|
2035
|
+
}
|
|
2036
|
+
if (variant === "oneTime") {
|
|
2037
|
+
return interpolate(copy.cta.payAmount, { amount: amountFormatted });
|
|
2038
|
+
}
|
|
2039
|
+
if (variant === "topup") {
|
|
2040
|
+
return interpolate(copy.cta.addAmount, { amount: amountFormatted });
|
|
2041
|
+
}
|
|
2042
|
+
if (variant === "usageMetered" || variant === "freeTier") {
|
|
2043
|
+
const productName = product?.name ?? (typeof plan?.metadata?.productName === "string" ? plan.metadata.productName : plan?.name ?? "service");
|
|
2044
|
+
return interpolate(copy.cta.startUsing, { product: productName });
|
|
2045
|
+
}
|
|
2046
|
+
return copy.cta.payNow;
|
|
2047
|
+
}
|
|
2048
|
+
|
|
2049
|
+
// src/primitives/PaymentForm.tsx
|
|
2050
|
+
import {
|
|
2051
|
+
forwardRef as forwardRef3,
|
|
2052
|
+
useCallback as useCallback8,
|
|
2053
|
+
useContext as useContext7,
|
|
2054
|
+
useEffect as useEffect6,
|
|
2055
|
+
useMemo as useMemo6,
|
|
2056
|
+
useRef as useRef4,
|
|
2057
|
+
useState as useState8
|
|
2058
|
+
} from "react";
|
|
2059
|
+
import {
|
|
2060
|
+
Elements,
|
|
2061
|
+
useStripe,
|
|
2062
|
+
useElements,
|
|
2063
|
+
PaymentElement as StripePaymentElement,
|
|
2064
|
+
CardElement as StripeCardElement
|
|
2065
|
+
} from "@stripe/react-stripe-js";
|
|
2066
|
+
|
|
2067
|
+
// src/utils/processPaymentResult.ts
|
|
2068
|
+
async function reconcilePayment(input) {
|
|
2069
|
+
const { paymentIntentId, productRef, planRef, processPayment, refetchPurchase, copy } = input;
|
|
2070
|
+
if (!processPayment || !productRef) {
|
|
2071
|
+
try {
|
|
2072
|
+
await refetchPurchase();
|
|
2073
|
+
return { status: "success" };
|
|
2074
|
+
} catch (err) {
|
|
2075
|
+
return {
|
|
2076
|
+
status: "error",
|
|
2077
|
+
error: err instanceof Error ? err : new Error(String(err))
|
|
2078
|
+
};
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
2081
|
+
try {
|
|
2082
|
+
const result = await processPayment({ paymentIntentId, productRef, planRef });
|
|
2083
|
+
const isTimeout = result?.status === "timeout";
|
|
2084
|
+
if (isTimeout) {
|
|
2085
|
+
for (let attempt = 1; attempt <= 5; attempt++) {
|
|
2086
|
+
await new Promise((resolve) => setTimeout(resolve, attempt * 1e3));
|
|
2087
|
+
await refetchPurchase();
|
|
2088
|
+
}
|
|
2089
|
+
return {
|
|
2090
|
+
status: "timeout",
|
|
2091
|
+
error: new Error(copy.errors.paymentProcessingTimeout)
|
|
2092
|
+
};
|
|
2093
|
+
}
|
|
2094
|
+
await refetchPurchase();
|
|
2095
|
+
return { status: "success" };
|
|
2096
|
+
} catch (err) {
|
|
2097
|
+
return {
|
|
2098
|
+
status: "error",
|
|
2099
|
+
error: err instanceof Error ? err : new Error(String(err))
|
|
2100
|
+
};
|
|
2101
|
+
}
|
|
2102
|
+
}
|
|
2103
|
+
|
|
2104
|
+
// src/primitives/PaymentForm.tsx
|
|
2105
|
+
import { Fragment as Fragment2, jsx as jsx10, jsxs as jsxs3 } from "react/jsx-runtime";
|
|
2106
|
+
function toSubmitVariant(variant) {
|
|
2107
|
+
switch (variant) {
|
|
2108
|
+
case "freeTier":
|
|
2109
|
+
return "free";
|
|
2110
|
+
case "topup":
|
|
2111
|
+
return "topup";
|
|
2112
|
+
case "usageMetered":
|
|
2113
|
+
return "activate";
|
|
2114
|
+
default:
|
|
2115
|
+
return "paid";
|
|
2116
|
+
}
|
|
2117
|
+
}
|
|
2118
|
+
var Root2 = forwardRef3(function PaymentFormRoot(props, forwardedRef) {
|
|
2119
|
+
const {
|
|
2120
|
+
planRef,
|
|
2121
|
+
productRef,
|
|
2122
|
+
onSuccess,
|
|
2123
|
+
onResult,
|
|
2124
|
+
onFreePlan,
|
|
2125
|
+
onError,
|
|
2126
|
+
returnUrl,
|
|
2127
|
+
submitButtonText,
|
|
2128
|
+
className,
|
|
2129
|
+
buttonClassName,
|
|
2130
|
+
prefillCustomer,
|
|
2131
|
+
requireTermsAcceptance = false,
|
|
2132
|
+
children
|
|
2133
|
+
} = props;
|
|
2134
|
+
const solva = useContext7(SolvaPayContext);
|
|
2135
|
+
if (!solva) throw new MissingProviderError("PaymentForm");
|
|
2136
|
+
const copy = useCopy();
|
|
2137
|
+
const locale = useLocale();
|
|
2138
|
+
const planSelection = usePlanSelection();
|
|
2139
|
+
const effectivePlanRef = planRef ?? planSelection?.selectedPlanRef ?? void 0;
|
|
2140
|
+
const effectiveProductRef = productRef ?? planSelection?.productRef;
|
|
2141
|
+
const { plan: resolvedPlan } = usePlan({
|
|
2142
|
+
planRef: effectivePlanRef,
|
|
2143
|
+
productRef: effectiveProductRef
|
|
2144
|
+
});
|
|
2145
|
+
const isFreePlan = resolvedPlan?.requiresPayment === false;
|
|
2146
|
+
const {
|
|
2147
|
+
loading: checkoutLoading,
|
|
2148
|
+
error: checkoutError,
|
|
2149
|
+
clientSecret,
|
|
2150
|
+
startCheckout,
|
|
2151
|
+
stripePromise,
|
|
2152
|
+
resolvedPlanRef
|
|
2153
|
+
} = useCheckout({
|
|
2154
|
+
planRef: effectivePlanRef,
|
|
2155
|
+
productRef: effectiveProductRef,
|
|
2156
|
+
customer: prefillCustomer
|
|
2157
|
+
});
|
|
2158
|
+
const hasInitializedRef = useRef4(false);
|
|
2159
|
+
const hasPlanOrProduct = !!(effectivePlanRef || effectiveProductRef);
|
|
2160
|
+
useEffect6(() => {
|
|
2161
|
+
if (isFreePlan) return;
|
|
2162
|
+
if (!hasInitializedRef.current && hasPlanOrProduct && !checkoutLoading && !checkoutError && !clientSecret) {
|
|
2163
|
+
hasInitializedRef.current = true;
|
|
2164
|
+
startCheckout().catch(() => {
|
|
2165
|
+
hasInitializedRef.current = false;
|
|
2166
|
+
});
|
|
2167
|
+
}
|
|
2168
|
+
if (hasPlanOrProduct && clientSecret) {
|
|
2169
|
+
hasInitializedRef.current = true;
|
|
2170
|
+
}
|
|
2171
|
+
}, [
|
|
2172
|
+
hasPlanOrProduct,
|
|
2173
|
+
checkoutLoading,
|
|
2174
|
+
checkoutError,
|
|
2175
|
+
clientSecret,
|
|
2176
|
+
startCheckout,
|
|
2177
|
+
isFreePlan
|
|
2178
|
+
]);
|
|
2179
|
+
const finalReturnUrl = returnUrl || (typeof window !== "undefined" ? window.location.href : "/");
|
|
2180
|
+
const elementsOptions = useMemo6(() => {
|
|
2181
|
+
if (!clientSecret) return void 0;
|
|
2182
|
+
return { clientSecret, locale };
|
|
2183
|
+
}, [clientSecret, locale]);
|
|
2184
|
+
const shouldRenderElements = !!(stripePromise && clientSecret);
|
|
2185
|
+
if (!hasPlanOrProduct) {
|
|
2186
|
+
return /* @__PURE__ */ jsx10(
|
|
2187
|
+
"div",
|
|
2188
|
+
{
|
|
2189
|
+
ref: forwardedRef,
|
|
2190
|
+
className,
|
|
2191
|
+
"data-solvapay-payment-form": "",
|
|
2192
|
+
"data-state": "error",
|
|
2193
|
+
children: /* @__PURE__ */ jsx10("div", { "data-solvapay-payment-form-error": "", children: copy.errors.configMissingPlanOrProduct })
|
|
2194
|
+
}
|
|
2195
|
+
);
|
|
2196
|
+
}
|
|
2197
|
+
if (checkoutError) {
|
|
2198
|
+
return /* @__PURE__ */ jsx10(
|
|
2199
|
+
"div",
|
|
2200
|
+
{
|
|
2201
|
+
ref: forwardedRef,
|
|
2202
|
+
className,
|
|
2203
|
+
"data-solvapay-payment-form": "",
|
|
2204
|
+
"data-state": "error",
|
|
2205
|
+
children: /* @__PURE__ */ jsxs3("div", { "data-solvapay-payment-form-error": "", children: [
|
|
2206
|
+
copy.errors.paymentInitFailed,
|
|
2207
|
+
" ",
|
|
2208
|
+
checkoutError.message || copy.errors.unknownError
|
|
2209
|
+
] })
|
|
2210
|
+
}
|
|
2211
|
+
);
|
|
2212
|
+
}
|
|
2213
|
+
if (isFreePlan && resolvedPlan) {
|
|
2214
|
+
return /* @__PURE__ */ jsx10(
|
|
2215
|
+
"div",
|
|
2216
|
+
{
|
|
2217
|
+
ref: forwardedRef,
|
|
2218
|
+
className,
|
|
2219
|
+
"data-solvapay-payment-form": "",
|
|
2220
|
+
"data-state": "ready",
|
|
2221
|
+
"data-variant": "free",
|
|
2222
|
+
children: /* @__PURE__ */ jsx10(
|
|
2223
|
+
FreeInner,
|
|
2224
|
+
{
|
|
2225
|
+
planRef: effectivePlanRef,
|
|
2226
|
+
productRef: effectiveProductRef,
|
|
2227
|
+
plan: resolvedPlan,
|
|
2228
|
+
resolvedPlanRef,
|
|
2229
|
+
requireTermsAcceptance,
|
|
2230
|
+
submitButtonText,
|
|
2231
|
+
buttonClassName,
|
|
2232
|
+
onFreePlan,
|
|
2233
|
+
onResult,
|
|
2234
|
+
onError,
|
|
2235
|
+
children
|
|
2236
|
+
}
|
|
2237
|
+
)
|
|
2238
|
+
}
|
|
2239
|
+
);
|
|
2240
|
+
}
|
|
2241
|
+
if (shouldRenderElements && elementsOptions) {
|
|
2242
|
+
return /* @__PURE__ */ jsx10(
|
|
2243
|
+
"div",
|
|
2244
|
+
{
|
|
2245
|
+
ref: forwardedRef,
|
|
2246
|
+
className,
|
|
2247
|
+
"data-solvapay-payment-form": "",
|
|
2248
|
+
"data-state": "ready",
|
|
2249
|
+
"data-variant": "paid",
|
|
2250
|
+
children: /* @__PURE__ */ jsx10(Elements, { stripe: stripePromise, options: elementsOptions, children: /* @__PURE__ */ jsx10(
|
|
2251
|
+
PaidInner,
|
|
2252
|
+
{
|
|
2253
|
+
planRef: effectivePlanRef,
|
|
2254
|
+
productRef: effectiveProductRef,
|
|
2255
|
+
prefillCustomer,
|
|
2256
|
+
resolvedPlanRef,
|
|
2257
|
+
plan: resolvedPlan ?? null,
|
|
2258
|
+
clientSecret,
|
|
2259
|
+
returnUrl: finalReturnUrl,
|
|
2260
|
+
submitButtonText,
|
|
2261
|
+
buttonClassName,
|
|
2262
|
+
requireTermsAcceptance,
|
|
2263
|
+
onSuccess,
|
|
2264
|
+
onResult,
|
|
2265
|
+
onError,
|
|
2266
|
+
children
|
|
2267
|
+
}
|
|
2268
|
+
) }, clientSecret)
|
|
2269
|
+
}
|
|
2270
|
+
);
|
|
2271
|
+
}
|
|
2272
|
+
return /* @__PURE__ */ jsx10(
|
|
2273
|
+
"div",
|
|
2274
|
+
{
|
|
2275
|
+
ref: forwardedRef,
|
|
2276
|
+
className,
|
|
2277
|
+
"data-solvapay-payment-form": "",
|
|
2278
|
+
"data-state": "loading",
|
|
2279
|
+
children: /* @__PURE__ */ jsx10("div", { "data-solvapay-payment-form-loading": "", children: /* @__PURE__ */ jsx10(Spinner, { size: "md" }) })
|
|
2280
|
+
}
|
|
2281
|
+
);
|
|
2282
|
+
});
|
|
2283
|
+
var PaidInner = ({
|
|
2284
|
+
planRef,
|
|
2285
|
+
productRef,
|
|
2286
|
+
prefillCustomer,
|
|
2287
|
+
resolvedPlanRef,
|
|
2288
|
+
plan,
|
|
2289
|
+
clientSecret,
|
|
2290
|
+
returnUrl,
|
|
2291
|
+
submitButtonText,
|
|
2292
|
+
buttonClassName,
|
|
2293
|
+
requireTermsAcceptance,
|
|
2294
|
+
onSuccess,
|
|
2295
|
+
onResult,
|
|
2296
|
+
onError,
|
|
2297
|
+
children
|
|
2298
|
+
}) => {
|
|
2299
|
+
const stripe = useStripe();
|
|
2300
|
+
const elements = useElements();
|
|
2301
|
+
const copy = useCopy();
|
|
2302
|
+
const customer = useCustomer();
|
|
2303
|
+
const { processPayment } = useSolvaPay();
|
|
2304
|
+
const { refetch } = usePurchase();
|
|
2305
|
+
const [elementKind, setElementKind] = useState8(
|
|
2306
|
+
children ? null : "payment-element"
|
|
2307
|
+
);
|
|
2308
|
+
const [paymentInputComplete, setPaymentInputComplete] = useState8(false);
|
|
2309
|
+
const [termsAccepted, setTermsAccepted] = useState8(false);
|
|
2310
|
+
const [isProcessing, setIsProcessing] = useState8(false);
|
|
2311
|
+
const [error, setError] = useState8(null);
|
|
2312
|
+
const isReady = !!(stripe && elements);
|
|
2313
|
+
const canSubmit = isReady && !!clientSecret && !!elementKind && paymentInputComplete && (!requireTermsAcceptance || termsAccepted) && !isProcessing;
|
|
2314
|
+
const submit = useCallback8(async () => {
|
|
2315
|
+
if (!stripe || !elements || !clientSecret || !elementKind) {
|
|
2316
|
+
const msg2 = !stripe || !elements ? copy.errors.stripeUnavailable : copy.errors.paymentIntentUnavailable;
|
|
2317
|
+
setError(msg2);
|
|
2318
|
+
onError?.(new Error(msg2));
|
|
2319
|
+
return;
|
|
2320
|
+
}
|
|
2321
|
+
setError(null);
|
|
2322
|
+
setIsProcessing(true);
|
|
2323
|
+
const result = await confirmPayment({
|
|
2324
|
+
stripe,
|
|
2325
|
+
elements,
|
|
2326
|
+
clientSecret,
|
|
2327
|
+
mode: elementKind,
|
|
2328
|
+
returnUrl,
|
|
2329
|
+
billingDetails: {
|
|
2330
|
+
name: customer.name ?? prefillCustomer?.name,
|
|
2331
|
+
email: customer.email ?? prefillCustomer?.email
|
|
2332
|
+
},
|
|
2333
|
+
copy
|
|
2334
|
+
});
|
|
2335
|
+
if (result.status === "error") {
|
|
2336
|
+
setError(result.message);
|
|
2337
|
+
setIsProcessing(false);
|
|
2338
|
+
onError?.(new Error(result.message));
|
|
2339
|
+
return;
|
|
2340
|
+
}
|
|
2341
|
+
if (result.status === "requires_action" || result.status === "other") {
|
|
2342
|
+
setError(result.message);
|
|
2343
|
+
setIsProcessing(false);
|
|
2344
|
+
return;
|
|
2345
|
+
}
|
|
2346
|
+
const paymentIntent = result.paymentIntent;
|
|
2347
|
+
const reconcileResult = await reconcilePayment({
|
|
2348
|
+
paymentIntentId: paymentIntent.id,
|
|
2349
|
+
productRef,
|
|
2350
|
+
planRef: planRef || resolvedPlanRef || void 0,
|
|
2351
|
+
processPayment,
|
|
2352
|
+
refetchPurchase: refetch,
|
|
2353
|
+
copy
|
|
2354
|
+
});
|
|
2355
|
+
setIsProcessing(false);
|
|
2356
|
+
if (reconcileResult.status === "success") {
|
|
2357
|
+
const pi = paymentIntent;
|
|
2358
|
+
onSuccess?.(pi);
|
|
2359
|
+
const paid = { kind: "paid", paymentIntent: pi };
|
|
2360
|
+
onResult?.(paid);
|
|
2361
|
+
return;
|
|
2362
|
+
}
|
|
2363
|
+
const msg = reconcileResult.status === "timeout" ? reconcileResult.error.message : copy.errors.paymentProcessingFailed;
|
|
2364
|
+
setError(msg);
|
|
2365
|
+
onError?.(reconcileResult.error);
|
|
2366
|
+
}, [
|
|
2367
|
+
stripe,
|
|
2368
|
+
elements,
|
|
2369
|
+
clientSecret,
|
|
2370
|
+
elementKind,
|
|
2371
|
+
returnUrl,
|
|
2372
|
+
customer,
|
|
2373
|
+
prefillCustomer,
|
|
2374
|
+
copy,
|
|
2375
|
+
processPayment,
|
|
2376
|
+
productRef,
|
|
2377
|
+
planRef,
|
|
2378
|
+
resolvedPlanRef,
|
|
2379
|
+
refetch,
|
|
2380
|
+
onSuccess,
|
|
2381
|
+
onResult,
|
|
2382
|
+
onError
|
|
2383
|
+
]);
|
|
2384
|
+
const contextValue = useMemo6(
|
|
2385
|
+
() => ({
|
|
2386
|
+
planRef,
|
|
2387
|
+
productRef,
|
|
2388
|
+
prefillCustomer,
|
|
2389
|
+
resolvedPlanRef,
|
|
2390
|
+
plan,
|
|
2391
|
+
clientSecret,
|
|
2392
|
+
stripe: stripe ?? null,
|
|
2393
|
+
elements: elements ?? null,
|
|
2394
|
+
isProcessing,
|
|
2395
|
+
isReady,
|
|
2396
|
+
paymentInputComplete,
|
|
2397
|
+
termsAccepted,
|
|
2398
|
+
requireTermsAcceptance,
|
|
2399
|
+
canSubmit,
|
|
2400
|
+
error,
|
|
2401
|
+
elementKind,
|
|
2402
|
+
returnUrl,
|
|
2403
|
+
submitButtonText,
|
|
2404
|
+
buttonClassName,
|
|
2405
|
+
setElementKind,
|
|
2406
|
+
setPaymentInputComplete,
|
|
2407
|
+
setTermsAccepted,
|
|
2408
|
+
submit
|
|
2409
|
+
}),
|
|
2410
|
+
[
|
|
2411
|
+
planRef,
|
|
2412
|
+
productRef,
|
|
2413
|
+
prefillCustomer,
|
|
2414
|
+
resolvedPlanRef,
|
|
2415
|
+
plan,
|
|
2416
|
+
clientSecret,
|
|
2417
|
+
stripe,
|
|
2418
|
+
elements,
|
|
2419
|
+
isProcessing,
|
|
2420
|
+
isReady,
|
|
2421
|
+
paymentInputComplete,
|
|
2422
|
+
termsAccepted,
|
|
2423
|
+
requireTermsAcceptance,
|
|
2424
|
+
canSubmit,
|
|
2425
|
+
error,
|
|
2426
|
+
elementKind,
|
|
2427
|
+
returnUrl,
|
|
2428
|
+
submitButtonText,
|
|
2429
|
+
buttonClassName,
|
|
2430
|
+
submit
|
|
2431
|
+
]
|
|
2432
|
+
);
|
|
2433
|
+
return /* @__PURE__ */ jsx10(PaymentFormProvider, { value: contextValue, children });
|
|
2434
|
+
};
|
|
2435
|
+
var FreeInner = ({
|
|
2436
|
+
planRef,
|
|
2437
|
+
productRef,
|
|
2438
|
+
plan,
|
|
2439
|
+
resolvedPlanRef,
|
|
2440
|
+
requireTermsAcceptance,
|
|
2441
|
+
submitButtonText,
|
|
2442
|
+
buttonClassName,
|
|
2443
|
+
onFreePlan,
|
|
2444
|
+
onResult,
|
|
2445
|
+
onError,
|
|
2446
|
+
children
|
|
2447
|
+
}) => {
|
|
2448
|
+
const copy = useCopy();
|
|
2449
|
+
const { refetch } = usePurchase();
|
|
2450
|
+
const { activate, state, error: activationError, result: activationResult } = useActivation();
|
|
2451
|
+
const [termsAccepted, setTermsAccepted] = useState8(false);
|
|
2452
|
+
const [localError, setLocalError] = useState8(null);
|
|
2453
|
+
const resultFiredRef = useRef4(false);
|
|
2454
|
+
useEffect6(() => {
|
|
2455
|
+
if (state === "activated" && activationResult && !resultFiredRef.current) {
|
|
2456
|
+
resultFiredRef.current = true;
|
|
2457
|
+
const res = { kind: "activated", result: activationResult };
|
|
2458
|
+
onResult?.(res);
|
|
2459
|
+
refetch().catch(() => {
|
|
2460
|
+
});
|
|
2461
|
+
}
|
|
2462
|
+
}, [state, activationResult, onResult, refetch]);
|
|
2463
|
+
const isProcessing = state === "activating";
|
|
2464
|
+
const canSubmit = !isProcessing && (!requireTermsAcceptance || termsAccepted) && !!productRef;
|
|
2465
|
+
const submit = useCallback8(async () => {
|
|
2466
|
+
if (!productRef) {
|
|
2467
|
+
const msg = copy.errors.configMissingPlanOrProduct;
|
|
2468
|
+
setLocalError(msg);
|
|
2469
|
+
onError?.(new Error(msg));
|
|
2470
|
+
return;
|
|
2471
|
+
}
|
|
2472
|
+
setLocalError(null);
|
|
2473
|
+
try {
|
|
2474
|
+
if (onFreePlan) {
|
|
2475
|
+
await onFreePlan(plan);
|
|
2476
|
+
onResult?.({
|
|
2477
|
+
kind: "activated",
|
|
2478
|
+
result: {
|
|
2479
|
+
status: "activated",
|
|
2480
|
+
productRef,
|
|
2481
|
+
planRef: plan.reference
|
|
2482
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
2483
|
+
}
|
|
2484
|
+
});
|
|
2485
|
+
return;
|
|
2486
|
+
}
|
|
2487
|
+
await activate({ productRef, planRef: plan.reference });
|
|
2488
|
+
} catch (err) {
|
|
2489
|
+
const msg = err instanceof Error ? err.message : copy.activation.failed;
|
|
2490
|
+
setLocalError(msg);
|
|
2491
|
+
onError?.(err instanceof Error ? err : new Error(msg));
|
|
2492
|
+
}
|
|
2493
|
+
}, [productRef, plan, onFreePlan, activate, onResult, onError, copy]);
|
|
2494
|
+
const error = localError ?? activationError;
|
|
2495
|
+
const contextValue = useMemo6(
|
|
2496
|
+
() => ({
|
|
2497
|
+
planRef,
|
|
2498
|
+
productRef,
|
|
2499
|
+
prefillCustomer: void 0,
|
|
2500
|
+
resolvedPlanRef,
|
|
2501
|
+
plan,
|
|
2502
|
+
clientSecret: null,
|
|
2503
|
+
stripe: null,
|
|
2504
|
+
elements: null,
|
|
2505
|
+
isProcessing,
|
|
2506
|
+
isReady: true,
|
|
2507
|
+
paymentInputComplete: true,
|
|
2508
|
+
termsAccepted,
|
|
2509
|
+
requireTermsAcceptance,
|
|
2510
|
+
canSubmit,
|
|
2511
|
+
error,
|
|
2512
|
+
elementKind: null,
|
|
2513
|
+
returnUrl: "",
|
|
2514
|
+
submitButtonText,
|
|
2515
|
+
buttonClassName,
|
|
2516
|
+
setElementKind: () => {
|
|
2517
|
+
},
|
|
2518
|
+
setPaymentInputComplete: () => {
|
|
2519
|
+
},
|
|
2520
|
+
setTermsAccepted,
|
|
2521
|
+
submit
|
|
2522
|
+
}),
|
|
2523
|
+
[
|
|
2524
|
+
planRef,
|
|
2525
|
+
productRef,
|
|
2526
|
+
resolvedPlanRef,
|
|
2527
|
+
plan,
|
|
2528
|
+
isProcessing,
|
|
2529
|
+
termsAccepted,
|
|
2530
|
+
requireTermsAcceptance,
|
|
2531
|
+
canSubmit,
|
|
2532
|
+
error,
|
|
2533
|
+
submitButtonText,
|
|
2534
|
+
buttonClassName,
|
|
2535
|
+
submit
|
|
2536
|
+
]
|
|
2537
|
+
);
|
|
2538
|
+
return /* @__PURE__ */ jsx10(PaymentFormProvider, { value: contextValue, children });
|
|
2539
|
+
};
|
|
2540
|
+
var Summary = (props) => {
|
|
2541
|
+
const ctx = usePaymentForm();
|
|
2542
|
+
return /* @__PURE__ */ jsx10(
|
|
2543
|
+
CheckoutSummary2,
|
|
2544
|
+
{
|
|
2545
|
+
...props,
|
|
2546
|
+
planRef: ctx.planRef || ctx.resolvedPlanRef || void 0,
|
|
2547
|
+
productRef: ctx.productRef
|
|
2548
|
+
}
|
|
2549
|
+
);
|
|
2550
|
+
};
|
|
2551
|
+
var MandateTextPrimitive = (props) => {
|
|
2552
|
+
const ctx = usePaymentForm();
|
|
2553
|
+
return /* @__PURE__ */ jsx10(
|
|
2554
|
+
MandateText,
|
|
2555
|
+
{
|
|
2556
|
+
...props,
|
|
2557
|
+
planRef: ctx.planRef || ctx.resolvedPlanRef || void 0,
|
|
2558
|
+
productRef: ctx.productRef
|
|
2559
|
+
}
|
|
2560
|
+
);
|
|
2561
|
+
};
|
|
2562
|
+
var CustomerFields = forwardRef3(
|
|
2563
|
+
function PaymentFormCustomerFields({ asChild, readOnly: _readOnly = true, children, ...rest }, ref) {
|
|
2564
|
+
const copy = useCopy();
|
|
2565
|
+
const customer = useCustomer();
|
|
2566
|
+
const { prefillCustomer } = usePaymentForm();
|
|
2567
|
+
const email = customer.email ?? prefillCustomer?.email;
|
|
2568
|
+
const name = customer.name ?? prefillCustomer?.name;
|
|
2569
|
+
if (!email && !name) return null;
|
|
2570
|
+
const Comp = asChild ? Slot : "div";
|
|
2571
|
+
return /* @__PURE__ */ jsx10(Comp, { ref, "data-solvapay-payment-form-customer-fields": "", ...rest, children: children ?? /* @__PURE__ */ jsxs3(Fragment2, { children: [
|
|
2572
|
+
email && /* @__PURE__ */ jsxs3("div", { "data-solvapay-payment-form-customer-email": "", children: [
|
|
2573
|
+
/* @__PURE__ */ jsxs3("span", { children: [
|
|
2574
|
+
copy.customer.emailLabel,
|
|
2575
|
+
": "
|
|
2576
|
+
] }),
|
|
2577
|
+
/* @__PURE__ */ jsx10("span", { children: email })
|
|
2578
|
+
] }),
|
|
2579
|
+
name && /* @__PURE__ */ jsxs3("div", { "data-solvapay-payment-form-customer-name": "", children: [
|
|
2580
|
+
/* @__PURE__ */ jsxs3("span", { children: [
|
|
2581
|
+
copy.customer.nameLabel,
|
|
2582
|
+
": "
|
|
2583
|
+
] }),
|
|
2584
|
+
/* @__PURE__ */ jsx10("span", { children: name })
|
|
2585
|
+
] })
|
|
2586
|
+
] }) });
|
|
2587
|
+
}
|
|
2588
|
+
);
|
|
2589
|
+
var PaymentElementSlot = ({ options }) => {
|
|
2590
|
+
const { setElementKind, setPaymentInputComplete, isReady, stripe, elements } = usePaymentForm();
|
|
2591
|
+
const locale = useLocale();
|
|
2592
|
+
useEffect6(() => {
|
|
2593
|
+
if (stripe && elements) setElementKind("payment-element");
|
|
2594
|
+
}, [setElementKind, stripe, elements]);
|
|
2595
|
+
if (!stripe || !elements) return null;
|
|
2596
|
+
if (!isReady) {
|
|
2597
|
+
return /* @__PURE__ */ jsx10("div", { "data-solvapay-payment-form-loading": "", children: /* @__PURE__ */ jsx10(Spinner, { size: "sm" }) });
|
|
2598
|
+
}
|
|
2599
|
+
return /* @__PURE__ */ jsx10("div", { "data-solvapay-payment-form-payment-element": "", children: /* @__PURE__ */ jsx10(
|
|
2600
|
+
StripePaymentElement,
|
|
2601
|
+
{
|
|
2602
|
+
options,
|
|
2603
|
+
onChange: (e) => setPaymentInputComplete(e.complete)
|
|
2604
|
+
},
|
|
2605
|
+
locale || "default"
|
|
2606
|
+
) });
|
|
2607
|
+
};
|
|
2608
|
+
var CardElementSlot = ({ options }) => {
|
|
2609
|
+
const { setElementKind, setPaymentInputComplete, isReady, stripe, elements } = usePaymentForm();
|
|
2610
|
+
useEffect6(() => {
|
|
2611
|
+
if (stripe && elements) setElementKind("card-element");
|
|
2612
|
+
}, [setElementKind, stripe, elements]);
|
|
2613
|
+
if (!stripe || !elements) return null;
|
|
2614
|
+
if (!isReady) {
|
|
2615
|
+
return /* @__PURE__ */ jsx10("div", { "data-solvapay-payment-form-loading": "", children: /* @__PURE__ */ jsx10(Spinner, { size: "sm" }) });
|
|
2616
|
+
}
|
|
2617
|
+
return /* @__PURE__ */ jsx10("div", { "data-solvapay-payment-form-card-element": "", children: /* @__PURE__ */ jsx10(
|
|
2618
|
+
StripeCardElement,
|
|
2619
|
+
{
|
|
2620
|
+
options,
|
|
2621
|
+
onChange: (e) => setPaymentInputComplete(e.complete)
|
|
2622
|
+
}
|
|
2623
|
+
) });
|
|
2624
|
+
};
|
|
2625
|
+
var TermsCheckbox = forwardRef3(
|
|
2626
|
+
function PaymentFormTermsCheckbox({ asChild, label, children, ...rest }, ref) {
|
|
2627
|
+
const { termsAccepted, setTermsAccepted } = usePaymentForm();
|
|
2628
|
+
const copy = useCopy();
|
|
2629
|
+
const id = "solvapay-terms-checkbox";
|
|
2630
|
+
if (asChild) {
|
|
2631
|
+
return /* @__PURE__ */ jsx10(Slot, { ref, "data-solvapay-payment-form-terms": "", ...rest, children });
|
|
2632
|
+
}
|
|
2633
|
+
return /* @__PURE__ */ jsxs3(
|
|
2634
|
+
"label",
|
|
2635
|
+
{
|
|
2636
|
+
ref,
|
|
2637
|
+
htmlFor: id,
|
|
2638
|
+
"data-solvapay-payment-form-terms": "",
|
|
2639
|
+
...rest,
|
|
2640
|
+
children: [
|
|
2641
|
+
/* @__PURE__ */ jsx10(
|
|
2642
|
+
"input",
|
|
2643
|
+
{
|
|
2644
|
+
id,
|
|
2645
|
+
type: "checkbox",
|
|
2646
|
+
checked: termsAccepted,
|
|
2647
|
+
onChange: (e) => setTermsAccepted(e.target.checked)
|
|
2648
|
+
}
|
|
2649
|
+
),
|
|
2650
|
+
/* @__PURE__ */ jsx10("span", { children: label ?? copy.terms.checkboxLabel })
|
|
2651
|
+
]
|
|
2652
|
+
}
|
|
2653
|
+
);
|
|
2654
|
+
}
|
|
2655
|
+
);
|
|
2656
|
+
var SubmitButton = forwardRef3(
|
|
2657
|
+
function PaymentFormSubmitButton({ asChild, onClick, children, ...rest }, ref) {
|
|
2658
|
+
const ctx = usePaymentForm();
|
|
2659
|
+
const copy = useCopy();
|
|
2660
|
+
const locale = useLocale();
|
|
2661
|
+
const { plan } = usePlan({
|
|
2662
|
+
planRef: ctx.planRef || ctx.resolvedPlanRef || void 0,
|
|
2663
|
+
productRef: ctx.productRef
|
|
2664
|
+
});
|
|
2665
|
+
const { product } = useProduct(ctx.productRef);
|
|
2666
|
+
const variant = deriveVariant(plan ?? ctx.plan ?? void 0);
|
|
2667
|
+
const dataVariant = toSubmitVariant(variant);
|
|
2668
|
+
const dataState = ctx.isProcessing ? "processing" : !ctx.canSubmit ? "disabled" : "idle";
|
|
2669
|
+
const amountFormatted = formatPrice(
|
|
2670
|
+
plan?.price ?? ctx.plan?.price ?? 0,
|
|
2671
|
+
plan?.currency ?? ctx.plan?.currency ?? "usd",
|
|
2672
|
+
{ locale, free: copy.interval.free }
|
|
2673
|
+
);
|
|
2674
|
+
const label = resolveCta({
|
|
2675
|
+
variant,
|
|
2676
|
+
plan: plan ?? ctx.plan,
|
|
2677
|
+
product,
|
|
2678
|
+
amountFormatted,
|
|
2679
|
+
copy,
|
|
2680
|
+
override: typeof children === "string" ? children : ctx.submitButtonText
|
|
2681
|
+
});
|
|
2682
|
+
const content = ctx.isProcessing ? /* @__PURE__ */ jsxs3(Fragment2, { children: [
|
|
2683
|
+
/* @__PURE__ */ jsx10(Spinner, { size: "sm" }),
|
|
2684
|
+
/* @__PURE__ */ jsx10("span", { children: copy.cta.processing })
|
|
2685
|
+
] }) : children && typeof children !== "string" ? children : label;
|
|
2686
|
+
const buttonProps = {
|
|
2687
|
+
"data-solvapay-payment-form-submit": "",
|
|
2688
|
+
"data-state": dataState,
|
|
2689
|
+
"data-variant": dataVariant,
|
|
2690
|
+
"aria-busy": ctx.isProcessing,
|
|
2691
|
+
"aria-disabled": !ctx.canSubmit,
|
|
2692
|
+
"aria-label": label,
|
|
2693
|
+
disabled: !ctx.canSubmit,
|
|
2694
|
+
className: rest.className ?? ctx.buttonClassName,
|
|
2695
|
+
onClick: composeEventHandlers(onClick, (e) => {
|
|
2696
|
+
e.preventDefault();
|
|
2697
|
+
ctx.submit();
|
|
2698
|
+
}),
|
|
2699
|
+
...rest
|
|
2700
|
+
};
|
|
2701
|
+
if (asChild) {
|
|
2702
|
+
return (
|
|
2703
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
2704
|
+
/* @__PURE__ */ jsx10(Slot, { ref, ...buttonProps, children: content })
|
|
2705
|
+
);
|
|
2706
|
+
}
|
|
2707
|
+
return /* @__PURE__ */ jsx10("button", { ref, type: "submit", ...buttonProps, children: content });
|
|
2708
|
+
}
|
|
2709
|
+
);
|
|
2710
|
+
var Loading = forwardRef3(function PaymentFormLoading({ asChild, children, ...rest }, ref) {
|
|
2711
|
+
const ctx = usePaymentForm();
|
|
2712
|
+
if (ctx.isReady && ctx.clientSecret) return null;
|
|
2713
|
+
const Comp = asChild ? Slot : "div";
|
|
2714
|
+
return /* @__PURE__ */ jsx10(Comp, { ref, "data-solvapay-payment-form-loading": "", ...rest, children: children ?? /* @__PURE__ */ jsx10(Spinner, { size: "sm" }) });
|
|
2715
|
+
});
|
|
2716
|
+
var ErrorSlot = forwardRef3(function PaymentFormError({ asChild, children, ...rest }, ref) {
|
|
2717
|
+
const ctx = usePaymentForm();
|
|
2718
|
+
if (!ctx.error) return null;
|
|
2719
|
+
const Comp = asChild ? Slot : "div";
|
|
2720
|
+
return /* @__PURE__ */ jsx10(
|
|
2721
|
+
Comp,
|
|
2722
|
+
{
|
|
2723
|
+
ref,
|
|
2724
|
+
role: "alert",
|
|
2725
|
+
"aria-live": "assertive",
|
|
2726
|
+
"aria-atomic": "true",
|
|
2727
|
+
"data-solvapay-payment-form-error": "",
|
|
2728
|
+
...rest,
|
|
2729
|
+
children: children ?? ctx.error
|
|
2730
|
+
}
|
|
2731
|
+
);
|
|
2732
|
+
});
|
|
2733
|
+
var PaymentFormRoot2 = Root2;
|
|
2734
|
+
var PaymentFormSummary = Summary;
|
|
2735
|
+
var PaymentFormCustomerFields2 = CustomerFields;
|
|
2736
|
+
var PaymentFormPaymentElement = PaymentElementSlot;
|
|
2737
|
+
var PaymentFormCardElement = CardElementSlot;
|
|
2738
|
+
var PaymentFormMandateText = MandateTextPrimitive;
|
|
2739
|
+
var PaymentFormTermsCheckbox2 = TermsCheckbox;
|
|
2740
|
+
var PaymentFormSubmitButton2 = SubmitButton;
|
|
2741
|
+
var PaymentFormLoading2 = Loading;
|
|
2742
|
+
var PaymentFormError2 = ErrorSlot;
|
|
2743
|
+
var PaymentForm = {
|
|
2744
|
+
Root: Root2,
|
|
2745
|
+
Summary,
|
|
2746
|
+
CustomerFields,
|
|
2747
|
+
PaymentElement: PaymentElementSlot,
|
|
2748
|
+
CardElement: CardElementSlot,
|
|
2749
|
+
MandateText: MandateTextPrimitive,
|
|
2750
|
+
TermsCheckbox,
|
|
2751
|
+
SubmitButton,
|
|
2752
|
+
Loading,
|
|
2753
|
+
Error: ErrorSlot
|
|
2754
|
+
};
|
|
2755
|
+
|
|
2756
|
+
// src/hooks/useTopupAmountSelector.ts
|
|
2757
|
+
import { useState as useState9, useCallback as useCallback9, useMemo as useMemo7 } from "react";
|
|
2758
|
+
function getQuickAmounts(currency) {
|
|
2759
|
+
switch (currency.toUpperCase()) {
|
|
2760
|
+
case "SEK":
|
|
2761
|
+
case "NOK":
|
|
2762
|
+
case "DKK":
|
|
2763
|
+
return [100, 500, 1e3, 5e3];
|
|
2764
|
+
case "JPY":
|
|
2765
|
+
return [1e3, 5e3, 1e4, 5e4];
|
|
2766
|
+
case "KRW":
|
|
2767
|
+
return [1e4, 5e4, 1e5, 5e5];
|
|
2768
|
+
case "ISK":
|
|
2769
|
+
case "HUF":
|
|
2770
|
+
return [1e3, 5e3, 1e4, 5e4];
|
|
2771
|
+
default:
|
|
2772
|
+
return [10, 50, 100, 500];
|
|
2773
|
+
}
|
|
2774
|
+
}
|
|
2775
|
+
function getCurrencySymbol(currency) {
|
|
2776
|
+
try {
|
|
2777
|
+
const parts = new Intl.NumberFormat("en", { style: "currency", currency }).formatToParts(0);
|
|
2778
|
+
const sym = parts.find((p) => p.type === "currency");
|
|
2779
|
+
return sym?.value || currency;
|
|
2780
|
+
} catch {
|
|
2781
|
+
return currency;
|
|
2782
|
+
}
|
|
2783
|
+
}
|
|
2784
|
+
var DEFAULT_MIN = 1;
|
|
2785
|
+
var DEFAULT_MAX = 1e5;
|
|
2786
|
+
function useTopupAmountSelector(options) {
|
|
2787
|
+
const { currency, minAmount = DEFAULT_MIN, maxAmount = DEFAULT_MAX } = options;
|
|
2788
|
+
const copy = useCopy();
|
|
2789
|
+
const [selectedAmount, setSelectedAmount] = useState9(null);
|
|
2790
|
+
const [customAmount, setCustomAmountRaw] = useState9("");
|
|
2791
|
+
const [error, setError] = useState9(null);
|
|
2792
|
+
const quickAmounts = useMemo7(() => getQuickAmounts(currency), [currency]);
|
|
2793
|
+
const currencySymbol = useMemo7(() => getCurrencySymbol(currency), [currency]);
|
|
2794
|
+
const resolvedAmount = useMemo7(() => {
|
|
2795
|
+
if (customAmount) {
|
|
2796
|
+
const parsed = parseFloat(customAmount);
|
|
2797
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
|
|
2798
|
+
}
|
|
2799
|
+
return selectedAmount;
|
|
2800
|
+
}, [selectedAmount, customAmount]);
|
|
2801
|
+
const selectQuickAmount = useCallback9(
|
|
2802
|
+
(amount) => {
|
|
2803
|
+
setSelectedAmount(amount);
|
|
2804
|
+
setCustomAmountRaw("");
|
|
2805
|
+
setError(null);
|
|
2806
|
+
},
|
|
2807
|
+
[]
|
|
2808
|
+
);
|
|
2809
|
+
const setCustomAmount = useCallback9(
|
|
2810
|
+
(value) => {
|
|
2811
|
+
const sanitized = value.replace(/[^0-9.]/g, "");
|
|
2812
|
+
const dotIndex = sanitized.indexOf(".");
|
|
2813
|
+
const cleaned = dotIndex === -1 ? sanitized : sanitized.slice(0, dotIndex + 1) + sanitized.slice(dotIndex + 1).replace(/\./g, "");
|
|
2814
|
+
setCustomAmountRaw(cleaned);
|
|
2815
|
+
setSelectedAmount(null);
|
|
2816
|
+
setError(null);
|
|
2817
|
+
},
|
|
2818
|
+
[]
|
|
2819
|
+
);
|
|
2820
|
+
const validate = useCallback9(() => {
|
|
2821
|
+
if (resolvedAmount == null) {
|
|
2822
|
+
setError(copy.topup.selectOrEnterAmount);
|
|
2823
|
+
return false;
|
|
2824
|
+
}
|
|
2825
|
+
if (resolvedAmount < minAmount) {
|
|
2826
|
+
setError(
|
|
2827
|
+
interpolate(copy.topup.minAmount, {
|
|
2828
|
+
amount: `${currencySymbol}${minAmount}`
|
|
2829
|
+
})
|
|
2830
|
+
);
|
|
2831
|
+
return false;
|
|
2832
|
+
}
|
|
2833
|
+
if (resolvedAmount > maxAmount) {
|
|
2834
|
+
setError(
|
|
2835
|
+
interpolate(copy.topup.maxAmount, {
|
|
2836
|
+
amount: `${currencySymbol}${maxAmount.toLocaleString()}`
|
|
2837
|
+
})
|
|
2838
|
+
);
|
|
2839
|
+
return false;
|
|
2840
|
+
}
|
|
2841
|
+
setError(null);
|
|
2842
|
+
return true;
|
|
2843
|
+
}, [resolvedAmount, minAmount, maxAmount, currencySymbol, copy]);
|
|
2844
|
+
const reset = useCallback9(() => {
|
|
2845
|
+
setSelectedAmount(null);
|
|
2846
|
+
setCustomAmountRaw("");
|
|
2847
|
+
setError(null);
|
|
2848
|
+
}, []);
|
|
2849
|
+
return {
|
|
2850
|
+
quickAmounts,
|
|
2851
|
+
selectedAmount,
|
|
2852
|
+
customAmount,
|
|
2853
|
+
resolvedAmount,
|
|
2854
|
+
selectQuickAmount,
|
|
2855
|
+
setCustomAmount,
|
|
2856
|
+
error,
|
|
2857
|
+
validate,
|
|
2858
|
+
reset,
|
|
2859
|
+
currencySymbol
|
|
2860
|
+
};
|
|
2861
|
+
}
|
|
2862
|
+
|
|
2863
|
+
// src/hooks/useBalance.ts
|
|
2864
|
+
import { useEffect as useEffect7 } from "react";
|
|
2865
|
+
function useBalance() {
|
|
2866
|
+
const { balance } = useSolvaPay();
|
|
2867
|
+
useEffect7(() => {
|
|
2868
|
+
balance.refetch();
|
|
2869
|
+
}, [balance.refetch]);
|
|
2870
|
+
return balance;
|
|
2871
|
+
}
|
|
2872
|
+
|
|
2873
|
+
// src/primitives/AmountPicker.tsx
|
|
2874
|
+
import {
|
|
2875
|
+
createContext as createContext6,
|
|
2876
|
+
forwardRef as forwardRef4,
|
|
2877
|
+
useCallback as useCallback10,
|
|
2878
|
+
useContext as useContext8,
|
|
2879
|
+
useEffect as useEffect8,
|
|
2880
|
+
useMemo as useMemo8
|
|
2881
|
+
} from "react";
|
|
2882
|
+
import { Fragment as Fragment3, jsx as jsx11, jsxs as jsxs4 } from "react/jsx-runtime";
|
|
2883
|
+
var AmountPickerContext = createContext6(null);
|
|
2884
|
+
function usePickerCtx(part) {
|
|
2885
|
+
const ctx = useContext8(AmountPickerContext);
|
|
2886
|
+
if (!ctx) {
|
|
2887
|
+
throw new Error(`AmountPicker.${part} must be rendered inside <AmountPicker.Root>.`);
|
|
2888
|
+
}
|
|
2889
|
+
return ctx;
|
|
2890
|
+
}
|
|
2891
|
+
var Root3 = forwardRef4(function AmountPickerRoot({ currency, minAmount, maxAmount, onChange, asChild, children, ...rest }, forwardedRef) {
|
|
2892
|
+
const solva = useContext8(SolvaPayContext);
|
|
2893
|
+
if (!solva) throw new MissingProviderError("AmountPicker");
|
|
2894
|
+
const selector = useTopupAmountSelector({ currency, minAmount, maxAmount });
|
|
2895
|
+
const { creditsPerMinorUnit, displayExchangeRate } = useBalance();
|
|
2896
|
+
useEffect8(() => {
|
|
2897
|
+
onChange?.(selector.resolvedAmount);
|
|
2898
|
+
}, [selector.resolvedAmount, onChange]);
|
|
2899
|
+
const resolvedAmountMinor = selector.resolvedAmount != null && selector.resolvedAmount > 0 ? Math.round(selector.resolvedAmount * 100) : null;
|
|
2900
|
+
const rate = displayExchangeRate ?? 1;
|
|
2901
|
+
const estimatedCredits = creditsPerMinorUnit != null && creditsPerMinorUnit > 0 && resolvedAmountMinor != null ? Math.floor(resolvedAmountMinor / rate * creditsPerMinorUnit) : null;
|
|
2902
|
+
const isApproximate = rate !== 1;
|
|
2903
|
+
const ctx = useMemo8(
|
|
2904
|
+
() => ({
|
|
2905
|
+
...selector,
|
|
2906
|
+
currency,
|
|
2907
|
+
creditsPerMinorUnit,
|
|
2908
|
+
displayExchangeRate,
|
|
2909
|
+
estimatedCredits,
|
|
2910
|
+
isApproximate
|
|
2911
|
+
}),
|
|
2912
|
+
[selector, currency, creditsPerMinorUnit, displayExchangeRate, estimatedCredits, isApproximate]
|
|
2913
|
+
);
|
|
2914
|
+
const Comp = asChild ? Slot : "div";
|
|
2915
|
+
return /* @__PURE__ */ jsx11(AmountPickerContext.Provider, { value: ctx, children: /* @__PURE__ */ jsx11(Comp, { ref: forwardedRef, "data-solvapay-amount-picker": "", ...rest, children }) });
|
|
2916
|
+
});
|
|
2917
|
+
var Option = forwardRef4(function AmountPickerOption({ asChild, amount, onClick, children, ...rest }, forwardedRef) {
|
|
2918
|
+
const ctx = usePickerCtx("Option");
|
|
2919
|
+
const isActive = ctx.selectedAmount === amount && !ctx.customAmount;
|
|
2920
|
+
const state = rest.disabled ? "disabled" : isActive ? "selected" : "idle";
|
|
2921
|
+
const commonProps = {
|
|
2922
|
+
"data-solvapay-amount-picker-option": "",
|
|
2923
|
+
"data-state": state,
|
|
2924
|
+
"data-amount": String(amount),
|
|
2925
|
+
"aria-pressed": isActive,
|
|
2926
|
+
onClick: composeEventHandlers(onClick, () => {
|
|
2927
|
+
ctx.selectQuickAmount(amount);
|
|
2928
|
+
}),
|
|
2929
|
+
...rest
|
|
2930
|
+
};
|
|
2931
|
+
if (asChild) {
|
|
2932
|
+
return (
|
|
2933
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
2934
|
+
/* @__PURE__ */ jsx11(Slot, { ref: forwardedRef, ...commonProps, children: children ?? /* @__PURE__ */ jsxs4(Fragment3, { children: [
|
|
2935
|
+
ctx.currencySymbol,
|
|
2936
|
+
amount.toLocaleString()
|
|
2937
|
+
] }) })
|
|
2938
|
+
);
|
|
2939
|
+
}
|
|
2940
|
+
return /* @__PURE__ */ jsx11("button", { ref: forwardedRef, type: "button", ...commonProps, children: children ?? /* @__PURE__ */ jsxs4(Fragment3, { children: [
|
|
2941
|
+
ctx.currencySymbol,
|
|
2942
|
+
amount.toLocaleString()
|
|
2943
|
+
] }) });
|
|
2944
|
+
});
|
|
2945
|
+
var Custom = forwardRef4(function AmountPickerCustom({ asChild, onChange, onFocus, ...rest }, forwardedRef) {
|
|
2946
|
+
const ctx = usePickerCtx("Custom");
|
|
2947
|
+
const state = ctx.customAmount ? "active" : "dormant";
|
|
2948
|
+
const commonProps = {
|
|
2949
|
+
"data-solvapay-amount-picker-custom": "",
|
|
2950
|
+
"data-state": state,
|
|
2951
|
+
type: "text",
|
|
2952
|
+
inputMode: "decimal",
|
|
2953
|
+
placeholder: "0.00",
|
|
2954
|
+
value: ctx.customAmount,
|
|
2955
|
+
onChange: composeEventHandlers(onChange, (e) => {
|
|
2956
|
+
ctx.setCustomAmount(e.target.value);
|
|
2957
|
+
}),
|
|
2958
|
+
onFocus: composeEventHandlers(onFocus, () => {
|
|
2959
|
+
if (ctx.selectedAmount != null) ctx.selectQuickAmount(0);
|
|
2960
|
+
}),
|
|
2961
|
+
...rest
|
|
2962
|
+
};
|
|
2963
|
+
if (asChild) {
|
|
2964
|
+
return (
|
|
2965
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
2966
|
+
/* @__PURE__ */ jsx11(Slot, { ref: forwardedRef, ...commonProps })
|
|
2967
|
+
);
|
|
2968
|
+
}
|
|
2969
|
+
return /* @__PURE__ */ jsx11("input", { ref: forwardedRef, ...commonProps });
|
|
2970
|
+
});
|
|
2971
|
+
var Confirm = forwardRef4(function AmountPickerConfirm({ asChild, onClick, onConfirm, disabled, children, ...rest }, forwardedRef) {
|
|
2972
|
+
const ctx = usePickerCtx("Confirm");
|
|
2973
|
+
const isDisabled = disabled || !ctx.resolvedAmount;
|
|
2974
|
+
const handleConfirm = useCallback10(() => {
|
|
2975
|
+
if (ctx.validate() && ctx.resolvedAmount != null) {
|
|
2976
|
+
onConfirm?.(ctx.resolvedAmount);
|
|
2977
|
+
}
|
|
2978
|
+
}, [ctx, onConfirm]);
|
|
2979
|
+
const commonProps = {
|
|
2980
|
+
"data-solvapay-amount-picker-confirm": "",
|
|
2981
|
+
"data-state": isDisabled ? "disabled" : "idle",
|
|
2982
|
+
disabled: isDisabled,
|
|
2983
|
+
"aria-disabled": isDisabled || void 0,
|
|
2984
|
+
onClick: composeEventHandlers(onClick, handleConfirm),
|
|
2985
|
+
...rest
|
|
2986
|
+
};
|
|
2987
|
+
if (asChild) {
|
|
2988
|
+
return (
|
|
2989
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
2990
|
+
/* @__PURE__ */ jsx11(Slot, { ref: forwardedRef, ...commonProps, children })
|
|
2991
|
+
);
|
|
2992
|
+
}
|
|
2993
|
+
return /* @__PURE__ */ jsx11("button", { ref: forwardedRef, type: "button", ...commonProps, children });
|
|
2994
|
+
});
|
|
2995
|
+
var AmountPickerRoot2 = Root3;
|
|
2996
|
+
var AmountPickerOption2 = Option;
|
|
2997
|
+
var AmountPickerCustom2 = Custom;
|
|
2998
|
+
var AmountPickerConfirm2 = Confirm;
|
|
2999
|
+
var AmountPicker = {
|
|
3000
|
+
Root: Root3,
|
|
3001
|
+
Option,
|
|
3002
|
+
Custom,
|
|
3003
|
+
Confirm
|
|
3004
|
+
};
|
|
3005
|
+
function useAmountPicker() {
|
|
3006
|
+
return usePickerCtx("useAmountPicker");
|
|
3007
|
+
}
|
|
3008
|
+
function useAmountPickerCopy() {
|
|
3009
|
+
const copy = useCopy();
|
|
3010
|
+
const ctx = usePickerCtx("useAmountPickerCopy");
|
|
3011
|
+
return {
|
|
3012
|
+
selectAmountLabel: copy.amountPicker.selectAmountLabel,
|
|
3013
|
+
customAmountLabel: copy.amountPicker.customAmountLabel,
|
|
3014
|
+
creditEstimate: (credits) => interpolate(
|
|
3015
|
+
ctx.isApproximate ? copy.amountPicker.creditEstimateApprox : copy.amountPicker.creditEstimateExact,
|
|
3016
|
+
{ credits: new Intl.NumberFormat().format(credits) }
|
|
3017
|
+
)
|
|
3018
|
+
};
|
|
3019
|
+
}
|
|
3020
|
+
|
|
3021
|
+
// src/hooks/useTopup.ts
|
|
3022
|
+
import { useState as useState10, useCallback as useCallback11, useRef as useRef5 } from "react";
|
|
3023
|
+
import { loadStripe as loadStripe2 } from "@stripe/stripe-js";
|
|
3024
|
+
var stripePromiseCache2 = /* @__PURE__ */ new Map();
|
|
3025
|
+
function getStripeCacheKey2(publishableKey, accountId) {
|
|
3026
|
+
return accountId ? `${publishableKey}:${accountId}` : publishableKey;
|
|
3027
|
+
}
|
|
3028
|
+
function useTopup(options) {
|
|
3029
|
+
const { amount, currency } = options;
|
|
3030
|
+
const { createTopupPayment, customerRef, updateCustomerRef } = useSolvaPay();
|
|
3031
|
+
const [loading, setLoading] = useState10(false);
|
|
3032
|
+
const [error, setError] = useState10(null);
|
|
3033
|
+
const [stripePromise, setStripePromise] = useState10(null);
|
|
3034
|
+
const [clientSecret, setClientSecret] = useState10(null);
|
|
3035
|
+
const isStartingRef = useRef5(false);
|
|
3036
|
+
const startTopup = useCallback11(async () => {
|
|
3037
|
+
if (isStartingRef.current || loading) {
|
|
3038
|
+
return;
|
|
3039
|
+
}
|
|
3040
|
+
if (!amount || amount <= 0) {
|
|
3041
|
+
setError(new Error("useTopup: amount must be a positive number"));
|
|
3042
|
+
return;
|
|
3043
|
+
}
|
|
3044
|
+
isStartingRef.current = true;
|
|
3045
|
+
setLoading(true);
|
|
3046
|
+
setError(null);
|
|
3047
|
+
try {
|
|
3048
|
+
const result = await createTopupPayment({ amount, currency });
|
|
3049
|
+
if (!result || typeof result !== "object") {
|
|
3050
|
+
throw new Error("Invalid topup payment intent response from server");
|
|
3051
|
+
}
|
|
3052
|
+
if (!result.clientSecret || typeof result.clientSecret !== "string") {
|
|
3053
|
+
throw new Error("Invalid client secret in topup payment intent response");
|
|
3054
|
+
}
|
|
3055
|
+
if (!result.publishableKey || typeof result.publishableKey !== "string") {
|
|
3056
|
+
throw new Error("Invalid publishable key in topup payment intent response");
|
|
3057
|
+
}
|
|
3058
|
+
if (result.customerRef && result.customerRef !== customerRef && updateCustomerRef) {
|
|
3059
|
+
updateCustomerRef(result.customerRef);
|
|
3060
|
+
}
|
|
3061
|
+
const stripeOptions = result.accountId ? { stripeAccount: result.accountId } : {};
|
|
3062
|
+
const cacheKey = getStripeCacheKey2(result.publishableKey, result.accountId);
|
|
3063
|
+
let stripe = stripePromiseCache2.get(cacheKey);
|
|
3064
|
+
if (!stripe) {
|
|
3065
|
+
stripe = loadStripe2(result.publishableKey, stripeOptions);
|
|
3066
|
+
stripePromiseCache2.set(cacheKey, stripe);
|
|
3067
|
+
}
|
|
3068
|
+
setStripePromise(stripe);
|
|
3069
|
+
setClientSecret(result.clientSecret);
|
|
3070
|
+
} catch (err) {
|
|
3071
|
+
const error2 = err instanceof Error ? err : new Error("Failed to start topup");
|
|
3072
|
+
setError(error2);
|
|
3073
|
+
} finally {
|
|
3074
|
+
setLoading(false);
|
|
3075
|
+
isStartingRef.current = false;
|
|
3076
|
+
}
|
|
3077
|
+
}, [amount, currency, createTopupPayment, customerRef, updateCustomerRef, loading]);
|
|
3078
|
+
const reset = useCallback11(() => {
|
|
3079
|
+
isStartingRef.current = false;
|
|
3080
|
+
setLoading(false);
|
|
3081
|
+
setError(null);
|
|
3082
|
+
setStripePromise(null);
|
|
3083
|
+
setClientSecret(null);
|
|
3084
|
+
}, []);
|
|
3085
|
+
return {
|
|
3086
|
+
loading,
|
|
3087
|
+
error,
|
|
3088
|
+
stripePromise,
|
|
3089
|
+
clientSecret,
|
|
3090
|
+
startTopup,
|
|
3091
|
+
reset
|
|
3092
|
+
};
|
|
3093
|
+
}
|
|
3094
|
+
|
|
3095
|
+
// src/primitives/TopupForm.tsx
|
|
3096
|
+
import {
|
|
3097
|
+
createContext as createContext7,
|
|
3098
|
+
forwardRef as forwardRef5,
|
|
3099
|
+
useCallback as useCallback12,
|
|
3100
|
+
useContext as useContext9,
|
|
3101
|
+
useEffect as useEffect9,
|
|
3102
|
+
useMemo as useMemo9,
|
|
3103
|
+
useRef as useRef6,
|
|
3104
|
+
useState as useState11
|
|
3105
|
+
} from "react";
|
|
3106
|
+
import {
|
|
3107
|
+
Elements as Elements2,
|
|
3108
|
+
useStripe as useStripe2,
|
|
3109
|
+
useElements as useElements2,
|
|
3110
|
+
PaymentElement as StripePaymentElement2
|
|
3111
|
+
} from "@stripe/react-stripe-js";
|
|
3112
|
+
import { Fragment as Fragment4, jsx as jsx12, jsxs as jsxs5 } from "react/jsx-runtime";
|
|
3113
|
+
var TopupFormContext = createContext7(null);
|
|
3114
|
+
function useTopupCtx(part) {
|
|
3115
|
+
const ctx = useContext9(TopupFormContext);
|
|
3116
|
+
if (!ctx) {
|
|
3117
|
+
throw new Error(`TopupForm.${part} must be rendered inside <TopupForm.Root>.`);
|
|
3118
|
+
}
|
|
3119
|
+
return ctx;
|
|
3120
|
+
}
|
|
3121
|
+
var Root4 = forwardRef5(function TopupFormRoot(props, forwardedRef) {
|
|
3122
|
+
const {
|
|
3123
|
+
amount,
|
|
3124
|
+
currency,
|
|
3125
|
+
onSuccess,
|
|
3126
|
+
onError,
|
|
3127
|
+
returnUrl,
|
|
3128
|
+
submitButtonText: _submitButtonText,
|
|
3129
|
+
buttonClassName: _buttonClassName,
|
|
3130
|
+
className,
|
|
3131
|
+
asChild,
|
|
3132
|
+
children,
|
|
3133
|
+
...rest
|
|
3134
|
+
} = props;
|
|
3135
|
+
const solva = useContext9(SolvaPayContext);
|
|
3136
|
+
if (!solva) throw new MissingProviderError("TopupForm");
|
|
3137
|
+
const copy = useCopy();
|
|
3138
|
+
const locale = useLocale();
|
|
3139
|
+
const { loading, error: topupError, clientSecret, startTopup, stripePromise } = useTopup({
|
|
3140
|
+
amount,
|
|
3141
|
+
currency
|
|
3142
|
+
});
|
|
3143
|
+
const hasInitializedRef = useRef6(false);
|
|
3144
|
+
const hasAmount = amount > 0;
|
|
3145
|
+
useEffect9(() => {
|
|
3146
|
+
if (!hasInitializedRef.current && hasAmount && !loading && !topupError && !clientSecret) {
|
|
3147
|
+
hasInitializedRef.current = true;
|
|
3148
|
+
startTopup().catch(() => {
|
|
3149
|
+
hasInitializedRef.current = false;
|
|
3150
|
+
});
|
|
3151
|
+
}
|
|
3152
|
+
if (hasAmount && clientSecret) hasInitializedRef.current = true;
|
|
3153
|
+
}, [hasAmount, loading, topupError, clientSecret, startTopup]);
|
|
3154
|
+
const finalReturnUrl = returnUrl || (typeof window !== "undefined" ? window.location.href : "/");
|
|
3155
|
+
const elementsOptions = useMemo9(() => {
|
|
3156
|
+
if (!clientSecret) return void 0;
|
|
3157
|
+
return { clientSecret, locale };
|
|
3158
|
+
}, [clientSecret, locale]);
|
|
3159
|
+
const Comp = asChild ? Slot : "div";
|
|
3160
|
+
const outerError = !hasAmount ? copy.errors.configMissingAmount : topupError ? `${copy.errors.topupInitFailed} ${topupError.message || copy.errors.unknownError}` : null;
|
|
3161
|
+
const dataState = outerError ? "error" : clientSecret && stripePromise ? "ready" : "loading";
|
|
3162
|
+
const canMountElements = !!(stripePromise && clientSecret && elementsOptions);
|
|
3163
|
+
const innerCommon = {
|
|
3164
|
+
amount,
|
|
3165
|
+
currency,
|
|
3166
|
+
clientSecret,
|
|
3167
|
+
returnUrl: finalReturnUrl,
|
|
3168
|
+
outerError,
|
|
3169
|
+
state: dataState,
|
|
3170
|
+
onSuccess,
|
|
3171
|
+
onError
|
|
3172
|
+
};
|
|
3173
|
+
const shell = /* @__PURE__ */ jsx12(
|
|
3174
|
+
Comp,
|
|
3175
|
+
{
|
|
3176
|
+
ref: forwardedRef,
|
|
3177
|
+
className,
|
|
3178
|
+
"data-solvapay-topup-form": "",
|
|
3179
|
+
"data-state": dataState,
|
|
3180
|
+
...rest,
|
|
3181
|
+
children
|
|
3182
|
+
}
|
|
3183
|
+
);
|
|
3184
|
+
if (canMountElements) {
|
|
3185
|
+
return /* @__PURE__ */ jsx12(Elements2, { stripe: stripePromise, options: elementsOptions, children: /* @__PURE__ */ jsx12(Inner, { ...innerCommon, children: shell }) }, clientSecret);
|
|
3186
|
+
}
|
|
3187
|
+
return /* @__PURE__ */ jsx12(OfflineInner, { ...innerCommon, children: shell });
|
|
3188
|
+
});
|
|
3189
|
+
var Inner = ({
|
|
3190
|
+
amount,
|
|
3191
|
+
currency,
|
|
3192
|
+
clientSecret,
|
|
3193
|
+
returnUrl,
|
|
3194
|
+
outerError,
|
|
3195
|
+
state,
|
|
3196
|
+
onSuccess,
|
|
3197
|
+
onError,
|
|
3198
|
+
children
|
|
3199
|
+
}) => {
|
|
3200
|
+
const stripe = useStripe2();
|
|
3201
|
+
const elements = useElements2();
|
|
3202
|
+
const copy = useCopy();
|
|
3203
|
+
const [paymentInputComplete, setPaymentInputComplete] = useState11(false);
|
|
3204
|
+
const [isProcessing, setIsProcessing] = useState11(false);
|
|
3205
|
+
const [error, setError] = useState11(null);
|
|
3206
|
+
const isReady = !!(stripe && elements);
|
|
3207
|
+
const canSubmit = isReady && paymentInputComplete && !isProcessing && !!clientSecret;
|
|
3208
|
+
const submit = useCallback12(async () => {
|
|
3209
|
+
if (!stripe || !elements || !clientSecret) {
|
|
3210
|
+
const msg = copy.errors.stripeUnavailable;
|
|
3211
|
+
setError(msg);
|
|
3212
|
+
onError?.(new Error(msg));
|
|
3213
|
+
return;
|
|
3214
|
+
}
|
|
3215
|
+
setError(null);
|
|
3216
|
+
setIsProcessing(true);
|
|
3217
|
+
const { error: confirmError, paymentIntent } = await stripe.confirmPayment({
|
|
3218
|
+
elements,
|
|
3219
|
+
clientSecret,
|
|
3220
|
+
confirmParams: { return_url: returnUrl },
|
|
3221
|
+
redirect: "if_required"
|
|
3222
|
+
});
|
|
3223
|
+
if (confirmError) {
|
|
3224
|
+
const msg = confirmError.message || copy.errors.paymentUnexpected;
|
|
3225
|
+
setError(msg);
|
|
3226
|
+
setIsProcessing(false);
|
|
3227
|
+
onError?.(new Error(msg));
|
|
3228
|
+
return;
|
|
3229
|
+
}
|
|
3230
|
+
setIsProcessing(false);
|
|
3231
|
+
if (paymentIntent) {
|
|
3232
|
+
await onSuccess?.(paymentIntent);
|
|
3233
|
+
}
|
|
3234
|
+
}, [stripe, elements, clientSecret, returnUrl, copy, onSuccess, onError]);
|
|
3235
|
+
const effectiveError = error ?? outerError;
|
|
3236
|
+
const ctx = useMemo9(
|
|
3237
|
+
() => ({
|
|
3238
|
+
amount,
|
|
3239
|
+
currency,
|
|
3240
|
+
state,
|
|
3241
|
+
clientSecret,
|
|
3242
|
+
stripe: stripe ?? null,
|
|
3243
|
+
elements: elements ?? null,
|
|
3244
|
+
isReady,
|
|
3245
|
+
isProcessing,
|
|
3246
|
+
paymentInputComplete,
|
|
3247
|
+
canSubmit,
|
|
3248
|
+
error: effectiveError,
|
|
3249
|
+
returnUrl,
|
|
3250
|
+
setPaymentInputComplete,
|
|
3251
|
+
submit
|
|
3252
|
+
}),
|
|
3253
|
+
[
|
|
3254
|
+
amount,
|
|
3255
|
+
currency,
|
|
3256
|
+
state,
|
|
3257
|
+
clientSecret,
|
|
3258
|
+
stripe,
|
|
3259
|
+
elements,
|
|
3260
|
+
isReady,
|
|
3261
|
+
isProcessing,
|
|
3262
|
+
paymentInputComplete,
|
|
3263
|
+
canSubmit,
|
|
3264
|
+
effectiveError,
|
|
3265
|
+
returnUrl,
|
|
3266
|
+
submit
|
|
3267
|
+
]
|
|
3268
|
+
);
|
|
3269
|
+
return /* @__PURE__ */ jsx12(TopupFormContext.Provider, { value: ctx, children });
|
|
3270
|
+
};
|
|
3271
|
+
var OfflineInner = ({
|
|
3272
|
+
amount,
|
|
3273
|
+
currency,
|
|
3274
|
+
clientSecret,
|
|
3275
|
+
returnUrl,
|
|
3276
|
+
outerError,
|
|
3277
|
+
state,
|
|
3278
|
+
children
|
|
3279
|
+
}) => {
|
|
3280
|
+
const noopSubmit = useCallback12(async () => {
|
|
3281
|
+
}, []);
|
|
3282
|
+
const noopSet = useCallback12(() => {
|
|
3283
|
+
}, []);
|
|
3284
|
+
const ctx = useMemo9(
|
|
3285
|
+
() => ({
|
|
3286
|
+
amount,
|
|
3287
|
+
currency,
|
|
3288
|
+
state,
|
|
3289
|
+
clientSecret,
|
|
3290
|
+
stripe: null,
|
|
3291
|
+
elements: null,
|
|
3292
|
+
isReady: false,
|
|
3293
|
+
isProcessing: false,
|
|
3294
|
+
paymentInputComplete: false,
|
|
3295
|
+
canSubmit: false,
|
|
3296
|
+
error: outerError,
|
|
3297
|
+
returnUrl,
|
|
3298
|
+
setPaymentInputComplete: noopSet,
|
|
3299
|
+
submit: noopSubmit
|
|
3300
|
+
}),
|
|
3301
|
+
[amount, currency, state, clientSecret, outerError, returnUrl, noopSet, noopSubmit]
|
|
3302
|
+
);
|
|
3303
|
+
return /* @__PURE__ */ jsx12(TopupFormContext.Provider, { value: ctx, children });
|
|
3304
|
+
};
|
|
3305
|
+
var PaymentElementSlot2 = ({ options }) => {
|
|
3306
|
+
const { setPaymentInputComplete, isReady, stripe, elements } = useTopupCtx("PaymentElement");
|
|
3307
|
+
const locale = useLocale();
|
|
3308
|
+
if (!stripe || !elements) return null;
|
|
3309
|
+
if (!isReady) {
|
|
3310
|
+
return /* @__PURE__ */ jsx12("div", { "data-solvapay-topup-form-loading": "", children: /* @__PURE__ */ jsx12(Spinner, { size: "sm" }) });
|
|
3311
|
+
}
|
|
3312
|
+
return /* @__PURE__ */ jsx12("div", { "data-solvapay-topup-form-payment-element": "", children: /* @__PURE__ */ jsx12(
|
|
3313
|
+
StripePaymentElement2,
|
|
3314
|
+
{
|
|
3315
|
+
options,
|
|
3316
|
+
onChange: (e) => setPaymentInputComplete(e.complete)
|
|
3317
|
+
},
|
|
3318
|
+
locale || "default"
|
|
3319
|
+
) });
|
|
3320
|
+
};
|
|
3321
|
+
var SubmitButton2 = forwardRef5(function TopupFormSubmitButton({ asChild, onClick, children, ...rest }, forwardedRef) {
|
|
3322
|
+
const ctx = useTopupCtx("SubmitButton");
|
|
3323
|
+
const copy = useCopy();
|
|
3324
|
+
const dataState = ctx.isProcessing ? "processing" : !ctx.canSubmit ? "disabled" : "idle";
|
|
3325
|
+
const content = ctx.isProcessing ? /* @__PURE__ */ jsxs5(Fragment4, { children: [
|
|
3326
|
+
/* @__PURE__ */ jsx12(Spinner, { size: "sm" }),
|
|
3327
|
+
/* @__PURE__ */ jsx12("span", { children: copy.cta.processing })
|
|
3328
|
+
] }) : children ? children : copy.cta.topUp;
|
|
3329
|
+
const commonProps = {
|
|
3330
|
+
"data-solvapay-topup-form-submit": "",
|
|
3331
|
+
"data-state": dataState,
|
|
3332
|
+
"aria-busy": ctx.isProcessing,
|
|
3333
|
+
"aria-disabled": !ctx.canSubmit,
|
|
3334
|
+
disabled: !ctx.canSubmit,
|
|
3335
|
+
onClick: composeEventHandlers(onClick, (e) => {
|
|
3336
|
+
e.preventDefault();
|
|
3337
|
+
void ctx.submit();
|
|
3338
|
+
}),
|
|
3339
|
+
...rest
|
|
3340
|
+
};
|
|
3341
|
+
if (asChild) {
|
|
3342
|
+
return (
|
|
3343
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
3344
|
+
/* @__PURE__ */ jsx12(Slot, { ref: forwardedRef, ...commonProps, children: content })
|
|
3345
|
+
);
|
|
3346
|
+
}
|
|
3347
|
+
return /* @__PURE__ */ jsx12("button", { ref: forwardedRef, type: "submit", ...commonProps, children: content });
|
|
3348
|
+
});
|
|
3349
|
+
var Loading2 = forwardRef5(function TopupFormLoading({ asChild, children, ...rest }, forwardedRef) {
|
|
3350
|
+
const ctx = useTopupCtx("Loading");
|
|
3351
|
+
if (ctx.state !== "loading") return null;
|
|
3352
|
+
const Comp = asChild ? Slot : "div";
|
|
3353
|
+
return /* @__PURE__ */ jsx12(Comp, { ref: forwardedRef, "data-solvapay-topup-form-loading": "", ...rest, children: children ?? /* @__PURE__ */ jsx12(Spinner, { size: "sm" }) });
|
|
3354
|
+
});
|
|
3355
|
+
var ErrorSlot2 = forwardRef5(function TopupFormError({ asChild, children, ...rest }, forwardedRef) {
|
|
3356
|
+
const ctx = useTopupCtx("Error");
|
|
3357
|
+
if (!ctx.error) return null;
|
|
3358
|
+
const Comp = asChild ? Slot : "div";
|
|
3359
|
+
return /* @__PURE__ */ jsx12(
|
|
3360
|
+
Comp,
|
|
3361
|
+
{
|
|
3362
|
+
ref: forwardedRef,
|
|
3363
|
+
role: "alert",
|
|
3364
|
+
"aria-live": "assertive",
|
|
3365
|
+
"aria-atomic": "true",
|
|
3366
|
+
"data-solvapay-topup-form-error": "",
|
|
3367
|
+
...rest,
|
|
3368
|
+
children: children ?? ctx.error
|
|
3369
|
+
}
|
|
3370
|
+
);
|
|
3371
|
+
});
|
|
3372
|
+
var TopupFormRoot2 = Root4;
|
|
3373
|
+
var TopupFormPaymentElement = PaymentElementSlot2;
|
|
3374
|
+
var TopupFormSubmitButton2 = SubmitButton2;
|
|
3375
|
+
var TopupFormLoading2 = Loading2;
|
|
3376
|
+
var TopupFormError2 = ErrorSlot2;
|
|
3377
|
+
var TopupForm = {
|
|
3378
|
+
Root: Root4,
|
|
3379
|
+
AmountPicker: AmountPicker.Root,
|
|
3380
|
+
PaymentElement: PaymentElementSlot2,
|
|
3381
|
+
SubmitButton: SubmitButton2,
|
|
3382
|
+
Loading: Loading2,
|
|
3383
|
+
Error: ErrorSlot2
|
|
3384
|
+
};
|
|
3385
|
+
function useTopupForm() {
|
|
3386
|
+
return useTopupCtx("useTopupForm");
|
|
3387
|
+
}
|
|
3388
|
+
|
|
3389
|
+
// src/TopupForm.tsx
|
|
3390
|
+
import { jsx as jsx13, jsxs as jsxs6 } from "react/jsx-runtime";
|
|
3391
|
+
var TopupForm2 = (props) => {
|
|
3392
|
+
const { className, buttonClassName, submitButtonText, ...rootProps } = props;
|
|
3393
|
+
const rootClass = ["solvapay-topup-form", className].filter(Boolean).join(" ");
|
|
3394
|
+
const buttonClass = ["solvapay-topup-form-submit", buttonClassName].filter(Boolean).join(" ");
|
|
3395
|
+
return /* @__PURE__ */ jsxs6(TopupForm.Root, { ...rootProps, className: rootClass, children: [
|
|
3396
|
+
/* @__PURE__ */ jsx13(TopupForm.PaymentElement, {}),
|
|
3397
|
+
/* @__PURE__ */ jsx13(TopupForm.Error, { className: "solvapay-topup-form-error" }),
|
|
3398
|
+
/* @__PURE__ */ jsx13(TopupForm.Loading, { className: "solvapay-topup-form-loading" }),
|
|
3399
|
+
/* @__PURE__ */ jsx13(TopupForm.SubmitButton, { className: buttonClass, children: submitButtonText })
|
|
3400
|
+
] });
|
|
3401
|
+
};
|
|
3402
|
+
|
|
3403
|
+
// src/primitives/ProductBadge.tsx
|
|
3404
|
+
import { forwardRef as forwardRef6, useContext as useContext10, useEffect as useEffect10, useState as useState12 } from "react";
|
|
3405
|
+
import { Fragment as Fragment5, jsx as jsx14 } from "react/jsx-runtime";
|
|
3406
|
+
var ProductBadgeImpl = forwardRef6(function ProductBadge({ asChild, children, ...rest }, forwardedRef) {
|
|
3407
|
+
const solva = useContext10(SolvaPayContext);
|
|
3408
|
+
if (!solva) throw new MissingProviderError("ProductBadge");
|
|
3409
|
+
const { purchases, loading, hasPaidPurchase, activePurchase } = usePurchase();
|
|
3410
|
+
const copy = useCopy();
|
|
3411
|
+
const [hasLoadedOnce, setHasLoadedOnce] = useState12(false);
|
|
3412
|
+
useEffect10(() => {
|
|
3413
|
+
if (!loading) setHasLoadedOnce(true);
|
|
3414
|
+
}, [loading]);
|
|
3415
|
+
const planToDisplay = activePurchase?.productName ?? null;
|
|
3416
|
+
const shouldShow = planToDisplay !== null && (!loading || hasLoadedOnce);
|
|
3417
|
+
if (!shouldShow) return null;
|
|
3418
|
+
const commonProps = {
|
|
3419
|
+
"data-solvapay-product-badge": "",
|
|
3420
|
+
"data-loading": loading ? "" : void 0,
|
|
3421
|
+
"data-has-purchase": activePurchase ? "" : void 0,
|
|
3422
|
+
"data-has-paid-purchase": hasPaidPurchase ? "" : void 0,
|
|
3423
|
+
role: "status",
|
|
3424
|
+
"aria-live": "polite",
|
|
3425
|
+
"aria-busy": loading,
|
|
3426
|
+
"aria-label": interpolate(copy.product.currentProductLabel, { name: planToDisplay }),
|
|
3427
|
+
...rest
|
|
3428
|
+
};
|
|
3429
|
+
if (asChild) {
|
|
3430
|
+
return (
|
|
3431
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
3432
|
+
/* @__PURE__ */ jsx14(Slot, { ref: forwardedRef, ...commonProps, children: children ?? /* @__PURE__ */ jsx14(Fragment5, { children: planToDisplay }) })
|
|
3433
|
+
);
|
|
3434
|
+
}
|
|
3435
|
+
void purchases;
|
|
3436
|
+
return (
|
|
3437
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
3438
|
+
/* @__PURE__ */ jsx14("div", { ref: forwardedRef, ...commonProps, children: children ?? planToDisplay })
|
|
3439
|
+
);
|
|
3440
|
+
});
|
|
3441
|
+
var ProductBadge2 = ProductBadgeImpl;
|
|
3442
|
+
var PlanBadge = ProductBadgeImpl;
|
|
3443
|
+
|
|
3444
|
+
// src/primitives/PurchaseGate.tsx
|
|
3445
|
+
import {
|
|
3446
|
+
createContext as createContext8,
|
|
3447
|
+
forwardRef as forwardRef7,
|
|
3448
|
+
useContext as useContext11,
|
|
3449
|
+
useMemo as useMemo10
|
|
3450
|
+
} from "react";
|
|
3451
|
+
import { jsx as jsx15 } from "react/jsx-runtime";
|
|
3452
|
+
var PurchaseGateContext = createContext8(null);
|
|
3453
|
+
function useGateCtx(part) {
|
|
3454
|
+
const ctx = useContext11(PurchaseGateContext);
|
|
3455
|
+
if (!ctx) {
|
|
3456
|
+
throw new Error(`PurchaseGate.${part} must be rendered inside <PurchaseGate.Root>.`);
|
|
3457
|
+
}
|
|
3458
|
+
return ctx;
|
|
3459
|
+
}
|
|
3460
|
+
var Root5 = forwardRef7(function PurchaseGateRoot({ productRef, planRef, asChild, children, ...rest }, forwardedRef) {
|
|
3461
|
+
const solva = useContext11(SolvaPayContext);
|
|
3462
|
+
if (!solva) throw new MissingProviderError("PurchaseGate");
|
|
3463
|
+
const { purchases, loading, error } = usePurchase();
|
|
3464
|
+
const hasAccess = useMemo10(() => {
|
|
3465
|
+
if (!productRef && !planRef) {
|
|
3466
|
+
return purchases.some((p) => p.status === "active");
|
|
3467
|
+
}
|
|
3468
|
+
return purchases.some(
|
|
3469
|
+
(p) => p.status === "active" && (!productRef || p.productRef === productRef) && (!planRef || p.planRef === planRef)
|
|
3470
|
+
);
|
|
3471
|
+
}, [purchases, productRef, planRef]);
|
|
3472
|
+
const state = loading ? "loading" : hasAccess ? "allowed" : "blocked";
|
|
3473
|
+
const ctx = useMemo10(
|
|
3474
|
+
() => ({ state, loading, hasAccess, error }),
|
|
3475
|
+
[state, loading, hasAccess, error]
|
|
3476
|
+
);
|
|
3477
|
+
const Comp = asChild ? Slot : "div";
|
|
3478
|
+
return /* @__PURE__ */ jsx15(PurchaseGateContext.Provider, { value: ctx, children: /* @__PURE__ */ jsx15(
|
|
3479
|
+
Comp,
|
|
3480
|
+
{
|
|
3481
|
+
ref: forwardedRef,
|
|
3482
|
+
"data-solvapay-purchase-gate": "",
|
|
3483
|
+
"data-state": state,
|
|
3484
|
+
...rest,
|
|
3485
|
+
children
|
|
3486
|
+
}
|
|
3487
|
+
) });
|
|
3488
|
+
});
|
|
3489
|
+
var Allowed = forwardRef7(function PurchaseGateAllowed({ asChild, children, ...rest }, forwardedRef) {
|
|
3490
|
+
const ctx = useGateCtx("Allowed");
|
|
3491
|
+
if (ctx.state !== "allowed") return null;
|
|
3492
|
+
const Comp = asChild ? Slot : "div";
|
|
3493
|
+
return /* @__PURE__ */ jsx15(Comp, { ref: forwardedRef, "data-solvapay-purchase-gate-allowed": "", ...rest, children });
|
|
3494
|
+
});
|
|
3495
|
+
var Blocked = forwardRef7(function PurchaseGateBlocked({ asChild, children, ...rest }, forwardedRef) {
|
|
3496
|
+
const ctx = useGateCtx("Blocked");
|
|
3497
|
+
if (ctx.state !== "blocked") return null;
|
|
3498
|
+
const Comp = asChild ? Slot : "div";
|
|
3499
|
+
return /* @__PURE__ */ jsx15(Comp, { ref: forwardedRef, "data-solvapay-purchase-gate-blocked": "", ...rest, children });
|
|
3500
|
+
});
|
|
3501
|
+
var Loading3 = forwardRef7(function PurchaseGateLoading({ asChild, children, ...rest }, forwardedRef) {
|
|
3502
|
+
const ctx = useGateCtx("Loading");
|
|
3503
|
+
if (ctx.state !== "loading") return null;
|
|
3504
|
+
const Comp = asChild ? Slot : "div";
|
|
3505
|
+
return /* @__PURE__ */ jsx15(Comp, { ref: forwardedRef, "data-solvapay-purchase-gate-loading": "", ...rest, children });
|
|
3506
|
+
});
|
|
3507
|
+
var ErrorSlot3 = forwardRef7(function PurchaseGateError({ asChild, children, ...rest }, forwardedRef) {
|
|
3508
|
+
const ctx = useGateCtx("Error");
|
|
3509
|
+
if (!ctx.error) return null;
|
|
3510
|
+
const Comp = asChild ? Slot : "div";
|
|
3511
|
+
return /* @__PURE__ */ jsx15(Comp, { ref: forwardedRef, "data-solvapay-purchase-gate-error": "", role: "alert", ...rest, children: children ?? ctx.error.message });
|
|
3512
|
+
});
|
|
3513
|
+
var PurchaseGateRoot2 = Root5;
|
|
3514
|
+
var PurchaseGateAllowed2 = Allowed;
|
|
3515
|
+
var PurchaseGateBlocked2 = Blocked;
|
|
3516
|
+
var PurchaseGateLoading2 = Loading3;
|
|
3517
|
+
var PurchaseGateError2 = ErrorSlot3;
|
|
3518
|
+
var PurchaseGate = {
|
|
3519
|
+
Root: Root5,
|
|
3520
|
+
Allowed,
|
|
3521
|
+
Blocked,
|
|
3522
|
+
Loading: Loading3,
|
|
3523
|
+
Error: ErrorSlot3
|
|
3524
|
+
};
|
|
3525
|
+
function usePurchaseGate() {
|
|
3526
|
+
return useGateCtx("usePurchaseGate");
|
|
3527
|
+
}
|
|
3528
|
+
|
|
3529
|
+
// src/primitives/BalanceBadge.tsx
|
|
3530
|
+
import { forwardRef as forwardRef8, useContext as useContext12 } from "react";
|
|
3531
|
+
import { Fragment as Fragment6, jsx as jsx16, jsxs as jsxs7 } from "react/jsx-runtime";
|
|
3532
|
+
var BalanceBadge = forwardRef8(function BalanceBadge2({ asChild, numberOnly, lowThreshold = 10, children, ...rest }, forwardedRef) {
|
|
3533
|
+
const solva = useContext12(SolvaPayContext);
|
|
3534
|
+
if (!solva) throw new MissingProviderError("BalanceBadge");
|
|
3535
|
+
const { credits, displayCurrency, creditsPerMinorUnit, displayExchangeRate, loading } = useBalance();
|
|
3536
|
+
const copy = useCopy();
|
|
3537
|
+
const locale = useLocale();
|
|
3538
|
+
const state = loading ? "loading" : credits == null || credits === 0 ? "zero" : credits <= lowThreshold ? "low" : "ok";
|
|
3539
|
+
const commonProps = {
|
|
3540
|
+
"data-solvapay-balance-badge": "",
|
|
3541
|
+
"data-state": state,
|
|
3542
|
+
"data-credits": credits == null ? void 0 : String(credits),
|
|
3543
|
+
"aria-busy": loading,
|
|
3544
|
+
...rest
|
|
3545
|
+
};
|
|
3546
|
+
if (state === "loading") {
|
|
3547
|
+
if (asChild) {
|
|
3548
|
+
return (
|
|
3549
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
3550
|
+
/* @__PURE__ */ jsx16(Slot, { ref: forwardedRef, ...commonProps, children: children ?? /* @__PURE__ */ jsx16(Fragment6, {}) })
|
|
3551
|
+
);
|
|
3552
|
+
}
|
|
3553
|
+
return /* @__PURE__ */ jsx16("span", { ref: forwardedRef, ...commonProps });
|
|
3554
|
+
}
|
|
3555
|
+
if (credits == null) return null;
|
|
3556
|
+
const formattedCredits = new Intl.NumberFormat(locale).format(credits);
|
|
3557
|
+
let currencyEquivalent = "";
|
|
3558
|
+
if (!numberOnly && displayCurrency && creditsPerMinorUnit) {
|
|
3559
|
+
const usdCents = credits / creditsPerMinorUnit;
|
|
3560
|
+
const displayMajorUnits = usdCents * (displayExchangeRate ?? 1) / 100;
|
|
3561
|
+
const formatted = new Intl.NumberFormat(locale, {
|
|
3562
|
+
style: "currency",
|
|
3563
|
+
currency: displayCurrency,
|
|
3564
|
+
minimumFractionDigits: 2
|
|
3565
|
+
}).format(displayMajorUnits);
|
|
3566
|
+
currencyEquivalent = interpolate(copy.balance.currencyEquivalent, { amount: formatted });
|
|
3567
|
+
}
|
|
3568
|
+
const content = children ?? /* @__PURE__ */ jsxs7(Fragment6, { children: [
|
|
3569
|
+
formattedCredits,
|
|
3570
|
+
!numberOnly && copy.balance.credits,
|
|
3571
|
+
!numberOnly && currencyEquivalent
|
|
3572
|
+
] });
|
|
3573
|
+
if (asChild) {
|
|
3574
|
+
return (
|
|
3575
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
3576
|
+
/* @__PURE__ */ jsx16(Slot, { ref: forwardedRef, ...commonProps, children: content })
|
|
3577
|
+
);
|
|
3578
|
+
}
|
|
3579
|
+
return /* @__PURE__ */ jsx16("span", { ref: forwardedRef, ...commonProps, children: content });
|
|
3580
|
+
});
|
|
3581
|
+
|
|
3582
|
+
// src/primitives/PlanSelector.tsx
|
|
3583
|
+
import {
|
|
3584
|
+
createContext as createContext9,
|
|
3585
|
+
forwardRef as forwardRef9,
|
|
3586
|
+
useCallback as useCallback13,
|
|
3587
|
+
useContext as useContext13,
|
|
3588
|
+
useMemo as useMemo11
|
|
3589
|
+
} from "react";
|
|
3590
|
+
import { jsx as jsx17 } from "react/jsx-runtime";
|
|
3591
|
+
var PlanSelectorContext = createContext9(null);
|
|
3592
|
+
function usePlanSelectorContext(part) {
|
|
3593
|
+
const ctx = useContext13(PlanSelectorContext);
|
|
3594
|
+
if (!ctx) {
|
|
3595
|
+
throw new Error(`PlanSelector.${part} must be rendered inside <PlanSelector.Root>.`);
|
|
3596
|
+
}
|
|
3597
|
+
return ctx;
|
|
3598
|
+
}
|
|
3599
|
+
var CardContext = createContext9(null);
|
|
3600
|
+
function useCardContext(part) {
|
|
3601
|
+
const ctx = useContext13(CardContext);
|
|
3602
|
+
if (!ctx) {
|
|
3603
|
+
throw new Error(`PlanSelector.${part} must be rendered inside <PlanSelector.Card>.`);
|
|
3604
|
+
}
|
|
3605
|
+
return ctx;
|
|
3606
|
+
}
|
|
3607
|
+
async function defaultListPlans(productRef, config) {
|
|
3608
|
+
const base = config?.api?.listPlans || "/api/list-plans";
|
|
3609
|
+
const url = `${base}?productRef=${encodeURIComponent(productRef)}`;
|
|
3610
|
+
const fetchFn = config?.fetch || fetch;
|
|
3611
|
+
const { headers } = await buildRequestHeaders(config);
|
|
3612
|
+
const res = await fetchFn(url, { method: "GET", headers });
|
|
3613
|
+
if (!res.ok) {
|
|
3614
|
+
const error = new Error(`Failed to fetch plans: ${res.statusText || res.status}`);
|
|
3615
|
+
config?.onError?.(error, "listPlans");
|
|
3616
|
+
throw error;
|
|
3617
|
+
}
|
|
3618
|
+
const data = await res.json();
|
|
3619
|
+
return data.plans ?? [];
|
|
3620
|
+
}
|
|
3621
|
+
var Root6 = forwardRef9(function PlanSelectorRoot(props, forwardedRef) {
|
|
3622
|
+
const {
|
|
3623
|
+
productRef,
|
|
3624
|
+
fetcher,
|
|
3625
|
+
filter,
|
|
3626
|
+
sortBy,
|
|
3627
|
+
autoSelectFirstPaid = true,
|
|
3628
|
+
initialPlanRef,
|
|
3629
|
+
currentPlanRef,
|
|
3630
|
+
popularPlanRef,
|
|
3631
|
+
onSelect,
|
|
3632
|
+
children,
|
|
3633
|
+
...rest
|
|
3634
|
+
} = props;
|
|
3635
|
+
const solva = useContext13(SolvaPayContext);
|
|
3636
|
+
if (!solva) throw new MissingProviderError("PlanSelector");
|
|
3637
|
+
if (!productRef) throw new MissingProductRefError("PlanSelector");
|
|
3638
|
+
const { _config } = solva;
|
|
3639
|
+
const { purchases } = usePurchase();
|
|
3640
|
+
const effectiveFetcher = useMemo11(
|
|
3641
|
+
() => fetcher ?? ((ref) => defaultListPlans(ref, _config)),
|
|
3642
|
+
[fetcher, _config]
|
|
3643
|
+
);
|
|
3644
|
+
const { plans, selectedPlan, selectPlan, loading, error } = usePlans({
|
|
3645
|
+
productRef,
|
|
3646
|
+
fetcher: effectiveFetcher,
|
|
3647
|
+
filter,
|
|
3648
|
+
sortBy,
|
|
3649
|
+
autoSelectFirstPaid,
|
|
3650
|
+
initialPlanRef
|
|
3651
|
+
});
|
|
3652
|
+
const autoCurrentPlanRef = useMemo11(() => {
|
|
3653
|
+
const active = purchases.filter((p) => p.status === "active").sort((a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime())[0];
|
|
3654
|
+
return active?.planSnapshot?.reference ?? null;
|
|
3655
|
+
}, [purchases]);
|
|
3656
|
+
const resolvedCurrentPlanRef = currentPlanRef === null ? null : currentPlanRef ?? autoCurrentPlanRef;
|
|
3657
|
+
const isCurrent = useCallback13(
|
|
3658
|
+
(ref) => resolvedCurrentPlanRef === ref,
|
|
3659
|
+
[resolvedCurrentPlanRef]
|
|
3660
|
+
);
|
|
3661
|
+
const isFree = useCallback13(
|
|
3662
|
+
(ref) => plans.find((p) => p.reference === ref)?.requiresPayment === false,
|
|
3663
|
+
[plans]
|
|
3664
|
+
);
|
|
3665
|
+
const isPopular = useCallback13(
|
|
3666
|
+
(ref) => popularPlanRef === ref,
|
|
3667
|
+
[popularPlanRef]
|
|
3668
|
+
);
|
|
3669
|
+
const select = useCallback13(
|
|
3670
|
+
(ref) => {
|
|
3671
|
+
const plan = plans.find((p) => p.reference === ref);
|
|
3672
|
+
if (!plan) return;
|
|
3673
|
+
if (plan.requiresPayment === false) return;
|
|
3674
|
+
selectPlan(ref);
|
|
3675
|
+
onSelect?.(ref, plan);
|
|
3676
|
+
},
|
|
3677
|
+
[plans, selectPlan, onSelect]
|
|
3678
|
+
);
|
|
3679
|
+
const selectedPlanRef = selectedPlan?.reference ?? null;
|
|
3680
|
+
const ctx = useMemo11(
|
|
3681
|
+
() => ({
|
|
3682
|
+
plans,
|
|
3683
|
+
loading,
|
|
3684
|
+
error,
|
|
3685
|
+
selectedPlan: selectedPlan ?? null,
|
|
3686
|
+
selectedPlanRef,
|
|
3687
|
+
popularPlanRef,
|
|
3688
|
+
currentPlanRef: resolvedCurrentPlanRef,
|
|
3689
|
+
isCurrent,
|
|
3690
|
+
isFree,
|
|
3691
|
+
isPopular,
|
|
3692
|
+
select
|
|
3693
|
+
}),
|
|
3694
|
+
[
|
|
3695
|
+
plans,
|
|
3696
|
+
loading,
|
|
3697
|
+
error,
|
|
3698
|
+
selectedPlan,
|
|
3699
|
+
selectedPlanRef,
|
|
3700
|
+
popularPlanRef,
|
|
3701
|
+
resolvedCurrentPlanRef,
|
|
3702
|
+
isCurrent,
|
|
3703
|
+
isFree,
|
|
3704
|
+
isPopular,
|
|
3705
|
+
select
|
|
3706
|
+
]
|
|
3707
|
+
);
|
|
3708
|
+
return /* @__PURE__ */ jsx17(
|
|
3709
|
+
PlanSelectionProvider,
|
|
3710
|
+
{
|
|
3711
|
+
value: {
|
|
3712
|
+
productRef,
|
|
3713
|
+
selectedPlanRef,
|
|
3714
|
+
setSelectedPlanRef: (ref) => {
|
|
3715
|
+
if (ref) select(ref);
|
|
3716
|
+
},
|
|
3717
|
+
plans,
|
|
3718
|
+
loading,
|
|
3719
|
+
error
|
|
3720
|
+
},
|
|
3721
|
+
children: /* @__PURE__ */ jsx17("div", { ref: forwardedRef, "data-solvapay-plan-selector": "", ...rest, children: /* @__PURE__ */ jsx17(PlanSelectorContext.Provider, { value: ctx, children }) })
|
|
3722
|
+
}
|
|
3723
|
+
);
|
|
3724
|
+
});
|
|
3725
|
+
var Heading = forwardRef9(function PlanSelectorHeading({ asChild, children, ...rest }, forwardedRef) {
|
|
3726
|
+
usePlanSelectorContext("Heading");
|
|
3727
|
+
const copy = useCopy();
|
|
3728
|
+
const Comp = asChild ? Slot : "h3";
|
|
3729
|
+
return /* @__PURE__ */ jsx17(Comp, { ref: forwardedRef, "data-solvapay-plan-selector-heading": "", ...rest, children: children ?? copy.planSelector.heading });
|
|
3730
|
+
});
|
|
3731
|
+
var Grid = forwardRef9(function PlanSelectorGrid({ children, ...rest }, forwardedRef) {
|
|
3732
|
+
const ctx = usePlanSelectorContext("Grid");
|
|
3733
|
+
return /* @__PURE__ */ jsx17("div", { ref: forwardedRef, "data-solvapay-plan-selector-grid": "", ...rest, children: ctx.plans.map((plan) => {
|
|
3734
|
+
const isCurrent = ctx.isCurrent(plan.reference);
|
|
3735
|
+
const isFree = ctx.isFree(plan.reference);
|
|
3736
|
+
const isPopular = ctx.isPopular(plan.reference);
|
|
3737
|
+
const selected = ctx.selectedPlanRef === plan.reference;
|
|
3738
|
+
const disabled = isCurrent || isFree;
|
|
3739
|
+
const state = isCurrent ? "current" : isFree ? "disabled" : selected ? "selected" : "idle";
|
|
3740
|
+
const cardCtx = {
|
|
3741
|
+
plan,
|
|
3742
|
+
state,
|
|
3743
|
+
isCurrent,
|
|
3744
|
+
isFree,
|
|
3745
|
+
isPopular,
|
|
3746
|
+
disabled,
|
|
3747
|
+
select: () => ctx.select(plan.reference)
|
|
3748
|
+
};
|
|
3749
|
+
return /* @__PURE__ */ jsx17(CardContext.Provider, { value: cardCtx, children }, plan.reference);
|
|
3750
|
+
}) });
|
|
3751
|
+
});
|
|
3752
|
+
var Card = forwardRef9(function PlanSelectorCard({ asChild, onClick, children, ...rest }, forwardedRef) {
|
|
3753
|
+
const card = useCardContext("Card");
|
|
3754
|
+
const dataTrial = !!(card.plan.trialDays && card.plan.trialDays > 0);
|
|
3755
|
+
const commonProps = {
|
|
3756
|
+
"data-solvapay-plan-selector-card": "",
|
|
3757
|
+
"data-state": card.state,
|
|
3758
|
+
"data-free": card.isFree ? "" : void 0,
|
|
3759
|
+
"data-popular": card.isPopular ? "" : void 0,
|
|
3760
|
+
"data-trial": dataTrial ? "" : void 0,
|
|
3761
|
+
"aria-disabled": card.disabled || void 0,
|
|
3762
|
+
onClick: composeEventHandlers(onClick, () => {
|
|
3763
|
+
if (!card.disabled) card.select();
|
|
3764
|
+
}),
|
|
3765
|
+
...rest
|
|
3766
|
+
};
|
|
3767
|
+
if (asChild) {
|
|
3768
|
+
return (
|
|
3769
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
3770
|
+
/* @__PURE__ */ jsx17(Slot, { ref: forwardedRef, ...commonProps, children })
|
|
3771
|
+
);
|
|
3772
|
+
}
|
|
3773
|
+
return /* @__PURE__ */ jsx17(
|
|
3774
|
+
"button",
|
|
3775
|
+
{
|
|
3776
|
+
ref: forwardedRef,
|
|
3777
|
+
type: "button",
|
|
3778
|
+
disabled: card.disabled,
|
|
3779
|
+
...commonProps,
|
|
3780
|
+
children
|
|
3781
|
+
}
|
|
3782
|
+
);
|
|
3783
|
+
});
|
|
3784
|
+
var CardName = forwardRef9(function PlanSelectorCardName({ asChild, children, ...rest }, forwardedRef) {
|
|
3785
|
+
const card = useCardContext("CardName");
|
|
3786
|
+
if (!card.plan.name) return null;
|
|
3787
|
+
const Comp = asChild ? Slot : "span";
|
|
3788
|
+
return /* @__PURE__ */ jsx17(Comp, { ref: forwardedRef, "data-solvapay-plan-selector-card-name": "", ...rest, children: children ?? card.plan.name });
|
|
3789
|
+
});
|
|
3790
|
+
var CardPrice = forwardRef9(function PlanSelectorCardPrice({ asChild, children, ...rest }, forwardedRef) {
|
|
3791
|
+
const card = useCardContext("CardPrice");
|
|
3792
|
+
const locale = useLocale();
|
|
3793
|
+
const copy = useCopy();
|
|
3794
|
+
const formatted = useMemo11(() => {
|
|
3795
|
+
if (card.isFree) return copy.planSelector.freeBadge;
|
|
3796
|
+
return formatPrice(card.plan.price ?? 0, card.plan.currency ?? "usd", {
|
|
3797
|
+
locale,
|
|
3798
|
+
free: copy.interval.free
|
|
3799
|
+
});
|
|
3800
|
+
}, [
|
|
3801
|
+
card.isFree,
|
|
3802
|
+
card.plan.price,
|
|
3803
|
+
card.plan.currency,
|
|
3804
|
+
locale,
|
|
3805
|
+
copy.planSelector.freeBadge,
|
|
3806
|
+
copy.interval.free
|
|
3807
|
+
]);
|
|
3808
|
+
const Comp = asChild ? Slot : "span";
|
|
3809
|
+
return /* @__PURE__ */ jsx17(Comp, { ref: forwardedRef, "data-solvapay-plan-selector-card-price": "", ...rest, children: children ?? formatted });
|
|
3810
|
+
});
|
|
3811
|
+
var CardInterval = forwardRef9(function PlanSelectorCardInterval({ asChild, children, ...rest }, forwardedRef) {
|
|
3812
|
+
const card = useCardContext("CardInterval");
|
|
3813
|
+
const copy = useCopy();
|
|
3814
|
+
if (card.isFree || !card.plan.interval) return null;
|
|
3815
|
+
const text = interpolate(copy.planSelector.perIntervalShort, { interval: card.plan.interval });
|
|
3816
|
+
const Comp = asChild ? Slot : "span";
|
|
3817
|
+
return /* @__PURE__ */ jsx17(Comp, { ref: forwardedRef, "data-solvapay-plan-selector-card-interval": "", ...rest, children: children ?? text });
|
|
3818
|
+
});
|
|
3819
|
+
var CardBadge = forwardRef9(function PlanSelectorCardBadge({ asChild, children, ...rest }, forwardedRef) {
|
|
3820
|
+
const card = useCardContext("CardBadge");
|
|
3821
|
+
const copy = useCopy();
|
|
3822
|
+
let variant = null;
|
|
3823
|
+
let label = "";
|
|
3824
|
+
if (card.isCurrent) {
|
|
3825
|
+
variant = "current";
|
|
3826
|
+
label = copy.planSelector.currentBadge;
|
|
3827
|
+
} else if (card.isPopular && !card.isFree) {
|
|
3828
|
+
variant = "popular";
|
|
3829
|
+
label = copy.planSelector.popularBadge;
|
|
3830
|
+
}
|
|
3831
|
+
if (!variant) return null;
|
|
3832
|
+
const Comp = asChild ? Slot : "span";
|
|
3833
|
+
return /* @__PURE__ */ jsx17(
|
|
3834
|
+
Comp,
|
|
3835
|
+
{
|
|
3836
|
+
ref: forwardedRef,
|
|
3837
|
+
"data-solvapay-plan-selector-card-badge": "",
|
|
3838
|
+
"data-variant": variant,
|
|
3839
|
+
...rest,
|
|
3840
|
+
children: children ?? label
|
|
3841
|
+
}
|
|
3842
|
+
);
|
|
3843
|
+
});
|
|
3844
|
+
var Loading4 = forwardRef9(function PlanSelectorLoading({ asChild, children, ...rest }, forwardedRef) {
|
|
3845
|
+
const ctx = usePlanSelectorContext("Loading");
|
|
3846
|
+
if (!ctx.loading || ctx.plans.length > 0) return null;
|
|
3847
|
+
const Comp = asChild ? Slot : "div";
|
|
3848
|
+
return /* @__PURE__ */ jsx17(Comp, { ref: forwardedRef, "data-solvapay-plan-selector-loading": "", ...rest, children });
|
|
3849
|
+
});
|
|
3850
|
+
var ErrorSlot4 = forwardRef9(function PlanSelectorError({ asChild, children, ...rest }, forwardedRef) {
|
|
3851
|
+
const ctx = usePlanSelectorContext("Error");
|
|
3852
|
+
if (!ctx.error) return null;
|
|
3853
|
+
const Comp = asChild ? Slot : "div";
|
|
3854
|
+
return /* @__PURE__ */ jsx17(Comp, { ref: forwardedRef, "data-solvapay-plan-selector-error": "", role: "alert", ...rest, children: children ?? ctx.error.message });
|
|
3855
|
+
});
|
|
3856
|
+
var PlanSelectorRoot2 = Root6;
|
|
3857
|
+
var PlanSelectorHeading2 = Heading;
|
|
3858
|
+
var PlanSelectorGrid2 = Grid;
|
|
3859
|
+
var PlanSelectorCard2 = Card;
|
|
3860
|
+
var PlanSelectorCardName2 = CardName;
|
|
3861
|
+
var PlanSelectorCardPrice2 = CardPrice;
|
|
3862
|
+
var PlanSelectorCardInterval2 = CardInterval;
|
|
3863
|
+
var PlanSelectorCardBadge2 = CardBadge;
|
|
3864
|
+
var PlanSelectorLoading2 = Loading4;
|
|
3865
|
+
var PlanSelectorError2 = ErrorSlot4;
|
|
3866
|
+
var PlanSelector = {
|
|
3867
|
+
Root: Root6,
|
|
3868
|
+
Heading,
|
|
3869
|
+
Grid,
|
|
3870
|
+
Card,
|
|
3871
|
+
CardName,
|
|
3872
|
+
CardPrice,
|
|
3873
|
+
CardInterval,
|
|
3874
|
+
CardBadge,
|
|
3875
|
+
Loading: Loading4,
|
|
3876
|
+
Error: ErrorSlot4
|
|
3877
|
+
};
|
|
3878
|
+
function usePlanSelector() {
|
|
3879
|
+
return usePlanSelectorContext("usePlanSelector");
|
|
3880
|
+
}
|
|
3881
|
+
|
|
3882
|
+
// src/primitives/ActivationFlow.tsx
|
|
3883
|
+
import {
|
|
3884
|
+
createContext as createContext10,
|
|
3885
|
+
forwardRef as forwardRef10,
|
|
3886
|
+
useCallback as useCallback14,
|
|
3887
|
+
useContext as useContext14,
|
|
3888
|
+
useEffect as useEffect11,
|
|
3889
|
+
useMemo as useMemo12,
|
|
3890
|
+
useRef as useRef7,
|
|
3891
|
+
useState as useState13
|
|
3892
|
+
} from "react";
|
|
3893
|
+
import { Fragment as Fragment7, jsx as jsx18 } from "react/jsx-runtime";
|
|
3894
|
+
var ActivationFlowContext = createContext10(null);
|
|
3895
|
+
function useFlowCtx(part) {
|
|
3896
|
+
const ctx = useContext14(ActivationFlowContext);
|
|
3897
|
+
if (!ctx) {
|
|
3898
|
+
throw new Error(`ActivationFlow.${part} must be rendered inside <ActivationFlow.Root>.`);
|
|
3899
|
+
}
|
|
3900
|
+
return ctx;
|
|
3901
|
+
}
|
|
3902
|
+
var Root7 = forwardRef10(function ActivationFlowRoot({
|
|
3903
|
+
productRef,
|
|
3904
|
+
planRef: planRefProp,
|
|
3905
|
+
onSuccess,
|
|
3906
|
+
onError,
|
|
3907
|
+
retryDelayMs = 1500,
|
|
3908
|
+
retryBackoffMs = 2e3,
|
|
3909
|
+
asChild,
|
|
3910
|
+
children,
|
|
3911
|
+
...rest
|
|
3912
|
+
}, forwardedRef) {
|
|
3913
|
+
const solva = useContext14(SolvaPayContext);
|
|
3914
|
+
if (!solva) throw new MissingProviderError("ActivationFlow");
|
|
3915
|
+
if (!productRef) throw new MissingProductRefError("ActivationFlow");
|
|
3916
|
+
const planSelection = usePlanSelection();
|
|
3917
|
+
const resolvedPlanRef = planRefProp ?? planSelection?.selectedPlanRef ?? void 0;
|
|
3918
|
+
const { plan } = usePlan({ planRef: resolvedPlanRef, productRef });
|
|
3919
|
+
const { activate, state, error, result, reset } = useActivation();
|
|
3920
|
+
const currency = plan?.currency ?? "USD";
|
|
3921
|
+
const amountSelector = useTopupAmountSelector({ currency });
|
|
3922
|
+
const { adjustBalance, creditsPerMinorUnit, displayExchangeRate } = useBalance();
|
|
3923
|
+
const [step, setStep] = useState13("summary");
|
|
3924
|
+
const calledSuccessRef = useRef7(false);
|
|
3925
|
+
const retryTimeoutRef = useRef7(null);
|
|
3926
|
+
useEffect11(() => {
|
|
3927
|
+
if (state === "activated" && !calledSuccessRef.current) {
|
|
3928
|
+
calledSuccessRef.current = true;
|
|
3929
|
+
setStep("activated");
|
|
3930
|
+
if (result) {
|
|
3931
|
+
const activationResult = { kind: "activated", result };
|
|
3932
|
+
onSuccess?.(activationResult);
|
|
3933
|
+
}
|
|
3934
|
+
}
|
|
3935
|
+
}, [state, result, onSuccess]);
|
|
3936
|
+
useEffect11(() => {
|
|
3937
|
+
if (state === "topup_required" && (step === "summary" || step === "activating")) {
|
|
3938
|
+
setStep("selectAmount");
|
|
3939
|
+
}
|
|
3940
|
+
}, [state, step]);
|
|
3941
|
+
useEffect11(() => {
|
|
3942
|
+
if ((state === "error" || state === "payment_required") && error) {
|
|
3943
|
+
setStep("error");
|
|
3944
|
+
if (state === "error") onError?.(new Error(error));
|
|
3945
|
+
}
|
|
3946
|
+
}, [state, error, onError]);
|
|
3947
|
+
const handleActivate = useCallback14(async () => {
|
|
3948
|
+
if (!resolvedPlanRef) return;
|
|
3949
|
+
setStep("activating");
|
|
3950
|
+
await activate({ productRef, planRef: resolvedPlanRef });
|
|
3951
|
+
}, [activate, productRef, resolvedPlanRef]);
|
|
3952
|
+
const goToTopupPayment = useCallback14(() => {
|
|
3953
|
+
if (amountSelector.validate()) setStep("topupPayment");
|
|
3954
|
+
}, [amountSelector]);
|
|
3955
|
+
const backToSelectAmount = useCallback14(() => {
|
|
3956
|
+
setStep("selectAmount");
|
|
3957
|
+
}, []);
|
|
3958
|
+
const retryActivation = useCallback14(async () => {
|
|
3959
|
+
if (!resolvedPlanRef) return;
|
|
3960
|
+
setStep("retrying");
|
|
3961
|
+
const amountMinor = Math.round((amountSelector.resolvedAmount || 0) * 100);
|
|
3962
|
+
const rate = displayExchangeRate ?? 1;
|
|
3963
|
+
if (creditsPerMinorUnit) {
|
|
3964
|
+
adjustBalance(Math.floor(amountMinor / rate * creditsPerMinorUnit));
|
|
3965
|
+
}
|
|
3966
|
+
await new Promise((r) => setTimeout(r, retryDelayMs));
|
|
3967
|
+
await activate({ productRef, planRef: resolvedPlanRef });
|
|
3968
|
+
}, [
|
|
3969
|
+
resolvedPlanRef,
|
|
3970
|
+
amountSelector.resolvedAmount,
|
|
3971
|
+
displayExchangeRate,
|
|
3972
|
+
creditsPerMinorUnit,
|
|
3973
|
+
adjustBalance,
|
|
3974
|
+
retryDelayMs,
|
|
3975
|
+
activate,
|
|
3976
|
+
productRef
|
|
3977
|
+
]);
|
|
3978
|
+
const handleTopupSuccess = useCallback14(async () => {
|
|
3979
|
+
await retryActivation();
|
|
3980
|
+
}, [retryActivation]);
|
|
3981
|
+
useEffect11(() => {
|
|
3982
|
+
if (step !== "retrying") return;
|
|
3983
|
+
if (state !== "topup_required") return;
|
|
3984
|
+
if (!resolvedPlanRef) return;
|
|
3985
|
+
retryTimeoutRef.current = setTimeout(async () => {
|
|
3986
|
+
await activate({ productRef, planRef: resolvedPlanRef });
|
|
3987
|
+
}, retryBackoffMs);
|
|
3988
|
+
return () => {
|
|
3989
|
+
if (retryTimeoutRef.current) clearTimeout(retryTimeoutRef.current);
|
|
3990
|
+
};
|
|
3991
|
+
}, [step, state, resolvedPlanRef, retryBackoffMs, activate, productRef]);
|
|
3992
|
+
const resetFlow = useCallback14(() => {
|
|
3993
|
+
reset();
|
|
3994
|
+
calledSuccessRef.current = false;
|
|
3995
|
+
setStep("summary");
|
|
3996
|
+
}, [reset]);
|
|
3997
|
+
const amountCents = Math.round((amountSelector.resolvedAmount || 0) * 100);
|
|
3998
|
+
const ctx = useMemo12(
|
|
3999
|
+
() => ({
|
|
4000
|
+
step,
|
|
4001
|
+
plan,
|
|
4002
|
+
productRef,
|
|
4003
|
+
planRef: resolvedPlanRef ?? "",
|
|
4004
|
+
amountSelector,
|
|
4005
|
+
amountCents,
|
|
4006
|
+
currency,
|
|
4007
|
+
activate: handleActivate,
|
|
4008
|
+
reset: resetFlow,
|
|
4009
|
+
goToTopupPayment,
|
|
4010
|
+
backToSelectAmount,
|
|
4011
|
+
onTopupSuccess: handleTopupSuccess,
|
|
4012
|
+
error,
|
|
4013
|
+
onError
|
|
4014
|
+
}),
|
|
4015
|
+
[
|
|
4016
|
+
step,
|
|
4017
|
+
plan,
|
|
4018
|
+
productRef,
|
|
4019
|
+
resolvedPlanRef,
|
|
4020
|
+
amountSelector,
|
|
4021
|
+
amountCents,
|
|
4022
|
+
currency,
|
|
4023
|
+
handleActivate,
|
|
4024
|
+
resetFlow,
|
|
4025
|
+
goToTopupPayment,
|
|
4026
|
+
backToSelectAmount,
|
|
4027
|
+
handleTopupSuccess,
|
|
4028
|
+
error,
|
|
4029
|
+
onError
|
|
4030
|
+
]
|
|
4031
|
+
);
|
|
4032
|
+
const Comp = asChild ? Slot : "div";
|
|
4033
|
+
return /* @__PURE__ */ jsx18(ActivationFlowContext.Provider, { value: ctx, children: /* @__PURE__ */ jsx18(
|
|
4034
|
+
Comp,
|
|
4035
|
+
{
|
|
4036
|
+
ref: forwardedRef,
|
|
4037
|
+
"data-solvapay-activation-flow": "",
|
|
4038
|
+
"data-state": step,
|
|
4039
|
+
...rest,
|
|
4040
|
+
children
|
|
4041
|
+
}
|
|
4042
|
+
) });
|
|
4043
|
+
});
|
|
4044
|
+
function matchStep(step, allowed) {
|
|
4045
|
+
return allowed.includes(step);
|
|
4046
|
+
}
|
|
4047
|
+
var Summary2 = forwardRef10(function ActivationFlowSummary({ asChild, children, ...rest }, forwardedRef) {
|
|
4048
|
+
const ctx = useFlowCtx("Summary");
|
|
4049
|
+
if (!matchStep(ctx.step, ["summary", "activating"])) return null;
|
|
4050
|
+
const Comp = asChild ? Slot : "div";
|
|
4051
|
+
return /* @__PURE__ */ jsx18(Comp, { ref: forwardedRef, "data-solvapay-activation-flow-summary": "", ...rest, children });
|
|
4052
|
+
});
|
|
4053
|
+
var ActivateButton = forwardRef10(
|
|
4054
|
+
function ActivationFlowActivateButton({ asChild, onClick, children, ...rest }, forwardedRef) {
|
|
4055
|
+
const ctx = useFlowCtx("ActivateButton");
|
|
4056
|
+
const copy = useCopy();
|
|
4057
|
+
if (!matchStep(ctx.step, ["summary", "activating"])) return null;
|
|
4058
|
+
const isActivating = ctx.step === "activating";
|
|
4059
|
+
const disabled = isActivating;
|
|
4060
|
+
const commonProps = {
|
|
4061
|
+
"data-solvapay-activation-flow-activate": "",
|
|
4062
|
+
"data-state": isActivating ? "activating" : "idle",
|
|
4063
|
+
"aria-busy": isActivating,
|
|
4064
|
+
disabled,
|
|
4065
|
+
onClick: composeEventHandlers(onClick, () => {
|
|
4066
|
+
void ctx.activate();
|
|
4067
|
+
}),
|
|
4068
|
+
...rest
|
|
4069
|
+
};
|
|
4070
|
+
const label = isActivating ? copy.activationFlow.activatingLabel : copy.activationFlow.activateButton;
|
|
4071
|
+
if (asChild) {
|
|
4072
|
+
return (
|
|
4073
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
4074
|
+
/* @__PURE__ */ jsx18(Slot, { ref: forwardedRef, ...commonProps, children: children ?? /* @__PURE__ */ jsx18(Fragment7, { children: label }) })
|
|
4075
|
+
);
|
|
4076
|
+
}
|
|
4077
|
+
return /* @__PURE__ */ jsx18("button", { ref: forwardedRef, type: "button", ...commonProps, children: children ?? label });
|
|
4078
|
+
}
|
|
4079
|
+
);
|
|
4080
|
+
var AmountPickerMount = ({ children }) => {
|
|
4081
|
+
const ctx = useFlowCtx("AmountPicker");
|
|
4082
|
+
if (ctx.step !== "selectAmount") return null;
|
|
4083
|
+
return /* @__PURE__ */ jsx18("div", { "data-solvapay-activation-flow-amount-picker": "", children: /* @__PURE__ */ jsx18(AmountPicker.Root, { currency: ctx.currency, children }) });
|
|
4084
|
+
};
|
|
4085
|
+
var ContinueButton = forwardRef10(
|
|
4086
|
+
function ActivationFlowContinueButton({ asChild, onClick, children, ...rest }, forwardedRef) {
|
|
4087
|
+
const ctx = useFlowCtx("ContinueButton");
|
|
4088
|
+
const copy = useCopy();
|
|
4089
|
+
if (ctx.step !== "selectAmount") return null;
|
|
4090
|
+
const disabled = !ctx.amountSelector.resolvedAmount;
|
|
4091
|
+
const commonProps = {
|
|
4092
|
+
"data-solvapay-activation-flow-continue": "",
|
|
4093
|
+
"data-state": disabled ? "disabled" : "idle",
|
|
4094
|
+
disabled,
|
|
4095
|
+
"aria-disabled": disabled || void 0,
|
|
4096
|
+
onClick: composeEventHandlers(onClick, () => {
|
|
4097
|
+
ctx.goToTopupPayment();
|
|
4098
|
+
}),
|
|
4099
|
+
...rest
|
|
4100
|
+
};
|
|
4101
|
+
if (asChild) {
|
|
4102
|
+
return (
|
|
4103
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
4104
|
+
/* @__PURE__ */ jsx18(Slot, { ref: forwardedRef, ...commonProps, children: children ?? /* @__PURE__ */ jsx18(Fragment7, { children: copy.activationFlow.continueToPayment }) })
|
|
4105
|
+
);
|
|
4106
|
+
}
|
|
4107
|
+
return /* @__PURE__ */ jsx18("button", { ref: forwardedRef, type: "button", ...commonProps, children: children ?? copy.activationFlow.continueToPayment });
|
|
4108
|
+
}
|
|
4109
|
+
);
|
|
4110
|
+
var Retrying = forwardRef10(function ActivationFlowRetrying({ asChild, children, ...rest }, forwardedRef) {
|
|
4111
|
+
const ctx = useFlowCtx("Retrying");
|
|
4112
|
+
if (ctx.step !== "retrying") return null;
|
|
4113
|
+
const Comp = asChild ? Slot : "div";
|
|
4114
|
+
return /* @__PURE__ */ jsx18(Comp, { ref: forwardedRef, "data-solvapay-activation-flow-retrying": "", ...rest, children });
|
|
4115
|
+
});
|
|
4116
|
+
var Activated = forwardRef10(function ActivationFlowActivated({ asChild, children, ...rest }, forwardedRef) {
|
|
4117
|
+
const ctx = useFlowCtx("Activated");
|
|
4118
|
+
if (ctx.step !== "activated") return null;
|
|
4119
|
+
const Comp = asChild ? Slot : "div";
|
|
4120
|
+
return /* @__PURE__ */ jsx18(Comp, { ref: forwardedRef, "data-solvapay-activation-flow-activated": "", ...rest, children });
|
|
4121
|
+
});
|
|
4122
|
+
var Loading5 = forwardRef10(function ActivationFlowLoading({ asChild, children, ...rest }, forwardedRef) {
|
|
4123
|
+
const ctx = useFlowCtx("Loading");
|
|
4124
|
+
if (ctx.plan) return null;
|
|
4125
|
+
const Comp = asChild ? Slot : "div";
|
|
4126
|
+
return /* @__PURE__ */ jsx18(Comp, { ref: forwardedRef, "data-solvapay-activation-flow-loading": "", ...rest, children });
|
|
4127
|
+
});
|
|
4128
|
+
var ErrorSlot5 = forwardRef10(function ActivationFlowError({ asChild, children, ...rest }, forwardedRef) {
|
|
4129
|
+
const ctx = useFlowCtx("Error");
|
|
4130
|
+
if (ctx.step !== "error") return null;
|
|
4131
|
+
const Comp = asChild ? Slot : "div";
|
|
4132
|
+
return /* @__PURE__ */ jsx18(
|
|
4133
|
+
Comp,
|
|
4134
|
+
{
|
|
4135
|
+
ref: forwardedRef,
|
|
4136
|
+
role: "alert",
|
|
4137
|
+
"data-solvapay-activation-flow-error": "",
|
|
4138
|
+
...rest,
|
|
4139
|
+
children: children ?? ctx.error
|
|
4140
|
+
}
|
|
4141
|
+
);
|
|
4142
|
+
});
|
|
4143
|
+
var ActivationFlowRoot2 = Root7;
|
|
4144
|
+
var ActivationFlowSummary2 = Summary2;
|
|
4145
|
+
var ActivationFlowActivateButton2 = ActivateButton;
|
|
4146
|
+
var ActivationFlowAmountPicker = AmountPickerMount;
|
|
4147
|
+
var ActivationFlowContinueButton2 = ContinueButton;
|
|
4148
|
+
var ActivationFlowRetrying2 = Retrying;
|
|
4149
|
+
var ActivationFlowActivated2 = Activated;
|
|
4150
|
+
var ActivationFlowLoading2 = Loading5;
|
|
4151
|
+
var ActivationFlowError2 = ErrorSlot5;
|
|
4152
|
+
var ActivationFlow = {
|
|
4153
|
+
Root: Root7,
|
|
4154
|
+
Summary: Summary2,
|
|
4155
|
+
ActivateButton,
|
|
4156
|
+
AmountPicker: AmountPickerMount,
|
|
4157
|
+
ContinueButton,
|
|
4158
|
+
Retrying,
|
|
4159
|
+
Activated,
|
|
4160
|
+
Loading: Loading5,
|
|
4161
|
+
Error: ErrorSlot5
|
|
4162
|
+
};
|
|
4163
|
+
function useActivationFlow() {
|
|
4164
|
+
return useFlowCtx("useActivationFlow");
|
|
4165
|
+
}
|
|
4166
|
+
|
|
4167
|
+
// src/hooks/usePurchaseActions.ts
|
|
4168
|
+
import { useState as useState14, useCallback as useCallback15 } from "react";
|
|
4169
|
+
function usePurchaseActions() {
|
|
4170
|
+
const ctx = useSolvaPay();
|
|
4171
|
+
const [isCancelling, setIsCancelling] = useState14(false);
|
|
4172
|
+
const [isReactivating, setIsReactivating] = useState14(false);
|
|
4173
|
+
const [isActivating, setIsActivating] = useState14(false);
|
|
4174
|
+
const cancelRenewal = useCallback15(
|
|
4175
|
+
async (params) => {
|
|
4176
|
+
setIsCancelling(true);
|
|
4177
|
+
try {
|
|
4178
|
+
return await ctx.cancelRenewal(params);
|
|
4179
|
+
} finally {
|
|
4180
|
+
setIsCancelling(false);
|
|
4181
|
+
}
|
|
4182
|
+
},
|
|
4183
|
+
[ctx.cancelRenewal]
|
|
4184
|
+
);
|
|
4185
|
+
const reactivateRenewal = useCallback15(
|
|
4186
|
+
async (params) => {
|
|
4187
|
+
setIsReactivating(true);
|
|
4188
|
+
try {
|
|
4189
|
+
return await ctx.reactivateRenewal(params);
|
|
4190
|
+
} finally {
|
|
4191
|
+
setIsReactivating(false);
|
|
4192
|
+
}
|
|
4193
|
+
},
|
|
4194
|
+
[ctx.reactivateRenewal]
|
|
4195
|
+
);
|
|
4196
|
+
const activatePlan = useCallback15(
|
|
4197
|
+
async (params) => {
|
|
4198
|
+
setIsActivating(true);
|
|
4199
|
+
try {
|
|
4200
|
+
return await ctx.activatePlan(params);
|
|
4201
|
+
} finally {
|
|
4202
|
+
setIsActivating(false);
|
|
4203
|
+
}
|
|
4204
|
+
},
|
|
4205
|
+
[ctx.activatePlan]
|
|
4206
|
+
);
|
|
4207
|
+
return {
|
|
4208
|
+
cancelRenewal,
|
|
4209
|
+
reactivateRenewal,
|
|
4210
|
+
activatePlan,
|
|
4211
|
+
isCancelling,
|
|
4212
|
+
isReactivating,
|
|
4213
|
+
isActivating
|
|
4214
|
+
};
|
|
4215
|
+
}
|
|
4216
|
+
|
|
4217
|
+
// src/primitives/CancelPlanButton.tsx
|
|
4218
|
+
import { forwardRef as forwardRef11, useCallback as useCallback16, useContext as useContext15 } from "react";
|
|
4219
|
+
import { Fragment as Fragment8, jsx as jsx19 } from "react/jsx-runtime";
|
|
4220
|
+
function resolveConfirmText(confirm, purchase, defaults) {
|
|
4221
|
+
if (confirm === false) return null;
|
|
4222
|
+
if (typeof confirm === "string") return confirm;
|
|
4223
|
+
const planType = purchase?.planSnapshot?.planType;
|
|
4224
|
+
if (planType === "usage-based") return defaults.usageBased;
|
|
4225
|
+
return defaults.recurring;
|
|
4226
|
+
}
|
|
4227
|
+
var CancelPlanButton = forwardRef11(
|
|
4228
|
+
function CancelPlanButton2({
|
|
4229
|
+
asChild,
|
|
4230
|
+
purchaseRef,
|
|
4231
|
+
reason,
|
|
4232
|
+
confirm = true,
|
|
4233
|
+
onCancelled,
|
|
4234
|
+
onError,
|
|
4235
|
+
onClick,
|
|
4236
|
+
children,
|
|
4237
|
+
...rest
|
|
4238
|
+
}, forwardedRef) {
|
|
4239
|
+
const solva = useContext15(SolvaPayContext);
|
|
4240
|
+
if (!solva) throw new MissingProviderError("CancelPlanButton");
|
|
4241
|
+
const copy = useCopy();
|
|
4242
|
+
const { activePurchase } = usePurchase();
|
|
4243
|
+
const { cancelRenewal, isCancelling } = usePurchaseActions();
|
|
4244
|
+
const effectivePurchase = purchaseRef ? activePurchase && activePurchase.reference === purchaseRef ? activePurchase : { reference: purchaseRef } : activePurchase;
|
|
4245
|
+
const effectiveRef = purchaseRef ?? effectivePurchase?.reference;
|
|
4246
|
+
const cancel = useCallback16(async () => {
|
|
4247
|
+
if (!effectiveRef) return;
|
|
4248
|
+
const confirmText = resolveConfirmText(confirm, effectivePurchase, {
|
|
4249
|
+
recurring: copy.cancelPlan.confirmRecurring,
|
|
4250
|
+
usageBased: copy.cancelPlan.confirmUsageBased
|
|
4251
|
+
});
|
|
4252
|
+
if (confirmText && typeof window !== "undefined" && !window.confirm(confirmText)) {
|
|
4253
|
+
return;
|
|
4254
|
+
}
|
|
4255
|
+
try {
|
|
4256
|
+
await cancelRenewal({ purchaseRef: effectiveRef, reason });
|
|
4257
|
+
onCancelled?.();
|
|
4258
|
+
} catch (err) {
|
|
4259
|
+
onError?.(err instanceof Error ? err : new Error(String(err)));
|
|
4260
|
+
}
|
|
4261
|
+
}, [effectiveRef, effectivePurchase, confirm, copy, cancelRenewal, reason, onCancelled, onError]);
|
|
4262
|
+
const disabled = isCancelling || !effectiveRef;
|
|
4263
|
+
const state = isCancelling ? "cancelling" : "idle";
|
|
4264
|
+
const commonProps = {
|
|
4265
|
+
"data-solvapay-cancel-plan": "",
|
|
4266
|
+
"data-state": state,
|
|
4267
|
+
"aria-busy": isCancelling,
|
|
4268
|
+
"aria-disabled": disabled || void 0,
|
|
4269
|
+
disabled,
|
|
4270
|
+
onClick: composeEventHandlers(onClick, () => {
|
|
4271
|
+
void cancel();
|
|
4272
|
+
}),
|
|
4273
|
+
...rest
|
|
4274
|
+
};
|
|
4275
|
+
const label = isCancelling ? copy.cancelPlan.buttonLoading : copy.cancelPlan.button;
|
|
4276
|
+
if (asChild) {
|
|
4277
|
+
return (
|
|
4278
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
4279
|
+
/* @__PURE__ */ jsx19(Slot, { ref: forwardedRef, ...commonProps, children: children ?? /* @__PURE__ */ jsx19(Fragment8, { children: label }) })
|
|
4280
|
+
);
|
|
4281
|
+
}
|
|
4282
|
+
return /* @__PURE__ */ jsx19("button", { ref: forwardedRef, type: "button", ...commonProps, children: children ?? label });
|
|
4283
|
+
}
|
|
4284
|
+
);
|
|
4285
|
+
|
|
4286
|
+
// src/hooks/usePurchaseStatus.ts
|
|
4287
|
+
import { useMemo as useMemo13, useCallback as useCallback17 } from "react";
|
|
4288
|
+
function usePurchaseStatus() {
|
|
4289
|
+
const { purchases } = usePurchase();
|
|
4290
|
+
const locale = useLocale();
|
|
4291
|
+
const isPaidPurchase2 = useCallback17((p) => {
|
|
4292
|
+
return (p.amount ?? 0) > 0;
|
|
4293
|
+
}, []);
|
|
4294
|
+
const purchaseData = useMemo13(() => {
|
|
4295
|
+
const cancelledPaidPurchases = purchases.filter((p) => {
|
|
4296
|
+
return p.status === "active" && p.cancelledAt && isPaidPurchase2(p);
|
|
4297
|
+
});
|
|
4298
|
+
const cancelledPurchase = cancelledPaidPurchases.sort(
|
|
4299
|
+
(a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime()
|
|
4300
|
+
)[0] || null;
|
|
4301
|
+
const shouldShowCancelledNotice = !!cancelledPurchase;
|
|
4302
|
+
return {
|
|
4303
|
+
cancelledPurchase,
|
|
4304
|
+
shouldShowCancelledNotice
|
|
4305
|
+
};
|
|
4306
|
+
}, [purchases, isPaidPurchase2]);
|
|
4307
|
+
const formatDate = useCallback17(
|
|
4308
|
+
(dateString) => {
|
|
4309
|
+
if (!dateString) return null;
|
|
4310
|
+
return new Date(dateString).toLocaleDateString(locale || "en-US", {
|
|
4311
|
+
year: "numeric",
|
|
4312
|
+
month: "long",
|
|
4313
|
+
day: "numeric"
|
|
4314
|
+
});
|
|
4315
|
+
},
|
|
4316
|
+
[locale]
|
|
4317
|
+
);
|
|
4318
|
+
const getDaysUntilExpiration = useCallback17((endDate) => {
|
|
4319
|
+
if (!endDate) return null;
|
|
4320
|
+
const now = /* @__PURE__ */ new Date();
|
|
4321
|
+
const expiration = new Date(endDate);
|
|
4322
|
+
const diffTime = expiration.getTime() - now.getTime();
|
|
4323
|
+
const diffDays = Math.ceil(diffTime / (1e3 * 60 * 60 * 24));
|
|
4324
|
+
return diffDays > 0 ? diffDays : 0;
|
|
4325
|
+
}, []);
|
|
4326
|
+
return {
|
|
4327
|
+
cancelledPurchase: purchaseData.cancelledPurchase,
|
|
4328
|
+
shouldShowCancelledNotice: purchaseData.shouldShowCancelledNotice,
|
|
4329
|
+
formatDate,
|
|
4330
|
+
getDaysUntilExpiration
|
|
4331
|
+
};
|
|
4332
|
+
}
|
|
4333
|
+
|
|
4334
|
+
// src/primitives/CancelledPlanNotice.tsx
|
|
4335
|
+
import {
|
|
4336
|
+
createContext as createContext11,
|
|
4337
|
+
forwardRef as forwardRef12,
|
|
4338
|
+
useCallback as useCallback18,
|
|
4339
|
+
useContext as useContext16,
|
|
4340
|
+
useMemo as useMemo14
|
|
4341
|
+
} from "react";
|
|
4342
|
+
import { Fragment as Fragment9, jsx as jsx20 } from "react/jsx-runtime";
|
|
4343
|
+
var CancelledPlanNoticeContext = createContext11(null);
|
|
4344
|
+
function useNoticeCtx(part) {
|
|
4345
|
+
const ctx = useContext16(CancelledPlanNoticeContext);
|
|
4346
|
+
if (!ctx) {
|
|
4347
|
+
throw new Error(
|
|
4348
|
+
`CancelledPlanNotice.${part} must be rendered inside <CancelledPlanNotice.Root>.`
|
|
4349
|
+
);
|
|
4350
|
+
}
|
|
4351
|
+
return ctx;
|
|
4352
|
+
}
|
|
4353
|
+
var Root8 = forwardRef12(function CancelledPlanNoticeRoot({ onReactivated, onError, asChild, children, ...rest }, forwardedRef) {
|
|
4354
|
+
const solva = useContext16(SolvaPayContext);
|
|
4355
|
+
if (!solva) throw new MissingProviderError("CancelledPlanNotice");
|
|
4356
|
+
const {
|
|
4357
|
+
cancelledPurchase,
|
|
4358
|
+
shouldShowCancelledNotice,
|
|
4359
|
+
formatDate,
|
|
4360
|
+
getDaysUntilExpiration
|
|
4361
|
+
} = usePurchaseStatus();
|
|
4362
|
+
const { reactivateRenewal, isReactivating } = usePurchaseActions();
|
|
4363
|
+
const reactivate = useCallback18(async () => {
|
|
4364
|
+
if (!cancelledPurchase) return;
|
|
4365
|
+
try {
|
|
4366
|
+
await reactivateRenewal({ purchaseRef: cancelledPurchase.reference });
|
|
4367
|
+
onReactivated?.();
|
|
4368
|
+
} catch (err) {
|
|
4369
|
+
onError?.(err instanceof Error ? err : new Error(String(err)));
|
|
4370
|
+
}
|
|
4371
|
+
}, [cancelledPurchase, reactivateRenewal, onReactivated, onError]);
|
|
4372
|
+
const daysRemaining = useMemo14(
|
|
4373
|
+
() => cancelledPurchase ? getDaysUntilExpiration(cancelledPurchase.endDate) : null,
|
|
4374
|
+
[cancelledPurchase, getDaysUntilExpiration]
|
|
4375
|
+
);
|
|
4376
|
+
const ctx = useMemo14(() => {
|
|
4377
|
+
if (!cancelledPurchase) return null;
|
|
4378
|
+
const state = daysRemaining != null && daysRemaining > 0 ? "active" : "expired";
|
|
4379
|
+
return {
|
|
4380
|
+
purchase: cancelledPurchase,
|
|
4381
|
+
state,
|
|
4382
|
+
daysRemaining,
|
|
4383
|
+
hasReason: !!cancelledPurchase.cancellationReason,
|
|
4384
|
+
formatDate,
|
|
4385
|
+
reactivate,
|
|
4386
|
+
isReactivating
|
|
4387
|
+
};
|
|
4388
|
+
}, [cancelledPurchase, daysRemaining, formatDate, reactivate, isReactivating]);
|
|
4389
|
+
if (!shouldShowCancelledNotice || !ctx) return null;
|
|
4390
|
+
const Comp = asChild ? Slot : "div";
|
|
4391
|
+
return /* @__PURE__ */ jsx20(CancelledPlanNoticeContext.Provider, { value: ctx, children: /* @__PURE__ */ jsx20(
|
|
4392
|
+
Comp,
|
|
4393
|
+
{
|
|
4394
|
+
ref: forwardedRef,
|
|
4395
|
+
"data-solvapay-cancelled-notice": "",
|
|
4396
|
+
"data-state": ctx.state,
|
|
4397
|
+
"data-has-reason": ctx.hasReason ? "" : void 0,
|
|
4398
|
+
...rest,
|
|
4399
|
+
children
|
|
4400
|
+
}
|
|
4401
|
+
) });
|
|
4402
|
+
});
|
|
4403
|
+
var Heading2 = forwardRef12(function CancelledPlanNoticeHeading({ asChild, children, ...rest }, forwardedRef) {
|
|
4404
|
+
useNoticeCtx("Heading");
|
|
4405
|
+
const copy = useCopy();
|
|
4406
|
+
const Comp = asChild ? Slot : "p";
|
|
4407
|
+
return /* @__PURE__ */ jsx20(Comp, { ref: forwardedRef, "data-solvapay-cancelled-notice-heading": "", ...rest, children: children ?? copy.cancelledNotice.heading });
|
|
4408
|
+
});
|
|
4409
|
+
var Expires = forwardRef12(function CancelledPlanNoticeExpires({ asChild, children, ...rest }, forwardedRef) {
|
|
4410
|
+
const ctx = useNoticeCtx("Expires");
|
|
4411
|
+
const copy = useCopy();
|
|
4412
|
+
const date = ctx.formatDate(ctx.purchase.endDate);
|
|
4413
|
+
if (!ctx.purchase.endDate) {
|
|
4414
|
+
const Comp2 = asChild ? Slot : "p";
|
|
4415
|
+
return /* @__PURE__ */ jsx20(Comp2, { ref: forwardedRef, "data-solvapay-cancelled-notice-expires": "", ...rest, children: children ?? copy.cancelledNotice.accessEnded });
|
|
4416
|
+
}
|
|
4417
|
+
const Comp = asChild ? Slot : "p";
|
|
4418
|
+
return /* @__PURE__ */ jsx20(Comp, { ref: forwardedRef, "data-solvapay-cancelled-notice-expires": "", ...rest, children: children ?? interpolate(copy.cancelledNotice.expiresLabel, { date: date ?? "" }) });
|
|
4419
|
+
});
|
|
4420
|
+
var DaysRemaining = forwardRef12(
|
|
4421
|
+
function CancelledPlanNoticeDaysRemaining({ asChild, children, ...rest }, forwardedRef) {
|
|
4422
|
+
const ctx = useNoticeCtx("DaysRemaining");
|
|
4423
|
+
const copy = useCopy();
|
|
4424
|
+
if (ctx.daysRemaining == null || ctx.daysRemaining <= 0) return null;
|
|
4425
|
+
const template = ctx.daysRemaining === 1 ? copy.cancelledNotice.dayRemaining : copy.cancelledNotice.daysRemaining;
|
|
4426
|
+
const Comp = asChild ? Slot : "p";
|
|
4427
|
+
return /* @__PURE__ */ jsx20(Comp, { ref: forwardedRef, "data-solvapay-cancelled-notice-days-remaining": "", ...rest, children: children ?? interpolate(template, { days: ctx.daysRemaining }) });
|
|
4428
|
+
}
|
|
4429
|
+
);
|
|
4430
|
+
var AccessUntil = forwardRef12(
|
|
4431
|
+
function CancelledPlanNoticeAccessUntil({ asChild, children, ...rest }, forwardedRef) {
|
|
4432
|
+
const ctx = useNoticeCtx("AccessUntil");
|
|
4433
|
+
const copy = useCopy();
|
|
4434
|
+
if (!ctx.purchase.endDate) return null;
|
|
4435
|
+
const Comp = asChild ? Slot : "p";
|
|
4436
|
+
return /* @__PURE__ */ jsx20(Comp, { ref: forwardedRef, "data-solvapay-cancelled-notice-access-until": "", ...rest, children: children ?? interpolate(copy.cancelledNotice.accessUntil, {
|
|
4437
|
+
product: ctx.purchase.productName
|
|
4438
|
+
}) });
|
|
4439
|
+
}
|
|
4440
|
+
);
|
|
4441
|
+
var CancelledOn = forwardRef12(
|
|
4442
|
+
function CancelledPlanNoticeCancelledOn({ asChild, children, ...rest }, forwardedRef) {
|
|
4443
|
+
const ctx = useNoticeCtx("CancelledOn");
|
|
4444
|
+
const copy = useCopy();
|
|
4445
|
+
if (!ctx.purchase.cancelledAt) return null;
|
|
4446
|
+
const date = ctx.formatDate(ctx.purchase.cancelledAt);
|
|
4447
|
+
const Comp = asChild ? Slot : "p";
|
|
4448
|
+
return /* @__PURE__ */ jsx20(Comp, { ref: forwardedRef, "data-solvapay-cancelled-notice-cancelled-on": "", ...rest, children: children ?? interpolate(copy.cancelledNotice.cancelledOn, { date: date ?? "" }) });
|
|
4449
|
+
}
|
|
4450
|
+
);
|
|
4451
|
+
var Reason = forwardRef12(function CancelledPlanNoticeReason({ asChild, children, ...rest }, forwardedRef) {
|
|
4452
|
+
const ctx = useNoticeCtx("Reason");
|
|
4453
|
+
if (!ctx.hasReason) return null;
|
|
4454
|
+
const Comp = asChild ? Slot : "span";
|
|
4455
|
+
return /* @__PURE__ */ jsx20(Comp, { ref: forwardedRef, "data-solvapay-cancelled-notice-reason": "", ...rest, children: children ?? ctx.purchase.cancellationReason });
|
|
4456
|
+
});
|
|
4457
|
+
var ReactivateButton = forwardRef12(
|
|
4458
|
+
function CancelledPlanNoticeReactivateButton({ asChild, onClick, children, ...rest }, forwardedRef) {
|
|
4459
|
+
const ctx = useNoticeCtx("ReactivateButton");
|
|
4460
|
+
const copy = useCopy();
|
|
4461
|
+
const disabled = ctx.isReactivating;
|
|
4462
|
+
const commonProps = {
|
|
4463
|
+
"data-solvapay-cancelled-notice-reactivate": "",
|
|
4464
|
+
"data-state": ctx.isReactivating ? "reactivating" : "idle",
|
|
4465
|
+
"aria-busy": ctx.isReactivating,
|
|
4466
|
+
"aria-disabled": disabled || void 0,
|
|
4467
|
+
disabled,
|
|
4468
|
+
onClick: composeEventHandlers(onClick, () => {
|
|
4469
|
+
void ctx.reactivate();
|
|
4470
|
+
}),
|
|
4471
|
+
...rest
|
|
4472
|
+
};
|
|
4473
|
+
const label = ctx.isReactivating ? copy.cancelledNotice.reactivateButtonLoading : copy.cancelledNotice.reactivateButton;
|
|
4474
|
+
if (asChild) {
|
|
4475
|
+
return (
|
|
4476
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
4477
|
+
/* @__PURE__ */ jsx20(Slot, { ref: forwardedRef, ...commonProps, children: children ?? /* @__PURE__ */ jsx20(Fragment9, { children: label }) })
|
|
4478
|
+
);
|
|
4479
|
+
}
|
|
4480
|
+
return /* @__PURE__ */ jsx20("button", { ref: forwardedRef, type: "button", ...commonProps, children: children ?? label });
|
|
4481
|
+
}
|
|
4482
|
+
);
|
|
4483
|
+
var CancelledPlanNoticeRoot2 = Root8;
|
|
4484
|
+
var CancelledPlanNoticeHeading2 = Heading2;
|
|
4485
|
+
var CancelledPlanNoticeExpires2 = Expires;
|
|
4486
|
+
var CancelledPlanNoticeDaysRemaining2 = DaysRemaining;
|
|
4487
|
+
var CancelledPlanNoticeAccessUntil2 = AccessUntil;
|
|
4488
|
+
var CancelledPlanNoticeCancelledOn2 = CancelledOn;
|
|
4489
|
+
var CancelledPlanNoticeReason2 = Reason;
|
|
4490
|
+
var CancelledPlanNoticeReactivateButton2 = ReactivateButton;
|
|
4491
|
+
var CancelledPlanNotice = {
|
|
4492
|
+
Root: Root8,
|
|
4493
|
+
Heading: Heading2,
|
|
4494
|
+
Expires,
|
|
4495
|
+
DaysRemaining,
|
|
4496
|
+
AccessUntil,
|
|
4497
|
+
CancelledOn,
|
|
4498
|
+
Reason,
|
|
4499
|
+
ReactivateButton
|
|
4500
|
+
};
|
|
4501
|
+
function useCancelledPlanNotice() {
|
|
4502
|
+
return useNoticeCtx("useCancelledPlanNotice");
|
|
4503
|
+
}
|
|
4504
|
+
|
|
4505
|
+
// src/primitives/CreditGate.tsx
|
|
4506
|
+
import {
|
|
4507
|
+
createContext as createContext12,
|
|
4508
|
+
forwardRef as forwardRef13,
|
|
4509
|
+
useContext as useContext17,
|
|
4510
|
+
useMemo as useMemo15
|
|
4511
|
+
} from "react";
|
|
4512
|
+
import { jsx as jsx21 } from "react/jsx-runtime";
|
|
4513
|
+
var CreditGateContext = createContext12(null);
|
|
4514
|
+
function useGateCtx2(part) {
|
|
4515
|
+
const ctx = useContext17(CreditGateContext);
|
|
4516
|
+
if (!ctx) {
|
|
4517
|
+
throw new Error(`CreditGate.${part} must be rendered inside <CreditGate.Root>.`);
|
|
4518
|
+
}
|
|
4519
|
+
return ctx;
|
|
4520
|
+
}
|
|
4521
|
+
var Root9 = forwardRef13(function CreditGateRoot({
|
|
4522
|
+
minCredits = 1,
|
|
4523
|
+
productRef,
|
|
4524
|
+
topupAmount = 1e3,
|
|
4525
|
+
topupCurrency = "usd",
|
|
4526
|
+
asChild,
|
|
4527
|
+
children,
|
|
4528
|
+
...rest
|
|
4529
|
+
}, forwardedRef) {
|
|
4530
|
+
const solva = useContext17(SolvaPayContext);
|
|
4531
|
+
if (!solva) throw new MissingProviderError("CreditGate");
|
|
4532
|
+
const { credits, loading } = useBalance();
|
|
4533
|
+
const { product } = useProduct(productRef);
|
|
4534
|
+
const hasCredits = credits != null && credits >= minCredits;
|
|
4535
|
+
const state = loading && credits == null ? "loading" : hasCredits ? "allowed" : "blocked";
|
|
4536
|
+
const ctx = useMemo15(
|
|
4537
|
+
() => ({
|
|
4538
|
+
state,
|
|
4539
|
+
loading,
|
|
4540
|
+
hasCredits,
|
|
4541
|
+
balance: credits,
|
|
4542
|
+
productName: product?.name ?? null,
|
|
4543
|
+
topupAmount,
|
|
4544
|
+
topupCurrency
|
|
4545
|
+
}),
|
|
4546
|
+
[state, loading, hasCredits, credits, product?.name, topupAmount, topupCurrency]
|
|
4547
|
+
);
|
|
4548
|
+
const Comp = asChild ? Slot : "div";
|
|
4549
|
+
return /* @__PURE__ */ jsx21(CreditGateContext.Provider, { value: ctx, children: /* @__PURE__ */ jsx21(
|
|
4550
|
+
Comp,
|
|
4551
|
+
{
|
|
4552
|
+
ref: forwardedRef,
|
|
4553
|
+
"data-solvapay-credit-gate": "",
|
|
4554
|
+
"data-state": state,
|
|
4555
|
+
...rest,
|
|
4556
|
+
children
|
|
4557
|
+
}
|
|
4558
|
+
) });
|
|
4559
|
+
});
|
|
4560
|
+
var Heading3 = forwardRef13(function CreditGateHeading({ asChild, children, ...rest }, forwardedRef) {
|
|
4561
|
+
const ctx = useGateCtx2("Heading");
|
|
4562
|
+
const copy = useCopy();
|
|
4563
|
+
if (ctx.state !== "blocked") return null;
|
|
4564
|
+
const Comp = asChild ? Slot : "h3";
|
|
4565
|
+
return /* @__PURE__ */ jsx21(Comp, { ref: forwardedRef, "data-solvapay-credit-gate-heading": "", ...rest, children: children ?? copy.creditGate.lowBalanceHeading });
|
|
4566
|
+
});
|
|
4567
|
+
var Subheading = forwardRef13(function CreditGateSubheading({ asChild, children, ...rest }, forwardedRef) {
|
|
4568
|
+
const ctx = useGateCtx2("Subheading");
|
|
4569
|
+
const copy = useCopy();
|
|
4570
|
+
if (ctx.state !== "blocked") return null;
|
|
4571
|
+
const text = interpolate(copy.creditGate.lowBalanceSubheading, {
|
|
4572
|
+
product: ctx.productName ?? "this product"
|
|
4573
|
+
});
|
|
4574
|
+
const Comp = asChild ? Slot : "p";
|
|
4575
|
+
return /* @__PURE__ */ jsx21(Comp, { ref: forwardedRef, "data-solvapay-credit-gate-subheading": "", ...rest, children: children ?? text });
|
|
4576
|
+
});
|
|
4577
|
+
var Topup = ({ amount, currency }) => {
|
|
4578
|
+
const ctx = useGateCtx2("Topup");
|
|
4579
|
+
if (ctx.state !== "blocked") return null;
|
|
4580
|
+
return /* @__PURE__ */ jsx21(
|
|
4581
|
+
TopupForm2,
|
|
4582
|
+
{
|
|
4583
|
+
amount: amount ?? ctx.topupAmount,
|
|
4584
|
+
currency: currency ?? ctx.topupCurrency
|
|
4585
|
+
}
|
|
4586
|
+
);
|
|
4587
|
+
};
|
|
4588
|
+
var Loading6 = forwardRef13(function CreditGateLoading({ asChild, children, ...rest }, forwardedRef) {
|
|
4589
|
+
const ctx = useGateCtx2("Loading");
|
|
4590
|
+
if (ctx.state !== "loading") return null;
|
|
4591
|
+
const Comp = asChild ? Slot : "div";
|
|
4592
|
+
return (
|
|
4593
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
4594
|
+
/* @__PURE__ */ jsx21(Comp, { ref: forwardedRef, "data-solvapay-credit-gate-loading": "", ...rest, children })
|
|
4595
|
+
);
|
|
4596
|
+
});
|
|
4597
|
+
var ErrorSlot6 = forwardRef13(function CreditGateError({ asChild, children, ...rest }, forwardedRef) {
|
|
4598
|
+
if (!children) return null;
|
|
4599
|
+
const Comp = asChild ? Slot : "div";
|
|
4600
|
+
return (
|
|
4601
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
4602
|
+
/* @__PURE__ */ jsx21(Comp, { ref: forwardedRef, "data-solvapay-credit-gate-error": "", role: "alert", ...rest, children })
|
|
4603
|
+
);
|
|
4604
|
+
});
|
|
4605
|
+
var CreditGateRoot2 = Root9;
|
|
4606
|
+
var CreditGateHeading2 = Heading3;
|
|
4607
|
+
var CreditGateSubheading2 = Subheading;
|
|
4608
|
+
var CreditGateTopup = Topup;
|
|
4609
|
+
var CreditGateLoading2 = Loading6;
|
|
4610
|
+
var CreditGateError2 = ErrorSlot6;
|
|
4611
|
+
var CreditGate = {
|
|
4612
|
+
Root: Root9,
|
|
4613
|
+
Heading: Heading3,
|
|
4614
|
+
Subheading,
|
|
4615
|
+
Topup,
|
|
4616
|
+
Loading: Loading6,
|
|
4617
|
+
Error: ErrorSlot6
|
|
4618
|
+
};
|
|
4619
|
+
function useCreditGate() {
|
|
4620
|
+
return useGateCtx2("useCreditGate");
|
|
4621
|
+
}
|
|
4622
|
+
|
|
4623
|
+
export {
|
|
4624
|
+
filterPurchases,
|
|
4625
|
+
getActivePurchases,
|
|
4626
|
+
getCancelledPurchasesWithEndDate,
|
|
4627
|
+
getMostRecentPurchase,
|
|
4628
|
+
getPrimaryPurchase,
|
|
4629
|
+
isPaidPurchase,
|
|
4630
|
+
buildRequestHeaders,
|
|
4631
|
+
enCopy,
|
|
4632
|
+
mergeCopy,
|
|
4633
|
+
CopyContext,
|
|
4634
|
+
CopyProvider,
|
|
4635
|
+
SolvaPayContext,
|
|
4636
|
+
SolvaPayProvider,
|
|
4637
|
+
setRef,
|
|
4638
|
+
composeRefs,
|
|
4639
|
+
Slot,
|
|
4640
|
+
Slottable,
|
|
4641
|
+
composeEventHandlers,
|
|
4642
|
+
useSolvaPay,
|
|
4643
|
+
useCheckout,
|
|
4644
|
+
usePurchase,
|
|
4645
|
+
useCustomer,
|
|
4646
|
+
useCopy,
|
|
4647
|
+
useLocale,
|
|
4648
|
+
usePlans,
|
|
4649
|
+
usePlan,
|
|
4650
|
+
useProduct,
|
|
4651
|
+
useActivation,
|
|
4652
|
+
PaymentFormContext,
|
|
4653
|
+
usePaymentForm,
|
|
4654
|
+
PaymentFormProvider,
|
|
4655
|
+
formatPrice,
|
|
4656
|
+
interpolate,
|
|
4657
|
+
CheckoutSummaryRoot2 as CheckoutSummaryRoot,
|
|
4658
|
+
CheckoutSummaryProduct2 as CheckoutSummaryProduct,
|
|
4659
|
+
CheckoutSummaryPlan2 as CheckoutSummaryPlan,
|
|
4660
|
+
CheckoutSummaryPrice2 as CheckoutSummaryPrice,
|
|
4661
|
+
CheckoutSummaryTrial2 as CheckoutSummaryTrial,
|
|
4662
|
+
CheckoutSummaryTaxNote2 as CheckoutSummaryTaxNote,
|
|
4663
|
+
CheckoutSummary,
|
|
4664
|
+
useCheckoutSummary,
|
|
4665
|
+
CheckoutSummary2,
|
|
4666
|
+
useMerchant,
|
|
4667
|
+
deriveVariant,
|
|
4668
|
+
MandateText,
|
|
4669
|
+
Spinner,
|
|
4670
|
+
confirmPayment,
|
|
4671
|
+
resolveCta,
|
|
4672
|
+
PaymentFormRoot2 as PaymentFormRoot,
|
|
4673
|
+
PaymentFormSummary,
|
|
4674
|
+
PaymentFormCustomerFields2 as PaymentFormCustomerFields,
|
|
4675
|
+
PaymentFormPaymentElement,
|
|
4676
|
+
PaymentFormCardElement,
|
|
4677
|
+
PaymentFormMandateText,
|
|
4678
|
+
PaymentFormTermsCheckbox2 as PaymentFormTermsCheckbox,
|
|
4679
|
+
PaymentFormSubmitButton2 as PaymentFormSubmitButton,
|
|
4680
|
+
PaymentFormLoading2 as PaymentFormLoading,
|
|
4681
|
+
PaymentFormError2 as PaymentFormError,
|
|
4682
|
+
PaymentForm,
|
|
4683
|
+
useTopupAmountSelector,
|
|
4684
|
+
useBalance,
|
|
4685
|
+
AmountPickerRoot2 as AmountPickerRoot,
|
|
4686
|
+
AmountPickerOption2 as AmountPickerOption,
|
|
4687
|
+
AmountPickerCustom2 as AmountPickerCustom,
|
|
4688
|
+
AmountPickerConfirm2 as AmountPickerConfirm,
|
|
4689
|
+
AmountPicker,
|
|
4690
|
+
useAmountPicker,
|
|
4691
|
+
useAmountPickerCopy,
|
|
4692
|
+
useTopup,
|
|
4693
|
+
TopupFormRoot2 as TopupFormRoot,
|
|
4694
|
+
TopupFormPaymentElement,
|
|
4695
|
+
TopupFormSubmitButton2 as TopupFormSubmitButton,
|
|
4696
|
+
TopupFormLoading2 as TopupFormLoading,
|
|
4697
|
+
TopupFormError2 as TopupFormError,
|
|
4698
|
+
TopupForm,
|
|
4699
|
+
useTopupForm,
|
|
4700
|
+
TopupForm2,
|
|
4701
|
+
ProductBadge2 as ProductBadge,
|
|
4702
|
+
PlanBadge,
|
|
4703
|
+
PurchaseGateRoot2 as PurchaseGateRoot,
|
|
4704
|
+
PurchaseGateAllowed2 as PurchaseGateAllowed,
|
|
4705
|
+
PurchaseGateBlocked2 as PurchaseGateBlocked,
|
|
4706
|
+
PurchaseGateLoading2 as PurchaseGateLoading,
|
|
4707
|
+
PurchaseGateError2 as PurchaseGateError,
|
|
4708
|
+
PurchaseGate,
|
|
4709
|
+
usePurchaseGate,
|
|
4710
|
+
BalanceBadge,
|
|
4711
|
+
PlanSelectorRoot2 as PlanSelectorRoot,
|
|
4712
|
+
PlanSelectorHeading2 as PlanSelectorHeading,
|
|
4713
|
+
PlanSelectorGrid2 as PlanSelectorGrid,
|
|
4714
|
+
PlanSelectorCard2 as PlanSelectorCard,
|
|
4715
|
+
PlanSelectorCardName2 as PlanSelectorCardName,
|
|
4716
|
+
PlanSelectorCardPrice2 as PlanSelectorCardPrice,
|
|
4717
|
+
PlanSelectorCardInterval2 as PlanSelectorCardInterval,
|
|
4718
|
+
PlanSelectorCardBadge2 as PlanSelectorCardBadge,
|
|
4719
|
+
PlanSelectorLoading2 as PlanSelectorLoading,
|
|
4720
|
+
PlanSelectorError2 as PlanSelectorError,
|
|
4721
|
+
PlanSelector,
|
|
4722
|
+
usePlanSelector,
|
|
4723
|
+
ActivationFlowRoot2 as ActivationFlowRoot,
|
|
4724
|
+
ActivationFlowSummary2 as ActivationFlowSummary,
|
|
4725
|
+
ActivationFlowActivateButton2 as ActivationFlowActivateButton,
|
|
4726
|
+
ActivationFlowAmountPicker,
|
|
4727
|
+
ActivationFlowContinueButton2 as ActivationFlowContinueButton,
|
|
4728
|
+
ActivationFlowRetrying2 as ActivationFlowRetrying,
|
|
4729
|
+
ActivationFlowActivated2 as ActivationFlowActivated,
|
|
4730
|
+
ActivationFlowLoading2 as ActivationFlowLoading,
|
|
4731
|
+
ActivationFlowError2 as ActivationFlowError,
|
|
4732
|
+
ActivationFlow,
|
|
4733
|
+
useActivationFlow,
|
|
4734
|
+
usePurchaseActions,
|
|
4735
|
+
CancelPlanButton,
|
|
4736
|
+
usePurchaseStatus,
|
|
4737
|
+
CancelledPlanNoticeRoot2 as CancelledPlanNoticeRoot,
|
|
4738
|
+
CancelledPlanNoticeHeading2 as CancelledPlanNoticeHeading,
|
|
4739
|
+
CancelledPlanNoticeExpires2 as CancelledPlanNoticeExpires,
|
|
4740
|
+
CancelledPlanNoticeDaysRemaining2 as CancelledPlanNoticeDaysRemaining,
|
|
4741
|
+
CancelledPlanNoticeAccessUntil2 as CancelledPlanNoticeAccessUntil,
|
|
4742
|
+
CancelledPlanNoticeCancelledOn2 as CancelledPlanNoticeCancelledOn,
|
|
4743
|
+
CancelledPlanNoticeReason2 as CancelledPlanNoticeReason,
|
|
4744
|
+
CancelledPlanNoticeReactivateButton2 as CancelledPlanNoticeReactivateButton,
|
|
4745
|
+
CancelledPlanNotice,
|
|
4746
|
+
useCancelledPlanNotice,
|
|
4747
|
+
CreditGateRoot2 as CreditGateRoot,
|
|
4748
|
+
CreditGateHeading2 as CreditGateHeading,
|
|
4749
|
+
CreditGateSubheading2 as CreditGateSubheading,
|
|
4750
|
+
CreditGateTopup,
|
|
4751
|
+
CreditGateLoading2 as CreditGateLoading,
|
|
4752
|
+
CreditGateError2 as CreditGateError,
|
|
4753
|
+
CreditGate,
|
|
4754
|
+
useCreditGate
|
|
4755
|
+
};
|