@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.
Files changed (106) hide show
  1. package/README.md +12 -95
  2. package/dist/CancelPlanButton-Bb7cvym9.d.cts +1105 -0
  3. package/dist/CancelPlanButton-CieT9swn.d.cts +1102 -0
  4. package/dist/CancelPlanButton-Cq117t7h.d.ts +1105 -0
  5. package/dist/CancelPlanButton-f56UlQN-.d.ts +1102 -0
  6. package/dist/PaymentForm-B5dw0i1X.d.ts +934 -0
  7. package/dist/PaymentForm-CesoRQWu.d.cts +934 -0
  8. package/dist/chunk-C7SKOENW.js +1889 -0
  9. package/dist/chunk-ISYAH4ZL.js +1889 -0
  10. package/dist/chunk-MOP3ZBGC.js +4749 -0
  11. package/dist/chunk-Q7GPX6X4.js +4748 -0
  12. package/dist/chunk-TP4JPKE2.js +3126 -0
  13. package/dist/chunk-VTGIXJQU.js +4755 -0
  14. package/dist/chunk-XMQ4GBWQ.js +4752 -0
  15. package/dist/index-DLl3UwO3.d.ts +798 -0
  16. package/dist/index-Sj2lHLl8.d.cts +798 -0
  17. package/dist/index.cjs +11 -25
  18. package/dist/index.d.cts +2 -2
  19. package/dist/index.d.ts +2 -2
  20. package/dist/index.js +1 -1
  21. package/dist/primitives/index.cjs +4 -21
  22. package/dist/primitives/index.d.cts +2 -2
  23. package/dist/primitives/index.d.ts +2 -2
  24. package/dist/primitives/index.js +1 -1
  25. package/dist/src/PaymentForm.d.ts +56 -0
  26. package/dist/src/PaymentForm.d.ts.map +1 -0
  27. package/dist/src/PaymentForm.js +212 -0
  28. package/dist/src/PaymentForm.js.map +1 -0
  29. package/dist/src/SolvaPayProvider.d.ts +84 -0
  30. package/dist/src/SolvaPayProvider.d.ts.map +1 -0
  31. package/dist/src/SolvaPayProvider.js +537 -0
  32. package/dist/src/SolvaPayProvider.js.map +1 -0
  33. package/dist/src/adapters/auth.d.ts +43 -0
  34. package/dist/src/adapters/auth.d.ts.map +1 -0
  35. package/dist/src/adapters/auth.js +38 -0
  36. package/dist/src/adapters/auth.js.map +1 -0
  37. package/dist/src/components/PlanBadge.d.ts +31 -0
  38. package/dist/src/components/PlanBadge.d.ts.map +1 -0
  39. package/dist/src/components/PlanBadge.js +119 -0
  40. package/dist/src/components/PlanBadge.js.map +1 -0
  41. package/dist/src/components/PlanSelector.d.ts +49 -0
  42. package/dist/src/components/PlanSelector.d.ts.map +1 -0
  43. package/dist/src/components/PlanSelector.js +82 -0
  44. package/dist/src/components/PlanSelector.js.map +1 -0
  45. package/dist/src/components/Spinner.d.ts +10 -0
  46. package/dist/src/components/Spinner.d.ts.map +1 -0
  47. package/dist/src/components/Spinner.js +14 -0
  48. package/dist/src/components/Spinner.js.map +1 -0
  49. package/dist/src/components/StripePaymentFormWrapper.d.ts +17 -0
  50. package/dist/src/components/StripePaymentFormWrapper.d.ts.map +1 -0
  51. package/dist/src/components/StripePaymentFormWrapper.js +158 -0
  52. package/dist/src/components/StripePaymentFormWrapper.js.map +1 -0
  53. package/dist/src/components/SubscriptionGate.d.ts +21 -0
  54. package/dist/src/components/SubscriptionGate.d.ts.map +1 -0
  55. package/dist/src/components/SubscriptionGate.js +32 -0
  56. package/dist/src/components/SubscriptionGate.js.map +1 -0
  57. package/dist/src/hooks/__tests__/useSubscription.test.d.ts +2 -0
  58. package/dist/src/hooks/__tests__/useSubscription.test.d.ts.map +1 -0
  59. package/dist/src/hooks/__tests__/useSubscription.test.js +554 -0
  60. package/dist/src/hooks/__tests__/useSubscription.test.js.map +1 -0
  61. package/dist/src/hooks/__tests__/useSubscriptionStatus.test.d.ts +2 -0
  62. package/dist/src/hooks/__tests__/useSubscriptionStatus.test.d.ts.map +1 -0
  63. package/dist/src/hooks/__tests__/useSubscriptionStatus.test.js +719 -0
  64. package/dist/src/hooks/__tests__/useSubscriptionStatus.test.js.map +1 -0
  65. package/dist/src/hooks/useCheckout.d.ts +59 -0
  66. package/dist/src/hooks/useCheckout.d.ts.map +1 -0
  67. package/dist/src/hooks/useCheckout.js +138 -0
  68. package/dist/src/hooks/useCheckout.js.map +1 -0
  69. package/dist/src/hooks/useCustomer.d.ts +43 -0
  70. package/dist/src/hooks/useCustomer.d.ts.map +1 -0
  71. package/dist/src/hooks/useCustomer.js +31 -0
  72. package/dist/src/hooks/useCustomer.js.map +1 -0
  73. package/dist/src/hooks/usePlans.d.ts +28 -0
  74. package/dist/src/hooks/usePlans.d.ts.map +1 -0
  75. package/dist/src/hooks/usePlans.js +181 -0
  76. package/dist/src/hooks/usePlans.js.map +1 -0
  77. package/dist/src/hooks/useSolvaPay.d.ts +44 -0
  78. package/dist/src/hooks/useSolvaPay.d.ts.map +1 -0
  79. package/dist/src/hooks/useSolvaPay.js +52 -0
  80. package/dist/src/hooks/useSolvaPay.js.map +1 -0
  81. package/dist/src/hooks/useSubscription.d.ts +46 -0
  82. package/dist/src/hooks/useSubscription.d.ts.map +1 -0
  83. package/dist/src/hooks/useSubscription.js +50 -0
  84. package/dist/src/hooks/useSubscription.js.map +1 -0
  85. package/dist/src/hooks/useSubscriptionStatus.d.ts +19 -0
  86. package/dist/src/hooks/useSubscriptionStatus.d.ts.map +1 -0
  87. package/dist/src/hooks/useSubscriptionStatus.js +68 -0
  88. package/dist/src/hooks/useSubscriptionStatus.js.map +1 -0
  89. package/dist/src/index.d.ts +24 -0
  90. package/dist/src/index.d.ts.map +1 -0
  91. package/dist/src/index.js +26 -0
  92. package/dist/src/index.js.map +1 -0
  93. package/dist/src/types/index.d.ts +339 -0
  94. package/dist/src/types/index.d.ts.map +1 -0
  95. package/dist/src/types/index.js +5 -0
  96. package/dist/src/types/index.js.map +1 -0
  97. package/dist/src/utils/__tests__/subscriptions.test.d.ts +2 -0
  98. package/dist/src/utils/__tests__/subscriptions.test.d.ts.map +1 -0
  99. package/dist/src/utils/__tests__/subscriptions.test.js +121 -0
  100. package/dist/src/utils/__tests__/subscriptions.test.js.map +1 -0
  101. package/dist/src/utils/subscriptions.d.ts +57 -0
  102. package/dist/src/utils/subscriptions.d.ts.map +1 -0
  103. package/dist/src/utils/subscriptions.js +85 -0
  104. package/dist/src/utils/subscriptions.js.map +1 -0
  105. package/dist/tsconfig.tsbuildinfo +1 -0
  106. package/package.json +2 -2
@@ -0,0 +1,4749 @@
1
+ import {
2
+ defaultAuthAdapter
3
+ } from "./chunk-OUSEQRCT.js";
4
+
5
+ // src/utils/purchases.ts
6
+ function filterPurchases(purchases) {
7
+ return purchases.filter((purchase) => purchase.status === "active");
8
+ }
9
+ function getActivePurchases(purchases) {
10
+ return purchases.filter((purchase) => purchase.status === "active");
11
+ }
12
+ function getCancelledPurchasesWithEndDate(purchases) {
13
+ const now = /* @__PURE__ */ new Date();
14
+ return purchases.filter((purchase) => {
15
+ return purchase.status === "active" && purchase.cancelledAt && purchase.endDate && new Date(purchase.endDate) > now;
16
+ });
17
+ }
18
+ function getMostRecentPurchase(purchases) {
19
+ if (purchases.length === 0) return null;
20
+ return purchases.reduce((latest, current) => {
21
+ return new Date(current.startDate) > new Date(latest.startDate) ? current : latest;
22
+ });
23
+ }
24
+ function getPrimaryPurchase(purchases) {
25
+ const filtered = filterPurchases(purchases);
26
+ if (filtered.length > 0) {
27
+ return getMostRecentPurchase(filtered);
28
+ }
29
+ return null;
30
+ }
31
+ function isPaidPurchase(purchase) {
32
+ return (purchase.amount ?? 0) > 0;
33
+ }
34
+
35
+ // src/i18n/en.ts
36
+ function intervalPhrase(ctx) {
37
+ const interval = ctx.plan?.interval;
38
+ const count = ctx.plan?.intervalCount ?? 1;
39
+ if (!interval) return "";
40
+ return count > 1 ? `${count} ${interval}s` : interval;
41
+ }
42
+ function trialPhrase(ctx) {
43
+ const trialDays = ctx.plan?.trialDays ?? ctx.trialDays;
44
+ return trialDays ? ` after your ${trialDays}-day free trial` : "";
45
+ }
46
+ function termsSentence(ctx) {
47
+ const { termsUrl, privacyUrl } = ctx.merchant;
48
+ if (termsUrl && privacyUrl) {
49
+ return ` See ${termsUrl} and ${privacyUrl}.`;
50
+ }
51
+ if (termsUrl) return ` See ${termsUrl}.`;
52
+ if (privacyUrl) return ` See ${privacyUrl}.`;
53
+ return "";
54
+ }
55
+ var enCopy = {
56
+ mandate: {
57
+ recurring: (ctx) => {
58
+ const period = intervalPhrase(ctx);
59
+ const trial = trialPhrase(ctx);
60
+ const every = period ? ` every ${period}` : "";
61
+ return `By subscribing, you authorize ${ctx.merchant.legalName} to charge ${ctx.amountFormatted}${every}${trial} until you cancel. You can cancel any time. Payments are processed by SolvaPay.${termsSentence(ctx)}`;
62
+ },
63
+ oneTime: (ctx) => {
64
+ const product = ctx.product?.name ? ` for ${ctx.product.name}` : "";
65
+ return `By confirming, you authorize ${ctx.merchant.legalName} to charge ${ctx.amountFormatted}${product}. Payments are processed by SolvaPay.${termsSentence(ctx)}`;
66
+ },
67
+ topup: (ctx) => {
68
+ const product = ctx.product?.name ? ` to add credits to your ${ctx.product.name} balance` : " to add credits to your balance";
69
+ return `By confirming, you authorize ${ctx.merchant.legalName} to charge ${ctx.amountFormatted}${product}. Credits are non-refundable once used. Payments are processed by SolvaPay.${termsSentence(ctx)}`;
70
+ },
71
+ usageMetered: (ctx) => {
72
+ const measures = ctx.plan?.measures ?? "unit";
73
+ const cycle = ctx.plan?.billingCycle ?? "monthly";
74
+ const product = ctx.product?.name ?? "the service";
75
+ return `By confirming, you authorize ${ctx.merchant.legalName} to charge your payment method for metered usage of ${product} at ${ctx.amountFormatted} per ${measures}, billed ${cycle}. You can cancel any time. Payments are processed by SolvaPay.${termsSentence(ctx)}`;
76
+ },
77
+ freeTier: (ctx) => {
78
+ const product = ctx.product?.name ?? "this plan";
79
+ const planPhrase = ctx.plan?.name ? ` on ${ctx.plan.name}` : "";
80
+ return `By confirming, you activate ${product}${planPhrase}. Payments are processed by SolvaPay.${termsSentence(ctx)}`;
81
+ }
82
+ },
83
+ cta: {
84
+ payNow: "Pay Now",
85
+ topUp: "Top Up",
86
+ subscribe: "Subscribe",
87
+ trialStart: "Start {trialDays}-day free trial",
88
+ payAmount: "Pay {amount}",
89
+ addAmount: "Add {amount}",
90
+ startUsing: "Start using {product}",
91
+ processing: "Processing..."
92
+ },
93
+ interval: {
94
+ day: "day",
95
+ week: "week",
96
+ month: "month",
97
+ year: "year",
98
+ every: "every {n} {unit}",
99
+ free: "Free",
100
+ trial: "{trialDays}-day free trial"
101
+ },
102
+ terms: {
103
+ checkboxLabel: "I agree to the terms and privacy policy"
104
+ },
105
+ customer: {
106
+ chargingTo: "Charging to {email}",
107
+ emailLabel: "Email",
108
+ nameLabel: "Name"
109
+ },
110
+ balance: {
111
+ credits: " credits",
112
+ currencyEquivalent: " (~{amount})"
113
+ },
114
+ product: {
115
+ currentProductLabel: "Current product: {name}"
116
+ },
117
+ topup: {
118
+ selectOrEnterAmount: "Please select or enter an amount",
119
+ minAmount: "Minimum amount is {amount}",
120
+ maxAmount: "Maximum amount is {amount}"
121
+ },
122
+ activation: {
123
+ paymentRequired: "This plan requires payment. Please select a different plan.",
124
+ invalidConfiguration: "Invalid plan configuration.",
125
+ unexpectedResponse: "Unexpected response from server.",
126
+ failed: "Activation failed"
127
+ },
128
+ planSelector: {
129
+ heading: "Choose your pricing",
130
+ currentBadge: "Current",
131
+ popularBadge: "Popular",
132
+ freeBadge: "Free",
133
+ perIntervalShort: "/{interval}",
134
+ continueButton: "Continue",
135
+ backButton: "\u2190 Back to plans",
136
+ trialBadge: "{trialDays}-day free trial"
137
+ },
138
+ amountPicker: {
139
+ selectAmountLabel: "Select an amount",
140
+ customAmountLabel: "Or enter a custom amount",
141
+ creditEstimateExact: "= {credits} credits",
142
+ creditEstimateApprox: "~ {credits} credits"
143
+ },
144
+ activationFlow: {
145
+ heading: "Confirm your plan",
146
+ activateButton: "Activate",
147
+ activatingLabel: "Activating...",
148
+ topupHeading: "Add credits",
149
+ topupSubheading: "Top up your credits to activate this plan.",
150
+ continueToPayment: "Continue to payment",
151
+ changeAmountButton: "Change amount",
152
+ retryingHeading: "Activating your plan...",
153
+ retryingSubheading: "Payment received. Setting up your plan.",
154
+ activatedHeading: "Plan selected",
155
+ activatedSubheading: "Your plan is now active.",
156
+ tryAgainButton: "Try Again",
157
+ backButton: "\u2190 Back to plan selection"
158
+ },
159
+ cancelPlan: {
160
+ button: "Cancel plan",
161
+ buttonLoading: "Cancelling...",
162
+ confirmRecurring: "Are you sure you want to cancel your subscription?",
163
+ confirmUsageBased: "Are you sure you want to deactivate your plan? This will take effect immediately."
164
+ },
165
+ cancelledNotice: {
166
+ heading: "Your purchase has been cancelled",
167
+ expiresLabel: "Purchase Expires: {date}",
168
+ daysRemaining: "{days} days remaining",
169
+ dayRemaining: "1 day remaining",
170
+ accessUntil: "You'll continue to have access to {product} features until this date",
171
+ accessEnded: "Your purchase access has ended",
172
+ cancelledOn: "Cancelled on {date}",
173
+ reactivateButton: "Undo Cancellation",
174
+ reactivateButtonLoading: "Reactivating..."
175
+ },
176
+ creditGate: {
177
+ lowBalanceHeading: "You're out of credits",
178
+ lowBalanceSubheading: "Top up to continue using {product}",
179
+ topUpCta: "Top up now"
180
+ },
181
+ errors: {
182
+ paymentInitFailed: "Payment initialization failed",
183
+ topupInitFailed: "Top-up initialization failed",
184
+ configMissingPlanOrProduct: "PaymentForm: either planRef or productRef is required",
185
+ configMissingAmount: "TopupForm: amount must be a positive number",
186
+ unknownError: "Unknown error",
187
+ stripeUnavailable: "Stripe is not available. Please refresh the page.",
188
+ paymentIntentUnavailable: "Payment intent not available. Please refresh the page.",
189
+ cardElementMissing: "Card element not found",
190
+ paymentUnexpected: "An unexpected error occurred.",
191
+ paymentProcessingFailed: "Payment processing failed. Please try again or contact support.",
192
+ paymentRequires3ds: "Payment requires additional authentication. Please complete the verification.",
193
+ paymentProcessingTimeout: "Payment processing timed out \u2014 webhooks may not be configured",
194
+ paymentStatusPrefix: "Payment status: {status}"
195
+ }
196
+ };
197
+
198
+ // src/i18n/merge.ts
199
+ function mergeCopy(defaults, overrides) {
200
+ if (!overrides) return defaults;
201
+ const merged = { ...defaults };
202
+ for (const sectionKey of Object.keys(overrides)) {
203
+ const defaultSection = defaults[sectionKey];
204
+ const overrideSection = overrides[sectionKey];
205
+ if (!overrideSection) continue;
206
+ const combined = { ...defaultSection, ...overrideSection };
207
+ merged[sectionKey] = combined;
208
+ }
209
+ return merged;
210
+ }
211
+
212
+ // src/i18n/context.tsx
213
+ import { createContext, useContext, useMemo } from "react";
214
+ import { jsx } from "react/jsx-runtime";
215
+ var CopyContext = createContext({
216
+ locale: void 0,
217
+ copy: enCopy
218
+ });
219
+ var CopyProvider = ({
220
+ locale,
221
+ copy: overrides,
222
+ children
223
+ }) => {
224
+ const value = useMemo(
225
+ () => ({
226
+ locale,
227
+ copy: mergeCopy(enCopy, overrides)
228
+ }),
229
+ [locale, overrides]
230
+ );
231
+ return /* @__PURE__ */ jsx(CopyContext.Provider, { value, children });
232
+ };
233
+ function useCopyContext() {
234
+ return useContext(CopyContext);
235
+ }
236
+
237
+ // src/SolvaPayProvider.tsx
238
+ import { createContext as createContext2, useState, useEffect, useCallback, useMemo as useMemo2, useRef } from "react";
239
+
240
+ // src/utils/headers.ts
241
+ var CUSTOMER_REF_KEY = "solvapay_customerRef";
242
+ var CUSTOMER_REF_EXPIRY = "solvapay_customerRef_expiry";
243
+ var CUSTOMER_REF_USER_ID_KEY = "solvapay_customerRef_userId";
244
+ function getAuthAdapter(config) {
245
+ if (config?.auth?.adapter) {
246
+ return config.auth.adapter;
247
+ }
248
+ if (config?.auth?.getToken || config?.auth?.getUserId) {
249
+ return {
250
+ async getToken() {
251
+ return config?.auth?.getToken?.() || null;
252
+ },
253
+ async getUserId() {
254
+ return config?.auth?.getUserId?.() || null;
255
+ }
256
+ };
257
+ }
258
+ return defaultAuthAdapter;
259
+ }
260
+ function getCachedCustomerRef(userId) {
261
+ if (typeof window === "undefined") return null;
262
+ const cached = localStorage.getItem(CUSTOMER_REF_KEY);
263
+ const expiry = localStorage.getItem(CUSTOMER_REF_EXPIRY);
264
+ const cachedUserId = localStorage.getItem(CUSTOMER_REF_USER_ID_KEY);
265
+ if (!cached || !expiry) return null;
266
+ if (Date.now() > parseInt(expiry)) {
267
+ localStorage.removeItem(CUSTOMER_REF_KEY);
268
+ localStorage.removeItem(CUSTOMER_REF_EXPIRY);
269
+ localStorage.removeItem(CUSTOMER_REF_USER_ID_KEY);
270
+ return null;
271
+ }
272
+ if (userId !== void 0 && userId !== null) {
273
+ if (cachedUserId !== userId) {
274
+ clearCachedCustomerRef();
275
+ return null;
276
+ }
277
+ }
278
+ return cached;
279
+ }
280
+ var CACHE_DURATION = 24 * 60 * 60 * 1e3;
281
+ function setCachedCustomerRef(customerRef, userId) {
282
+ if (typeof window === "undefined") return;
283
+ if (userId === void 0 || userId === null) {
284
+ return;
285
+ }
286
+ localStorage.setItem(CUSTOMER_REF_KEY, customerRef);
287
+ localStorage.setItem(CUSTOMER_REF_EXPIRY, String(Date.now() + CACHE_DURATION));
288
+ localStorage.setItem(CUSTOMER_REF_USER_ID_KEY, userId);
289
+ }
290
+ function clearCachedCustomerRef() {
291
+ if (typeof window === "undefined") return;
292
+ localStorage.removeItem(CUSTOMER_REF_KEY);
293
+ localStorage.removeItem(CUSTOMER_REF_EXPIRY);
294
+ localStorage.removeItem(CUSTOMER_REF_USER_ID_KEY);
295
+ }
296
+ async function buildRequestHeaders(config) {
297
+ const adapter = getAuthAdapter(config);
298
+ const token = await adapter.getToken();
299
+ const userId = await adapter.getUserId();
300
+ const cachedRef = getCachedCustomerRef(userId);
301
+ const headers = {
302
+ "Content-Type": "application/json"
303
+ };
304
+ if (token) {
305
+ headers["Authorization"] = `Bearer ${token}`;
306
+ }
307
+ if (cachedRef) {
308
+ headers["x-solvapay-customer-ref"] = cachedRef;
309
+ }
310
+ if (config?.headers) {
311
+ const custom = typeof config.headers === "function" ? await config.headers() : config.headers;
312
+ Object.assign(headers, custom);
313
+ }
314
+ return { headers, userId };
315
+ }
316
+
317
+ // src/SolvaPayProvider.tsx
318
+ import { jsx as jsx2 } from "react/jsx-runtime";
319
+ var SolvaPayContext = createContext2(null);
320
+ var SolvaPayProvider = ({
321
+ config,
322
+ createPayment: customCreatePayment,
323
+ checkPurchase: customCheckPurchase,
324
+ processPayment: customProcessPayment,
325
+ createTopupPayment: customCreateTopupPayment,
326
+ children
327
+ }) => {
328
+ const [purchaseData, setPurchaseData] = useState({
329
+ purchases: []
330
+ });
331
+ const [loading, setLoading] = useState(false);
332
+ const [isRefetching, setIsRefetching] = useState(false);
333
+ const [purchaseError, setPurchaseError] = useState(null);
334
+ const [internalCustomerRef, setInternalCustomerRef] = useState(void 0);
335
+ const [userId, setUserId] = useState(null);
336
+ const [isAuthenticated, setIsAuthenticated] = useState(false);
337
+ const [creditsValue, setCreditsValue] = useState(null);
338
+ const [displayCurrencyValue, setDisplayCurrencyValue] = useState(null);
339
+ const [creditsPerMinorUnitValue, setCreditsPerMinorUnitValue] = useState(null);
340
+ const [displayExchangeRateValue, setDisplayExchangeRateValue] = useState(null);
341
+ const [balanceLoading, setBalanceLoading] = useState(false);
342
+ const balanceInFlightRef = useRef(false);
343
+ const balanceLoadedRef = useRef(false);
344
+ const optimisticUntilRef = useRef(0);
345
+ const optimisticTimerRef = useRef(null);
346
+ const fetchBalanceRef = useRef(null);
347
+ const inFlightRef = useRef(null);
348
+ const checkPurchaseRef = useRef(null);
349
+ const createPaymentRef = useRef(null);
350
+ const processPaymentRef = useRef(null);
351
+ const createTopupPaymentRef = useRef(null);
352
+ const configRef = useRef(config);
353
+ const buildDefaultCheckPurchaseRef = useRef(
354
+ null
355
+ );
356
+ useEffect(() => {
357
+ configRef.current = config;
358
+ }, [config]);
359
+ useEffect(() => {
360
+ checkPurchaseRef.current = customCheckPurchase || null;
361
+ }, [customCheckPurchase]);
362
+ useEffect(() => {
363
+ createPaymentRef.current = customCreatePayment || null;
364
+ }, [customCreatePayment]);
365
+ useEffect(() => {
366
+ processPaymentRef.current = customProcessPayment || null;
367
+ }, [customProcessPayment]);
368
+ useEffect(() => {
369
+ createTopupPaymentRef.current = customCreateTopupPayment || null;
370
+ }, [customCreateTopupPayment]);
371
+ const buildDefaultCheckPurchase = useCallback(async () => {
372
+ const currentConfig = configRef.current;
373
+ const { headers } = await buildRequestHeaders(currentConfig);
374
+ const route = currentConfig?.api?.checkPurchase || "/api/check-purchase";
375
+ const fetchFn = currentConfig?.fetch || fetch;
376
+ const res = await fetchFn(route, { method: "GET", headers });
377
+ if (!res.ok) {
378
+ const error = new Error(`Failed to check purchase: ${res.statusText}`);
379
+ currentConfig?.onError?.(error, "checkPurchase");
380
+ throw error;
381
+ }
382
+ return res.json();
383
+ }, []);
384
+ useEffect(() => {
385
+ buildDefaultCheckPurchaseRef.current = buildDefaultCheckPurchase;
386
+ }, [buildDefaultCheckPurchase]);
387
+ const buildDefaultCreatePayment = useCallback(
388
+ async (params) => {
389
+ const currentConfig = configRef.current;
390
+ const { headers } = await buildRequestHeaders(currentConfig);
391
+ const route = currentConfig?.api?.createPayment || "/api/create-payment-intent";
392
+ const fetchFn = currentConfig?.fetch || fetch;
393
+ const body = {};
394
+ if (params.planRef) {
395
+ body.planRef = params.planRef;
396
+ }
397
+ if (params.productRef) {
398
+ body.productRef = params.productRef;
399
+ }
400
+ if (params.customer && (params.customer.name || params.customer.email)) {
401
+ body.customer = params.customer;
402
+ }
403
+ const res = await fetchFn(route, {
404
+ method: "POST",
405
+ headers,
406
+ body: JSON.stringify(body)
407
+ });
408
+ if (!res.ok) {
409
+ const error = new Error(`Failed to create payment: ${res.statusText}`);
410
+ currentConfig?.onError?.(error, "createPayment");
411
+ throw error;
412
+ }
413
+ return res.json();
414
+ },
415
+ []
416
+ );
417
+ const buildDefaultProcessPayment = useCallback(
418
+ async (params) => {
419
+ const currentConfig = configRef.current;
420
+ const { headers } = await buildRequestHeaders(currentConfig);
421
+ const route = currentConfig?.api?.processPayment || "/api/process-payment";
422
+ const fetchFn = currentConfig?.fetch || fetch;
423
+ const res = await fetchFn(route, {
424
+ method: "POST",
425
+ headers,
426
+ body: JSON.stringify(params)
427
+ });
428
+ if (!res.ok) {
429
+ const error = new Error(`Failed to process payment: ${res.statusText}`);
430
+ currentConfig?.onError?.(error, "processPayment");
431
+ throw error;
432
+ }
433
+ return res.json();
434
+ },
435
+ []
436
+ );
437
+ const buildDefaultCreateTopupPayment = useCallback(
438
+ async (params) => {
439
+ const currentConfig = configRef.current;
440
+ const { headers } = await buildRequestHeaders(currentConfig);
441
+ const route = currentConfig?.api?.createTopupPayment || "/api/create-topup-payment-intent";
442
+ const fetchFn = currentConfig?.fetch || fetch;
443
+ const res = await fetchFn(route, {
444
+ method: "POST",
445
+ headers,
446
+ body: JSON.stringify({
447
+ amount: params.amount,
448
+ currency: params.currency
449
+ })
450
+ });
451
+ if (!res.ok) {
452
+ const error = new Error(`Failed to create topup payment: ${res.statusText}`);
453
+ currentConfig?.onError?.(error, "createTopupPayment");
454
+ throw error;
455
+ }
456
+ return res.json();
457
+ },
458
+ []
459
+ );
460
+ const fetchBalanceImpl = useCallback(async () => {
461
+ if (optimisticUntilRef.current > Date.now()) return;
462
+ if (!isAuthenticated && !internalCustomerRef) {
463
+ setCreditsValue(null);
464
+ setDisplayCurrencyValue(null);
465
+ setCreditsPerMinorUnitValue(null);
466
+ setDisplayExchangeRateValue(null);
467
+ setBalanceLoading(false);
468
+ balanceLoadedRef.current = false;
469
+ return;
470
+ }
471
+ if (balanceInFlightRef.current) return;
472
+ balanceInFlightRef.current = true;
473
+ if (!balanceLoadedRef.current) {
474
+ setBalanceLoading(true);
475
+ }
476
+ try {
477
+ const currentConfig = configRef.current;
478
+ const { headers } = await buildRequestHeaders(currentConfig);
479
+ const route = currentConfig?.api?.customerBalance || "/api/customer-balance";
480
+ const fetchFn = currentConfig?.fetch || fetch;
481
+ const res = await fetchFn(route, { method: "GET", headers });
482
+ if (!res.ok) {
483
+ console.error("[SolvaPayProvider] Failed to fetch balance:", res.statusText);
484
+ return;
485
+ }
486
+ const data = await res.json();
487
+ setCreditsValue(data.credits ?? null);
488
+ setDisplayCurrencyValue(data.displayCurrency ?? null);
489
+ setCreditsPerMinorUnitValue(data.creditsPerMinorUnit ?? null);
490
+ setDisplayExchangeRateValue(data.displayExchangeRate ?? null);
491
+ balanceLoadedRef.current = true;
492
+ } catch (error) {
493
+ console.error("[SolvaPayProvider] Failed to fetch balance:", error);
494
+ } finally {
495
+ setBalanceLoading(false);
496
+ balanceInFlightRef.current = false;
497
+ }
498
+ }, [isAuthenticated, internalCustomerRef]);
499
+ useEffect(() => {
500
+ fetchBalanceRef.current = fetchBalanceImpl;
501
+ }, [fetchBalanceImpl]);
502
+ useEffect(() => {
503
+ return () => {
504
+ if (optimisticTimerRef.current) clearTimeout(optimisticTimerRef.current);
505
+ };
506
+ }, []);
507
+ const OPTIMISTIC_GRACE_MS = 8e3;
508
+ const adjustBalanceImpl = useCallback((credits) => {
509
+ setCreditsValue((prev) => (prev ?? 0) + credits);
510
+ optimisticUntilRef.current = Date.now() + OPTIMISTIC_GRACE_MS;
511
+ if (optimisticTimerRef.current) clearTimeout(optimisticTimerRef.current);
512
+ optimisticTimerRef.current = setTimeout(() => {
513
+ optimisticUntilRef.current = 0;
514
+ fetchBalanceRef.current?.();
515
+ }, OPTIMISTIC_GRACE_MS);
516
+ }, []);
517
+ const _checkPurchase = useCallback(async () => {
518
+ if (checkPurchaseRef.current) {
519
+ return checkPurchaseRef.current();
520
+ }
521
+ if (buildDefaultCheckPurchaseRef.current) {
522
+ return buildDefaultCheckPurchaseRef.current();
523
+ }
524
+ return buildDefaultCheckPurchase();
525
+ }, [buildDefaultCheckPurchase]);
526
+ const createPayment = useCallback(
527
+ async (params) => {
528
+ if (createPaymentRef.current) {
529
+ return createPaymentRef.current(params);
530
+ }
531
+ return buildDefaultCreatePayment(params);
532
+ },
533
+ [buildDefaultCreatePayment]
534
+ );
535
+ const processPayment = useCallback(
536
+ async (params) => {
537
+ if (processPaymentRef.current) {
538
+ return processPaymentRef.current(params);
539
+ }
540
+ return buildDefaultProcessPayment(params);
541
+ },
542
+ [buildDefaultProcessPayment]
543
+ );
544
+ const createTopupPayment = useCallback(
545
+ async (params) => {
546
+ if (createTopupPaymentRef.current) {
547
+ return createTopupPaymentRef.current(params);
548
+ }
549
+ return buildDefaultCreateTopupPayment(params);
550
+ },
551
+ [buildDefaultCreateTopupPayment]
552
+ );
553
+ useEffect(() => {
554
+ const detectAuth = async () => {
555
+ const currentConfig = configRef.current;
556
+ const adapter = getAuthAdapter(currentConfig);
557
+ const token = await adapter.getToken();
558
+ const detectedUserId = await adapter.getUserId();
559
+ const prevUserId = userId;
560
+ setIsAuthenticated(!!token);
561
+ setUserId(detectedUserId);
562
+ if (prevUserId !== null && detectedUserId !== prevUserId) {
563
+ clearCachedCustomerRef();
564
+ setInternalCustomerRef(void 0);
565
+ return;
566
+ }
567
+ const cachedRef = getCachedCustomerRef(detectedUserId);
568
+ if (cachedRef && token) {
569
+ setInternalCustomerRef(cachedRef);
570
+ } else if (!token) {
571
+ clearCachedCustomerRef();
572
+ setInternalCustomerRef(void 0);
573
+ } else if (token && !cachedRef) {
574
+ setInternalCustomerRef(void 0);
575
+ }
576
+ };
577
+ detectAuth();
578
+ const interval = setInterval(detectAuth, 3e4);
579
+ return () => clearInterval(interval);
580
+ }, [userId]);
581
+ const fetchPurchase = useCallback(
582
+ async (force = false) => {
583
+ if (!isAuthenticated && !internalCustomerRef) {
584
+ setPurchaseData({ purchases: [] });
585
+ setPurchaseError(null);
586
+ setLoading(false);
587
+ setIsRefetching(false);
588
+ inFlightRef.current = null;
589
+ return;
590
+ }
591
+ const cacheKey = internalCustomerRef || userId || "anonymous";
592
+ if (inFlightRef.current === cacheKey && !force) {
593
+ return;
594
+ }
595
+ inFlightRef.current = cacheKey;
596
+ const hasExistingData = purchaseData.purchases.length > 0;
597
+ if (hasExistingData) {
598
+ setIsRefetching(true);
599
+ } else {
600
+ setLoading(true);
601
+ }
602
+ try {
603
+ const checkFn = checkPurchaseRef.current || buildDefaultCheckPurchaseRef.current;
604
+ if (!checkFn) {
605
+ throw new Error("checkPurchase function not available");
606
+ }
607
+ const data = await checkFn();
608
+ if (data.customerRef) {
609
+ setInternalCustomerRef(data.customerRef);
610
+ const currentAdapter = getAuthAdapter(configRef.current);
611
+ const currentUserId = await currentAdapter.getUserId();
612
+ setCachedCustomerRef(data.customerRef, currentUserId);
613
+ }
614
+ if (inFlightRef.current === cacheKey) {
615
+ const filteredData = {
616
+ ...data,
617
+ purchases: filterPurchases(data.purchases || [])
618
+ };
619
+ setPurchaseData(filteredData);
620
+ setPurchaseError(null);
621
+ }
622
+ } catch (err) {
623
+ console.error("[SolvaPayProvider] Failed to fetch purchase:", err);
624
+ if (inFlightRef.current === cacheKey) {
625
+ setPurchaseError(err instanceof Error ? err : new Error(String(err)));
626
+ }
627
+ } finally {
628
+ if (inFlightRef.current === cacheKey) {
629
+ setLoading(false);
630
+ setIsRefetching(false);
631
+ inFlightRef.current = null;
632
+ }
633
+ }
634
+ },
635
+ [isAuthenticated, internalCustomerRef, userId, purchaseData.purchases.length]
636
+ );
637
+ const fetchPurchaseRef = useRef(fetchPurchase);
638
+ useEffect(() => {
639
+ fetchPurchaseRef.current = fetchPurchase;
640
+ }, [fetchPurchase]);
641
+ const refetchPurchase = useCallback(async () => {
642
+ inFlightRef.current = null;
643
+ await fetchPurchaseRef.current(true);
644
+ }, []);
645
+ const cancelRenewal = useCallback(
646
+ async (params) => {
647
+ const currentConfig = configRef.current;
648
+ const { headers } = await buildRequestHeaders(currentConfig);
649
+ const route = currentConfig?.api?.cancelRenewal || "/api/cancel-renewal";
650
+ const fetchFn = currentConfig?.fetch || fetch;
651
+ const res = await fetchFn(route, {
652
+ method: "POST",
653
+ headers,
654
+ body: JSON.stringify(params)
655
+ });
656
+ if (!res.ok) {
657
+ const data = await res.json().catch(() => ({}));
658
+ const error = new Error(data.error || `Failed to cancel renewal: ${res.statusText}`);
659
+ currentConfig?.onError?.(error, "cancelRenewal");
660
+ throw error;
661
+ }
662
+ const result = await res.json();
663
+ await refetchPurchase();
664
+ return result;
665
+ },
666
+ [refetchPurchase]
667
+ );
668
+ const reactivateRenewal = useCallback(
669
+ async (params) => {
670
+ const currentConfig = configRef.current;
671
+ const { headers } = await buildRequestHeaders(currentConfig);
672
+ const route = currentConfig?.api?.reactivateRenewal || "/api/reactivate-renewal";
673
+ const fetchFn = currentConfig?.fetch || fetch;
674
+ const res = await fetchFn(route, {
675
+ method: "POST",
676
+ headers,
677
+ body: JSON.stringify(params)
678
+ });
679
+ if (!res.ok) {
680
+ const data = await res.json().catch(() => ({}));
681
+ const error = new Error(data.error || `Failed to reactivate renewal: ${res.statusText}`);
682
+ currentConfig?.onError?.(error, "reactivateRenewal");
683
+ throw error;
684
+ }
685
+ const result = await res.json();
686
+ await refetchPurchase();
687
+ return result;
688
+ },
689
+ [refetchPurchase]
690
+ );
691
+ const activatePlan = useCallback(
692
+ async (params) => {
693
+ const currentConfig = configRef.current;
694
+ const { headers } = await buildRequestHeaders(currentConfig);
695
+ const route = currentConfig?.api?.activatePlan || "/api/activate-plan";
696
+ const fetchFn = currentConfig?.fetch || fetch;
697
+ const res = await fetchFn(route, {
698
+ method: "POST",
699
+ headers,
700
+ body: JSON.stringify(params)
701
+ });
702
+ if (!res.ok) {
703
+ const data = await res.json().catch(() => ({}));
704
+ const error = new Error(data.error || `Failed to activate plan: ${res.statusText}`);
705
+ currentConfig?.onError?.(error, "activatePlan");
706
+ throw error;
707
+ }
708
+ const result = await res.json();
709
+ if (result.status === "activated" || result.status === "already_active") {
710
+ await refetchPurchase();
711
+ }
712
+ return result;
713
+ },
714
+ [refetchPurchase]
715
+ );
716
+ useEffect(() => {
717
+ inFlightRef.current = null;
718
+ if (isAuthenticated || internalCustomerRef) {
719
+ fetchPurchase();
720
+ } else {
721
+ setPurchaseData({ purchases: [] });
722
+ setPurchaseError(null);
723
+ setLoading(false);
724
+ setIsRefetching(false);
725
+ }
726
+ }, [isAuthenticated, internalCustomerRef, userId]);
727
+ const updateCustomerRef = useCallback(
728
+ (newCustomerRef) => {
729
+ setInternalCustomerRef(newCustomerRef);
730
+ setCachedCustomerRef(newCustomerRef, userId);
731
+ fetchPurchase(true);
732
+ },
733
+ [fetchPurchase, userId]
734
+ );
735
+ const purchase = useMemo2(() => {
736
+ const activePurchase = getPrimaryPurchase(purchaseData.purchases);
737
+ const activePaidPurchases = purchaseData.purchases.filter(
738
+ (p) => p.status === "active" && isPaidPurchase(p)
739
+ );
740
+ const activePaidPurchase = activePaidPurchases.sort(
741
+ (a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime()
742
+ )[0] || null;
743
+ return {
744
+ loading,
745
+ isRefetching,
746
+ error: purchaseError,
747
+ customerRef: purchaseData.customerRef || internalCustomerRef,
748
+ email: purchaseData.email,
749
+ name: purchaseData.name,
750
+ purchases: purchaseData.purchases,
751
+ hasProduct: (productName) => {
752
+ return purchaseData.purchases.some(
753
+ (p) => p.productName.toLowerCase() === productName.toLowerCase() && p.status === "active"
754
+ );
755
+ },
756
+ hasPlan: (productName) => {
757
+ return purchaseData.purchases.some(
758
+ (p) => p.productName.toLowerCase() === productName.toLowerCase() && p.status === "active"
759
+ );
760
+ },
761
+ activePurchase,
762
+ hasPaidPurchase: activePaidPurchases.length > 0,
763
+ activePaidPurchase
764
+ };
765
+ }, [loading, isRefetching, purchaseError, purchaseData, internalCustomerRef]);
766
+ const balance = useMemo2(
767
+ () => ({
768
+ loading: balanceLoading,
769
+ credits: creditsValue,
770
+ displayCurrency: displayCurrencyValue,
771
+ creditsPerMinorUnit: creditsPerMinorUnitValue,
772
+ displayExchangeRate: displayExchangeRateValue,
773
+ refetch: fetchBalanceImpl,
774
+ adjustBalance: adjustBalanceImpl
775
+ }),
776
+ [balanceLoading, creditsValue, displayCurrencyValue, creditsPerMinorUnitValue, displayExchangeRateValue, fetchBalanceImpl, adjustBalanceImpl]
777
+ );
778
+ const contextValue = useMemo2(
779
+ () => ({
780
+ purchase,
781
+ refetchPurchase,
782
+ createPayment,
783
+ processPayment,
784
+ createTopupPayment,
785
+ cancelRenewal,
786
+ reactivateRenewal,
787
+ activatePlan,
788
+ customerRef: purchaseData.customerRef || internalCustomerRef,
789
+ updateCustomerRef,
790
+ balance,
791
+ _config: configRef.current
792
+ }),
793
+ [
794
+ purchase,
795
+ refetchPurchase,
796
+ createPayment,
797
+ processPayment,
798
+ createTopupPayment,
799
+ cancelRenewal,
800
+ reactivateRenewal,
801
+ activatePlan,
802
+ purchaseData.customerRef,
803
+ internalCustomerRef,
804
+ updateCustomerRef,
805
+ balance
806
+ ]
807
+ );
808
+ return /* @__PURE__ */ jsx2(SolvaPayContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsx2(CopyProvider, { locale: config?.locale, copy: config?.copy, children }) });
809
+ };
810
+
811
+ // src/primitives/composeRefs.ts
812
+ function setRef(ref, value) {
813
+ if (typeof ref === "function") {
814
+ ref(value);
815
+ } else if (ref !== null && ref !== void 0) {
816
+ ;
817
+ ref.current = value;
818
+ }
819
+ }
820
+ function composeRefs(...refs) {
821
+ return (node) => {
822
+ for (const ref of refs) {
823
+ setRef(ref, node);
824
+ }
825
+ };
826
+ }
827
+
828
+ // src/primitives/slot.tsx
829
+ import React3 from "react";
830
+ import { Fragment, jsx as jsx3 } from "react/jsx-runtime";
831
+ var Slot = React3.forwardRef((props, forwardedRef) => {
832
+ const { children, ...slotProps } = props;
833
+ const childrenArray = React3.Children.toArray(children);
834
+ const slottable = childrenArray.find(isSlottable);
835
+ if (slottable) {
836
+ const newElement = slottable.props.children;
837
+ const newChildren = childrenArray.map((child) => {
838
+ if (child === slottable) {
839
+ if (React3.Children.count(newElement) > 1) return React3.Children.only(null);
840
+ return React3.isValidElement(newElement) ? newElement.props.children : null;
841
+ }
842
+ return child;
843
+ });
844
+ return /* @__PURE__ */ jsx3(SlotClone, { ...slotProps, ref: forwardedRef, children: React3.isValidElement(newElement) ? React3.cloneElement(newElement, void 0, newChildren) : null });
845
+ }
846
+ return /* @__PURE__ */ jsx3(SlotClone, { ...slotProps, ref: forwardedRef, children });
847
+ });
848
+ Slot.displayName = "Slot";
849
+ var SlotClone = React3.forwardRef(
850
+ (props, forwardedRef) => {
851
+ const { children, ...slotProps } = props;
852
+ if (React3.isValidElement(children)) {
853
+ const childProps = children.props ?? {};
854
+ const childRef = getElementRef(children);
855
+ const props2 = mergeProps(slotProps, childProps);
856
+ const cloneProps = { ...props2 };
857
+ if (forwardedRef) {
858
+ cloneProps.ref = childRef ? composeRefs(forwardedRef, childRef) : forwardedRef;
859
+ } else {
860
+ cloneProps.ref = childRef;
861
+ }
862
+ return React3.cloneElement(children, cloneProps);
863
+ }
864
+ return React3.Children.count(children) > 1 ? React3.Children.only(null) : null;
865
+ }
866
+ );
867
+ SlotClone.displayName = "SlotClone";
868
+ var Slottable = ({ children }) => {
869
+ return /* @__PURE__ */ jsx3(Fragment, { children });
870
+ };
871
+ function isSlottable(child) {
872
+ return React3.isValidElement(child) && child.type === Slottable;
873
+ }
874
+ function mergeProps(slotProps, childProps) {
875
+ const overrideProps = { ...childProps };
876
+ for (const propName in slotProps) {
877
+ const slotPropValue = slotProps[propName];
878
+ const childPropValue = childProps[propName];
879
+ const isHandler = /^on[A-Z]/.test(propName);
880
+ if (isHandler) {
881
+ if (slotPropValue && childPropValue) {
882
+ overrideProps[propName] = (...args) => {
883
+ ;
884
+ childPropValue(...args);
885
+ const first = args[0];
886
+ if (!first?.defaultPrevented) {
887
+ ;
888
+ slotPropValue(...args);
889
+ }
890
+ };
891
+ } else if (slotPropValue) {
892
+ overrideProps[propName] = slotPropValue;
893
+ }
894
+ } else if (propName === "style") {
895
+ overrideProps[propName] = {
896
+ ...slotPropValue,
897
+ ...childPropValue
898
+ };
899
+ } else if (propName === "className") {
900
+ overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
901
+ } else if (propName === "ref") {
902
+ } else if (childPropValue === void 0) {
903
+ overrideProps[propName] = slotPropValue;
904
+ }
905
+ }
906
+ return overrideProps;
907
+ }
908
+ function getElementRef(element) {
909
+ const el = element;
910
+ return el.props?.ref ?? el.ref ?? null;
911
+ }
912
+
913
+ // src/primitives/composeEventHandlers.ts
914
+ function composeEventHandlers(originalEventHandler, ourEventHandler, { checkForDefaultPrevented = true } = {}) {
915
+ return function handleEvent(event) {
916
+ originalEventHandler?.(event);
917
+ if (checkForDefaultPrevented === false || !event.defaultPrevented) {
918
+ ourEventHandler?.(event);
919
+ }
920
+ };
921
+ }
922
+
923
+ // src/hooks/useSolvaPay.ts
924
+ import { useContext as useContext2 } from "react";
925
+ function useSolvaPay() {
926
+ const context = useContext2(SolvaPayContext);
927
+ if (!context) {
928
+ throw new Error(
929
+ "useSolvaPay must be used within a SolvaPayProvider. Wrap your component tree with <SolvaPayProvider> to use this hook."
930
+ );
931
+ }
932
+ return context;
933
+ }
934
+
935
+ // src/hooks/useCheckout.ts
936
+ import { useState as useState2, useCallback as useCallback2, useRef as useRef2 } from "react";
937
+ import { loadStripe } from "@stripe/stripe-js";
938
+ var stripePromiseCache = /* @__PURE__ */ new Map();
939
+ function getStripeCacheKey(publishableKey, accountId) {
940
+ return accountId ? `${publishableKey}:${accountId}` : publishableKey;
941
+ }
942
+ async function resolvePlanRef(productRef, fetchFn, headers, listPlansRoute) {
943
+ const url = `${listPlansRoute}?productRef=${encodeURIComponent(productRef)}`;
944
+ const res = await fetchFn(url, { method: "GET", headers });
945
+ if (!res.ok) {
946
+ throw new Error(`Failed to fetch plans for product "${productRef}": ${res.statusText}`);
947
+ }
948
+ const data = await res.json();
949
+ const allPlans = data.plans ?? [];
950
+ const activePlans = allPlans.filter((p) => p.isActive !== false && p.status !== "inactive");
951
+ if (activePlans.length === 0) {
952
+ throw new Error(
953
+ `No active plans found for product "${productRef}". Configure at least one plan in the SolvaPay Console.`
954
+ );
955
+ }
956
+ if (activePlans.length === 1) {
957
+ return activePlans[0].reference;
958
+ }
959
+ const defaultPlan = activePlans.find((p) => p.default === true);
960
+ if (defaultPlan) {
961
+ return defaultPlan.reference;
962
+ }
963
+ throw new Error(
964
+ `Product "${productRef}" has ${activePlans.length} active plans but none is marked as default. Either pass planRef explicitly, use <PricingSelector> for user selection, or mark one plan as default in the SolvaPay Console.`
965
+ );
966
+ }
967
+ function useCheckout(options) {
968
+ const { planRef, productRef, customer } = options;
969
+ const { createPayment, customerRef, updateCustomerRef, _config } = useSolvaPay();
970
+ const [loading, setLoading] = useState2(false);
971
+ const [error, setError] = useState2(null);
972
+ const [stripePromise, setStripePromise] = useState2(null);
973
+ const [clientSecret, setClientSecret] = useState2(null);
974
+ const [resolvedPlanRef, setResolvedPlanRef] = useState2(planRef || null);
975
+ const isStartingRef = useRef2(false);
976
+ const startCheckout = useCallback2(async () => {
977
+ if (isStartingRef.current || loading) {
978
+ return;
979
+ }
980
+ if (!planRef && !productRef) {
981
+ setError(
982
+ new Error(
983
+ "useCheckout: either planRef or productRef is required. Pass planRef directly, or pass productRef to auto-resolve the plan."
984
+ )
985
+ );
986
+ return;
987
+ }
988
+ isStartingRef.current = true;
989
+ setLoading(true);
990
+ setError(null);
991
+ try {
992
+ let effectivePlanRef = planRef;
993
+ if (!effectivePlanRef && productRef) {
994
+ const listPlansRoute = _config?.api?.listPlans || "/api/list-plans";
995
+ effectivePlanRef = await resolvePlanRef(productRef, fetch, {}, listPlansRoute);
996
+ setResolvedPlanRef(effectivePlanRef);
997
+ }
998
+ if (!effectivePlanRef) {
999
+ throw new Error("Could not determine plan reference for checkout");
1000
+ }
1001
+ const result = await createPayment({
1002
+ planRef: effectivePlanRef,
1003
+ productRef,
1004
+ customer
1005
+ });
1006
+ if (!result || typeof result !== "object") {
1007
+ throw new Error("Invalid payment intent response from server");
1008
+ }
1009
+ if (!result.clientSecret || typeof result.clientSecret !== "string") {
1010
+ throw new Error("Invalid client secret in payment intent response");
1011
+ }
1012
+ if (!result.publishableKey || typeof result.publishableKey !== "string") {
1013
+ throw new Error("Invalid publishable key in payment intent response");
1014
+ }
1015
+ if (result.customerRef && result.customerRef !== customerRef && updateCustomerRef) {
1016
+ updateCustomerRef(result.customerRef);
1017
+ }
1018
+ const stripeOptions = result.accountId ? { stripeAccount: result.accountId } : {};
1019
+ const cacheKey = getStripeCacheKey(result.publishableKey, result.accountId);
1020
+ let stripe = stripePromiseCache.get(cacheKey);
1021
+ if (!stripe) {
1022
+ stripe = loadStripe(result.publishableKey, stripeOptions);
1023
+ stripePromiseCache.set(cacheKey, stripe);
1024
+ }
1025
+ setStripePromise(stripe);
1026
+ setClientSecret(result.clientSecret);
1027
+ } catch (err) {
1028
+ const error2 = err instanceof Error ? err : new Error("Failed to start checkout");
1029
+ setError(error2);
1030
+ } finally {
1031
+ setLoading(false);
1032
+ isStartingRef.current = false;
1033
+ }
1034
+ }, [planRef, productRef, customer, createPayment, updateCustomerRef, loading, _config]);
1035
+ const reset = useCallback2(() => {
1036
+ isStartingRef.current = false;
1037
+ setLoading(false);
1038
+ setError(null);
1039
+ setStripePromise(null);
1040
+ setClientSecret(null);
1041
+ setResolvedPlanRef(planRef || null);
1042
+ }, [planRef]);
1043
+ return {
1044
+ loading,
1045
+ error,
1046
+ stripePromise,
1047
+ clientSecret,
1048
+ resolvedPlanRef,
1049
+ startCheckout,
1050
+ reset
1051
+ };
1052
+ }
1053
+
1054
+ // src/hooks/usePurchase.ts
1055
+ function usePurchase() {
1056
+ const { purchase, refetchPurchase } = useSolvaPay();
1057
+ return {
1058
+ ...purchase,
1059
+ refetch: refetchPurchase
1060
+ };
1061
+ }
1062
+
1063
+ // src/hooks/useCustomer.ts
1064
+ function useCustomer() {
1065
+ const { purchase, customerRef } = useSolvaPay();
1066
+ return {
1067
+ customerRef: purchase.customerRef || customerRef,
1068
+ email: purchase.email,
1069
+ name: purchase.name,
1070
+ loading: purchase.loading
1071
+ };
1072
+ }
1073
+
1074
+ // src/hooks/useCopy.ts
1075
+ function useCopy() {
1076
+ return useCopyContext().copy;
1077
+ }
1078
+ function useLocale() {
1079
+ return useCopyContext().locale;
1080
+ }
1081
+
1082
+ // src/hooks/usePlans.ts
1083
+ import { useState as useState3, useEffect as useEffect2, useCallback as useCallback3, useMemo as useMemo3, useRef as useRef3 } from "react";
1084
+ var plansCache = /* @__PURE__ */ new Map();
1085
+ var CACHE_DURATION2 = 5 * 60 * 1e3;
1086
+ function processPlans(raw, filter, sortBy) {
1087
+ let result = sortBy ? [...raw].sort(sortBy) : raw;
1088
+ if (filter) result = result.filter(filter);
1089
+ return result;
1090
+ }
1091
+ function computeInitialIndex(plans, initialPlanRef, autoSelectFirstPaid) {
1092
+ if (plans.length === 0) return 0;
1093
+ if (initialPlanRef) {
1094
+ const idx = plans.findIndex((p) => p.reference === initialPlanRef);
1095
+ if (idx >= 0) return idx;
1096
+ }
1097
+ if (autoSelectFirstPaid) {
1098
+ const idx = plans.findIndex((p) => p.requiresPayment !== false);
1099
+ return idx >= 0 ? idx : 0;
1100
+ }
1101
+ return 0;
1102
+ }
1103
+ function usePlans(options) {
1104
+ const {
1105
+ fetcher,
1106
+ productRef,
1107
+ filter,
1108
+ sortBy,
1109
+ autoSelectFirstPaid = false,
1110
+ initialPlanRef,
1111
+ selectionReady = true
1112
+ } = options;
1113
+ const fetcherRef = useRef3(fetcher);
1114
+ const filterRef = useRef3(filter);
1115
+ const sortByRef = useRef3(sortBy);
1116
+ const autoSelectFirstPaidRef = useRef3(autoSelectFirstPaid);
1117
+ const initialPlanRefRef = useRef3(initialPlanRef);
1118
+ const selectionReadyRef = useRef3(selectionReady);
1119
+ const hasAppliedInitialRef = useRef3(false);
1120
+ const userHasSelectedRef = useRef3(false);
1121
+ const [selectedPlanIndex, setSelectedPlanIndexState] = useState3(() => {
1122
+ if (!selectionReady || !productRef) return 0;
1123
+ const cached = plansCache.get(productRef);
1124
+ if (!cached || Date.now() - cached.timestamp >= CACHE_DURATION2 || cached.plans.length === 0) {
1125
+ return 0;
1126
+ }
1127
+ const processed = processPlans(cached.plans, filter, sortBy);
1128
+ if (processed.length === 0) return 0;
1129
+ const idx = computeInitialIndex(processed, initialPlanRef, autoSelectFirstPaid);
1130
+ hasAppliedInitialRef.current = true;
1131
+ return idx;
1132
+ });
1133
+ const [plans, setPlans] = useState3(() => {
1134
+ if (!productRef) return [];
1135
+ const cached = plansCache.get(productRef);
1136
+ if (!cached || Date.now() - cached.timestamp >= CACHE_DURATION2 || cached.plans.length === 0) {
1137
+ return [];
1138
+ }
1139
+ return processPlans(cached.plans, filter, sortBy);
1140
+ });
1141
+ const [loading, setLoading] = useState3(() => plans.length === 0);
1142
+ const [error, setError] = useState3(null);
1143
+ useEffect2(() => {
1144
+ fetcherRef.current = fetcher;
1145
+ }, [fetcher]);
1146
+ useEffect2(() => {
1147
+ filterRef.current = filter;
1148
+ }, [filter]);
1149
+ useEffect2(() => {
1150
+ sortByRef.current = sortBy;
1151
+ }, [sortBy]);
1152
+ useEffect2(() => {
1153
+ autoSelectFirstPaidRef.current = autoSelectFirstPaid;
1154
+ }, [autoSelectFirstPaid]);
1155
+ useEffect2(() => {
1156
+ initialPlanRefRef.current = initialPlanRef;
1157
+ }, [initialPlanRef]);
1158
+ useEffect2(() => {
1159
+ selectionReadyRef.current = selectionReady;
1160
+ }, [selectionReady]);
1161
+ const setSelectedPlanIndex = useCallback3((index) => {
1162
+ userHasSelectedRef.current = true;
1163
+ setSelectedPlanIndexState(index);
1164
+ }, []);
1165
+ const applyInitialSelection = useCallback3((processedPlans) => {
1166
+ if (hasAppliedInitialRef.current || userHasSelectedRef.current) return;
1167
+ if (!selectionReadyRef.current || processedPlans.length === 0) return;
1168
+ hasAppliedInitialRef.current = true;
1169
+ const idx = computeInitialIndex(
1170
+ processedPlans,
1171
+ initialPlanRefRef.current,
1172
+ autoSelectFirstPaidRef.current
1173
+ );
1174
+ setSelectedPlanIndexState(idx);
1175
+ }, []);
1176
+ const fetchPlans = useCallback3(
1177
+ async (force = false) => {
1178
+ if (!productRef) {
1179
+ setError(new Error("Product reference not configured"));
1180
+ setLoading(false);
1181
+ return;
1182
+ }
1183
+ const cached = plansCache.get(productRef);
1184
+ const now = Date.now();
1185
+ if (!force && cached && now - cached.timestamp < CACHE_DURATION2) {
1186
+ const processedPlans = processPlans(
1187
+ cached.plans,
1188
+ filterRef.current,
1189
+ sortByRef.current
1190
+ );
1191
+ setPlans(processedPlans);
1192
+ setLoading(false);
1193
+ setError(null);
1194
+ applyInitialSelection(processedPlans);
1195
+ return;
1196
+ }
1197
+ if (cached?.promise) {
1198
+ try {
1199
+ setLoading(true);
1200
+ const fetchedPlans = await cached.promise;
1201
+ const processedPlans = processPlans(
1202
+ fetchedPlans,
1203
+ filterRef.current,
1204
+ sortByRef.current
1205
+ );
1206
+ setPlans(processedPlans);
1207
+ setError(null);
1208
+ applyInitialSelection(processedPlans);
1209
+ } catch (err) {
1210
+ setError(err instanceof Error ? err : new Error("Failed to load plans"));
1211
+ } finally {
1212
+ setLoading(false);
1213
+ }
1214
+ return;
1215
+ }
1216
+ try {
1217
+ setLoading(true);
1218
+ setError(null);
1219
+ const fetchPromise = fetcherRef.current(productRef);
1220
+ plansCache.set(productRef, { plans: [], timestamp: now, promise: fetchPromise });
1221
+ const fetchedPlans = await fetchPromise;
1222
+ plansCache.set(productRef, { plans: fetchedPlans, timestamp: now, promise: null });
1223
+ const processedPlans = processPlans(
1224
+ fetchedPlans,
1225
+ filterRef.current,
1226
+ sortByRef.current
1227
+ );
1228
+ setPlans(processedPlans);
1229
+ applyInitialSelection(processedPlans);
1230
+ } catch (err) {
1231
+ plansCache.delete(productRef);
1232
+ setError(err instanceof Error ? err : new Error("Failed to load plans"));
1233
+ } finally {
1234
+ setLoading(false);
1235
+ }
1236
+ },
1237
+ [productRef, applyInitialSelection]
1238
+ );
1239
+ useEffect2(() => {
1240
+ fetchPlans();
1241
+ }, [fetchPlans]);
1242
+ useEffect2(() => {
1243
+ if (hasAppliedInitialRef.current || userHasSelectedRef.current) return;
1244
+ if (!selectionReady || plans.length === 0) return;
1245
+ applyInitialSelection(plans);
1246
+ }, [selectionReady, plans, applyInitialSelection]);
1247
+ const selectedPlan = useMemo3(() => plans[selectedPlanIndex] || null, [plans, selectedPlanIndex]);
1248
+ const selectPlan = useCallback3(
1249
+ (planRef) => {
1250
+ const index = plans.findIndex((p) => p.reference === planRef);
1251
+ if (index >= 0) {
1252
+ setSelectedPlanIndex(index);
1253
+ }
1254
+ },
1255
+ [plans, setSelectedPlanIndex]
1256
+ );
1257
+ return {
1258
+ plans,
1259
+ loading,
1260
+ error,
1261
+ selectedPlanIndex,
1262
+ selectedPlan,
1263
+ setSelectedPlanIndex,
1264
+ selectPlan,
1265
+ refetch: () => fetchPlans(true),
1266
+ isSelectionReady: hasAppliedInitialRef.current
1267
+ };
1268
+ }
1269
+
1270
+ // src/hooks/usePlan.ts
1271
+ import { useCallback as useCallback4, useEffect as useEffect3, useState as useState4 } from "react";
1272
+ async function listPlans(productRef, config) {
1273
+ const base = config?.api?.listPlans || "/api/list-plans";
1274
+ const url = `${base}?productRef=${encodeURIComponent(productRef)}`;
1275
+ const fetchFn = config?.fetch || fetch;
1276
+ const { headers } = await buildRequestHeaders(config);
1277
+ const res = await fetchFn(url, { method: "GET", headers });
1278
+ if (!res.ok) {
1279
+ const error = new Error(`Failed to fetch plans: ${res.statusText || res.status}`);
1280
+ config?.onError?.(error, "listPlans");
1281
+ throw error;
1282
+ }
1283
+ const data = await res.json();
1284
+ return data.plans ?? [];
1285
+ }
1286
+ function usePlan(options) {
1287
+ const { planRef, productRef } = options;
1288
+ const { _config } = useSolvaPay();
1289
+ const findPlan = useCallback4(
1290
+ (plans) => {
1291
+ if (!planRef) return null;
1292
+ return plans.find((p) => p.reference === planRef) || null;
1293
+ },
1294
+ [planRef]
1295
+ );
1296
+ const [plan, setPlan] = useState4(() => {
1297
+ if (!planRef || !productRef) return null;
1298
+ const cached = plansCache.get(productRef);
1299
+ if (!cached || Date.now() - cached.timestamp >= CACHE_DURATION2) return null;
1300
+ return findPlan(cached.plans);
1301
+ });
1302
+ const [loading, setLoading] = useState4(() => !!(planRef && !plan));
1303
+ const [error, setError] = useState4(null);
1304
+ const load = useCallback4(
1305
+ async (force = false) => {
1306
+ if (!planRef) {
1307
+ setPlan(null);
1308
+ setLoading(false);
1309
+ setError(null);
1310
+ return;
1311
+ }
1312
+ if (!productRef) {
1313
+ setLoading(false);
1314
+ setError(
1315
+ new Error("usePlan: productRef is required to resolve a plan reference")
1316
+ );
1317
+ return;
1318
+ }
1319
+ const cached = plansCache.get(productRef);
1320
+ const now = Date.now();
1321
+ if (!force && cached?.plans.length && now - cached.timestamp < CACHE_DURATION2) {
1322
+ const p = findPlan(cached.plans);
1323
+ setPlan(p);
1324
+ setLoading(false);
1325
+ setError(
1326
+ p ? null : new Error(
1327
+ `Plan "${planRef}" not found in product "${productRef}"`
1328
+ )
1329
+ );
1330
+ return;
1331
+ }
1332
+ if (!force && cached?.promise) {
1333
+ try {
1334
+ setLoading(true);
1335
+ const plans = await cached.promise;
1336
+ const p = findPlan(plans);
1337
+ setPlan(p);
1338
+ setError(
1339
+ p ? null : new Error(
1340
+ `Plan "${planRef}" not found in product "${productRef}"`
1341
+ )
1342
+ );
1343
+ } catch (err) {
1344
+ setError(err instanceof Error ? err : new Error("Failed to load plan"));
1345
+ } finally {
1346
+ setLoading(false);
1347
+ }
1348
+ return;
1349
+ }
1350
+ try {
1351
+ setLoading(true);
1352
+ setError(null);
1353
+ const promise = listPlans(productRef, _config);
1354
+ plansCache.set(productRef, { plans: [], timestamp: now, promise });
1355
+ const plans = await promise;
1356
+ plansCache.set(productRef, { plans, timestamp: now, promise: null });
1357
+ const p = findPlan(plans);
1358
+ setPlan(p);
1359
+ if (!p) {
1360
+ setError(new Error(`Plan "${planRef}" not found in product "${productRef}"`));
1361
+ }
1362
+ } catch (err) {
1363
+ plansCache.delete(productRef);
1364
+ setError(err instanceof Error ? err : new Error("Failed to load plan"));
1365
+ } finally {
1366
+ setLoading(false);
1367
+ }
1368
+ },
1369
+ [planRef, productRef, _config, findPlan]
1370
+ );
1371
+ useEffect3(() => {
1372
+ load();
1373
+ }, [load]);
1374
+ return {
1375
+ plan,
1376
+ loading,
1377
+ error,
1378
+ refetch: () => load(true)
1379
+ };
1380
+ }
1381
+
1382
+ // src/hooks/useProduct.ts
1383
+ import { useCallback as useCallback5, useEffect as useEffect4, useState as useState5 } from "react";
1384
+ var productCache = /* @__PURE__ */ new Map();
1385
+ var CACHE_DURATION3 = 5 * 60 * 1e3;
1386
+ function routeFor(config) {
1387
+ return config?.api?.getProduct || "/api/get-product";
1388
+ }
1389
+ async function fetchProduct(productRef, config) {
1390
+ const base = routeFor(config);
1391
+ const url = `${base}?productRef=${encodeURIComponent(productRef)}`;
1392
+ const fetchFn = config?.fetch || fetch;
1393
+ const { headers } = await buildRequestHeaders(config);
1394
+ const res = await fetchFn(url, { method: "GET", headers });
1395
+ if (!res.ok) {
1396
+ const error = new Error(`Failed to fetch product: ${res.statusText || res.status}`);
1397
+ config?.onError?.(error, "getProduct");
1398
+ throw error;
1399
+ }
1400
+ return await res.json();
1401
+ }
1402
+ function useProduct(productRef) {
1403
+ const { _config } = useSolvaPay();
1404
+ const cacheKey = productRef || "";
1405
+ const [product, setProduct] = useState5(
1406
+ () => productRef ? productCache.get(cacheKey)?.product ?? null : null
1407
+ );
1408
+ const [loading, setLoading] = useState5(() => {
1409
+ if (!productRef) return false;
1410
+ const cached = productCache.get(cacheKey);
1411
+ return !cached || !cached.product && !cached.promise;
1412
+ });
1413
+ const [error, setError] = useState5(null);
1414
+ const load = useCallback5(
1415
+ async (force = false) => {
1416
+ if (!productRef) {
1417
+ setProduct(null);
1418
+ setLoading(false);
1419
+ setError(null);
1420
+ return;
1421
+ }
1422
+ const cached = productCache.get(productRef);
1423
+ const now = Date.now();
1424
+ if (!force && cached?.product && now - cached.timestamp < CACHE_DURATION3) {
1425
+ setProduct(cached.product);
1426
+ setLoading(false);
1427
+ setError(null);
1428
+ return;
1429
+ }
1430
+ if (!force && cached?.promise) {
1431
+ try {
1432
+ setLoading(true);
1433
+ const p = await cached.promise;
1434
+ setProduct(p);
1435
+ setError(null);
1436
+ } catch (err) {
1437
+ setError(err instanceof Error ? err : new Error("Failed to load product"));
1438
+ } finally {
1439
+ setLoading(false);
1440
+ }
1441
+ return;
1442
+ }
1443
+ try {
1444
+ setLoading(true);
1445
+ setError(null);
1446
+ const promise = fetchProduct(productRef, _config);
1447
+ productCache.set(productRef, { product: null, promise, timestamp: now });
1448
+ const p = await promise;
1449
+ productCache.set(productRef, { product: p, promise: null, timestamp: now });
1450
+ setProduct(p);
1451
+ } catch (err) {
1452
+ productCache.delete(productRef);
1453
+ setError(err instanceof Error ? err : new Error("Failed to load product"));
1454
+ } finally {
1455
+ setLoading(false);
1456
+ }
1457
+ },
1458
+ [productRef, _config]
1459
+ );
1460
+ useEffect4(() => {
1461
+ load();
1462
+ }, [load]);
1463
+ return {
1464
+ product,
1465
+ loading,
1466
+ error,
1467
+ refetch: () => load(true)
1468
+ };
1469
+ }
1470
+
1471
+ // src/hooks/useActivation.ts
1472
+ import { useState as useState6, useCallback as useCallback6 } from "react";
1473
+ function useActivation() {
1474
+ const { activatePlan } = useSolvaPay();
1475
+ const copy = useCopy();
1476
+ const [state, setState] = useState6("idle");
1477
+ const [error, setError] = useState6(null);
1478
+ const [result, setResult] = useState6(null);
1479
+ const activate = useCallback6(
1480
+ async (params) => {
1481
+ setState("activating");
1482
+ setError(null);
1483
+ setResult(null);
1484
+ try {
1485
+ const data = await activatePlan(params);
1486
+ setResult(data);
1487
+ switch (data.status) {
1488
+ case "activated":
1489
+ case "already_active":
1490
+ setState("activated");
1491
+ break;
1492
+ case "topup_required":
1493
+ setState("topup_required");
1494
+ break;
1495
+ case "payment_required":
1496
+ setError(copy.activation.paymentRequired);
1497
+ setState("payment_required");
1498
+ break;
1499
+ case "invalid":
1500
+ setError(data.message || copy.activation.invalidConfiguration);
1501
+ setState("error");
1502
+ break;
1503
+ default:
1504
+ setError(copy.activation.unexpectedResponse);
1505
+ setState("error");
1506
+ }
1507
+ } catch (err) {
1508
+ setError(err instanceof Error ? err.message : copy.activation.failed);
1509
+ setState("error");
1510
+ }
1511
+ },
1512
+ [activatePlan, copy]
1513
+ );
1514
+ const reset = useCallback6(() => {
1515
+ setState("idle");
1516
+ setError(null);
1517
+ setResult(null);
1518
+ }, []);
1519
+ return { activate, state, error, result, reset };
1520
+ }
1521
+
1522
+ // src/components/PaymentFormContext.tsx
1523
+ import { createContext as createContext3, useContext as useContext3 } from "react";
1524
+ import { jsx as jsx4 } from "react/jsx-runtime";
1525
+ var PaymentFormContext = createContext3(null);
1526
+ function usePaymentForm() {
1527
+ const ctx = useContext3(PaymentFormContext);
1528
+ if (!ctx) {
1529
+ throw new Error(
1530
+ "PaymentForm subcomponents must be used inside a <PaymentForm>. Wrap the slots with <PaymentForm planRef=... productRef=...>."
1531
+ );
1532
+ }
1533
+ return ctx;
1534
+ }
1535
+ var PaymentFormProvider = ({ value, children }) => /* @__PURE__ */ jsx4(PaymentFormContext.Provider, { value, children });
1536
+
1537
+ // src/utils/format.ts
1538
+ var ZERO_DECIMAL_CURRENCIES = /* @__PURE__ */ new Set([
1539
+ "bif",
1540
+ "clp",
1541
+ "djf",
1542
+ "gnf",
1543
+ "jpy",
1544
+ "kmf",
1545
+ "krw",
1546
+ "mga",
1547
+ "pyg",
1548
+ "rwf",
1549
+ "ugx",
1550
+ "vnd",
1551
+ "vuv",
1552
+ "xaf",
1553
+ "xof",
1554
+ "xpf"
1555
+ ]);
1556
+ function getFractionDigits(currency) {
1557
+ return ZERO_DECIMAL_CURRENCIES.has(currency.toLowerCase()) ? 0 : 2;
1558
+ }
1559
+ function toMajorUnits(amountMinor, currency) {
1560
+ const fractionDigits = getFractionDigits(currency);
1561
+ return fractionDigits === 0 ? amountMinor : amountMinor / 100;
1562
+ }
1563
+ function formatPrice(amountMinor, currency, opts = {}) {
1564
+ const { locale, interval, intervalCount = 1, free = "Free" } = opts;
1565
+ if (amountMinor === 0 && free !== "") {
1566
+ return free;
1567
+ }
1568
+ const fractionDigits = getFractionDigits(currency);
1569
+ const major = toMajorUnits(amountMinor, currency);
1570
+ const formatter = new Intl.NumberFormat(locale, {
1571
+ style: "currency",
1572
+ currency: currency.toUpperCase(),
1573
+ minimumFractionDigits: fractionDigits,
1574
+ maximumFractionDigits: fractionDigits
1575
+ });
1576
+ const formatted = formatter.format(major);
1577
+ if (!interval) return formatted;
1578
+ const suffix = intervalCount > 1 ? `${intervalCount} ${interval}s` : interval;
1579
+ return `${formatted} / ${suffix}`;
1580
+ }
1581
+
1582
+ // src/i18n/interpolate.ts
1583
+ function interpolate(template, vars) {
1584
+ return template.replace(/\{(\w+)\}/g, (match, key) => {
1585
+ const value = vars[key];
1586
+ if (value === void 0 || value === null) return match;
1587
+ return String(value);
1588
+ });
1589
+ }
1590
+
1591
+ // src/primitives/CheckoutSummary.tsx
1592
+ import { createContext as createContext5, forwardRef, useContext as useContext5, useMemo as useMemo4 } from "react";
1593
+
1594
+ // src/components/PlanSelectionContext.tsx
1595
+ import { createContext as createContext4, useContext as useContext4 } from "react";
1596
+ import { jsx as jsx5 } from "react/jsx-runtime";
1597
+ var PlanSelectionContext = createContext4(null);
1598
+ var PlanSelectionProvider = ({
1599
+ value,
1600
+ children
1601
+ }) => /* @__PURE__ */ jsx5(PlanSelectionContext.Provider, { value, children });
1602
+ function usePlanSelection() {
1603
+ return useContext4(PlanSelectionContext);
1604
+ }
1605
+
1606
+ // src/utils/errors.ts
1607
+ var DOCS_BASE_URL = "https://solvapay.com/docs";
1608
+ var SolvaPayError = class extends Error {
1609
+ code;
1610
+ docsUrl;
1611
+ constructor(code, message, docsUrl) {
1612
+ super(message);
1613
+ this.name = "SolvaPayError";
1614
+ this.code = code;
1615
+ this.docsUrl = docsUrl;
1616
+ }
1617
+ };
1618
+ var MissingProviderError = class extends SolvaPayError {
1619
+ constructor(primitiveName) {
1620
+ const docsUrl = `${DOCS_BASE_URL}/troubleshooting/missing-provider`;
1621
+ super(
1622
+ "MISSING_PROVIDER",
1623
+ `${primitiveName} must be rendered inside <SolvaPayProvider>. Wrap your app (or the section using ${primitiveName}) with <SolvaPayProvider config={{ ... }}>. See ${docsUrl}`,
1624
+ docsUrl
1625
+ );
1626
+ this.name = "MissingProviderError";
1627
+ }
1628
+ };
1629
+ var MissingProductRefError = class extends SolvaPayError {
1630
+ constructor(primitiveName) {
1631
+ const docsUrl = `${DOCS_BASE_URL}/primitives/product-ref`;
1632
+ super(
1633
+ "MISSING_PRODUCT_REF",
1634
+ `${primitiveName} requires a productRef. Pass the \`productRef\` prop (or set NEXT_PUBLIC_SOLVAPAY_PRODUCT_REF). See ${docsUrl}`,
1635
+ docsUrl
1636
+ );
1637
+ this.name = "MissingProductRefError";
1638
+ }
1639
+ };
1640
+
1641
+ // src/primitives/CheckoutSummary.tsx
1642
+ import { jsx as jsx6 } from "react/jsx-runtime";
1643
+ var CheckoutSummaryContext = createContext5(null);
1644
+ function useCheckoutSummaryContext(part) {
1645
+ const ctx = useContext5(CheckoutSummaryContext);
1646
+ if (!ctx) {
1647
+ throw new Error(
1648
+ `CheckoutSummary.${part} must be rendered inside <CheckoutSummary.Root>.`
1649
+ );
1650
+ }
1651
+ return ctx;
1652
+ }
1653
+ var Root = forwardRef(function CheckoutSummaryRoot({ planRef, productRef, asChild, children, ...rest }, forwardedRef) {
1654
+ const solva = useContext5(SolvaPayContext);
1655
+ if (!solva) throw new MissingProviderError("CheckoutSummary");
1656
+ const locale = useLocale();
1657
+ const copy = useCopy();
1658
+ const planSelection = usePlanSelection();
1659
+ const resolvedPlanRef = planRef ?? planSelection?.selectedPlanRef ?? void 0;
1660
+ const resolvedProductRef = productRef ?? planSelection?.productRef;
1661
+ const { plan, loading: planLoading } = usePlan({
1662
+ planRef: resolvedPlanRef,
1663
+ productRef: resolvedProductRef
1664
+ });
1665
+ const { product, loading: productLoading } = useProduct(resolvedProductRef);
1666
+ const loading = planLoading || productLoading;
1667
+ const priceFormatted = useMemo4(() => {
1668
+ const price = plan?.price ?? 0;
1669
+ const currency = plan?.currency ?? "usd";
1670
+ return formatPrice(price, currency, {
1671
+ locale,
1672
+ interval: plan?.interval,
1673
+ intervalCount: 1,
1674
+ free: copy.interval.free
1675
+ });
1676
+ }, [plan, locale, copy.interval.free]);
1677
+ const trialBanner = useMemo4(() => {
1678
+ const trialDays = plan?.trialDays;
1679
+ if (!trialDays || trialDays <= 0) return null;
1680
+ return interpolate(copy.interval.trial, { trialDays });
1681
+ }, [plan?.trialDays, copy.interval.trial]);
1682
+ const ctx = useMemo4(
1683
+ () => ({ plan, product, priceFormatted, trialBanner, loading }),
1684
+ [plan, product, priceFormatted, trialBanner, loading]
1685
+ );
1686
+ const Comp = asChild ? Slot : "div";
1687
+ return /* @__PURE__ */ jsx6(Comp, { ref: forwardedRef, "data-solvapay-checkout-summary": "", ...rest, children: /* @__PURE__ */ jsx6(CheckoutSummaryContext.Provider, { value: ctx, children }) });
1688
+ });
1689
+ var ProductSlot = forwardRef(function CheckoutSummaryProduct({ asChild, children, ...rest }, forwardedRef) {
1690
+ const ctx = useCheckoutSummaryContext("Product");
1691
+ const name = ctx.product?.name;
1692
+ if (!name) return null;
1693
+ const Comp = asChild ? Slot : "span";
1694
+ return /* @__PURE__ */ jsx6(Comp, { ref: forwardedRef, "data-solvapay-checkout-summary-product": "", ...rest, children: children ?? name });
1695
+ });
1696
+ var PlanSlot = forwardRef(function CheckoutSummaryPlan({ asChild, children, ...rest }, forwardedRef) {
1697
+ const ctx = useCheckoutSummaryContext("Plan");
1698
+ const name = ctx.plan?.name;
1699
+ if (!name) return null;
1700
+ const Comp = asChild ? Slot : "span";
1701
+ return /* @__PURE__ */ jsx6(Comp, { ref: forwardedRef, "data-solvapay-checkout-summary-plan": "", ...rest, children: children ?? name });
1702
+ });
1703
+ var PriceSlot = forwardRef(function CheckoutSummaryPrice({ asChild, children, ...rest }, forwardedRef) {
1704
+ const ctx = useCheckoutSummaryContext("Price");
1705
+ const Comp = asChild ? Slot : "span";
1706
+ return /* @__PURE__ */ jsx6(Comp, { ref: forwardedRef, "data-solvapay-checkout-summary-price": "", ...rest, children: children ?? ctx.priceFormatted });
1707
+ });
1708
+ var TrialSlot = forwardRef(function CheckoutSummaryTrial({ asChild, children, ...rest }, forwardedRef) {
1709
+ const ctx = useCheckoutSummaryContext("Trial");
1710
+ if (!ctx.trialBanner) return null;
1711
+ const Comp = asChild ? Slot : "span";
1712
+ return /* @__PURE__ */ jsx6(Comp, { ref: forwardedRef, "data-solvapay-checkout-summary-trial": "", ...rest, children: children ?? ctx.trialBanner });
1713
+ });
1714
+ var TaxNoteSlot = forwardRef(function CheckoutSummaryTaxNote({ asChild, children, ...rest }, forwardedRef) {
1715
+ useCheckoutSummaryContext("TaxNote");
1716
+ const Comp = asChild ? Slot : "span";
1717
+ return /* @__PURE__ */ jsx6(Comp, { ref: forwardedRef, "data-solvapay-checkout-summary-tax-note": "", ...rest, children: children ?? "Taxes calculated at checkout" });
1718
+ });
1719
+ var CheckoutSummaryRoot2 = Root;
1720
+ var CheckoutSummaryProduct2 = ProductSlot;
1721
+ var CheckoutSummaryPlan2 = PlanSlot;
1722
+ var CheckoutSummaryPrice2 = PriceSlot;
1723
+ var CheckoutSummaryTrial2 = TrialSlot;
1724
+ var CheckoutSummaryTaxNote2 = TaxNoteSlot;
1725
+ var CheckoutSummary = {
1726
+ Root,
1727
+ Product: ProductSlot,
1728
+ Plan: PlanSlot,
1729
+ Price: PriceSlot,
1730
+ Trial: TrialSlot,
1731
+ TaxNote: TaxNoteSlot
1732
+ };
1733
+ function useCheckoutSummary() {
1734
+ return useCheckoutSummaryContext("useCheckoutSummary");
1735
+ }
1736
+
1737
+ // src/components/CheckoutSummary.tsx
1738
+ import { jsx as jsx7, jsxs } from "react/jsx-runtime";
1739
+ var CheckoutSummary2 = ({
1740
+ planRef,
1741
+ productRef,
1742
+ showTrial = true,
1743
+ showTaxNote = false,
1744
+ className
1745
+ }) => {
1746
+ const rootClass = ["solvapay-checkout-summary", className].filter(Boolean).join(" ");
1747
+ return /* @__PURE__ */ jsxs(CheckoutSummary.Root, { planRef, productRef, className: rootClass, children: [
1748
+ /* @__PURE__ */ jsx7(CheckoutSummary.Product, { className: "solvapay-checkout-summary-product" }),
1749
+ /* @__PURE__ */ jsxs("div", { className: "solvapay-checkout-summary-row", children: [
1750
+ /* @__PURE__ */ jsx7(CheckoutSummary.Plan, { className: "solvapay-checkout-summary-plan" }),
1751
+ /* @__PURE__ */ jsx7(CheckoutSummary.Price, { className: "solvapay-checkout-summary-price" })
1752
+ ] }),
1753
+ showTrial && /* @__PURE__ */ jsx7(CheckoutSummary.Trial, { className: "solvapay-checkout-summary-trial" }),
1754
+ showTaxNote && /* @__PURE__ */ jsx7(CheckoutSummary.TaxNote, { className: "solvapay-checkout-summary-tax-note" })
1755
+ ] });
1756
+ };
1757
+
1758
+ // src/hooks/useMerchant.ts
1759
+ import { useCallback as useCallback7, useEffect as useEffect5, useState as useState7 } from "react";
1760
+ var merchantCache = /* @__PURE__ */ new Map();
1761
+ var CACHE_DURATION4 = 5 * 60 * 1e3;
1762
+ function cacheKeyFor(config) {
1763
+ return config?.api?.getMerchant || "/api/merchant";
1764
+ }
1765
+ async function fetchMerchant(config) {
1766
+ const route = cacheKeyFor(config);
1767
+ const fetchFn = config?.fetch || fetch;
1768
+ const { headers } = await buildRequestHeaders(config);
1769
+ const res = await fetchFn(route, { method: "GET", headers });
1770
+ if (!res.ok) {
1771
+ const error = new Error(`Failed to fetch merchant: ${res.statusText || res.status}`);
1772
+ config?.onError?.(error, "getMerchant");
1773
+ throw error;
1774
+ }
1775
+ return await res.json();
1776
+ }
1777
+ function useMerchant() {
1778
+ const { _config } = useSolvaPay();
1779
+ const key = cacheKeyFor(_config);
1780
+ const [merchant, setMerchant] = useState7(
1781
+ () => merchantCache.get(key)?.merchant ?? null
1782
+ );
1783
+ const [loading, setLoading] = useState7(() => {
1784
+ const cached = merchantCache.get(key);
1785
+ return !cached || !cached.merchant && !cached.promise;
1786
+ });
1787
+ const [error, setError] = useState7(null);
1788
+ const load = useCallback7(
1789
+ async (force = false) => {
1790
+ const cached = merchantCache.get(key);
1791
+ const now = Date.now();
1792
+ if (!force && cached?.merchant && now - cached.timestamp < CACHE_DURATION4) {
1793
+ setMerchant(cached.merchant);
1794
+ setLoading(false);
1795
+ setError(null);
1796
+ return;
1797
+ }
1798
+ if (!force && cached?.promise) {
1799
+ try {
1800
+ setLoading(true);
1801
+ const m = await cached.promise;
1802
+ setMerchant(m);
1803
+ setError(null);
1804
+ } catch (err) {
1805
+ setError(err instanceof Error ? err : new Error("Failed to load merchant"));
1806
+ } finally {
1807
+ setLoading(false);
1808
+ }
1809
+ return;
1810
+ }
1811
+ try {
1812
+ setLoading(true);
1813
+ setError(null);
1814
+ const promise = fetchMerchant(_config);
1815
+ merchantCache.set(key, { merchant: null, promise, timestamp: now });
1816
+ const m = await promise;
1817
+ merchantCache.set(key, { merchant: m, promise: null, timestamp: now });
1818
+ setMerchant(m);
1819
+ } catch (err) {
1820
+ merchantCache.delete(key);
1821
+ setError(err instanceof Error ? err : new Error("Failed to load merchant"));
1822
+ } finally {
1823
+ setLoading(false);
1824
+ }
1825
+ },
1826
+ [_config, key]
1827
+ );
1828
+ useEffect5(() => {
1829
+ load();
1830
+ }, [load]);
1831
+ return {
1832
+ merchant,
1833
+ loading,
1834
+ error,
1835
+ refetch: () => load(true)
1836
+ };
1837
+ }
1838
+
1839
+ // src/utils/checkoutVariant.ts
1840
+ function deriveVariant(plan, mode) {
1841
+ if (mode === "topup") return "topup";
1842
+ if (!plan?.type) return "oneTime";
1843
+ if (plan.type === "usage-based") {
1844
+ return plan.billingModel === "post-paid" ? "usageMetered" : "topup";
1845
+ }
1846
+ if (plan.requiresPayment === false) return "freeTier";
1847
+ switch (plan.type) {
1848
+ case "recurring":
1849
+ return "recurring";
1850
+ case "one-time":
1851
+ default:
1852
+ return "oneTime";
1853
+ }
1854
+ }
1855
+
1856
+ // src/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({ requirePlan, requireProduct, asChild, children, ...rest }, forwardedRef) {
3461
+ const solva = useContext11(SolvaPayContext);
3462
+ if (!solva) throw new MissingProviderError("PurchaseGate");
3463
+ const { purchases, loading, hasProduct, error } = usePurchase();
3464
+ const productToCheck = requireProduct || requirePlan;
3465
+ const hasAccess = productToCheck ? hasProduct(productToCheck) : purchases.some((p) => p.status === "active");
3466
+ const state = loading ? "loading" : hasAccess ? "allowed" : "blocked";
3467
+ const ctx = useMemo10(
3468
+ () => ({ state, loading, hasAccess, error }),
3469
+ [state, loading, hasAccess, error]
3470
+ );
3471
+ const Comp = asChild ? Slot : "div";
3472
+ return /* @__PURE__ */ jsx15(PurchaseGateContext.Provider, { value: ctx, children: /* @__PURE__ */ jsx15(
3473
+ Comp,
3474
+ {
3475
+ ref: forwardedRef,
3476
+ "data-solvapay-purchase-gate": "",
3477
+ "data-state": state,
3478
+ ...rest,
3479
+ children
3480
+ }
3481
+ ) });
3482
+ });
3483
+ var Allowed = forwardRef7(function PurchaseGateAllowed({ asChild, children, ...rest }, forwardedRef) {
3484
+ const ctx = useGateCtx("Allowed");
3485
+ if (ctx.state !== "allowed") return null;
3486
+ const Comp = asChild ? Slot : "div";
3487
+ return /* @__PURE__ */ jsx15(Comp, { ref: forwardedRef, "data-solvapay-purchase-gate-allowed": "", ...rest, children });
3488
+ });
3489
+ var Blocked = forwardRef7(function PurchaseGateBlocked({ asChild, children, ...rest }, forwardedRef) {
3490
+ const ctx = useGateCtx("Blocked");
3491
+ if (ctx.state !== "blocked") return null;
3492
+ const Comp = asChild ? Slot : "div";
3493
+ return /* @__PURE__ */ jsx15(Comp, { ref: forwardedRef, "data-solvapay-purchase-gate-blocked": "", ...rest, children });
3494
+ });
3495
+ var Loading3 = forwardRef7(function PurchaseGateLoading({ asChild, children, ...rest }, forwardedRef) {
3496
+ const ctx = useGateCtx("Loading");
3497
+ if (ctx.state !== "loading") return null;
3498
+ const Comp = asChild ? Slot : "div";
3499
+ return /* @__PURE__ */ jsx15(Comp, { ref: forwardedRef, "data-solvapay-purchase-gate-loading": "", ...rest, children });
3500
+ });
3501
+ var ErrorSlot3 = forwardRef7(function PurchaseGateError({ asChild, children, ...rest }, forwardedRef) {
3502
+ const ctx = useGateCtx("Error");
3503
+ if (!ctx.error) return null;
3504
+ const Comp = asChild ? Slot : "div";
3505
+ return /* @__PURE__ */ jsx15(Comp, { ref: forwardedRef, "data-solvapay-purchase-gate-error": "", role: "alert", ...rest, children: children ?? ctx.error.message });
3506
+ });
3507
+ var PurchaseGateRoot2 = Root5;
3508
+ var PurchaseGateAllowed2 = Allowed;
3509
+ var PurchaseGateBlocked2 = Blocked;
3510
+ var PurchaseGateLoading2 = Loading3;
3511
+ var PurchaseGateError2 = ErrorSlot3;
3512
+ var PurchaseGate = {
3513
+ Root: Root5,
3514
+ Allowed,
3515
+ Blocked,
3516
+ Loading: Loading3,
3517
+ Error: ErrorSlot3
3518
+ };
3519
+ function usePurchaseGate() {
3520
+ return useGateCtx("usePurchaseGate");
3521
+ }
3522
+
3523
+ // src/primitives/BalanceBadge.tsx
3524
+ import { forwardRef as forwardRef8, useContext as useContext12 } from "react";
3525
+ import { Fragment as Fragment6, jsx as jsx16, jsxs as jsxs7 } from "react/jsx-runtime";
3526
+ var BalanceBadge = forwardRef8(function BalanceBadge2({ asChild, numberOnly, lowThreshold = 10, children, ...rest }, forwardedRef) {
3527
+ const solva = useContext12(SolvaPayContext);
3528
+ if (!solva) throw new MissingProviderError("BalanceBadge");
3529
+ const { credits, displayCurrency, creditsPerMinorUnit, displayExchangeRate, loading } = useBalance();
3530
+ const copy = useCopy();
3531
+ const locale = useLocale();
3532
+ const state = loading ? "loading" : credits == null || credits === 0 ? "zero" : credits <= lowThreshold ? "low" : "ok";
3533
+ const commonProps = {
3534
+ "data-solvapay-balance-badge": "",
3535
+ "data-state": state,
3536
+ "data-credits": credits == null ? void 0 : String(credits),
3537
+ "aria-busy": loading,
3538
+ ...rest
3539
+ };
3540
+ if (state === "loading") {
3541
+ if (asChild) {
3542
+ return (
3543
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
3544
+ /* @__PURE__ */ jsx16(Slot, { ref: forwardedRef, ...commonProps, children: children ?? /* @__PURE__ */ jsx16(Fragment6, {}) })
3545
+ );
3546
+ }
3547
+ return /* @__PURE__ */ jsx16("span", { ref: forwardedRef, ...commonProps });
3548
+ }
3549
+ if (credits == null) return null;
3550
+ const formattedCredits = new Intl.NumberFormat(locale).format(credits);
3551
+ let currencyEquivalent = "";
3552
+ if (!numberOnly && displayCurrency && creditsPerMinorUnit) {
3553
+ const usdCents = credits / creditsPerMinorUnit;
3554
+ const displayMajorUnits = usdCents * (displayExchangeRate ?? 1) / 100;
3555
+ const formatted = new Intl.NumberFormat(locale, {
3556
+ style: "currency",
3557
+ currency: displayCurrency,
3558
+ minimumFractionDigits: 2
3559
+ }).format(displayMajorUnits);
3560
+ currencyEquivalent = interpolate(copy.balance.currencyEquivalent, { amount: formatted });
3561
+ }
3562
+ const content = children ?? /* @__PURE__ */ jsxs7(Fragment6, { children: [
3563
+ formattedCredits,
3564
+ !numberOnly && copy.balance.credits,
3565
+ !numberOnly && currencyEquivalent
3566
+ ] });
3567
+ if (asChild) {
3568
+ return (
3569
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
3570
+ /* @__PURE__ */ jsx16(Slot, { ref: forwardedRef, ...commonProps, children: content })
3571
+ );
3572
+ }
3573
+ return /* @__PURE__ */ jsx16("span", { ref: forwardedRef, ...commonProps, children: content });
3574
+ });
3575
+
3576
+ // src/primitives/PlanSelector.tsx
3577
+ import {
3578
+ createContext as createContext9,
3579
+ forwardRef as forwardRef9,
3580
+ useCallback as useCallback13,
3581
+ useContext as useContext13,
3582
+ useMemo as useMemo11
3583
+ } from "react";
3584
+ import { jsx as jsx17 } from "react/jsx-runtime";
3585
+ var PlanSelectorContext = createContext9(null);
3586
+ function usePlanSelectorContext(part) {
3587
+ const ctx = useContext13(PlanSelectorContext);
3588
+ if (!ctx) {
3589
+ throw new Error(`PlanSelector.${part} must be rendered inside <PlanSelector.Root>.`);
3590
+ }
3591
+ return ctx;
3592
+ }
3593
+ var CardContext = createContext9(null);
3594
+ function useCardContext(part) {
3595
+ const ctx = useContext13(CardContext);
3596
+ if (!ctx) {
3597
+ throw new Error(`PlanSelector.${part} must be rendered inside <PlanSelector.Card>.`);
3598
+ }
3599
+ return ctx;
3600
+ }
3601
+ async function defaultListPlans(productRef, config) {
3602
+ const base = config?.api?.listPlans || "/api/list-plans";
3603
+ const url = `${base}?productRef=${encodeURIComponent(productRef)}`;
3604
+ const fetchFn = config?.fetch || fetch;
3605
+ const { headers } = await buildRequestHeaders(config);
3606
+ const res = await fetchFn(url, { method: "GET", headers });
3607
+ if (!res.ok) {
3608
+ const error = new Error(`Failed to fetch plans: ${res.statusText || res.status}`);
3609
+ config?.onError?.(error, "listPlans");
3610
+ throw error;
3611
+ }
3612
+ const data = await res.json();
3613
+ return data.plans ?? [];
3614
+ }
3615
+ var Root6 = forwardRef9(function PlanSelectorRoot(props, forwardedRef) {
3616
+ const {
3617
+ productRef,
3618
+ fetcher,
3619
+ filter,
3620
+ sortBy,
3621
+ autoSelectFirstPaid = true,
3622
+ initialPlanRef,
3623
+ currentPlanRef,
3624
+ popularPlanRef,
3625
+ onSelect,
3626
+ children,
3627
+ ...rest
3628
+ } = props;
3629
+ const solva = useContext13(SolvaPayContext);
3630
+ if (!solva) throw new MissingProviderError("PlanSelector");
3631
+ if (!productRef) throw new MissingProductRefError("PlanSelector");
3632
+ const { _config } = solva;
3633
+ const { purchases } = usePurchase();
3634
+ const effectiveFetcher = useMemo11(
3635
+ () => fetcher ?? ((ref) => defaultListPlans(ref, _config)),
3636
+ [fetcher, _config]
3637
+ );
3638
+ const { plans, selectedPlan, selectPlan, loading, error } = usePlans({
3639
+ productRef,
3640
+ fetcher: effectiveFetcher,
3641
+ filter,
3642
+ sortBy,
3643
+ autoSelectFirstPaid,
3644
+ initialPlanRef
3645
+ });
3646
+ const autoCurrentPlanRef = useMemo11(() => {
3647
+ const active = purchases.filter((p) => p.status === "active").sort((a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime())[0];
3648
+ return active?.planSnapshot?.reference ?? null;
3649
+ }, [purchases]);
3650
+ const resolvedCurrentPlanRef = currentPlanRef === null ? null : currentPlanRef ?? autoCurrentPlanRef;
3651
+ const isCurrent = useCallback13(
3652
+ (ref) => resolvedCurrentPlanRef === ref,
3653
+ [resolvedCurrentPlanRef]
3654
+ );
3655
+ const isFree = useCallback13(
3656
+ (ref) => plans.find((p) => p.reference === ref)?.requiresPayment === false,
3657
+ [plans]
3658
+ );
3659
+ const isPopular = useCallback13(
3660
+ (ref) => popularPlanRef === ref,
3661
+ [popularPlanRef]
3662
+ );
3663
+ const select = useCallback13(
3664
+ (ref) => {
3665
+ const plan = plans.find((p) => p.reference === ref);
3666
+ if (!plan) return;
3667
+ if (plan.requiresPayment === false) return;
3668
+ selectPlan(ref);
3669
+ onSelect?.(ref, plan);
3670
+ },
3671
+ [plans, selectPlan, onSelect]
3672
+ );
3673
+ const selectedPlanRef = selectedPlan?.reference ?? null;
3674
+ const ctx = useMemo11(
3675
+ () => ({
3676
+ plans,
3677
+ loading,
3678
+ error,
3679
+ selectedPlan: selectedPlan ?? null,
3680
+ selectedPlanRef,
3681
+ popularPlanRef,
3682
+ currentPlanRef: resolvedCurrentPlanRef,
3683
+ isCurrent,
3684
+ isFree,
3685
+ isPopular,
3686
+ select
3687
+ }),
3688
+ [
3689
+ plans,
3690
+ loading,
3691
+ error,
3692
+ selectedPlan,
3693
+ selectedPlanRef,
3694
+ popularPlanRef,
3695
+ resolvedCurrentPlanRef,
3696
+ isCurrent,
3697
+ isFree,
3698
+ isPopular,
3699
+ select
3700
+ ]
3701
+ );
3702
+ return /* @__PURE__ */ jsx17(
3703
+ PlanSelectionProvider,
3704
+ {
3705
+ value: {
3706
+ productRef,
3707
+ selectedPlanRef,
3708
+ setSelectedPlanRef: (ref) => {
3709
+ if (ref) select(ref);
3710
+ },
3711
+ plans,
3712
+ loading,
3713
+ error
3714
+ },
3715
+ children: /* @__PURE__ */ jsx17("div", { ref: forwardedRef, "data-solvapay-plan-selector": "", ...rest, children: /* @__PURE__ */ jsx17(PlanSelectorContext.Provider, { value: ctx, children }) })
3716
+ }
3717
+ );
3718
+ });
3719
+ var Heading = forwardRef9(function PlanSelectorHeading({ asChild, children, ...rest }, forwardedRef) {
3720
+ usePlanSelectorContext("Heading");
3721
+ const copy = useCopy();
3722
+ const Comp = asChild ? Slot : "h3";
3723
+ return /* @__PURE__ */ jsx17(Comp, { ref: forwardedRef, "data-solvapay-plan-selector-heading": "", ...rest, children: children ?? copy.planSelector.heading });
3724
+ });
3725
+ var Grid = forwardRef9(function PlanSelectorGrid({ children, ...rest }, forwardedRef) {
3726
+ const ctx = usePlanSelectorContext("Grid");
3727
+ return /* @__PURE__ */ jsx17("div", { ref: forwardedRef, "data-solvapay-plan-selector-grid": "", ...rest, children: ctx.plans.map((plan) => {
3728
+ const isCurrent = ctx.isCurrent(plan.reference);
3729
+ const isFree = ctx.isFree(plan.reference);
3730
+ const isPopular = ctx.isPopular(plan.reference);
3731
+ const selected = ctx.selectedPlanRef === plan.reference;
3732
+ const disabled = isCurrent || isFree;
3733
+ const state = isCurrent ? "current" : isFree ? "disabled" : selected ? "selected" : "idle";
3734
+ const cardCtx = {
3735
+ plan,
3736
+ state,
3737
+ isCurrent,
3738
+ isFree,
3739
+ isPopular,
3740
+ disabled,
3741
+ select: () => ctx.select(plan.reference)
3742
+ };
3743
+ return /* @__PURE__ */ jsx17(CardContext.Provider, { value: cardCtx, children }, plan.reference);
3744
+ }) });
3745
+ });
3746
+ var Card = forwardRef9(function PlanSelectorCard({ asChild, onClick, children, ...rest }, forwardedRef) {
3747
+ const card = useCardContext("Card");
3748
+ const dataTrial = !!(card.plan.trialDays && card.plan.trialDays > 0);
3749
+ const commonProps = {
3750
+ "data-solvapay-plan-selector-card": "",
3751
+ "data-state": card.state,
3752
+ "data-free": card.isFree ? "" : void 0,
3753
+ "data-popular": card.isPopular ? "" : void 0,
3754
+ "data-trial": dataTrial ? "" : void 0,
3755
+ "aria-disabled": card.disabled || void 0,
3756
+ onClick: composeEventHandlers(onClick, () => {
3757
+ if (!card.disabled) card.select();
3758
+ }),
3759
+ ...rest
3760
+ };
3761
+ if (asChild) {
3762
+ return (
3763
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
3764
+ /* @__PURE__ */ jsx17(Slot, { ref: forwardedRef, ...commonProps, children })
3765
+ );
3766
+ }
3767
+ return /* @__PURE__ */ jsx17(
3768
+ "button",
3769
+ {
3770
+ ref: forwardedRef,
3771
+ type: "button",
3772
+ disabled: card.disabled,
3773
+ ...commonProps,
3774
+ children
3775
+ }
3776
+ );
3777
+ });
3778
+ var CardName = forwardRef9(function PlanSelectorCardName({ asChild, children, ...rest }, forwardedRef) {
3779
+ const card = useCardContext("CardName");
3780
+ if (!card.plan.name) return null;
3781
+ const Comp = asChild ? Slot : "span";
3782
+ return /* @__PURE__ */ jsx17(Comp, { ref: forwardedRef, "data-solvapay-plan-selector-card-name": "", ...rest, children: children ?? card.plan.name });
3783
+ });
3784
+ var CardPrice = forwardRef9(function PlanSelectorCardPrice({ asChild, children, ...rest }, forwardedRef) {
3785
+ const card = useCardContext("CardPrice");
3786
+ const locale = useLocale();
3787
+ const copy = useCopy();
3788
+ const formatted = useMemo11(() => {
3789
+ if (card.isFree) return copy.planSelector.freeBadge;
3790
+ return formatPrice(card.plan.price ?? 0, card.plan.currency ?? "usd", {
3791
+ locale,
3792
+ free: copy.interval.free
3793
+ });
3794
+ }, [
3795
+ card.isFree,
3796
+ card.plan.price,
3797
+ card.plan.currency,
3798
+ locale,
3799
+ copy.planSelector.freeBadge,
3800
+ copy.interval.free
3801
+ ]);
3802
+ const Comp = asChild ? Slot : "span";
3803
+ return /* @__PURE__ */ jsx17(Comp, { ref: forwardedRef, "data-solvapay-plan-selector-card-price": "", ...rest, children: children ?? formatted });
3804
+ });
3805
+ var CardInterval = forwardRef9(function PlanSelectorCardInterval({ asChild, children, ...rest }, forwardedRef) {
3806
+ const card = useCardContext("CardInterval");
3807
+ const copy = useCopy();
3808
+ if (card.isFree || !card.plan.interval) return null;
3809
+ const text = interpolate(copy.planSelector.perIntervalShort, { interval: card.plan.interval });
3810
+ const Comp = asChild ? Slot : "span";
3811
+ return /* @__PURE__ */ jsx17(Comp, { ref: forwardedRef, "data-solvapay-plan-selector-card-interval": "", ...rest, children: children ?? text });
3812
+ });
3813
+ var CardBadge = forwardRef9(function PlanSelectorCardBadge({ asChild, children, ...rest }, forwardedRef) {
3814
+ const card = useCardContext("CardBadge");
3815
+ const copy = useCopy();
3816
+ let variant = null;
3817
+ let label = "";
3818
+ if (card.isCurrent) {
3819
+ variant = "current";
3820
+ label = copy.planSelector.currentBadge;
3821
+ } else if (card.isPopular && !card.isFree) {
3822
+ variant = "popular";
3823
+ label = copy.planSelector.popularBadge;
3824
+ }
3825
+ if (!variant) return null;
3826
+ const Comp = asChild ? Slot : "span";
3827
+ return /* @__PURE__ */ jsx17(
3828
+ Comp,
3829
+ {
3830
+ ref: forwardedRef,
3831
+ "data-solvapay-plan-selector-card-badge": "",
3832
+ "data-variant": variant,
3833
+ ...rest,
3834
+ children: children ?? label
3835
+ }
3836
+ );
3837
+ });
3838
+ var Loading4 = forwardRef9(function PlanSelectorLoading({ asChild, children, ...rest }, forwardedRef) {
3839
+ const ctx = usePlanSelectorContext("Loading");
3840
+ if (!ctx.loading || ctx.plans.length > 0) return null;
3841
+ const Comp = asChild ? Slot : "div";
3842
+ return /* @__PURE__ */ jsx17(Comp, { ref: forwardedRef, "data-solvapay-plan-selector-loading": "", ...rest, children });
3843
+ });
3844
+ var ErrorSlot4 = forwardRef9(function PlanSelectorError({ asChild, children, ...rest }, forwardedRef) {
3845
+ const ctx = usePlanSelectorContext("Error");
3846
+ if (!ctx.error) return null;
3847
+ const Comp = asChild ? Slot : "div";
3848
+ return /* @__PURE__ */ jsx17(Comp, { ref: forwardedRef, "data-solvapay-plan-selector-error": "", role: "alert", ...rest, children: children ?? ctx.error.message });
3849
+ });
3850
+ var PlanSelectorRoot2 = Root6;
3851
+ var PlanSelectorHeading2 = Heading;
3852
+ var PlanSelectorGrid2 = Grid;
3853
+ var PlanSelectorCard2 = Card;
3854
+ var PlanSelectorCardName2 = CardName;
3855
+ var PlanSelectorCardPrice2 = CardPrice;
3856
+ var PlanSelectorCardInterval2 = CardInterval;
3857
+ var PlanSelectorCardBadge2 = CardBadge;
3858
+ var PlanSelectorLoading2 = Loading4;
3859
+ var PlanSelectorError2 = ErrorSlot4;
3860
+ var PlanSelector = {
3861
+ Root: Root6,
3862
+ Heading,
3863
+ Grid,
3864
+ Card,
3865
+ CardName,
3866
+ CardPrice,
3867
+ CardInterval,
3868
+ CardBadge,
3869
+ Loading: Loading4,
3870
+ Error: ErrorSlot4
3871
+ };
3872
+ function usePlanSelector() {
3873
+ return usePlanSelectorContext("usePlanSelector");
3874
+ }
3875
+
3876
+ // src/primitives/ActivationFlow.tsx
3877
+ import {
3878
+ createContext as createContext10,
3879
+ forwardRef as forwardRef10,
3880
+ useCallback as useCallback14,
3881
+ useContext as useContext14,
3882
+ useEffect as useEffect11,
3883
+ useMemo as useMemo12,
3884
+ useRef as useRef7,
3885
+ useState as useState13
3886
+ } from "react";
3887
+ import { Fragment as Fragment7, jsx as jsx18 } from "react/jsx-runtime";
3888
+ var ActivationFlowContext = createContext10(null);
3889
+ function useFlowCtx(part) {
3890
+ const ctx = useContext14(ActivationFlowContext);
3891
+ if (!ctx) {
3892
+ throw new Error(`ActivationFlow.${part} must be rendered inside <ActivationFlow.Root>.`);
3893
+ }
3894
+ return ctx;
3895
+ }
3896
+ var Root7 = forwardRef10(function ActivationFlowRoot({
3897
+ productRef,
3898
+ planRef: planRefProp,
3899
+ onSuccess,
3900
+ onError,
3901
+ retryDelayMs = 1500,
3902
+ retryBackoffMs = 2e3,
3903
+ asChild,
3904
+ children,
3905
+ ...rest
3906
+ }, forwardedRef) {
3907
+ const solva = useContext14(SolvaPayContext);
3908
+ if (!solva) throw new MissingProviderError("ActivationFlow");
3909
+ if (!productRef) throw new MissingProductRefError("ActivationFlow");
3910
+ const planSelection = usePlanSelection();
3911
+ const resolvedPlanRef = planRefProp ?? planSelection?.selectedPlanRef ?? void 0;
3912
+ const { plan } = usePlan({ planRef: resolvedPlanRef, productRef });
3913
+ const { activate, state, error, result, reset } = useActivation();
3914
+ const currency = plan?.currency ?? "USD";
3915
+ const amountSelector = useTopupAmountSelector({ currency });
3916
+ const { adjustBalance, creditsPerMinorUnit, displayExchangeRate } = useBalance();
3917
+ const [step, setStep] = useState13("summary");
3918
+ const calledSuccessRef = useRef7(false);
3919
+ const retryTimeoutRef = useRef7(null);
3920
+ useEffect11(() => {
3921
+ if (state === "activated" && !calledSuccessRef.current) {
3922
+ calledSuccessRef.current = true;
3923
+ setStep("activated");
3924
+ if (result) {
3925
+ const activationResult = { kind: "activated", result };
3926
+ onSuccess?.(activationResult);
3927
+ }
3928
+ }
3929
+ }, [state, result, onSuccess]);
3930
+ useEffect11(() => {
3931
+ if (state === "topup_required" && (step === "summary" || step === "activating")) {
3932
+ setStep("selectAmount");
3933
+ }
3934
+ }, [state, step]);
3935
+ useEffect11(() => {
3936
+ if ((state === "error" || state === "payment_required") && error) {
3937
+ setStep("error");
3938
+ if (state === "error") onError?.(new Error(error));
3939
+ }
3940
+ }, [state, error, onError]);
3941
+ const handleActivate = useCallback14(async () => {
3942
+ if (!resolvedPlanRef) return;
3943
+ setStep("activating");
3944
+ await activate({ productRef, planRef: resolvedPlanRef });
3945
+ }, [activate, productRef, resolvedPlanRef]);
3946
+ const goToTopupPayment = useCallback14(() => {
3947
+ if (amountSelector.validate()) setStep("topupPayment");
3948
+ }, [amountSelector]);
3949
+ const backToSelectAmount = useCallback14(() => {
3950
+ setStep("selectAmount");
3951
+ }, []);
3952
+ const retryActivation = useCallback14(async () => {
3953
+ if (!resolvedPlanRef) return;
3954
+ setStep("retrying");
3955
+ const amountMinor = Math.round((amountSelector.resolvedAmount || 0) * 100);
3956
+ const rate = displayExchangeRate ?? 1;
3957
+ if (creditsPerMinorUnit) {
3958
+ adjustBalance(Math.floor(amountMinor / rate * creditsPerMinorUnit));
3959
+ }
3960
+ await new Promise((r) => setTimeout(r, retryDelayMs));
3961
+ await activate({ productRef, planRef: resolvedPlanRef });
3962
+ }, [
3963
+ resolvedPlanRef,
3964
+ amountSelector.resolvedAmount,
3965
+ displayExchangeRate,
3966
+ creditsPerMinorUnit,
3967
+ adjustBalance,
3968
+ retryDelayMs,
3969
+ activate,
3970
+ productRef
3971
+ ]);
3972
+ const handleTopupSuccess = useCallback14(async () => {
3973
+ await retryActivation();
3974
+ }, [retryActivation]);
3975
+ useEffect11(() => {
3976
+ if (step !== "retrying") return;
3977
+ if (state !== "topup_required") return;
3978
+ if (!resolvedPlanRef) return;
3979
+ retryTimeoutRef.current = setTimeout(async () => {
3980
+ await activate({ productRef, planRef: resolvedPlanRef });
3981
+ }, retryBackoffMs);
3982
+ return () => {
3983
+ if (retryTimeoutRef.current) clearTimeout(retryTimeoutRef.current);
3984
+ };
3985
+ }, [step, state, resolvedPlanRef, retryBackoffMs, activate, productRef]);
3986
+ const resetFlow = useCallback14(() => {
3987
+ reset();
3988
+ calledSuccessRef.current = false;
3989
+ setStep("summary");
3990
+ }, [reset]);
3991
+ const amountCents = Math.round((amountSelector.resolvedAmount || 0) * 100);
3992
+ const ctx = useMemo12(
3993
+ () => ({
3994
+ step,
3995
+ plan,
3996
+ productRef,
3997
+ planRef: resolvedPlanRef ?? "",
3998
+ amountSelector,
3999
+ amountCents,
4000
+ currency,
4001
+ activate: handleActivate,
4002
+ reset: resetFlow,
4003
+ goToTopupPayment,
4004
+ backToSelectAmount,
4005
+ onTopupSuccess: handleTopupSuccess,
4006
+ error,
4007
+ onError
4008
+ }),
4009
+ [
4010
+ step,
4011
+ plan,
4012
+ productRef,
4013
+ resolvedPlanRef,
4014
+ amountSelector,
4015
+ amountCents,
4016
+ currency,
4017
+ handleActivate,
4018
+ resetFlow,
4019
+ goToTopupPayment,
4020
+ backToSelectAmount,
4021
+ handleTopupSuccess,
4022
+ error,
4023
+ onError
4024
+ ]
4025
+ );
4026
+ const Comp = asChild ? Slot : "div";
4027
+ return /* @__PURE__ */ jsx18(ActivationFlowContext.Provider, { value: ctx, children: /* @__PURE__ */ jsx18(
4028
+ Comp,
4029
+ {
4030
+ ref: forwardedRef,
4031
+ "data-solvapay-activation-flow": "",
4032
+ "data-state": step,
4033
+ ...rest,
4034
+ children
4035
+ }
4036
+ ) });
4037
+ });
4038
+ function matchStep(step, allowed) {
4039
+ return allowed.includes(step);
4040
+ }
4041
+ var Summary2 = forwardRef10(function ActivationFlowSummary({ asChild, children, ...rest }, forwardedRef) {
4042
+ const ctx = useFlowCtx("Summary");
4043
+ if (!matchStep(ctx.step, ["summary", "activating"])) return null;
4044
+ const Comp = asChild ? Slot : "div";
4045
+ return /* @__PURE__ */ jsx18(Comp, { ref: forwardedRef, "data-solvapay-activation-flow-summary": "", ...rest, children });
4046
+ });
4047
+ var ActivateButton = forwardRef10(
4048
+ function ActivationFlowActivateButton({ asChild, onClick, children, ...rest }, forwardedRef) {
4049
+ const ctx = useFlowCtx("ActivateButton");
4050
+ const copy = useCopy();
4051
+ if (!matchStep(ctx.step, ["summary", "activating"])) return null;
4052
+ const isActivating = ctx.step === "activating";
4053
+ const disabled = isActivating;
4054
+ const commonProps = {
4055
+ "data-solvapay-activation-flow-activate": "",
4056
+ "data-state": isActivating ? "activating" : "idle",
4057
+ "aria-busy": isActivating,
4058
+ disabled,
4059
+ onClick: composeEventHandlers(onClick, () => {
4060
+ void ctx.activate();
4061
+ }),
4062
+ ...rest
4063
+ };
4064
+ const label = isActivating ? copy.activationFlow.activatingLabel : copy.activationFlow.activateButton;
4065
+ if (asChild) {
4066
+ return (
4067
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4068
+ /* @__PURE__ */ jsx18(Slot, { ref: forwardedRef, ...commonProps, children: children ?? /* @__PURE__ */ jsx18(Fragment7, { children: label }) })
4069
+ );
4070
+ }
4071
+ return /* @__PURE__ */ jsx18("button", { ref: forwardedRef, type: "button", ...commonProps, children: children ?? label });
4072
+ }
4073
+ );
4074
+ var AmountPickerMount = ({ children }) => {
4075
+ const ctx = useFlowCtx("AmountPicker");
4076
+ if (ctx.step !== "selectAmount") return null;
4077
+ return /* @__PURE__ */ jsx18("div", { "data-solvapay-activation-flow-amount-picker": "", children: /* @__PURE__ */ jsx18(AmountPicker.Root, { currency: ctx.currency, children }) });
4078
+ };
4079
+ var ContinueButton = forwardRef10(
4080
+ function ActivationFlowContinueButton({ asChild, onClick, children, ...rest }, forwardedRef) {
4081
+ const ctx = useFlowCtx("ContinueButton");
4082
+ const copy = useCopy();
4083
+ if (ctx.step !== "selectAmount") return null;
4084
+ const disabled = !ctx.amountSelector.resolvedAmount;
4085
+ const commonProps = {
4086
+ "data-solvapay-activation-flow-continue": "",
4087
+ "data-state": disabled ? "disabled" : "idle",
4088
+ disabled,
4089
+ "aria-disabled": disabled || void 0,
4090
+ onClick: composeEventHandlers(onClick, () => {
4091
+ ctx.goToTopupPayment();
4092
+ }),
4093
+ ...rest
4094
+ };
4095
+ if (asChild) {
4096
+ return (
4097
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4098
+ /* @__PURE__ */ jsx18(Slot, { ref: forwardedRef, ...commonProps, children: children ?? /* @__PURE__ */ jsx18(Fragment7, { children: copy.activationFlow.continueToPayment }) })
4099
+ );
4100
+ }
4101
+ return /* @__PURE__ */ jsx18("button", { ref: forwardedRef, type: "button", ...commonProps, children: children ?? copy.activationFlow.continueToPayment });
4102
+ }
4103
+ );
4104
+ var Retrying = forwardRef10(function ActivationFlowRetrying({ asChild, children, ...rest }, forwardedRef) {
4105
+ const ctx = useFlowCtx("Retrying");
4106
+ if (ctx.step !== "retrying") return null;
4107
+ const Comp = asChild ? Slot : "div";
4108
+ return /* @__PURE__ */ jsx18(Comp, { ref: forwardedRef, "data-solvapay-activation-flow-retrying": "", ...rest, children });
4109
+ });
4110
+ var Activated = forwardRef10(function ActivationFlowActivated({ asChild, children, ...rest }, forwardedRef) {
4111
+ const ctx = useFlowCtx("Activated");
4112
+ if (ctx.step !== "activated") return null;
4113
+ const Comp = asChild ? Slot : "div";
4114
+ return /* @__PURE__ */ jsx18(Comp, { ref: forwardedRef, "data-solvapay-activation-flow-activated": "", ...rest, children });
4115
+ });
4116
+ var Loading5 = forwardRef10(function ActivationFlowLoading({ asChild, children, ...rest }, forwardedRef) {
4117
+ const ctx = useFlowCtx("Loading");
4118
+ if (ctx.plan) return null;
4119
+ const Comp = asChild ? Slot : "div";
4120
+ return /* @__PURE__ */ jsx18(Comp, { ref: forwardedRef, "data-solvapay-activation-flow-loading": "", ...rest, children });
4121
+ });
4122
+ var ErrorSlot5 = forwardRef10(function ActivationFlowError({ asChild, children, ...rest }, forwardedRef) {
4123
+ const ctx = useFlowCtx("Error");
4124
+ if (ctx.step !== "error") return null;
4125
+ const Comp = asChild ? Slot : "div";
4126
+ return /* @__PURE__ */ jsx18(
4127
+ Comp,
4128
+ {
4129
+ ref: forwardedRef,
4130
+ role: "alert",
4131
+ "data-solvapay-activation-flow-error": "",
4132
+ ...rest,
4133
+ children: children ?? ctx.error
4134
+ }
4135
+ );
4136
+ });
4137
+ var ActivationFlowRoot2 = Root7;
4138
+ var ActivationFlowSummary2 = Summary2;
4139
+ var ActivationFlowActivateButton2 = ActivateButton;
4140
+ var ActivationFlowAmountPicker = AmountPickerMount;
4141
+ var ActivationFlowContinueButton2 = ContinueButton;
4142
+ var ActivationFlowRetrying2 = Retrying;
4143
+ var ActivationFlowActivated2 = Activated;
4144
+ var ActivationFlowLoading2 = Loading5;
4145
+ var ActivationFlowError2 = ErrorSlot5;
4146
+ var ActivationFlow = {
4147
+ Root: Root7,
4148
+ Summary: Summary2,
4149
+ ActivateButton,
4150
+ AmountPicker: AmountPickerMount,
4151
+ ContinueButton,
4152
+ Retrying,
4153
+ Activated,
4154
+ Loading: Loading5,
4155
+ Error: ErrorSlot5
4156
+ };
4157
+ function useActivationFlow() {
4158
+ return useFlowCtx("useActivationFlow");
4159
+ }
4160
+
4161
+ // src/hooks/usePurchaseActions.ts
4162
+ import { useState as useState14, useCallback as useCallback15 } from "react";
4163
+ function usePurchaseActions() {
4164
+ const ctx = useSolvaPay();
4165
+ const [isCancelling, setIsCancelling] = useState14(false);
4166
+ const [isReactivating, setIsReactivating] = useState14(false);
4167
+ const [isActivating, setIsActivating] = useState14(false);
4168
+ const cancelRenewal = useCallback15(
4169
+ async (params) => {
4170
+ setIsCancelling(true);
4171
+ try {
4172
+ return await ctx.cancelRenewal(params);
4173
+ } finally {
4174
+ setIsCancelling(false);
4175
+ }
4176
+ },
4177
+ [ctx.cancelRenewal]
4178
+ );
4179
+ const reactivateRenewal = useCallback15(
4180
+ async (params) => {
4181
+ setIsReactivating(true);
4182
+ try {
4183
+ return await ctx.reactivateRenewal(params);
4184
+ } finally {
4185
+ setIsReactivating(false);
4186
+ }
4187
+ },
4188
+ [ctx.reactivateRenewal]
4189
+ );
4190
+ const activatePlan = useCallback15(
4191
+ async (params) => {
4192
+ setIsActivating(true);
4193
+ try {
4194
+ return await ctx.activatePlan(params);
4195
+ } finally {
4196
+ setIsActivating(false);
4197
+ }
4198
+ },
4199
+ [ctx.activatePlan]
4200
+ );
4201
+ return {
4202
+ cancelRenewal,
4203
+ reactivateRenewal,
4204
+ activatePlan,
4205
+ isCancelling,
4206
+ isReactivating,
4207
+ isActivating
4208
+ };
4209
+ }
4210
+
4211
+ // src/primitives/CancelPlanButton.tsx
4212
+ import { forwardRef as forwardRef11, useCallback as useCallback16, useContext as useContext15 } from "react";
4213
+ import { Fragment as Fragment8, jsx as jsx19 } from "react/jsx-runtime";
4214
+ function resolveConfirmText(confirm, purchase, defaults) {
4215
+ if (confirm === false) return null;
4216
+ if (typeof confirm === "string") return confirm;
4217
+ const planType = purchase?.planSnapshot?.planType;
4218
+ if (planType === "usage-based") return defaults.usageBased;
4219
+ return defaults.recurring;
4220
+ }
4221
+ var CancelPlanButton = forwardRef11(
4222
+ function CancelPlanButton2({
4223
+ asChild,
4224
+ purchaseRef,
4225
+ reason,
4226
+ confirm = true,
4227
+ onCancelled,
4228
+ onError,
4229
+ onClick,
4230
+ children,
4231
+ ...rest
4232
+ }, forwardedRef) {
4233
+ const solva = useContext15(SolvaPayContext);
4234
+ if (!solva) throw new MissingProviderError("CancelPlanButton");
4235
+ const copy = useCopy();
4236
+ const { activePurchase } = usePurchase();
4237
+ const { cancelRenewal, isCancelling } = usePurchaseActions();
4238
+ const effectivePurchase = purchaseRef ? activePurchase && activePurchase.reference === purchaseRef ? activePurchase : { reference: purchaseRef } : activePurchase;
4239
+ const effectiveRef = purchaseRef ?? effectivePurchase?.reference;
4240
+ const cancel = useCallback16(async () => {
4241
+ if (!effectiveRef) return;
4242
+ const confirmText = resolveConfirmText(confirm, effectivePurchase, {
4243
+ recurring: copy.cancelPlan.confirmRecurring,
4244
+ usageBased: copy.cancelPlan.confirmUsageBased
4245
+ });
4246
+ if (confirmText && typeof window !== "undefined" && !window.confirm(confirmText)) {
4247
+ return;
4248
+ }
4249
+ try {
4250
+ await cancelRenewal({ purchaseRef: effectiveRef, reason });
4251
+ onCancelled?.();
4252
+ } catch (err) {
4253
+ onError?.(err instanceof Error ? err : new Error(String(err)));
4254
+ }
4255
+ }, [effectiveRef, effectivePurchase, confirm, copy, cancelRenewal, reason, onCancelled, onError]);
4256
+ const disabled = isCancelling || !effectiveRef;
4257
+ const state = isCancelling ? "cancelling" : "idle";
4258
+ const commonProps = {
4259
+ "data-solvapay-cancel-plan": "",
4260
+ "data-state": state,
4261
+ "aria-busy": isCancelling,
4262
+ "aria-disabled": disabled || void 0,
4263
+ disabled,
4264
+ onClick: composeEventHandlers(onClick, () => {
4265
+ void cancel();
4266
+ }),
4267
+ ...rest
4268
+ };
4269
+ const label = isCancelling ? copy.cancelPlan.buttonLoading : copy.cancelPlan.button;
4270
+ if (asChild) {
4271
+ return (
4272
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4273
+ /* @__PURE__ */ jsx19(Slot, { ref: forwardedRef, ...commonProps, children: children ?? /* @__PURE__ */ jsx19(Fragment8, { children: label }) })
4274
+ );
4275
+ }
4276
+ return /* @__PURE__ */ jsx19("button", { ref: forwardedRef, type: "button", ...commonProps, children: children ?? label });
4277
+ }
4278
+ );
4279
+
4280
+ // src/hooks/usePurchaseStatus.ts
4281
+ import { useMemo as useMemo13, useCallback as useCallback17 } from "react";
4282
+ function usePurchaseStatus() {
4283
+ const { purchases } = usePurchase();
4284
+ const locale = useLocale();
4285
+ const isPaidPurchase2 = useCallback17((p) => {
4286
+ return (p.amount ?? 0) > 0;
4287
+ }, []);
4288
+ const purchaseData = useMemo13(() => {
4289
+ const cancelledPaidPurchases = purchases.filter((p) => {
4290
+ return p.status === "active" && p.cancelledAt && isPaidPurchase2(p);
4291
+ });
4292
+ const cancelledPurchase = cancelledPaidPurchases.sort(
4293
+ (a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime()
4294
+ )[0] || null;
4295
+ const shouldShowCancelledNotice = !!cancelledPurchase;
4296
+ return {
4297
+ cancelledPurchase,
4298
+ shouldShowCancelledNotice
4299
+ };
4300
+ }, [purchases, isPaidPurchase2]);
4301
+ const formatDate = useCallback17(
4302
+ (dateString) => {
4303
+ if (!dateString) return null;
4304
+ return new Date(dateString).toLocaleDateString(locale || "en-US", {
4305
+ year: "numeric",
4306
+ month: "long",
4307
+ day: "numeric"
4308
+ });
4309
+ },
4310
+ [locale]
4311
+ );
4312
+ const getDaysUntilExpiration = useCallback17((endDate) => {
4313
+ if (!endDate) return null;
4314
+ const now = /* @__PURE__ */ new Date();
4315
+ const expiration = new Date(endDate);
4316
+ const diffTime = expiration.getTime() - now.getTime();
4317
+ const diffDays = Math.ceil(diffTime / (1e3 * 60 * 60 * 24));
4318
+ return diffDays > 0 ? diffDays : 0;
4319
+ }, []);
4320
+ return {
4321
+ cancelledPurchase: purchaseData.cancelledPurchase,
4322
+ shouldShowCancelledNotice: purchaseData.shouldShowCancelledNotice,
4323
+ formatDate,
4324
+ getDaysUntilExpiration
4325
+ };
4326
+ }
4327
+
4328
+ // src/primitives/CancelledPlanNotice.tsx
4329
+ import {
4330
+ createContext as createContext11,
4331
+ forwardRef as forwardRef12,
4332
+ useCallback as useCallback18,
4333
+ useContext as useContext16,
4334
+ useMemo as useMemo14
4335
+ } from "react";
4336
+ import { Fragment as Fragment9, jsx as jsx20 } from "react/jsx-runtime";
4337
+ var CancelledPlanNoticeContext = createContext11(null);
4338
+ function useNoticeCtx(part) {
4339
+ const ctx = useContext16(CancelledPlanNoticeContext);
4340
+ if (!ctx) {
4341
+ throw new Error(
4342
+ `CancelledPlanNotice.${part} must be rendered inside <CancelledPlanNotice.Root>.`
4343
+ );
4344
+ }
4345
+ return ctx;
4346
+ }
4347
+ var Root8 = forwardRef12(function CancelledPlanNoticeRoot({ onReactivated, onError, asChild, children, ...rest }, forwardedRef) {
4348
+ const solva = useContext16(SolvaPayContext);
4349
+ if (!solva) throw new MissingProviderError("CancelledPlanNotice");
4350
+ const {
4351
+ cancelledPurchase,
4352
+ shouldShowCancelledNotice,
4353
+ formatDate,
4354
+ getDaysUntilExpiration
4355
+ } = usePurchaseStatus();
4356
+ const { reactivateRenewal, isReactivating } = usePurchaseActions();
4357
+ const reactivate = useCallback18(async () => {
4358
+ if (!cancelledPurchase) return;
4359
+ try {
4360
+ await reactivateRenewal({ purchaseRef: cancelledPurchase.reference });
4361
+ onReactivated?.();
4362
+ } catch (err) {
4363
+ onError?.(err instanceof Error ? err : new Error(String(err)));
4364
+ }
4365
+ }, [cancelledPurchase, reactivateRenewal, onReactivated, onError]);
4366
+ const daysRemaining = useMemo14(
4367
+ () => cancelledPurchase ? getDaysUntilExpiration(cancelledPurchase.endDate) : null,
4368
+ [cancelledPurchase, getDaysUntilExpiration]
4369
+ );
4370
+ const ctx = useMemo14(() => {
4371
+ if (!cancelledPurchase) return null;
4372
+ const state = daysRemaining != null && daysRemaining > 0 ? "active" : "expired";
4373
+ return {
4374
+ purchase: cancelledPurchase,
4375
+ state,
4376
+ daysRemaining,
4377
+ hasReason: !!cancelledPurchase.cancellationReason,
4378
+ formatDate,
4379
+ reactivate,
4380
+ isReactivating
4381
+ };
4382
+ }, [cancelledPurchase, daysRemaining, formatDate, reactivate, isReactivating]);
4383
+ if (!shouldShowCancelledNotice || !ctx) return null;
4384
+ const Comp = asChild ? Slot : "div";
4385
+ return /* @__PURE__ */ jsx20(CancelledPlanNoticeContext.Provider, { value: ctx, children: /* @__PURE__ */ jsx20(
4386
+ Comp,
4387
+ {
4388
+ ref: forwardedRef,
4389
+ "data-solvapay-cancelled-notice": "",
4390
+ "data-state": ctx.state,
4391
+ "data-has-reason": ctx.hasReason ? "" : void 0,
4392
+ ...rest,
4393
+ children
4394
+ }
4395
+ ) });
4396
+ });
4397
+ var Heading2 = forwardRef12(function CancelledPlanNoticeHeading({ asChild, children, ...rest }, forwardedRef) {
4398
+ useNoticeCtx("Heading");
4399
+ const copy = useCopy();
4400
+ const Comp = asChild ? Slot : "p";
4401
+ return /* @__PURE__ */ jsx20(Comp, { ref: forwardedRef, "data-solvapay-cancelled-notice-heading": "", ...rest, children: children ?? copy.cancelledNotice.heading });
4402
+ });
4403
+ var Expires = forwardRef12(function CancelledPlanNoticeExpires({ asChild, children, ...rest }, forwardedRef) {
4404
+ const ctx = useNoticeCtx("Expires");
4405
+ const copy = useCopy();
4406
+ const date = ctx.formatDate(ctx.purchase.endDate);
4407
+ if (!ctx.purchase.endDate) {
4408
+ const Comp2 = asChild ? Slot : "p";
4409
+ return /* @__PURE__ */ jsx20(Comp2, { ref: forwardedRef, "data-solvapay-cancelled-notice-expires": "", ...rest, children: children ?? copy.cancelledNotice.accessEnded });
4410
+ }
4411
+ const Comp = asChild ? Slot : "p";
4412
+ return /* @__PURE__ */ jsx20(Comp, { ref: forwardedRef, "data-solvapay-cancelled-notice-expires": "", ...rest, children: children ?? interpolate(copy.cancelledNotice.expiresLabel, { date: date ?? "" }) });
4413
+ });
4414
+ var DaysRemaining = forwardRef12(
4415
+ function CancelledPlanNoticeDaysRemaining({ asChild, children, ...rest }, forwardedRef) {
4416
+ const ctx = useNoticeCtx("DaysRemaining");
4417
+ const copy = useCopy();
4418
+ if (ctx.daysRemaining == null || ctx.daysRemaining <= 0) return null;
4419
+ const template = ctx.daysRemaining === 1 ? copy.cancelledNotice.dayRemaining : copy.cancelledNotice.daysRemaining;
4420
+ const Comp = asChild ? Slot : "p";
4421
+ return /* @__PURE__ */ jsx20(Comp, { ref: forwardedRef, "data-solvapay-cancelled-notice-days-remaining": "", ...rest, children: children ?? interpolate(template, { days: ctx.daysRemaining }) });
4422
+ }
4423
+ );
4424
+ var AccessUntil = forwardRef12(
4425
+ function CancelledPlanNoticeAccessUntil({ asChild, children, ...rest }, forwardedRef) {
4426
+ const ctx = useNoticeCtx("AccessUntil");
4427
+ const copy = useCopy();
4428
+ if (!ctx.purchase.endDate) return null;
4429
+ const Comp = asChild ? Slot : "p";
4430
+ return /* @__PURE__ */ jsx20(Comp, { ref: forwardedRef, "data-solvapay-cancelled-notice-access-until": "", ...rest, children: children ?? interpolate(copy.cancelledNotice.accessUntil, {
4431
+ product: ctx.purchase.productName
4432
+ }) });
4433
+ }
4434
+ );
4435
+ var CancelledOn = forwardRef12(
4436
+ function CancelledPlanNoticeCancelledOn({ asChild, children, ...rest }, forwardedRef) {
4437
+ const ctx = useNoticeCtx("CancelledOn");
4438
+ const copy = useCopy();
4439
+ if (!ctx.purchase.cancelledAt) return null;
4440
+ const date = ctx.formatDate(ctx.purchase.cancelledAt);
4441
+ const Comp = asChild ? Slot : "p";
4442
+ return /* @__PURE__ */ jsx20(Comp, { ref: forwardedRef, "data-solvapay-cancelled-notice-cancelled-on": "", ...rest, children: children ?? interpolate(copy.cancelledNotice.cancelledOn, { date: date ?? "" }) });
4443
+ }
4444
+ );
4445
+ var Reason = forwardRef12(function CancelledPlanNoticeReason({ asChild, children, ...rest }, forwardedRef) {
4446
+ const ctx = useNoticeCtx("Reason");
4447
+ if (!ctx.hasReason) return null;
4448
+ const Comp = asChild ? Slot : "span";
4449
+ return /* @__PURE__ */ jsx20(Comp, { ref: forwardedRef, "data-solvapay-cancelled-notice-reason": "", ...rest, children: children ?? ctx.purchase.cancellationReason });
4450
+ });
4451
+ var ReactivateButton = forwardRef12(
4452
+ function CancelledPlanNoticeReactivateButton({ asChild, onClick, children, ...rest }, forwardedRef) {
4453
+ const ctx = useNoticeCtx("ReactivateButton");
4454
+ const copy = useCopy();
4455
+ const disabled = ctx.isReactivating;
4456
+ const commonProps = {
4457
+ "data-solvapay-cancelled-notice-reactivate": "",
4458
+ "data-state": ctx.isReactivating ? "reactivating" : "idle",
4459
+ "aria-busy": ctx.isReactivating,
4460
+ "aria-disabled": disabled || void 0,
4461
+ disabled,
4462
+ onClick: composeEventHandlers(onClick, () => {
4463
+ void ctx.reactivate();
4464
+ }),
4465
+ ...rest
4466
+ };
4467
+ const label = ctx.isReactivating ? copy.cancelledNotice.reactivateButtonLoading : copy.cancelledNotice.reactivateButton;
4468
+ if (asChild) {
4469
+ return (
4470
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4471
+ /* @__PURE__ */ jsx20(Slot, { ref: forwardedRef, ...commonProps, children: children ?? /* @__PURE__ */ jsx20(Fragment9, { children: label }) })
4472
+ );
4473
+ }
4474
+ return /* @__PURE__ */ jsx20("button", { ref: forwardedRef, type: "button", ...commonProps, children: children ?? label });
4475
+ }
4476
+ );
4477
+ var CancelledPlanNoticeRoot2 = Root8;
4478
+ var CancelledPlanNoticeHeading2 = Heading2;
4479
+ var CancelledPlanNoticeExpires2 = Expires;
4480
+ var CancelledPlanNoticeDaysRemaining2 = DaysRemaining;
4481
+ var CancelledPlanNoticeAccessUntil2 = AccessUntil;
4482
+ var CancelledPlanNoticeCancelledOn2 = CancelledOn;
4483
+ var CancelledPlanNoticeReason2 = Reason;
4484
+ var CancelledPlanNoticeReactivateButton2 = ReactivateButton;
4485
+ var CancelledPlanNotice = {
4486
+ Root: Root8,
4487
+ Heading: Heading2,
4488
+ Expires,
4489
+ DaysRemaining,
4490
+ AccessUntil,
4491
+ CancelledOn,
4492
+ Reason,
4493
+ ReactivateButton
4494
+ };
4495
+ function useCancelledPlanNotice() {
4496
+ return useNoticeCtx("useCancelledPlanNotice");
4497
+ }
4498
+
4499
+ // src/primitives/CreditGate.tsx
4500
+ import {
4501
+ createContext as createContext12,
4502
+ forwardRef as forwardRef13,
4503
+ useContext as useContext17,
4504
+ useMemo as useMemo15
4505
+ } from "react";
4506
+ import { jsx as jsx21 } from "react/jsx-runtime";
4507
+ var CreditGateContext = createContext12(null);
4508
+ function useGateCtx2(part) {
4509
+ const ctx = useContext17(CreditGateContext);
4510
+ if (!ctx) {
4511
+ throw new Error(`CreditGate.${part} must be rendered inside <CreditGate.Root>.`);
4512
+ }
4513
+ return ctx;
4514
+ }
4515
+ var Root9 = forwardRef13(function CreditGateRoot({
4516
+ minCredits = 1,
4517
+ productRef,
4518
+ topupAmount = 1e3,
4519
+ topupCurrency = "usd",
4520
+ asChild,
4521
+ children,
4522
+ ...rest
4523
+ }, forwardedRef) {
4524
+ const solva = useContext17(SolvaPayContext);
4525
+ if (!solva) throw new MissingProviderError("CreditGate");
4526
+ const { credits, loading } = useBalance();
4527
+ const { product } = useProduct(productRef);
4528
+ const hasCredits = credits != null && credits >= minCredits;
4529
+ const state = loading && credits == null ? "loading" : hasCredits ? "allowed" : "blocked";
4530
+ const ctx = useMemo15(
4531
+ () => ({
4532
+ state,
4533
+ loading,
4534
+ hasCredits,
4535
+ balance: credits,
4536
+ productName: product?.name ?? null,
4537
+ topupAmount,
4538
+ topupCurrency
4539
+ }),
4540
+ [state, loading, hasCredits, credits, product?.name, topupAmount, topupCurrency]
4541
+ );
4542
+ const Comp = asChild ? Slot : "div";
4543
+ return /* @__PURE__ */ jsx21(CreditGateContext.Provider, { value: ctx, children: /* @__PURE__ */ jsx21(
4544
+ Comp,
4545
+ {
4546
+ ref: forwardedRef,
4547
+ "data-solvapay-credit-gate": "",
4548
+ "data-state": state,
4549
+ ...rest,
4550
+ children
4551
+ }
4552
+ ) });
4553
+ });
4554
+ var Heading3 = forwardRef13(function CreditGateHeading({ asChild, children, ...rest }, forwardedRef) {
4555
+ const ctx = useGateCtx2("Heading");
4556
+ const copy = useCopy();
4557
+ if (ctx.state !== "blocked") return null;
4558
+ const Comp = asChild ? Slot : "h3";
4559
+ return /* @__PURE__ */ jsx21(Comp, { ref: forwardedRef, "data-solvapay-credit-gate-heading": "", ...rest, children: children ?? copy.creditGate.lowBalanceHeading });
4560
+ });
4561
+ var Subheading = forwardRef13(function CreditGateSubheading({ asChild, children, ...rest }, forwardedRef) {
4562
+ const ctx = useGateCtx2("Subheading");
4563
+ const copy = useCopy();
4564
+ if (ctx.state !== "blocked") return null;
4565
+ const text = interpolate(copy.creditGate.lowBalanceSubheading, {
4566
+ product: ctx.productName ?? "this product"
4567
+ });
4568
+ const Comp = asChild ? Slot : "p";
4569
+ return /* @__PURE__ */ jsx21(Comp, { ref: forwardedRef, "data-solvapay-credit-gate-subheading": "", ...rest, children: children ?? text });
4570
+ });
4571
+ var Topup = ({ amount, currency }) => {
4572
+ const ctx = useGateCtx2("Topup");
4573
+ if (ctx.state !== "blocked") return null;
4574
+ return /* @__PURE__ */ jsx21(
4575
+ TopupForm2,
4576
+ {
4577
+ amount: amount ?? ctx.topupAmount,
4578
+ currency: currency ?? ctx.topupCurrency
4579
+ }
4580
+ );
4581
+ };
4582
+ var Loading6 = forwardRef13(function CreditGateLoading({ asChild, children, ...rest }, forwardedRef) {
4583
+ const ctx = useGateCtx2("Loading");
4584
+ if (ctx.state !== "loading") return null;
4585
+ const Comp = asChild ? Slot : "div";
4586
+ return (
4587
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4588
+ /* @__PURE__ */ jsx21(Comp, { ref: forwardedRef, "data-solvapay-credit-gate-loading": "", ...rest, children })
4589
+ );
4590
+ });
4591
+ var ErrorSlot6 = forwardRef13(function CreditGateError({ asChild, children, ...rest }, forwardedRef) {
4592
+ if (!children) return null;
4593
+ const Comp = asChild ? Slot : "div";
4594
+ return (
4595
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4596
+ /* @__PURE__ */ jsx21(Comp, { ref: forwardedRef, "data-solvapay-credit-gate-error": "", role: "alert", ...rest, children })
4597
+ );
4598
+ });
4599
+ var CreditGateRoot2 = Root9;
4600
+ var CreditGateHeading2 = Heading3;
4601
+ var CreditGateSubheading2 = Subheading;
4602
+ var CreditGateTopup = Topup;
4603
+ var CreditGateLoading2 = Loading6;
4604
+ var CreditGateError2 = ErrorSlot6;
4605
+ var CreditGate = {
4606
+ Root: Root9,
4607
+ Heading: Heading3,
4608
+ Subheading,
4609
+ Topup,
4610
+ Loading: Loading6,
4611
+ Error: ErrorSlot6
4612
+ };
4613
+ function useCreditGate() {
4614
+ return useGateCtx2("useCreditGate");
4615
+ }
4616
+
4617
+ export {
4618
+ filterPurchases,
4619
+ getActivePurchases,
4620
+ getCancelledPurchasesWithEndDate,
4621
+ getMostRecentPurchase,
4622
+ getPrimaryPurchase,
4623
+ isPaidPurchase,
4624
+ buildRequestHeaders,
4625
+ enCopy,
4626
+ mergeCopy,
4627
+ CopyContext,
4628
+ CopyProvider,
4629
+ SolvaPayContext,
4630
+ SolvaPayProvider,
4631
+ setRef,
4632
+ composeRefs,
4633
+ Slot,
4634
+ Slottable,
4635
+ composeEventHandlers,
4636
+ useSolvaPay,
4637
+ useCheckout,
4638
+ usePurchase,
4639
+ useCustomer,
4640
+ useCopy,
4641
+ useLocale,
4642
+ usePlans,
4643
+ usePlan,
4644
+ useProduct,
4645
+ useActivation,
4646
+ PaymentFormContext,
4647
+ usePaymentForm,
4648
+ PaymentFormProvider,
4649
+ formatPrice,
4650
+ interpolate,
4651
+ CheckoutSummaryRoot2 as CheckoutSummaryRoot,
4652
+ CheckoutSummaryProduct2 as CheckoutSummaryProduct,
4653
+ CheckoutSummaryPlan2 as CheckoutSummaryPlan,
4654
+ CheckoutSummaryPrice2 as CheckoutSummaryPrice,
4655
+ CheckoutSummaryTrial2 as CheckoutSummaryTrial,
4656
+ CheckoutSummaryTaxNote2 as CheckoutSummaryTaxNote,
4657
+ CheckoutSummary,
4658
+ useCheckoutSummary,
4659
+ CheckoutSummary2,
4660
+ useMerchant,
4661
+ deriveVariant,
4662
+ MandateText,
4663
+ Spinner,
4664
+ confirmPayment,
4665
+ resolveCta,
4666
+ PaymentFormRoot2 as PaymentFormRoot,
4667
+ PaymentFormSummary,
4668
+ PaymentFormCustomerFields2 as PaymentFormCustomerFields,
4669
+ PaymentFormPaymentElement,
4670
+ PaymentFormCardElement,
4671
+ PaymentFormMandateText,
4672
+ PaymentFormTermsCheckbox2 as PaymentFormTermsCheckbox,
4673
+ PaymentFormSubmitButton2 as PaymentFormSubmitButton,
4674
+ PaymentFormLoading2 as PaymentFormLoading,
4675
+ PaymentFormError2 as PaymentFormError,
4676
+ PaymentForm,
4677
+ useTopupAmountSelector,
4678
+ useBalance,
4679
+ AmountPickerRoot2 as AmountPickerRoot,
4680
+ AmountPickerOption2 as AmountPickerOption,
4681
+ AmountPickerCustom2 as AmountPickerCustom,
4682
+ AmountPickerConfirm2 as AmountPickerConfirm,
4683
+ AmountPicker,
4684
+ useAmountPicker,
4685
+ useAmountPickerCopy,
4686
+ useTopup,
4687
+ TopupFormRoot2 as TopupFormRoot,
4688
+ TopupFormPaymentElement,
4689
+ TopupFormSubmitButton2 as TopupFormSubmitButton,
4690
+ TopupFormLoading2 as TopupFormLoading,
4691
+ TopupFormError2 as TopupFormError,
4692
+ TopupForm,
4693
+ useTopupForm,
4694
+ TopupForm2,
4695
+ ProductBadge2 as ProductBadge,
4696
+ PlanBadge,
4697
+ PurchaseGateRoot2 as PurchaseGateRoot,
4698
+ PurchaseGateAllowed2 as PurchaseGateAllowed,
4699
+ PurchaseGateBlocked2 as PurchaseGateBlocked,
4700
+ PurchaseGateLoading2 as PurchaseGateLoading,
4701
+ PurchaseGateError2 as PurchaseGateError,
4702
+ PurchaseGate,
4703
+ usePurchaseGate,
4704
+ BalanceBadge,
4705
+ PlanSelectorRoot2 as PlanSelectorRoot,
4706
+ PlanSelectorHeading2 as PlanSelectorHeading,
4707
+ PlanSelectorGrid2 as PlanSelectorGrid,
4708
+ PlanSelectorCard2 as PlanSelectorCard,
4709
+ PlanSelectorCardName2 as PlanSelectorCardName,
4710
+ PlanSelectorCardPrice2 as PlanSelectorCardPrice,
4711
+ PlanSelectorCardInterval2 as PlanSelectorCardInterval,
4712
+ PlanSelectorCardBadge2 as PlanSelectorCardBadge,
4713
+ PlanSelectorLoading2 as PlanSelectorLoading,
4714
+ PlanSelectorError2 as PlanSelectorError,
4715
+ PlanSelector,
4716
+ usePlanSelector,
4717
+ ActivationFlowRoot2 as ActivationFlowRoot,
4718
+ ActivationFlowSummary2 as ActivationFlowSummary,
4719
+ ActivationFlowActivateButton2 as ActivationFlowActivateButton,
4720
+ ActivationFlowAmountPicker,
4721
+ ActivationFlowContinueButton2 as ActivationFlowContinueButton,
4722
+ ActivationFlowRetrying2 as ActivationFlowRetrying,
4723
+ ActivationFlowActivated2 as ActivationFlowActivated,
4724
+ ActivationFlowLoading2 as ActivationFlowLoading,
4725
+ ActivationFlowError2 as ActivationFlowError,
4726
+ ActivationFlow,
4727
+ useActivationFlow,
4728
+ usePurchaseActions,
4729
+ CancelPlanButton,
4730
+ usePurchaseStatus,
4731
+ CancelledPlanNoticeRoot2 as CancelledPlanNoticeRoot,
4732
+ CancelledPlanNoticeHeading2 as CancelledPlanNoticeHeading,
4733
+ CancelledPlanNoticeExpires2 as CancelledPlanNoticeExpires,
4734
+ CancelledPlanNoticeDaysRemaining2 as CancelledPlanNoticeDaysRemaining,
4735
+ CancelledPlanNoticeAccessUntil2 as CancelledPlanNoticeAccessUntil,
4736
+ CancelledPlanNoticeCancelledOn2 as CancelledPlanNoticeCancelledOn,
4737
+ CancelledPlanNoticeReason2 as CancelledPlanNoticeReason,
4738
+ CancelledPlanNoticeReactivateButton2 as CancelledPlanNoticeReactivateButton,
4739
+ CancelledPlanNotice,
4740
+ useCancelledPlanNotice,
4741
+ CreditGateRoot2 as CreditGateRoot,
4742
+ CreditGateHeading2 as CreditGateHeading,
4743
+ CreditGateSubheading2 as CreditGateSubheading,
4744
+ CreditGateTopup,
4745
+ CreditGateLoading2 as CreditGateLoading,
4746
+ CreditGateError2 as CreditGateError,
4747
+ CreditGate,
4748
+ useCreditGate
4749
+ };