@cedros/pay-react 1.1.4 → 1.1.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 (44) hide show
  1. package/dist/CedrosContext-C2v_s8cc.js +6 -0
  2. package/dist/CedrosContext-D7nh5-Zh.mjs +2100 -0
  3. package/dist/WalletManager-B5KLZK2D.js +1 -0
  4. package/dist/WalletManager-oEjZhaFk.mjs +219 -0
  5. package/dist/components/CedrosPay.d.ts.map +1 -1
  6. package/dist/context/CedrosContext.d.ts +9 -3
  7. package/dist/context/CedrosContext.d.ts.map +1 -1
  8. package/dist/crypto-only.d.ts +9 -19
  9. package/dist/crypto-only.d.ts.map +1 -1
  10. package/dist/crypto-only.js +1 -1
  11. package/dist/crypto-only.mjs +766 -32
  12. package/dist/index-BFt38o8Q.mjs +88 -0
  13. package/dist/{index-CUoeIbXT.mjs → index-DjnqYAvN.mjs} +10300 -9055
  14. package/dist/index-WcOlBYZJ.js +1 -0
  15. package/dist/index-cW1q6Jp0.js +136 -0
  16. package/dist/index.d.ts +1 -7
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +1 -1
  19. package/dist/index.mjs +68 -75
  20. package/dist/managers/ManagerCache.d.ts +2 -2
  21. package/dist/managers/ManagerCache.d.ts.map +1 -1
  22. package/dist/pay-react.css +1 -1
  23. package/dist/{sections-TiollkCu.mjs → sections-DN09osp3.mjs} +2 -2
  24. package/dist/{sections-D7gSCYck.js → sections-DT8Vsm7s.js} +1 -1
  25. package/dist/solanaCheck-BS3QTE63.js +6 -0
  26. package/dist/solanaCheck-IlYsbXDd.mjs +27 -0
  27. package/dist/stripe-only.d.ts +4 -21
  28. package/dist/stripe-only.d.ts.map +1 -1
  29. package/dist/stripe-only.js +1 -1
  30. package/dist/stripe-only.mjs +71 -29
  31. package/dist/testing/index.js +1 -1
  32. package/dist/testing/index.mjs +1 -1
  33. package/dist/types/componentOptions.d.ts +15 -2
  34. package/dist/types/componentOptions.d.ts.map +1 -1
  35. package/dist/utils/index.d.ts +0 -1
  36. package/dist/utils/index.d.ts.map +1 -1
  37. package/dist/walletPool-BR6etEiq.mjs +67 -0
  38. package/dist/walletPool-BZyAG4YS.js +1 -0
  39. package/package.json +6 -1
  40. package/dist/CedrosContext-DUT3cLZg.mjs +0 -2474
  41. package/dist/CedrosContext-efFL4kQz.js +0 -11
  42. package/dist/index-CWbWPgXt.js +0 -136
  43. package/dist/styles-C4-_hbgr.js +0 -1
  44. package/dist/styles-QcAsIVWl.mjs +0 -1909
@@ -0,0 +1,2100 @@
1
+ import { jsx as J } from "react/jsx-runtime";
2
+ import { createContext as le, useContext as _, useState as U, useRef as de, useEffect as k, useMemo as K } from "react";
3
+ import { g as C } from "./uuid-_z3jSatJ.mjs";
4
+ var fe = "https://js.stripe.com/v3", Ne = /^https:\/\/js\.stripe\.com\/v3\/?(\?.*)?$/;
5
+ var Ue = function() {
6
+ for (var e = document.querySelectorAll('script[src^="'.concat(fe, '"]')), r = 0; r < e.length; r++) {
7
+ var a = e[r];
8
+ if (Ne.test(a.src))
9
+ return a;
10
+ }
11
+ return null;
12
+ }, re = function(e) {
13
+ var r = "", a = document.createElement("script");
14
+ a.src = "".concat(fe).concat(r);
15
+ var n = document.head || document.body;
16
+ if (!n)
17
+ throw new Error("Expected document.body not to be null. Stripe.js requires a <body> element.");
18
+ return n.appendChild(a), a;
19
+ }, Fe = function(e, r) {
20
+ !e || !e._registerWrapper || e._registerWrapper({
21
+ name: "stripe-js",
22
+ version: "4.6.0",
23
+ startTime: r
24
+ });
25
+ }, O = null, I = null, j = null, Le = function(e) {
26
+ return function() {
27
+ e(new Error("Failed to load Stripe.js"));
28
+ };
29
+ }, Ie = function(e, r) {
30
+ return function() {
31
+ window.Stripe ? e(window.Stripe) : r(new Error("Stripe.js not available"));
32
+ };
33
+ }, je = function(e) {
34
+ return O !== null ? O : (O = new Promise(function(r, a) {
35
+ if (typeof window > "u" || typeof document > "u") {
36
+ r(null);
37
+ return;
38
+ }
39
+ if (window.Stripe) {
40
+ r(window.Stripe);
41
+ return;
42
+ }
43
+ try {
44
+ var n = Ue();
45
+ if (!(n && e)) {
46
+ if (!n)
47
+ n = re(e);
48
+ else if (n && j !== null && I !== null) {
49
+ var i;
50
+ n.removeEventListener("load", j), n.removeEventListener("error", I), (i = n.parentNode) === null || i === void 0 || i.removeChild(n), n = re(e);
51
+ }
52
+ }
53
+ j = Ie(r, a), I = Le(a), n.addEventListener("load", j), n.addEventListener("error", I);
54
+ } catch (o) {
55
+ a(o);
56
+ return;
57
+ }
58
+ }), O.catch(function(r) {
59
+ return O = null, Promise.reject(r);
60
+ }));
61
+ }, Qe = function(e, r, a) {
62
+ if (e === null)
63
+ return null;
64
+ var n = e.apply(void 0, r);
65
+ return Fe(n, a), n;
66
+ }, B, Ae = !1, he = function() {
67
+ return B || (B = je(null).catch(function(e) {
68
+ return B = null, Promise.reject(e);
69
+ }), B);
70
+ };
71
+ Promise.resolve().then(function() {
72
+ return he();
73
+ }).catch(function(t) {
74
+ Ae || console.warn(t);
75
+ });
76
+ var pe = function() {
77
+ for (var e = arguments.length, r = new Array(e), a = 0; a < e; a++)
78
+ r[a] = arguments[a];
79
+ Ae = !0;
80
+ var n = Date.now();
81
+ return he().then(function(i) {
82
+ return Qe(i, r, n);
83
+ });
84
+ }, ze = /* @__PURE__ */ ((t) => (t[t.DEBUG = 0] = "DEBUG", t[t.INFO = 1] = "INFO", t[t.WARN = 2] = "WARN", t[t.ERROR = 3] = "ERROR", t[t.SILENT = 4] = "SILENT", t))(ze || {});
85
+ class ye {
86
+ config;
87
+ constructor(e) {
88
+ this.config = e;
89
+ }
90
+ /**
91
+ * Update the log level dynamically
92
+ */
93
+ setLevel(e) {
94
+ this.config.level = e;
95
+ }
96
+ /**
97
+ * Get the current log level
98
+ */
99
+ getLevel() {
100
+ return this.config.level;
101
+ }
102
+ /**
103
+ * Debug-level logging (most verbose)
104
+ * Use for detailed debugging information
105
+ */
106
+ debug(...e) {
107
+ this.config.level <= 0 && this.log("DEBUG", console.log, e);
108
+ }
109
+ /**
110
+ * Info-level logging
111
+ * Use for general informational messages
112
+ */
113
+ info(...e) {
114
+ this.config.level <= 1 && this.log("INFO", console.info, e);
115
+ }
116
+ /**
117
+ * Warning-level logging
118
+ * Use for potentially problematic situations
119
+ */
120
+ warn(...e) {
121
+ this.config.level <= 2 && this.log("WARN", console.warn, e);
122
+ }
123
+ /**
124
+ * Error-level logging
125
+ * Use for error conditions
126
+ */
127
+ error(...e) {
128
+ this.config.level <= 3 && this.log("ERROR", console.error, e);
129
+ }
130
+ /**
131
+ * Internal log method with formatting
132
+ */
133
+ log(e, r, a) {
134
+ const n = this.config.prefix ? `${this.config.prefix} ` : "", i = (/* @__PURE__ */ new Date()).toISOString();
135
+ r(`[${i}] ${n}[${e}]`, ...a);
136
+ }
137
+ }
138
+ const qe = () => typeof process < "u" && process.env.NODE_ENV === "development" ? 0 : 2;
139
+ let z = null;
140
+ function c() {
141
+ return z || (z = new ye({
142
+ level: qe(),
143
+ prefix: "[CedrosPay]"
144
+ })), z;
145
+ }
146
+ function He(t) {
147
+ z = t;
148
+ }
149
+ function Ve(t) {
150
+ return new ye(t);
151
+ }
152
+ function x(t, e) {
153
+ return t instanceof Error ? t.message : typeof t == "string" ? t : e;
154
+ }
155
+ const Ge = {
156
+ service_unavailable: "Service temporarily unavailable. Please try again later or contact support.",
157
+ server_insufficient_funds: "Service temporarily unavailable. Please try again later or contact support.",
158
+ insufficient_funds_token: "Insufficient token balance in your wallet. Please add more tokens and try again.",
159
+ insufficient_funds_sol: "Insufficient SOL for transaction fees. Please add some SOL to your wallet and try again.",
160
+ insufficient_amount: "Payment amount is insufficient. Please check the required amount.",
161
+ invalid_signature: "Transaction signature is invalid. Please try again.",
162
+ send_failed: "Failed to send transaction. Please try again or contact support.",
163
+ timeout: "Transaction timed out. Please check the blockchain explorer or try again."
164
+ };
165
+ async function p(t, e, r = !1) {
166
+ try {
167
+ const a = await t.json();
168
+ if (r && a.verificationError) {
169
+ c().debug(`Payment verification failed: ${a.verificationError.code}`);
170
+ const n = a.verificationError.code;
171
+ return Ge[n] || a.verificationError.message || e;
172
+ }
173
+ return typeof a.error == "string" ? a.error : a.error && typeof a.error == "object" && "message" in a.error ? a.error.message : e;
174
+ } catch {
175
+ return await t.text() || e;
176
+ }
177
+ }
178
+ const We = 15e3;
179
+ async function h(t, e = {}, r = We) {
180
+ const a = new AbortController(), n = e.signal;
181
+ if (n?.aborted)
182
+ throw a.abort(), new DOMException("The operation was aborted", "AbortError");
183
+ const i = setTimeout(() => a.abort(), r);
184
+ let o = null;
185
+ n && (o = () => a.abort(), n.addEventListener("abort", o));
186
+ try {
187
+ return await fetch(t, {
188
+ ...e,
189
+ signal: a.signal
190
+ });
191
+ } catch (s) {
192
+ throw s instanceof Error && s.name === "AbortError" ? n?.aborted ? s : new Error(`Request timeout after ${r}ms`) : s;
193
+ } finally {
194
+ clearTimeout(i), n && o && n.removeEventListener("abort", o);
195
+ }
196
+ }
197
+ function P(t) {
198
+ const { maxRequests: e, windowMs: r } = t;
199
+ let a = e, n = Date.now();
200
+ const i = e / r;
201
+ function o() {
202
+ const u = Date.now(), d = u - n;
203
+ if (d > 0) {
204
+ const y = d * i;
205
+ a = Math.min(e, a + y), n = u;
206
+ }
207
+ }
208
+ function s() {
209
+ return o(), a >= 1 ? (a -= 1, !0) : !1;
210
+ }
211
+ function l() {
212
+ return o(), Math.floor(a);
213
+ }
214
+ function A() {
215
+ if (o(), a >= 1)
216
+ return 0;
217
+ const d = (1 - a) / i;
218
+ return Math.ceil(d);
219
+ }
220
+ function f() {
221
+ a = e, n = Date.now();
222
+ }
223
+ return {
224
+ tryConsume: s,
225
+ getAvailableTokens: l,
226
+ getTimeUntilRefill: A,
227
+ reset: f
228
+ };
229
+ }
230
+ const T = {
231
+ /** 10 requests per minute - recommended for payment requests */
232
+ PAYMENT: { maxRequests: 10, windowMs: 6e4 },
233
+ /** 30 requests per minute - for quote fetching */
234
+ QUOTE: { maxRequests: 30, windowMs: 6e4 },
235
+ /** 5 requests per minute - strict limit for sensitive operations */
236
+ STRICT: { maxRequests: 5, windowMs: 6e4 },
237
+ /** 100 requests per minute - permissive for UI interactions */
238
+ PERMISSIVE: { maxRequests: 100, windowMs: 6e4 }
239
+ };
240
+ var Je = /* @__PURE__ */ ((t) => (t.CLOSED = "CLOSED", t.OPEN = "OPEN", t.HALF_OPEN = "HALF_OPEN", t))(Je || {});
241
+ class m extends Error {
242
+ constructor(e) {
243
+ super(e), this.name = "CircuitBreakerOpenError";
244
+ }
245
+ }
246
+ function F(t) {
247
+ const { failureThreshold: e, timeout: r, name: a = "circuit-breaker" } = t;
248
+ let n = "CLOSED", i = 0, o = 0, s = 0, l = null, A = null, f = null;
249
+ function u() {
250
+ n === "OPEN" && f !== null && Date.now() >= f && (c().debug(`[CircuitBreaker:${a}] Transitioning OPEN → HALF_OPEN (timeout expired)`), n = "HALF_OPEN", f = null);
251
+ }
252
+ function d() {
253
+ A = Date.now(), o++, n === "HALF_OPEN" ? (c().debug(`[CircuitBreaker:${a}] Success in HALF_OPEN → CLOSED`), n = "CLOSED", i = 0) : n === "CLOSED" && (i = 0);
254
+ }
255
+ function y(L) {
256
+ l = Date.now(), i++, c().warn(`[CircuitBreaker:${a}] Failure recorded (${i}/${e}):`, L.message), n === "HALF_OPEN" ? (c().warn(`[CircuitBreaker:${a}] Failed in HALF_OPEN → OPEN`), n = "OPEN", f = Date.now() + r) : n === "CLOSED" && i >= e && (c().error(`[CircuitBreaker:${a}] Failure threshold reached (${i}) → OPEN`), n = "OPEN", f = Date.now() + r);
257
+ }
258
+ async function E(L) {
259
+ if (u(), n === "OPEN") {
260
+ s++;
261
+ const S = f ? Math.ceil((f - Date.now()) / 1e3) : 0;
262
+ throw new m(
263
+ `Circuit breaker is OPEN. Service is unavailable. Retry in ${S}s.`
264
+ );
265
+ }
266
+ try {
267
+ const S = await L();
268
+ return d(), S;
269
+ } catch (S) {
270
+ throw y(S instanceof Error ? S : new Error(String(S))), S;
271
+ }
272
+ }
273
+ function v() {
274
+ return u(), n;
275
+ }
276
+ function R() {
277
+ return u(), {
278
+ state: n,
279
+ failures: i,
280
+ successes: o,
281
+ rejections: s,
282
+ lastFailureTime: l,
283
+ lastSuccessTime: A
284
+ };
285
+ }
286
+ function V() {
287
+ c().debug(`[CircuitBreaker:${a}] Manual reset → CLOSED`), n = "CLOSED", i = 0, o = 0, s = 0, l = null, A = null, f = null;
288
+ }
289
+ function Be() {
290
+ c().warn(`[CircuitBreaker:${a}] Manual trip → OPEN`), n = "OPEN", f = Date.now() + r;
291
+ }
292
+ return {
293
+ execute: E,
294
+ getState: v,
295
+ getStats: R,
296
+ reset: V,
297
+ trip: Be
298
+ };
299
+ }
300
+ const Ut = {
301
+ /** Strict: Opens quickly (3 failures), long timeout (60s) */
302
+ STRICT: { failureThreshold: 3, timeout: 6e4 },
303
+ /** Standard: Balanced settings (5 failures, 30s timeout) */
304
+ STANDARD: { failureThreshold: 5, timeout: 3e4 },
305
+ /** Lenient: Tolerates more failures (10 failures, 15s timeout) */
306
+ LENIENT: { failureThreshold: 10, timeout: 15e3 }
307
+ };
308
+ function Ke(t, e) {
309
+ if (e >= 3)
310
+ return !1;
311
+ const r = t.message.toLowerCase();
312
+ return r.includes("network") || r.includes("timeout") || r.includes("fetch failed") || r.includes("econnrefused") || r.includes("503") || r.includes("502") || r.includes("500") || r.includes("429") ? !0 : (r.includes("400") || r.includes("401") || r.includes("403") || r.includes("404"), !1);
313
+ }
314
+ function Ye(t, e, r, a, n) {
315
+ const i = e * Math.pow(r, t), o = Math.min(i, a);
316
+ if (n) {
317
+ const s = Math.random() * o;
318
+ return Math.floor(s);
319
+ }
320
+ return Math.floor(o);
321
+ }
322
+ function Xe(t) {
323
+ return new Promise((e) => setTimeout(e, t));
324
+ }
325
+ async function w(t, e = {}) {
326
+ const {
327
+ maxRetries: r = 3,
328
+ initialDelayMs: a = 1e3,
329
+ backoffFactor: n = 2,
330
+ maxDelayMs: i = 3e4,
331
+ jitter: o = !0,
332
+ shouldRetry: s = Ke,
333
+ name: l = "retry"
334
+ } = e;
335
+ let A = null, f = 0;
336
+ for (let u = 0; u <= r; u++)
337
+ try {
338
+ const d = await t();
339
+ return u > 0 && c().debug(
340
+ `[Retry:${l}] Succeeded on attempt ${u + 1}/${r + 1} after ${f}ms`
341
+ ), d;
342
+ } catch (d) {
343
+ A = d instanceof Error ? d : new Error(String(d));
344
+ const y = u === r, E = s(A, u);
345
+ if (y || !E)
346
+ throw c().warn(
347
+ `[Retry:${l}] Failed on attempt ${u + 1}/${r + 1}. ${y ? "No more retries." : "Error not retryable."}`
348
+ ), A;
349
+ const v = Ye(u, a, n, i, o);
350
+ f += v, c().warn(
351
+ `[Retry:${l}] Attempt ${u + 1}/${r + 1} failed: ${A.message}. Retrying in ${v}ms...`
352
+ ), await Xe(v);
353
+ }
354
+ throw A || new Error("Retry failed with no error");
355
+ }
356
+ const g = {
357
+ /** Quick retries for transient errors (3 retries, 1s initial, 2x backoff) */
358
+ QUICK: {
359
+ maxRetries: 3,
360
+ initialDelayMs: 1e3,
361
+ backoffFactor: 2,
362
+ maxDelayMs: 1e4
363
+ },
364
+ /** Standard retries (3 retries, 2s initial, 2x backoff) */
365
+ STANDARD: {
366
+ maxRetries: 3,
367
+ initialDelayMs: 2e3,
368
+ backoffFactor: 2,
369
+ maxDelayMs: 3e4
370
+ },
371
+ /** Aggressive retries for critical operations (5 retries, 500ms initial) */
372
+ AGGRESSIVE: {
373
+ maxRetries: 5,
374
+ initialDelayMs: 500,
375
+ backoffFactor: 1.5,
376
+ maxDelayMs: 15e3
377
+ },
378
+ /** Patient retries for slow backends (5 retries, 5s initial) */
379
+ PATIENT: {
380
+ maxRetries: 5,
381
+ initialDelayMs: 5e3,
382
+ backoffFactor: 2,
383
+ maxDelayMs: 6e4
384
+ }
385
+ };
386
+ class Ze {
387
+ stripe = null;
388
+ publicKey;
389
+ routeDiscovery;
390
+ rateLimiter = P(T.PAYMENT);
391
+ circuitBreaker = F({
392
+ failureThreshold: 5,
393
+ timeout: 1e4,
394
+ // 10 seconds for faster recovery in payment flows
395
+ name: "stripe-manager"
396
+ });
397
+ constructor(e, r) {
398
+ this.publicKey = e, this.routeDiscovery = r;
399
+ }
400
+ /**
401
+ * Initialize Stripe.js library
402
+ */
403
+ async initialize() {
404
+ if (!this.stripe && (this.stripe = await pe(this.publicKey), !this.stripe))
405
+ throw new Error("Failed to initialize Stripe");
406
+ }
407
+ /**
408
+ * Create a Stripe checkout session
409
+ */
410
+ async createSession(e) {
411
+ if (!this.rateLimiter.tryConsume())
412
+ throw new Error("Rate limit exceeded for Stripe session creation. Please try again later.");
413
+ try {
414
+ return await this.circuitBreaker.execute(async () => await w(
415
+ async () => {
416
+ const r = await this.routeDiscovery.buildUrl("/paywall/v1/stripe-session");
417
+ c().debug("[StripeManager] Creating session with request:", e), e.couponCode ? c().debug("[StripeManager] Coupon code included:", e.couponCode) : c().debug("[StripeManager] No coupon code in request");
418
+ const a = await h(r, {
419
+ method: "POST",
420
+ headers: {
421
+ "Content-Type": "application/json",
422
+ "Idempotency-Key": C()
423
+ },
424
+ body: JSON.stringify(e)
425
+ });
426
+ if (!a.ok) {
427
+ const n = await p(a, "Failed to create Stripe session");
428
+ throw new Error(n);
429
+ }
430
+ return await a.json();
431
+ },
432
+ { ...g.STANDARD, name: "stripe-create-session" }
433
+ ));
434
+ } catch (r) {
435
+ throw r instanceof m ? (c().error("[StripeManager] Circuit breaker is OPEN - Stripe service unavailable"), new Error("Stripe payment service is temporarily unavailable. Please try again in a few moments.")) : r;
436
+ }
437
+ }
438
+ /**
439
+ * Redirect to Stripe checkout
440
+ */
441
+ async redirectToCheckout(e) {
442
+ if (this.stripe || await this.initialize(), !this.stripe)
443
+ return {
444
+ success: !1,
445
+ error: "Stripe not initialized"
446
+ };
447
+ const r = await this.stripe.redirectToCheckout({ sessionId: e });
448
+ return r.error ? {
449
+ success: !1,
450
+ error: r.error.message
451
+ } : { success: !0 };
452
+ }
453
+ /**
454
+ * Handle complete payment flow: create session and redirect
455
+ */
456
+ async processPayment(e) {
457
+ try {
458
+ const r = await this.createSession(e);
459
+ return await this.redirectToCheckout(r.sessionId);
460
+ } catch (r) {
461
+ return {
462
+ success: !1,
463
+ error: x(r, "Unknown error")
464
+ };
465
+ }
466
+ }
467
+ /**
468
+ * Create a Stripe cart checkout session for multiple items
469
+ */
470
+ async processCartCheckout(e) {
471
+ const { items: r, successUrl: a, cancelUrl: n, metadata: i, customerEmail: o, couponCode: s } = e;
472
+ if (!this.rateLimiter.tryConsume())
473
+ return {
474
+ success: !1,
475
+ error: "Rate limit exceeded for cart checkout. Please try again later."
476
+ };
477
+ try {
478
+ const l = await this.circuitBreaker.execute(async () => await w(
479
+ async () => {
480
+ const A = await this.routeDiscovery.buildUrl("/paywall/v1/cart/checkout"), f = {
481
+ items: r,
482
+ successUrl: a,
483
+ cancelUrl: n,
484
+ metadata: i,
485
+ customerEmail: o,
486
+ coupon: s,
487
+ // New Rust server field
488
+ couponCode: s
489
+ // Legacy Go server field (backwards compat)
490
+ }, u = await h(A, {
491
+ method: "POST",
492
+ headers: {
493
+ "Content-Type": "application/json",
494
+ "Idempotency-Key": C()
495
+ },
496
+ body: JSON.stringify(f)
497
+ });
498
+ if (!u.ok) {
499
+ const d = await p(u, "Failed to create cart checkout session");
500
+ throw new Error(d);
501
+ }
502
+ return await u.json();
503
+ },
504
+ { ...g.STANDARD, name: "stripe-cart-checkout" }
505
+ ));
506
+ return await this.redirectToCheckout(l.sessionId);
507
+ } catch (l) {
508
+ return l instanceof m ? {
509
+ success: !1,
510
+ error: "Stripe payment service is temporarily unavailable. Please try again in a few moments."
511
+ } : {
512
+ success: !1,
513
+ error: x(l, "Cart checkout failed")
514
+ };
515
+ }
516
+ }
517
+ }
518
+ const me = "3.7.8", _e = me, D = typeof Buffer == "function", ae = typeof TextDecoder == "function" ? new TextDecoder() : void 0, ne = typeof TextEncoder == "function" ? new TextEncoder() : void 0, $e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", N = Array.prototype.slice.call($e), Q = ((t) => {
519
+ let e = {};
520
+ return t.forEach((r, a) => e[r] = a), e;
521
+ })(N), et = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/, b = String.fromCharCode.bind(String), ie = typeof Uint8Array.from == "function" ? Uint8Array.from.bind(Uint8Array) : (t) => new Uint8Array(Array.prototype.slice.call(t, 0)), we = (t) => t.replace(/=/g, "").replace(/[+\/]/g, (e) => e == "+" ? "-" : "_"), ge = (t) => t.replace(/[^A-Za-z0-9\+\/]/g, ""), be = (t) => {
522
+ let e, r, a, n, i = "";
523
+ const o = t.length % 3;
524
+ for (let s = 0; s < t.length; ) {
525
+ if ((r = t.charCodeAt(s++)) > 255 || (a = t.charCodeAt(s++)) > 255 || (n = t.charCodeAt(s++)) > 255)
526
+ throw new TypeError("invalid character found");
527
+ e = r << 16 | a << 8 | n, i += N[e >> 18 & 63] + N[e >> 12 & 63] + N[e >> 6 & 63] + N[e & 63];
528
+ }
529
+ return o ? i.slice(0, o - 3) + "===".substring(o) : i;
530
+ }, $ = typeof btoa == "function" ? (t) => btoa(t) : D ? (t) => Buffer.from(t, "binary").toString("base64") : be, Y = D ? (t) => Buffer.from(t).toString("base64") : (t) => {
531
+ let r = [];
532
+ for (let a = 0, n = t.length; a < n; a += 4096)
533
+ r.push(b.apply(null, t.subarray(a, a + 4096)));
534
+ return $(r.join(""));
535
+ }, q = (t, e = !1) => e ? we(Y(t)) : Y(t), tt = (t) => {
536
+ if (t.length < 2) {
537
+ var e = t.charCodeAt(0);
538
+ return e < 128 ? t : e < 2048 ? b(192 | e >>> 6) + b(128 | e & 63) : b(224 | e >>> 12 & 15) + b(128 | e >>> 6 & 63) + b(128 | e & 63);
539
+ } else {
540
+ var e = 65536 + (t.charCodeAt(0) - 55296) * 1024 + (t.charCodeAt(1) - 56320);
541
+ return b(240 | e >>> 18 & 7) + b(128 | e >>> 12 & 63) + b(128 | e >>> 6 & 63) + b(128 | e & 63);
542
+ }
543
+ }, rt = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g, ve = (t) => t.replace(rt, tt), oe = D ? (t) => Buffer.from(t, "utf8").toString("base64") : ne ? (t) => Y(ne.encode(t)) : (t) => $(ve(t)), M = (t, e = !1) => e ? we(oe(t)) : oe(t), se = (t) => M(t, !0), at = /[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g, nt = (t) => {
544
+ switch (t.length) {
545
+ case 4:
546
+ var e = (7 & t.charCodeAt(0)) << 18 | (63 & t.charCodeAt(1)) << 12 | (63 & t.charCodeAt(2)) << 6 | 63 & t.charCodeAt(3), r = e - 65536;
547
+ return b((r >>> 10) + 55296) + b((r & 1023) + 56320);
548
+ case 3:
549
+ return b((15 & t.charCodeAt(0)) << 12 | (63 & t.charCodeAt(1)) << 6 | 63 & t.charCodeAt(2));
550
+ default:
551
+ return b((31 & t.charCodeAt(0)) << 6 | 63 & t.charCodeAt(1));
552
+ }
553
+ }, Ee = (t) => t.replace(at, nt), Ce = (t) => {
554
+ if (t = t.replace(/\s+/g, ""), !et.test(t))
555
+ throw new TypeError("malformed base64.");
556
+ t += "==".slice(2 - (t.length & 3));
557
+ let e, r, a, n = [];
558
+ for (let i = 0; i < t.length; )
559
+ e = Q[t.charAt(i++)] << 18 | Q[t.charAt(i++)] << 12 | (r = Q[t.charAt(i++)]) << 6 | (a = Q[t.charAt(i++)]), r === 64 ? n.push(b(e >> 16 & 255)) : a === 64 ? n.push(b(e >> 16 & 255, e >> 8 & 255)) : n.push(b(e >> 16 & 255, e >> 8 & 255, e & 255));
560
+ return n.join("");
561
+ }, ee = typeof atob == "function" ? (t) => atob(ge(t)) : D ? (t) => Buffer.from(t, "base64").toString("binary") : Ce, Se = D ? (t) => ie(Buffer.from(t, "base64")) : (t) => ie(ee(t).split("").map((e) => e.charCodeAt(0))), xe = (t) => Se(Pe(t)), it = D ? (t) => Buffer.from(t, "base64").toString("utf8") : ae ? (t) => ae.decode(Se(t)) : (t) => Ee(ee(t)), Pe = (t) => ge(t.replace(/[-_]/g, (e) => e == "-" ? "+" : "/")), X = (t) => it(Pe(t)), ot = (t) => {
562
+ if (typeof t != "string")
563
+ return !1;
564
+ const e = t.replace(/\s+/g, "").replace(/={0,2}$/, "");
565
+ return !/[^\s0-9a-zA-Z\+/]/.test(e) || !/[^\s0-9a-zA-Z\-_]/.test(e);
566
+ }, Te = (t) => ({
567
+ value: t,
568
+ enumerable: !1,
569
+ writable: !0,
570
+ configurable: !0
571
+ }), Re = function() {
572
+ const t = (e, r) => Object.defineProperty(String.prototype, e, Te(r));
573
+ t("fromBase64", function() {
574
+ return X(this);
575
+ }), t("toBase64", function(e) {
576
+ return M(this, e);
577
+ }), t("toBase64URI", function() {
578
+ return M(this, !0);
579
+ }), t("toBase64URL", function() {
580
+ return M(this, !0);
581
+ }), t("toUint8Array", function() {
582
+ return xe(this);
583
+ });
584
+ }, ke = function() {
585
+ const t = (e, r) => Object.defineProperty(Uint8Array.prototype, e, Te(r));
586
+ t("toBase64", function(e) {
587
+ return q(this, e);
588
+ }), t("toBase64URI", function() {
589
+ return q(this, !0);
590
+ }), t("toBase64URL", function() {
591
+ return q(this, !0);
592
+ });
593
+ }, st = () => {
594
+ Re(), ke();
595
+ }, ce = {
596
+ version: me,
597
+ VERSION: _e,
598
+ atob: ee,
599
+ atobPolyfill: Ce,
600
+ btoa: $,
601
+ btoaPolyfill: be,
602
+ fromBase64: X,
603
+ toBase64: M,
604
+ encode: M,
605
+ encodeURI: se,
606
+ encodeURL: se,
607
+ utob: ve,
608
+ btou: Ee,
609
+ decode: X,
610
+ isValid: ot,
611
+ fromUint8Array: q,
612
+ toUint8Array: xe,
613
+ extendString: Re,
614
+ extendUint8Array: ke,
615
+ extendBuiltins: st
616
+ };
617
+ class ct {
618
+ routeDiscovery;
619
+ quoteRateLimiter = P(T.QUOTE);
620
+ verifyRateLimiter = P(T.PAYMENT);
621
+ circuitBreaker = F({
622
+ failureThreshold: 5,
623
+ timeout: 1e4,
624
+ // 10 seconds for faster recovery in payment flows
625
+ name: "x402-manager"
626
+ });
627
+ constructor(e) {
628
+ this.routeDiscovery = e;
629
+ }
630
+ /**
631
+ * Request a protected resource and get x402 requirement
632
+ * SECURITY: Resource ID and coupon codes sent in request body to prevent leakage
633
+ * Prevents exposure of product IDs, SKUs, and business-sensitive identifiers in logs
634
+ */
635
+ async requestQuote(e) {
636
+ const { resource: r, couponCode: a } = e;
637
+ if (!this.quoteRateLimiter.tryConsume())
638
+ throw new Error("Rate limit exceeded for quote requests. Please try again later.");
639
+ try {
640
+ return await this.circuitBreaker.execute(async () => await w(
641
+ async () => {
642
+ const n = "/paywall/v1/quote";
643
+ c().debug(
644
+ "[X402Manager] Requesting quote",
645
+ a ? "with coupon" : "without coupon"
646
+ );
647
+ const i = await this.routeDiscovery.buildUrl(n), o = await h(i, {
648
+ method: "POST",
649
+ headers: {
650
+ "Content-Type": "application/json"
651
+ },
652
+ body: JSON.stringify({
653
+ resource: r,
654
+ couponCode: a || null
655
+ })
656
+ });
657
+ if (o.status !== 402)
658
+ throw new Error(`Expected 402 status, got ${o.status}`);
659
+ const s = await o.json();
660
+ if (s.crypto)
661
+ return s.crypto;
662
+ if (s.accepts && s.accepts.length > 0)
663
+ return s.accepts[0];
664
+ throw new Error("Invalid x402 response: missing crypto or accepts field");
665
+ },
666
+ { ...g.QUICK, name: "x402-quote" }
667
+ ));
668
+ } catch (n) {
669
+ throw n instanceof m ? (c().error("[X402Manager] Circuit breaker is OPEN - x402 service unavailable"), new Error("Payment service is temporarily unavailable. Please try again in a few moments.")) : n;
670
+ }
671
+ }
672
+ /**
673
+ * Request a cart quote for multiple items
674
+ */
675
+ async requestCartQuote(e) {
676
+ const { items: r, metadata: a, couponCode: n } = e;
677
+ if (!this.quoteRateLimiter.tryConsume())
678
+ throw new Error("Rate limit exceeded for cart quote requests. Please try again later.");
679
+ try {
680
+ return await this.circuitBreaker.execute(async () => await w(
681
+ async () => {
682
+ const i = await this.routeDiscovery.buildUrl("/paywall/v1/cart/quote"), o = {
683
+ items: r,
684
+ metadata: a,
685
+ coupon: n,
686
+ // New Rust server field
687
+ couponCode: n
688
+ // Legacy Go server field (backwards compat)
689
+ }, s = await h(i, {
690
+ method: "POST",
691
+ headers: {
692
+ "Content-Type": "application/json",
693
+ "Idempotency-Key": C()
694
+ },
695
+ body: JSON.stringify(o)
696
+ });
697
+ if (s.status !== 402 && !s.ok) {
698
+ const l = await p(s, "Failed to get cart quote");
699
+ throw new Error(l);
700
+ }
701
+ return await s.json();
702
+ },
703
+ { ...g.QUICK, name: "x402-cart-quote" }
704
+ ));
705
+ } catch (i) {
706
+ throw i instanceof m ? (c().error("[X402Manager] Circuit breaker is OPEN - cart quote service unavailable"), new Error("Payment service is temporarily unavailable. Please try again in a few moments.")) : i;
707
+ }
708
+ }
709
+ /**
710
+ * Build X-PAYMENT header from payment payload (base64 encoded)
711
+ */
712
+ buildPaymentHeader(e) {
713
+ const r = JSON.stringify(e);
714
+ return ce.encode(r);
715
+ }
716
+ /**
717
+ * Parse X-PAYMENT-RESPONSE header (base64 encoded settlement response)
718
+ */
719
+ parseSettlementResponse(e) {
720
+ const r = e.headers.get("X-PAYMENT-RESPONSE");
721
+ if (!r)
722
+ return null;
723
+ try {
724
+ const a = ce.decode(r), n = JSON.parse(a);
725
+ return typeof n.success != "boolean" ? (c().error("Invalid settlement response: missing success field"), null) : n;
726
+ } catch (a) {
727
+ return c().error("Failed to parse settlement response:", a), null;
728
+ }
729
+ }
730
+ /**
731
+ * Retry request with payment proof
732
+ * SECURITY: Coupon and metadata sent in X-PAYMENT header payload, NOT query strings
733
+ */
734
+ async submitPayment(e) {
735
+ const {
736
+ resource: r,
737
+ payload: a,
738
+ couponCode: n,
739
+ metadata: i,
740
+ resourceType: o = "regular"
741
+ } = e;
742
+ if (!this.verifyRateLimiter.tryConsume())
743
+ return {
744
+ success: !1,
745
+ error: "Rate limit exceeded for payment verification. Please try again later."
746
+ };
747
+ try {
748
+ return await this.circuitBreaker.execute(async () => await w(
749
+ async () => {
750
+ const l = {
751
+ ...a,
752
+ payload: {
753
+ ...a.payload,
754
+ resource: r,
755
+ resourceType: o,
756
+ metadata: {
757
+ ...a.payload.metadata || {},
758
+ // Preserve existing metadata
759
+ ...i || {},
760
+ // Layer in new metadata
761
+ ...n ? { couponCode: n } : {}
762
+ // Add coupon if present
763
+ }
764
+ }
765
+ }, A = this.buildPaymentHeader(l), f = "/paywall/v1/verify";
766
+ c().debug("[X402Manager] Submitting payment", {
767
+ resourceType: o,
768
+ hasCoupon: !!n,
769
+ hasMetadata: !!i
770
+ });
771
+ const u = await this.routeDiscovery.buildUrl(f), d = await h(u, {
772
+ method: "POST",
773
+ headers: {
774
+ "Content-Type": "application/json",
775
+ "X-PAYMENT": A,
776
+ "Idempotency-Key": C()
777
+ }
778
+ });
779
+ if (d.ok) {
780
+ const { settlement: E, transactionId: v } = await this.handlePaymentVerification(
781
+ d,
782
+ a.payload.signature
783
+ );
784
+ return {
785
+ success: !0,
786
+ transactionId: v,
787
+ settlement: E || void 0
788
+ };
789
+ }
790
+ return {
791
+ success: !1,
792
+ error: await p(d, "Payment verification failed", !0)
793
+ };
794
+ },
795
+ { ...g.STANDARD, name: "x402-verify" }
796
+ ));
797
+ } catch (s) {
798
+ return s instanceof m ? {
799
+ success: !1,
800
+ error: "Payment verification service is temporarily unavailable. Please try again in a few moments."
801
+ } : {
802
+ success: !1,
803
+ error: x(s, "Unknown error")
804
+ };
805
+ }
806
+ }
807
+ /**
808
+ * Build a complete gasless transaction on the backend
809
+ * Returns an unsigned transaction with all instructions (compute budget, transfer, memo)
810
+ */
811
+ async buildGaslessTransaction(e) {
812
+ const { resourceId: r, userWallet: a, feePayer: n, couponCode: i } = e;
813
+ if (!this.quoteRateLimiter.tryConsume())
814
+ throw new Error("Rate limit exceeded for gasless transaction requests. Please try again later.");
815
+ try {
816
+ return await this.circuitBreaker.execute(async () => await w(
817
+ async () => {
818
+ const o = await this.routeDiscovery.buildUrl(
819
+ "/paywall/v1/gasless-transaction"
820
+ ), s = await h(o, {
821
+ method: "POST",
822
+ headers: {
823
+ "Content-Type": "application/json"
824
+ },
825
+ body: JSON.stringify({
826
+ resourceId: r,
827
+ userWallet: a,
828
+ feePayer: n,
829
+ couponCode: i
830
+ })
831
+ });
832
+ if (!s.ok) {
833
+ const l = await p(s, "Failed to build gasless transaction");
834
+ throw new Error(l);
835
+ }
836
+ return await s.json();
837
+ },
838
+ { ...g.QUICK, name: "x402-gasless-build" }
839
+ ));
840
+ } catch (o) {
841
+ throw o instanceof m ? (c().error("[X402Manager] Circuit breaker is OPEN - gasless transaction service unavailable"), new Error("Gasless transaction service is temporarily unavailable. Please try again in a few moments.")) : o;
842
+ }
843
+ }
844
+ /**
845
+ * Submit gasless partial transaction for co-signing
846
+ * Sends the partially-signed transaction in X-Payment header for backend co-signing
847
+ * SECURITY: Coupon and metadata sent in X-PAYMENT header payload, NOT query strings
848
+ */
849
+ async submitGaslessTransaction(e) {
850
+ const {
851
+ resource: r,
852
+ partialTx: a,
853
+ couponCode: n,
854
+ metadata: i,
855
+ resourceType: o = "regular",
856
+ requirement: s
857
+ } = e;
858
+ if (!this.verifyRateLimiter.tryConsume())
859
+ return {
860
+ success: !1,
861
+ error: "Rate limit exceeded for gasless transaction verification. Please try again later."
862
+ };
863
+ try {
864
+ return await this.circuitBreaker.execute(async () => await w(
865
+ async () => {
866
+ const A = {
867
+ x402Version: 0,
868
+ scheme: s?.scheme || "solana-spl-transfer",
869
+ network: s?.network || "mainnet-beta",
870
+ payload: {
871
+ signature: "",
872
+ // Placeholder - backend will finalize after co-signing
873
+ transaction: a,
874
+ feePayer: s?.extra?.feePayer || "",
875
+ resource: r,
876
+ resourceType: o,
877
+ metadata: {
878
+ ...i || {},
879
+ ...n ? { couponCode: n } : {}
880
+ }
881
+ }
882
+ }, f = this.buildPaymentHeader(A), d = await this.routeDiscovery.buildUrl("/paywall/v1/verify"), y = await h(d, {
883
+ method: "POST",
884
+ headers: {
885
+ "Content-Type": "application/json",
886
+ "X-PAYMENT": f,
887
+ "Idempotency-Key": C()
888
+ }
889
+ });
890
+ if (y.ok) {
891
+ const { settlement: v, transactionId: R } = await this.handlePaymentVerification(
892
+ y,
893
+ "gasless-tx"
894
+ );
895
+ return {
896
+ success: !0,
897
+ transactionId: R,
898
+ settlement: v || void 0
899
+ };
900
+ }
901
+ return {
902
+ success: !1,
903
+ error: await p(y, "Gasless transaction failed", !0)
904
+ };
905
+ },
906
+ { ...g.STANDARD, name: "x402-gasless-verify" }
907
+ ));
908
+ } catch (l) {
909
+ return l instanceof m ? {
910
+ success: !1,
911
+ error: "Gasless transaction verification service is temporarily unavailable. Please try again in a few moments."
912
+ } : {
913
+ success: !1,
914
+ error: x(l, "Unknown error")
915
+ };
916
+ }
917
+ }
918
+ /**
919
+ * Handle payment verification response (shared logic for both submitPayment and submitGaslessTransaction)
920
+ * Parses settlement header and extracts transaction ID from response body
921
+ * @param response - HTTP response from payment verification endpoint
922
+ * @param defaultTxId - Fallback transaction ID if JSON parsing fails
923
+ * @returns Settlement data and transaction ID
924
+ */
925
+ async handlePaymentVerification(e, r) {
926
+ const a = this.parseSettlementResponse(e), n = e.headers.get("Content-Type") || "";
927
+ let i = r;
928
+ if (n.includes("application/json"))
929
+ try {
930
+ i = (await e.json()).signature || r;
931
+ } catch (o) {
932
+ c().warn("Failed to parse JSON response body:", o);
933
+ }
934
+ return { settlement: a, transactionId: i };
935
+ }
936
+ /**
937
+ * Validate x402 requirement structure
938
+ */
939
+ validateRequirement(e) {
940
+ return !!(e.scheme && e.network && e.maxAmountRequired && e.resource && e.payTo && e.asset && e.maxTimeoutSeconds > 0);
941
+ }
942
+ }
943
+ class ut {
944
+ stripe = null;
945
+ publicKey;
946
+ routeDiscovery;
947
+ // Separate rate limiters for different operation types
948
+ sessionRateLimiter = P(T.PAYMENT);
949
+ statusRateLimiter = P(T.QUOTE);
950
+ circuitBreaker = F({
951
+ failureThreshold: 5,
952
+ timeout: 1e4,
953
+ // 10 seconds for faster recovery
954
+ name: "subscription-manager"
955
+ });
956
+ constructor(e, r) {
957
+ this.publicKey = e, this.routeDiscovery = r;
958
+ }
959
+ /** Initialize Stripe.js library */
960
+ async initialize() {
961
+ if (!this.stripe && (this.stripe = await pe(this.publicKey), !this.stripe))
962
+ throw new Error("Failed to initialize Stripe");
963
+ }
964
+ /** Internal helper: execute with rate limiting, circuit breaker, and retry */
965
+ async executeWithResilience(e, r, a, n) {
966
+ if (!e.tryConsume())
967
+ throw new Error("Rate limit exceeded. Please try again later.");
968
+ try {
969
+ return await this.circuitBreaker.execute(
970
+ () => w(r, { ...g.STANDARD, name: a })
971
+ );
972
+ } catch (i) {
973
+ throw i instanceof m ? (c().error(`[SubscriptionManager] Circuit breaker OPEN for ${n}`), new Error("Service temporarily unavailable. Please try again in a few moments.")) : i;
974
+ }
975
+ }
976
+ /**
977
+ * Create a Stripe subscription checkout session
978
+ */
979
+ async createSubscriptionSession(e) {
980
+ if (!this.sessionRateLimiter.tryConsume())
981
+ throw new Error("Rate limit exceeded for subscription session creation. Please try again later.");
982
+ try {
983
+ return await this.circuitBreaker.execute(async () => await w(
984
+ async () => {
985
+ const r = await this.routeDiscovery.buildUrl("/paywall/v1/subscription/stripe-session");
986
+ c().debug("[SubscriptionManager] Creating subscription session:", {
987
+ resource: e.resource,
988
+ interval: e.interval,
989
+ trialDays: e.trialDays
990
+ });
991
+ const a = await h(r, {
992
+ method: "POST",
993
+ headers: {
994
+ "Content-Type": "application/json",
995
+ "Idempotency-Key": C()
996
+ },
997
+ body: JSON.stringify(e)
998
+ });
999
+ if (!a.ok) {
1000
+ const n = await p(
1001
+ a,
1002
+ "Failed to create subscription session"
1003
+ );
1004
+ throw new Error(n);
1005
+ }
1006
+ return await a.json();
1007
+ },
1008
+ { ...g.STANDARD, name: "subscription-create-session" }
1009
+ ));
1010
+ } catch (r) {
1011
+ throw r instanceof m ? (c().error("[SubscriptionManager] Circuit breaker is OPEN - service unavailable"), new Error(
1012
+ "Subscription service is temporarily unavailable. Please try again in a few moments."
1013
+ )) : r;
1014
+ }
1015
+ }
1016
+ /**
1017
+ * Redirect to Stripe checkout
1018
+ */
1019
+ async redirectToCheckout(e) {
1020
+ if (this.stripe || await this.initialize(), !this.stripe)
1021
+ return {
1022
+ success: !1,
1023
+ error: "Stripe not initialized"
1024
+ };
1025
+ const r = await this.stripe.redirectToCheckout({ sessionId: e });
1026
+ return r.error ? {
1027
+ success: !1,
1028
+ error: r.error.message
1029
+ } : { success: !0, transactionId: e };
1030
+ }
1031
+ /**
1032
+ * Complete subscription flow: create session and redirect
1033
+ */
1034
+ async processSubscription(e) {
1035
+ try {
1036
+ const r = await this.createSubscriptionSession(e);
1037
+ return await this.redirectToCheckout(r.sessionId);
1038
+ } catch (r) {
1039
+ return {
1040
+ success: !1,
1041
+ error: x(r, "Subscription failed")
1042
+ };
1043
+ }
1044
+ }
1045
+ /**
1046
+ * Check subscription status (for x402 gating)
1047
+ */
1048
+ async checkSubscriptionStatus(e) {
1049
+ if (!this.statusRateLimiter.tryConsume())
1050
+ throw new Error("Rate limit exceeded for subscription status check. Please try again later.");
1051
+ try {
1052
+ return await this.circuitBreaker.execute(async () => await w(
1053
+ async () => {
1054
+ const r = new URLSearchParams({
1055
+ resource: e.resource,
1056
+ userId: e.userId
1057
+ }), a = await this.routeDiscovery.buildUrl(
1058
+ `/paywall/v1/subscription/status?${r.toString()}`
1059
+ );
1060
+ c().debug("[SubscriptionManager] Checking subscription status:", e);
1061
+ const n = await h(a, {
1062
+ method: "GET",
1063
+ headers: {
1064
+ "Content-Type": "application/json"
1065
+ }
1066
+ });
1067
+ if (!n.ok) {
1068
+ const i = await p(
1069
+ n,
1070
+ "Failed to check subscription status"
1071
+ );
1072
+ throw new Error(i);
1073
+ }
1074
+ return await n.json();
1075
+ },
1076
+ { ...g.STANDARD, name: "subscription-status-check" }
1077
+ ));
1078
+ } catch (r) {
1079
+ throw r instanceof m ? (c().error("[SubscriptionManager] Circuit breaker is OPEN for status check"), new Error(
1080
+ "Subscription status service is temporarily unavailable. Please try again in a few moments."
1081
+ )) : r;
1082
+ }
1083
+ }
1084
+ /**
1085
+ * Request a subscription quote for x402 crypto payment
1086
+ */
1087
+ async requestSubscriptionQuote(e, r, a) {
1088
+ if (!this.statusRateLimiter.tryConsume())
1089
+ throw new Error("Rate limit exceeded for subscription quote. Please try again later.");
1090
+ try {
1091
+ return await this.circuitBreaker.execute(async () => await w(
1092
+ async () => {
1093
+ const n = await this.routeDiscovery.buildUrl("/paywall/v1/subscription/quote"), i = {
1094
+ resource: e,
1095
+ interval: r,
1096
+ couponCode: a?.couponCode,
1097
+ intervalDays: a?.intervalDays
1098
+ };
1099
+ c().debug("[SubscriptionManager] Requesting subscription quote:", i);
1100
+ const o = await h(n, {
1101
+ method: "POST",
1102
+ headers: {
1103
+ "Content-Type": "application/json"
1104
+ },
1105
+ body: JSON.stringify(i)
1106
+ });
1107
+ if (o.status !== 402 && !o.ok) {
1108
+ const s = await p(
1109
+ o,
1110
+ "Failed to get subscription quote"
1111
+ );
1112
+ throw new Error(s);
1113
+ }
1114
+ return await o.json();
1115
+ },
1116
+ { ...g.STANDARD, name: "subscription-quote" }
1117
+ ));
1118
+ } catch (n) {
1119
+ throw n instanceof m ? (c().error("[SubscriptionManager] Circuit breaker is OPEN for quote"), new Error(
1120
+ "Subscription quote service is temporarily unavailable. Please try again in a few moments."
1121
+ )) : n;
1122
+ }
1123
+ }
1124
+ /** Cancel a subscription */
1125
+ async cancelSubscription(e) {
1126
+ return this.executeWithResilience(
1127
+ this.sessionRateLimiter,
1128
+ async () => {
1129
+ const r = await this.routeDiscovery.buildUrl("/paywall/v1/subscription/cancel");
1130
+ c().debug("[SubscriptionManager] Canceling subscription:", e);
1131
+ const a = await h(r, {
1132
+ method: "POST",
1133
+ headers: { "Content-Type": "application/json" },
1134
+ body: JSON.stringify(e)
1135
+ });
1136
+ if (!a.ok) throw new Error(await p(a, "Failed to cancel"));
1137
+ return await a.json();
1138
+ },
1139
+ "subscription-cancel",
1140
+ "cancellation"
1141
+ );
1142
+ }
1143
+ /** Get Stripe billing portal URL for subscription management */
1144
+ async getBillingPortalUrl(e) {
1145
+ return this.executeWithResilience(
1146
+ this.statusRateLimiter,
1147
+ async () => {
1148
+ const r = await this.routeDiscovery.buildUrl("/paywall/v1/subscription/portal");
1149
+ c().debug("[SubscriptionManager] Getting billing portal URL:", e);
1150
+ const a = await h(r, {
1151
+ method: "POST",
1152
+ headers: { "Content-Type": "application/json" },
1153
+ body: JSON.stringify(e)
1154
+ });
1155
+ if (!a.ok) throw new Error(await p(a, "Failed to get portal"));
1156
+ return await a.json();
1157
+ },
1158
+ "subscription-portal",
1159
+ "portal"
1160
+ );
1161
+ }
1162
+ /** Activate x402 subscription after payment verification */
1163
+ async activateX402Subscription(e) {
1164
+ return this.executeWithResilience(
1165
+ this.sessionRateLimiter,
1166
+ async () => {
1167
+ const r = await this.routeDiscovery.buildUrl("/paywall/v1/subscription/x402/activate");
1168
+ c().debug("[SubscriptionManager] Activating x402 subscription:", e);
1169
+ const a = await h(r, {
1170
+ method: "POST",
1171
+ headers: { "Content-Type": "application/json" },
1172
+ body: JSON.stringify(e)
1173
+ });
1174
+ if (!a.ok) throw new Error(await p(a, "Failed to activate"));
1175
+ return await a.json();
1176
+ },
1177
+ "subscription-activate",
1178
+ "activation"
1179
+ );
1180
+ }
1181
+ }
1182
+ class lt {
1183
+ routeDiscovery;
1184
+ rateLimiter = P(T.PAYMENT);
1185
+ queryRateLimiter = P(T.QUOTE);
1186
+ circuitBreaker = F({
1187
+ failureThreshold: 5,
1188
+ timeout: 1e4,
1189
+ name: "subscription-change-manager"
1190
+ });
1191
+ constructor(e) {
1192
+ this.routeDiscovery = e;
1193
+ }
1194
+ /** Internal helper: execute with rate limiting, circuit breaker, and retry */
1195
+ async executeWithResilience(e, r, a, n) {
1196
+ if (!e.tryConsume())
1197
+ throw new Error("Rate limit exceeded. Please try again later.");
1198
+ try {
1199
+ return await this.circuitBreaker.execute(
1200
+ () => w(r, { ...g.STANDARD, name: a })
1201
+ );
1202
+ } catch (i) {
1203
+ throw i instanceof m ? (c().error(`[SubscriptionChangeManager] Circuit breaker OPEN for ${n}`), new Error("Service temporarily unavailable. Please try again in a few moments.")) : i;
1204
+ }
1205
+ }
1206
+ /** Change subscription plan (upgrade or downgrade) */
1207
+ async changeSubscription(e) {
1208
+ return this.executeWithResilience(
1209
+ this.rateLimiter,
1210
+ async () => {
1211
+ const r = await this.routeDiscovery.buildUrl("/paywall/v1/subscription/change");
1212
+ c().debug("[SubscriptionChangeManager] Changing subscription:", e);
1213
+ const a = await h(r, {
1214
+ method: "POST",
1215
+ headers: { "Content-Type": "application/json", "Idempotency-Key": C() },
1216
+ body: JSON.stringify(e)
1217
+ });
1218
+ if (!a.ok)
1219
+ throw new Error(await p(a, "Failed to change subscription"));
1220
+ return await a.json();
1221
+ },
1222
+ "subscription-change",
1223
+ "plan change"
1224
+ );
1225
+ }
1226
+ /** Preview subscription change (get proration details) */
1227
+ async previewChange(e) {
1228
+ return this.executeWithResilience(
1229
+ this.queryRateLimiter,
1230
+ async () => {
1231
+ const r = await this.routeDiscovery.buildUrl("/paywall/v1/subscription/change/preview");
1232
+ c().debug("[SubscriptionChangeManager] Previewing subscription change:", e);
1233
+ const a = await h(r, {
1234
+ method: "POST",
1235
+ headers: { "Content-Type": "application/json" },
1236
+ body: JSON.stringify(e)
1237
+ });
1238
+ if (!a.ok)
1239
+ throw new Error(await p(a, "Failed to preview change"));
1240
+ return await a.json();
1241
+ },
1242
+ "subscription-preview",
1243
+ "change preview"
1244
+ );
1245
+ }
1246
+ /** Get full subscription details */
1247
+ async getDetails(e, r) {
1248
+ return this.executeWithResilience(
1249
+ this.queryRateLimiter,
1250
+ async () => {
1251
+ const a = new URLSearchParams({ resource: e, userId: r }), n = await this.routeDiscovery.buildUrl(`/paywall/v1/subscription/details?${a}`);
1252
+ c().debug("[SubscriptionChangeManager] Getting subscription details:", { resource: e, userId: r });
1253
+ const i = await h(n, {
1254
+ method: "GET",
1255
+ headers: { "Content-Type": "application/json" }
1256
+ });
1257
+ if (!i.ok)
1258
+ throw new Error(await p(i, "Failed to get subscription details"));
1259
+ return await i.json();
1260
+ },
1261
+ "subscription-details",
1262
+ "details"
1263
+ );
1264
+ }
1265
+ /** Cancel a subscription */
1266
+ async cancel(e) {
1267
+ return this.executeWithResilience(
1268
+ this.rateLimiter,
1269
+ async () => {
1270
+ const r = await this.routeDiscovery.buildUrl("/paywall/v1/subscription/cancel");
1271
+ c().debug("[SubscriptionChangeManager] Canceling subscription:", e);
1272
+ const a = await h(r, {
1273
+ method: "POST",
1274
+ headers: { "Content-Type": "application/json" },
1275
+ body: JSON.stringify(e)
1276
+ });
1277
+ if (!a.ok)
1278
+ throw new Error(await p(a, "Failed to cancel subscription"));
1279
+ return await a.json();
1280
+ },
1281
+ "subscription-cancel",
1282
+ "cancellation"
1283
+ );
1284
+ }
1285
+ /** Get Stripe billing portal URL */
1286
+ async getBillingPortalUrl(e) {
1287
+ return this.executeWithResilience(
1288
+ this.queryRateLimiter,
1289
+ async () => {
1290
+ const r = await this.routeDiscovery.buildUrl("/paywall/v1/subscription/portal");
1291
+ c().debug("[SubscriptionChangeManager] Getting billing portal URL:", e);
1292
+ const a = await h(r, {
1293
+ method: "POST",
1294
+ headers: { "Content-Type": "application/json" },
1295
+ body: JSON.stringify(e)
1296
+ });
1297
+ if (!a.ok)
1298
+ throw new Error(await p(a, "Failed to get billing portal URL"));
1299
+ return await a.json();
1300
+ },
1301
+ "subscription-portal",
1302
+ "portal"
1303
+ );
1304
+ }
1305
+ }
1306
+ class dt {
1307
+ routeDiscovery;
1308
+ rateLimiter = P(T.PAYMENT);
1309
+ circuitBreaker = F({
1310
+ failureThreshold: 5,
1311
+ timeout: 1e4,
1312
+ name: "credits-manager"
1313
+ });
1314
+ constructor(e) {
1315
+ this.routeDiscovery = e;
1316
+ }
1317
+ async requestQuote(e, r) {
1318
+ if (!this.rateLimiter.tryConsume())
1319
+ throw new Error("Rate limit exceeded for credits quote. Please try again later.");
1320
+ try {
1321
+ return await this.circuitBreaker.execute(async () => await w(
1322
+ async () => {
1323
+ const a = await this.routeDiscovery.buildUrl("/paywall/v1/quote");
1324
+ c().debug("[CreditsManager] Requesting quote for resource:", e);
1325
+ const n = await h(a, {
1326
+ method: "POST",
1327
+ headers: { "Content-Type": "application/json" },
1328
+ body: JSON.stringify({ resource: e, couponCode: r })
1329
+ });
1330
+ if (n.status === 402)
1331
+ return (await n.json()).credits || null;
1332
+ if (!n.ok) {
1333
+ const i = await p(n, "Failed to get credits quote");
1334
+ throw new Error(i);
1335
+ }
1336
+ return null;
1337
+ },
1338
+ { ...g.STANDARD, name: "credits-quote" }
1339
+ ));
1340
+ } catch (a) {
1341
+ throw a instanceof m ? (c().error("[CreditsManager] Circuit breaker is OPEN - credits service unavailable"), new Error("Credits service is temporarily unavailable. Please try again in a few moments.")) : a;
1342
+ }
1343
+ }
1344
+ async requestCartQuote(e, r) {
1345
+ if (!this.rateLimiter.tryConsume())
1346
+ throw new Error("Rate limit exceeded for cart credits quote. Please try again later.");
1347
+ try {
1348
+ return await this.circuitBreaker.execute(async () => await w(
1349
+ async () => {
1350
+ const a = await this.routeDiscovery.buildUrl("/paywall/v1/cart/quote");
1351
+ c().debug("[CreditsManager] Requesting cart quote for items:", e.length);
1352
+ const n = await h(a, {
1353
+ method: "POST",
1354
+ headers: { "Content-Type": "application/json" },
1355
+ body: JSON.stringify({ items: e, couponCode: r })
1356
+ });
1357
+ if (!n.ok) {
1358
+ const o = await p(n, "Failed to get cart credits quote");
1359
+ throw new Error(o);
1360
+ }
1361
+ const i = await n.json();
1362
+ return i.credits ? {
1363
+ cartId: i.cartId,
1364
+ credits: i.credits
1365
+ } : null;
1366
+ },
1367
+ { ...g.STANDARD, name: "credits-cart-quote" }
1368
+ ));
1369
+ } catch (a) {
1370
+ throw a instanceof m ? new Error("Credits service is temporarily unavailable. Please try again in a few moments.") : a;
1371
+ }
1372
+ }
1373
+ /**
1374
+ * Create a hold on user's credits
1375
+ * Requires Authorization header with cedros-login JWT token
1376
+ */
1377
+ async createHold(e) {
1378
+ const { resource: r, couponCode: a, authToken: n } = e;
1379
+ if (!this.rateLimiter.tryConsume())
1380
+ throw new Error("Rate limit exceeded for credits hold. Please try again later.");
1381
+ try {
1382
+ return await this.circuitBreaker.execute(async () => await w(
1383
+ async () => {
1384
+ const i = await this.routeDiscovery.buildUrl("/paywall/v1/credits/hold");
1385
+ c().debug("[CreditsManager] Creating hold for resource:", r);
1386
+ const o = await h(i, {
1387
+ method: "POST",
1388
+ headers: {
1389
+ "Content-Type": "application/json",
1390
+ Authorization: `Bearer ${n}`,
1391
+ "Idempotency-Key": C()
1392
+ },
1393
+ body: JSON.stringify({ resource: r, couponCode: a })
1394
+ });
1395
+ if (!o.ok) {
1396
+ const s = await p(o, "Failed to create credits hold");
1397
+ throw new Error(s);
1398
+ }
1399
+ return await o.json();
1400
+ },
1401
+ { ...g.STANDARD, name: "credits-create-hold" }
1402
+ ));
1403
+ } catch (i) {
1404
+ throw i instanceof m ? new Error("Credits service is temporarily unavailable. Please try again in a few moments.") : i;
1405
+ }
1406
+ }
1407
+ /**
1408
+ * Create a hold on user's credits for a cart
1409
+ * Requires Authorization header with cedros-login JWT token
1410
+ */
1411
+ async createCartHold(e) {
1412
+ const { cartId: r, authToken: a } = e;
1413
+ if (!this.rateLimiter.tryConsume())
1414
+ throw new Error("Rate limit exceeded for cart credits hold. Please try again later.");
1415
+ try {
1416
+ return await this.circuitBreaker.execute(async () => await w(
1417
+ async () => {
1418
+ const n = await this.routeDiscovery.buildUrl(`/paywall/v1/cart/${r}/credits/hold`);
1419
+ c().debug("[CreditsManager] Creating cart hold for cart:", r);
1420
+ const i = await h(n, {
1421
+ method: "POST",
1422
+ headers: {
1423
+ "Content-Type": "application/json",
1424
+ Authorization: `Bearer ${a}`,
1425
+ "Idempotency-Key": C()
1426
+ },
1427
+ body: JSON.stringify({})
1428
+ });
1429
+ if (!i.ok) {
1430
+ const o = await p(i, "Failed to create cart credits hold");
1431
+ throw new Error(o);
1432
+ }
1433
+ return await i.json();
1434
+ },
1435
+ { ...g.STANDARD, name: "credits-create-cart-hold" }
1436
+ ));
1437
+ } catch (n) {
1438
+ throw n instanceof m ? new Error("Credits service is temporarily unavailable. Please try again in a few moments.") : n;
1439
+ }
1440
+ }
1441
+ async authorizePayment(e) {
1442
+ const { resource: r, holdId: a, couponCode: n, authToken: i, metadata: o } = e;
1443
+ if (!this.rateLimiter.tryConsume())
1444
+ return {
1445
+ success: !1,
1446
+ error: "Rate limit exceeded for credits authorization. Please try again later.",
1447
+ errorCode: "rate_limit_exceeded"
1448
+ };
1449
+ try {
1450
+ return await this.circuitBreaker.execute(async () => await w(
1451
+ async () => {
1452
+ const s = await this.routeDiscovery.buildUrl("/paywall/v1/credits/authorize");
1453
+ c().debug("[CreditsManager] Authorizing payment for resource:", r);
1454
+ const l = await h(s, {
1455
+ method: "POST",
1456
+ headers: {
1457
+ "Content-Type": "application/json",
1458
+ Authorization: `Bearer ${i}`,
1459
+ "Idempotency-Key": C()
1460
+ },
1461
+ body: JSON.stringify({
1462
+ resource: r,
1463
+ holdId: a,
1464
+ couponCode: n,
1465
+ ...o && { metadata: o }
1466
+ })
1467
+ });
1468
+ if (!l.ok) {
1469
+ const f = await l.json().catch(() => ({}));
1470
+ return {
1471
+ success: !1,
1472
+ error: f.error?.message || "Credits authorization failed",
1473
+ errorCode: f.error?.code || "authorization_failed"
1474
+ };
1475
+ }
1476
+ return {
1477
+ success: !0,
1478
+ transactionId: (await l.json()).transactionId
1479
+ };
1480
+ },
1481
+ { ...g.STANDARD, name: "credits-authorize" }
1482
+ ));
1483
+ } catch (s) {
1484
+ return s instanceof m ? {
1485
+ success: !1,
1486
+ error: "Credits service is temporarily unavailable. Please try again in a few moments.",
1487
+ errorCode: "service_unavailable"
1488
+ } : {
1489
+ success: !1,
1490
+ error: x(s, "Credits authorization failed"),
1491
+ errorCode: "authorization_failed"
1492
+ };
1493
+ }
1494
+ }
1495
+ async authorizeCartPayment(e) {
1496
+ const { cartId: r, holdId: a, authToken: n, metadata: i } = e;
1497
+ if (!this.rateLimiter.tryConsume())
1498
+ return {
1499
+ success: !1,
1500
+ error: "Rate limit exceeded for cart credits authorization. Please try again later.",
1501
+ errorCode: "rate_limit_exceeded"
1502
+ };
1503
+ try {
1504
+ return await this.circuitBreaker.execute(async () => await w(
1505
+ async () => {
1506
+ const o = await this.routeDiscovery.buildUrl(`/paywall/v1/cart/${r}/credits/authorize`);
1507
+ c().debug("[CreditsManager] Authorizing cart payment for cart:", r);
1508
+ const s = await h(o, {
1509
+ method: "POST",
1510
+ headers: {
1511
+ "Content-Type": "application/json",
1512
+ Authorization: `Bearer ${n}`,
1513
+ "Idempotency-Key": C()
1514
+ },
1515
+ body: JSON.stringify({
1516
+ holdId: a,
1517
+ ...i && { metadata: i }
1518
+ })
1519
+ });
1520
+ if (!s.ok) {
1521
+ const A = await s.json().catch((f) => (c().error("[CreditsManager] Failed to parse error response JSON:", f, {
1522
+ cartId: r,
1523
+ status: s.status,
1524
+ statusText: s.statusText
1525
+ }), {}));
1526
+ return {
1527
+ success: !1,
1528
+ error: A.error?.message || "Cart credits authorization failed",
1529
+ errorCode: A.error?.code || "authorization_failed"
1530
+ };
1531
+ }
1532
+ return {
1533
+ success: !0,
1534
+ transactionId: (await s.json()).transactionId
1535
+ };
1536
+ },
1537
+ { ...g.STANDARD, name: "credits-cart-authorize" }
1538
+ ));
1539
+ } catch (o) {
1540
+ return o instanceof m ? {
1541
+ success: !1,
1542
+ error: "Credits service is temporarily unavailable. Please try again in a few moments.",
1543
+ errorCode: "service_unavailable"
1544
+ } : {
1545
+ success: !1,
1546
+ error: x(o, "Cart credits authorization failed"),
1547
+ errorCode: "authorization_failed"
1548
+ };
1549
+ }
1550
+ }
1551
+ /**
1552
+ * Process a complete credits payment (convenience method)
1553
+ * Combines createHold + authorizePayment in one call
1554
+ *
1555
+ * @param resource - Resource being purchased
1556
+ * @param authToken - JWT token from cedros-login
1557
+ * @param couponCode - Optional coupon code
1558
+ * @param metadata - Optional metadata
1559
+ */
1560
+ async processPayment(e, r, a, n) {
1561
+ try {
1562
+ const i = await this.createHold({ resource: e, couponCode: a, authToken: r }), o = await this.authorizePayment({
1563
+ resource: e,
1564
+ holdId: i.holdId,
1565
+ couponCode: a,
1566
+ authToken: r,
1567
+ metadata: n
1568
+ });
1569
+ return {
1570
+ success: o.success,
1571
+ transactionId: o.transactionId,
1572
+ error: o.error
1573
+ };
1574
+ } catch (i) {
1575
+ return {
1576
+ success: !1,
1577
+ error: x(i, "Credits payment failed")
1578
+ };
1579
+ }
1580
+ }
1581
+ }
1582
+ class ft {
1583
+ serverUrl;
1584
+ routePrefix = null;
1585
+ discoveryPromise = null;
1586
+ maxRetries = 3;
1587
+ baseDelayMs = 1e3;
1588
+ constructor(e) {
1589
+ this.serverUrl = e;
1590
+ }
1591
+ /**
1592
+ * Discover route prefix from backend health endpoint
1593
+ *
1594
+ * DEDUPLICATION: Multiple concurrent calls share the same in-flight request
1595
+ * SECURITY FIX: Only cache on success, retry on failures with exponential backoff
1596
+ * This prevents permanent bricking of payments due to transient failures
1597
+ */
1598
+ async discoverPrefix() {
1599
+ if (this.routePrefix !== null)
1600
+ return this.routePrefix;
1601
+ if (this.discoveryPromise)
1602
+ return this.discoveryPromise;
1603
+ const e = (async () => {
1604
+ let r = 0;
1605
+ for (; r < this.maxRetries; )
1606
+ try {
1607
+ const a = await h(`${this.serverUrl}/cedros-health`);
1608
+ if (!a.ok) {
1609
+ if (a.status >= 400 && a.status < 500)
1610
+ return c().warn(`Route discovery received ${a.status} - not retrying client error`), this.routePrefix = "", "";
1611
+ throw new Error(`Health check returned ${a.status}`);
1612
+ }
1613
+ const i = (await a.json()).routePrefix || "";
1614
+ return this.routePrefix = i, c().debug("Route discovery successful, prefix:", i || "(empty)"), i;
1615
+ } catch (a) {
1616
+ if (r++, r >= this.maxRetries)
1617
+ return c().warn(
1618
+ `Route discovery failed after ${r} attempts, using empty prefix for this request:`,
1619
+ a
1620
+ ), "";
1621
+ const n = this.baseDelayMs * Math.pow(2, r - 1);
1622
+ c().warn(
1623
+ `Route discovery failed (attempt ${r}/${this.maxRetries}), retrying in ${n}ms:`,
1624
+ a
1625
+ ), await new Promise((i) => setTimeout(i, n));
1626
+ }
1627
+ return "";
1628
+ })();
1629
+ this.discoveryPromise = e;
1630
+ try {
1631
+ return await this.discoveryPromise;
1632
+ } finally {
1633
+ this.discoveryPromise === e && (this.discoveryPromise = null);
1634
+ }
1635
+ }
1636
+ /**
1637
+ * Build API URL with discovered prefix
1638
+ */
1639
+ async buildUrl(e) {
1640
+ const r = await this.discoverPrefix(), a = e.startsWith("/") ? e : `/${e}`;
1641
+ return `${this.serverUrl}${r}${a}`;
1642
+ }
1643
+ /**
1644
+ * Reset cached prefix (useful for testing or reconnecting)
1645
+ */
1646
+ reset() {
1647
+ this.routePrefix = null, this.discoveryPromise = null;
1648
+ }
1649
+ }
1650
+ let G = null;
1651
+ async function At() {
1652
+ return G || (G = (await import("./WalletManager-oEjZhaFk.mjs")).WalletManager), G;
1653
+ }
1654
+ const H = /* @__PURE__ */ new Map();
1655
+ function Me(t, e, r, a, n) {
1656
+ return JSON.stringify({
1657
+ stripePublicKey: t,
1658
+ serverUrl: e,
1659
+ solanaCluster: r,
1660
+ solanaEndpoint: a || "",
1661
+ dangerouslyAllowUnknownMint: n || !1
1662
+ });
1663
+ }
1664
+ async function ht(t, e, r, a, n) {
1665
+ const i = Me(
1666
+ t,
1667
+ e,
1668
+ r,
1669
+ a,
1670
+ n
1671
+ );
1672
+ let o = H.get(i);
1673
+ if (o)
1674
+ return o.refCount++, c().debug(
1675
+ `[ManagerCache] Reusing cached managers (refCount: ${o.refCount}):`,
1676
+ { stripePublicKey: t.slice(0, 10) + "...", serverUrl: e }
1677
+ ), o;
1678
+ c().debug(
1679
+ "[ManagerCache] Creating new manager instances:",
1680
+ { stripePublicKey: t.slice(0, 10) + "...", serverUrl: e }
1681
+ );
1682
+ const s = new ft(e), l = new Ze(t, s), A = new ct(s), f = await At(), u = new f(
1683
+ r,
1684
+ a,
1685
+ n ?? !1
1686
+ ), d = new ut(t, s), y = new lt(s), E = new dt(s);
1687
+ return o = {
1688
+ stripeManager: l,
1689
+ x402Manager: A,
1690
+ walletManager: u,
1691
+ subscriptionManager: d,
1692
+ subscriptionChangeManager: y,
1693
+ creditsManager: E,
1694
+ routeDiscovery: s,
1695
+ refCount: 1
1696
+ }, H.set(i, o), o;
1697
+ }
1698
+ function pt(t, e, r, a, n) {
1699
+ const i = Me(
1700
+ t,
1701
+ e,
1702
+ r,
1703
+ a,
1704
+ n
1705
+ ), o = H.get(i);
1706
+ if (!o) {
1707
+ c().warn("[ManagerCache] Attempted to release non-existent managers:", { cacheKey: i });
1708
+ return;
1709
+ }
1710
+ o.refCount--, c().debug(
1711
+ `[ManagerCache] Released manager reference (refCount: ${o.refCount}):`,
1712
+ { stripePublicKey: t.slice(0, 10) + "...", serverUrl: e }
1713
+ ), o.refCount <= 0 && (H.delete(i), c().debug("[ManagerCache] Removed managers from cache (refCount reached 0)"));
1714
+ }
1715
+ const yt = "data:image/webp;base64,UklGRnIIAABXRUJQVlA4WAoAAAAYAAAAOwAAOwAAQUxQSK4BAAABkHPbtrE9+z73/RTbqWw7Lf+BbbNKbTudbZe2qy+VbVv3PmeHj05G6ohg4LaRounNMtN1voB42ABA5R7TNlx5+O7du9e3Tiwb0b4EgFyAOCQM1Z16+DWFUZC7m3uVB2zKQGBhe+77RGHonJffCL1zQuHDxQ1hrEmTatDjHIXOC2MgzpNf1tVJkWgsGhyihI7JIE74aUYp2ITFAoz9QO+ZAs7zanvkEilKbIkMJS5ANwoJmrCodYVOmBqh5zIEJjZc9xods4A4rrPGxGitrJSU71yNyH4Myl7JTEl+5zzYSH9nlkrxHBzxWUzLVEnhh+YI/gq3+UphpvA8m/s7/wg9M4bjFNg/0vplrxQ+rQEDg/xihmT23jxYJZ8UPq8OA5z77Wt405FDR4poSMjiAJhPRxUIu8D+UVonOhfNPEVHPM9juFacwo+1V6kJQ3Y9Sa8ljhPuUvRk4UdNWU9ST3b9n0W3iG5DumdS9y7o3kHVu6/75ii/dbpvrO7brvtPUf2X6f5DVf/dmpxBmauociRVbqbKCXW5qCoHVuXempxf1dZQtXFUbat/yKZTtSUBVlA4INwFAABwGgCdASo8ADwAPm0qj0WkIqEZ+zYAQAbEtgBOmZoZF+E8zGoP3X8VbcdLvma8t+jH0E+YB+ofSA8wH7VdQv0AP75/iOsG9ADy3/Y5/b/91fgI/Y7MOesb0e/q+TUR1vt7VO6mwG0imO70GM5/0P7BX6qelv7EP209lz9oDRea09ZR+SjhX7sBu/ZS7tG917rPgI3Q7XsB7luy2hAg/95C2Z1L362OH1oFziDY/K5gWoSytSAtiKvA/jW1MehBzdLzJfszPPBvGa15IYwIVRTjO2Hz5ZS9HjLMehwAAP64SgjD3qeg6NRe/Ok+iFhrG3pgglCfbam3yBaDUH36sUiQx0PB1ZZyOHq0ky+f97h6tJMvo0p9LkfXecWOFJ8J5G7yRPuL4tzGLT09QulTJw42xp2hd+lMgIa51XoHx/iftn8B2D3k92H5jOQr+uIXFHHK5FpcTG+qGEF+np0LiQa+vdW7/+ZzOLVRf7jR5X3ANPt93Ng92DW7NflVr6kMr88O/v2ZNb0vtgao2Am/R3CDKiNq89f86CT6r2L2g1oTui7H3E1yhSPQpEOz01I3fhfiMMv4weqKuoedxn/xLg5uzHa6Gte4C/dQYkG3ZFSy4CXQtRjftBrjX/Oj+HpSUPDsv0wPW+ml5NbBKDCj2f3SD8TVMf2ZfHrOkR602RVk2UmKC+H0Y9iK6k98vsgPINtz0II8X7Mj2nJkTC6IMLuQ8dNTUq9VXOnhXrdhNZoaH94ePo6baBl3hTGFAnD3/b+gR/vtbqV7wktuX6fpnjeTBe/Drp6z3neeANj/aX4CsU9w67nwYOjZhueCjxaDKUnNjLPjI1e0BoTbcOzOQ0wHJHZJ+Pt608StBu4HiJ8NjH46fnvXL3yiMoSvkAuwCE1AakA+eU1u3unyjl1/MnZQmbp8fzfsfrFesehLPcIkYdCiZ+52QbmINNTjEsvjuBuZRubBE+Laihppsxoo4efGIo0xkw0etu1+yzvkqp88w3pBq0mRl13gnnc+2zl6SmhwgmNFbz+F8qAqmdfJL8iaNSGEWlPlpczDDe62GBZMlBhQmq/XCn/1b+VazHvJXkoIFDF+wktMg+rKfLyfTlXdK0cs+Kn8h+rjMakkf3WLo1TftMLn+O+x/Gat+BGstJrM1xvCSSnHQY+NV4B4gRqyZ55gRNnqN/0lWrATOcHUaGXpkTIM/yxFjxcePcSFo+t2aJ5lShtVukETzRxaIXgRkpROeWQHWpTHOaexmXOzF0b833qJSoXMk2zB/uMrgDzKd7d3ohUz8Ra08WYKlAuMQD08bF4+jUepEspqPLoYLQ73TfmL+1LwKxyTV3gEu6WnxBPWPLnYIGYN9U47ZNlB+NgHgYtKTyii6060RAG+wN32WUVFxCZw0HMHnHFgwxD34L/anlpS7mOrjKgyuGYhFC7iHqTQHuoAO1ekBHV+rndnbETKfa1F7LxNLYq+dmJyytmQrJUCGjelorI1m/TMQNiFVrY4FCI1Gl2W1JsZsw9zA+Bh3JmjkC0H5/0JV6JotNMatJIZ4v5PqwJe3r8xd+FNS3ynccdu+xtVdc27qwVdoomciZD5oXYey9KAFSAKO594sBKZNWUJTLXnt0BJbdF8FkQYvg3DQajYY2p+ixd5Ag7o92gw0pVVDDOP+WQxiEmKqgWJyTBsnsBk2Bxi2Unsv8S/4PmE8Hy/vy+Mij+aTAKZvg716IHfHX0/JMeFfmAnsZ39Q0qkfdPtq6+CxbGZ7wKDsK/8l/MVGuyd6faJFt5wyoOXuNrr3JC9EoBmjcOzkVw/6RNP49poZ1xzsX3q7B4HGfI/XSfRQq3HeZ2j12d0E3gCAube4oExaT1sx/v8F+f61QOsGdSaqM2im6qOGkSRkrRQ7L8hvS8vEYJeVkAbFvX5ov7e/egYYNToMHj651c5/rCVYtB9Ned6GvGN8R0x3t7+lsf8+ofhHRzpyvwxd6c5pREZVOKnXzplhJ61mki4JmAAAABFWElGugAAAEV4aWYAAElJKgAIAAAABgASAQMAAQAAAAEAAAAaAQUAAQAAAFYAAAAbAQUAAQAAAF4AAAAoAQMAAQAAAAIAAAATAgMAAQAAAAEAAABphwQAAQAAAGYAAAAAAAAASAAAAAEAAABIAAAAAQAAAAYAAJAHAAQAAAAwMjEwAZEHAAQAAAABAgMAAKAHAAQAAAAwMTAwAaADAAEAAAD//wAAAqAEAAEAAAA8AAAAA6AEAAEAAAA8AAAAAAAAAA==", mt = "data:image/svg+xml,%3csvg%20width='868'%20height='868'%20viewBox='0%200%20868%20868'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3ccircle%20cx='434'%20cy='434'%20r='434'%20fill='%231B262D'/%3e%3cpath%20fill-rule='evenodd'%20clip-rule='evenodd'%20d='M234.563%20184H640.697C650.387%20184%20659.339%20189.164%20664.172%20197.542L782.495%20402.657C788.631%20413.294%20786.808%20426.72%20778.056%20435.346L452.368%20756.327C441.818%20766.724%20424.846%20766.724%20414.296%20756.327L89.0484%20435.78C80.0927%20426.954%2078.4157%20413.136%2085.0013%20402.433L211.48%20196.884C216.405%20188.879%20225.146%20184%20234.563%20184ZM588.257%20275.577V333.129H472.567V373.032C553.82%20377.296%20614.782%20394.81%20615.234%20415.802L615.231%20459.563C614.779%20480.556%20553.82%20498.069%20472.567%20502.333V600.259H395.746V502.333C314.492%20498.069%20253.531%20480.555%20253.078%20459.563L253.081%20415.802C253.533%20394.81%20314.492%20377.296%20395.746%20373.032V333.129H280.055V275.577H588.257ZM434.156%20472.268C520.868%20472.268%20593.345%20457.459%20611.082%20437.683C596.041%20420.912%20541.636%20407.713%20472.567%20404.089V445.867C460.187%20446.516%20447.336%20446.858%20434.156%20446.858C420.976%20446.858%20408.125%20446.516%20395.746%20445.867V404.089C326.676%20407.713%20272.271%20420.912%20257.23%20437.683C274.968%20457.459%20347.444%20472.268%20434.156%20472.268Z'%20fill='%23009393'/%3e%3c/svg%3e", wt = "data:image/webp;base64,UklGRqwEAABXRUJQVlA4WAoAAAAYAAAAOwAAOwAAQUxQSL8BAAABkGvbtmlLc5997yvbmW19gBnbDm2kjF5UmW3bthXZVZFdZ+81r+87Z1XlEaHIbSNlMstwos4XUBSTLAFQo/u01Zdf/yLDDze3zB/YwADJEoOoJAKg7oTdH4SF+XxiZlMgSESzwAJdVn2iUJzzOUMiLhQKf+/va2FtBLMBuu1zpHcsincUXhtoTKLsCTVX/KF3wrLhPLm/OWzZtjQWfZ7RhYyAC/lxMowpSzJYJAyFkZDQc21FBMUT7BqGjpHxf3m+XlEPUHE/f3vGgPzmw4awRUaTexkyJhwfNShctVgZXyJDXq4CUyjNy6Y4fVOBIkAPR2GcOE7Jm2NQ/RE9YzXht3a5VYvlOX0xF0fy+tp/ozBuQg6DzZYb6Bi7ed4rB5Mp/1Co4cNhLUo1StLxDIDqrynUoRswiF6nFnIxsDpnZ5WBW0GFZ1qZ8HfLDk5txHHsGDpSa6B0cXZEa+DsTr1M+P4qPdXwjynU4+1/a7oN3Sm6G+meSd27oHsHde++7puj+tYpv7G6b7vun6L7l6n+oZp/t7JmUNUqqhpJV5upakJVLaqqgVW1t6rmV401NGMc1djqH4rpIseSfyPFkgAAVlA4IAQCAABQDACdASo8ADwAPm0yk0akIyGhJgzogA2JaQAThroHvLxu+aPf5G2BYxv+B6XHzx6GPon/o+qz/tOAA/TM82gR0vnExWoiQRM36jlg2UIvwCSqySErzuguz9EP2x/7hsNazr91aIworWI7AAD+/TZ+6Ipl444OdT+2wU0Ov+T8oJuVP/vUbT/w1Jsv6Awnl6rvF/xetfOPt3gTQZZi0Y/AOx563J7CJkqTR/fc/n34zyeKzR80fhfv4ef+Hjhz/CX5aQo+58zg/FdE+7bLoophGfG0szI513EH+q+Gc73H1PFdJYf7CF8v5dhr3tMwEVX5Ji2ZxejK8xrf/E6nVXqlA4DrYNRP09InHc+fEqO/fH8xr+rMf4y1F9TOnwVffZblLoTP6lot0m/sh7sTiDQr0mIA8TiHoOffGDG6KzV+B3239udfhzD740gkRi/m53abX0Ku3vAgadgFFqL0vk8M/4aI+cI+0fbLW17mWGeMu21wSRRQiv5iNgGKR3vEGXAItcLDft1uUzWAfbe1X3zK/ymT7bA/76PB6UUknm+Y5MM4osurUXU/k7P38pN/3slnGfpFzjl4c3USY4mH9ZCJYUuC/kGEnq/yRPalPdODNFvW6s8MiQeQejYNRY0LsJ0WXkK8vXiDmihCivYAOPoSovesL7on+WAArDNM/BcQSQvCYABFWElGugAAAEV4aWYAAElJKgAIAAAABgASAQMAAQAAAAEAAAAaAQUAAQAAAFYAAAAbAQUAAQAAAF4AAAAoAQMAAQAAAAIAAAATAgMAAQAAAAEAAABphwQAAQAAAGYAAAAAAAAASAAAAAEAAABIAAAAAQAAAAYAAJAHAAQAAAAwMjEwAZEHAAQAAAABAgMAAKAHAAQAAAAwMTAwAaADAAEAAAD//wAAAqAEAAEAAAA8AAAAA6AEAAEAAAA8AAAAAAAAAA==", gt = "data:image/webp;base64,UklGRtgCAABXRUJQVlA4WAoAAAAIAAAAOwAAOwAAVlA4IPgBAABQCwCdASo8ADwAPm0wk0ekIqGhKBQMqIANiWkADPF3uV2D8VcQGk1mg+P36i9SLnZvYAQxszEWYzEwX1RVkqG/4BGbJgMSHqhKDFsjWsGfPPrvfef11goNmCDDlBJHVVD+8gAA/vu4q03kl+E7FpjtZ2gc8pQ619Hjv9NywoRZ6az43C1wcrRr/lWzJlJhLWMHN0MkVl1ueAf6Hn8StVzeUfMBXOKkgfe2msx7QWR5PnHW/5c6/35yrtWnrURc2q6UYlGin+v8C2dQqexkW6rX2EEijTI9eEQ46PWH3/59fM2AlMvvR2abaRk5XX7V1triQncRxvMfz5YmYDN+PY/ikcZUNaiFucKoUq5riv0eKCezuFNHecE11ojwJqWRSTWpalkz5autXp6vFS+FT1tWUsB/fs1CCOZxaA1vR1grOEaiuKe1RYm7e05psWtqbXLVmm1bA8Ly9PFkVdCbc6hR3UuBBsFGnVeGOUeMn2onnfvYhBMcM9YPxGdQkwZLXOk1VuQSTk01Shf3fZrFyRlFauftFdPYhKXwqrr+meav1P+KLKBVosqmHnFFfgExsQ/rOf3TSd+mOqQfJA+cF+HojNU7nmM3uDkoCBi+//Gqp+gPNNW8M4LFrol8rxE+7WsjqMgfwv1f+Nr25RtG1Wa/KkniRCAAAABFWElGugAAAEV4aWYAAElJKgAIAAAABgASAQMAAQAAAAEAAAAaAQUAAQAAAFYAAAAbAQUAAQAAAF4AAAAoAQMAAQAAAAIAAAATAgMAAQAAAAEAAABphwQAAQAAAGYAAAAAAAAASAAAAAEAAABIAAAAAQAAAAYAAJAHAAQAAAAwMjEwAZEHAAQAAAABAgMAAKAHAAQAAAAwMTAwAaADAAEAAAD//wAAAqAEAAEAAAA8AAAAA6AEAAEAAAA8AAAAAAAAAA==", bt = {
1716
+ EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: {
1717
+ symbol: "USDC",
1718
+ decimals: 6,
1719
+ icon: yt
1720
+ },
1721
+ Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB: {
1722
+ symbol: "USDT",
1723
+ decimals: 6,
1724
+ icon: mt
1725
+ },
1726
+ "2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo": {
1727
+ symbol: "PYUSD",
1728
+ decimals: 6,
1729
+ icon: wt
1730
+ },
1731
+ CASHx9KJUStyftLFWGvEVf59SGeG9sh5FfcnZMVPCASH: {
1732
+ symbol: "CASH",
1733
+ decimals: 6,
1734
+ icon: gt
1735
+ }
1736
+ }, Z = Object.fromEntries(
1737
+ Object.entries(bt).map(([t, e]) => [t, e.symbol])
1738
+ );
1739
+ function vt(t) {
1740
+ return t in Z;
1741
+ }
1742
+ function De(t, e = "token mint", r = !1) {
1743
+ if (!t || t.trim().length === 0)
1744
+ return {
1745
+ isValid: !0,
1746
+ isKnownStablecoin: !1
1747
+ };
1748
+ const a = t.trim();
1749
+ if (vt(a))
1750
+ return {
1751
+ isValid: !0,
1752
+ isKnownStablecoin: !0,
1753
+ symbol: Z[a]
1754
+ };
1755
+ const n = Object.entries(Z).map(([i, o]) => ` ${o}: ${i}`).join(`
1756
+ `);
1757
+ return r ? {
1758
+ isValid: !0,
1759
+ // Allow but warn
1760
+ isKnownStablecoin: !1,
1761
+ warning: [
1762
+ `Warning: Unrecognized token mint address in ${e}`,
1763
+ ` Provided: ${a}`,
1764
+ "",
1765
+ "This token mint does not match any known stablecoin addresses.",
1766
+ "You have set dangerouslyAllowUnknownMint=true, so this will proceed.",
1767
+ "If this is a typo, payments will be sent to the wrong token and funds will be PERMANENTLY LOST.",
1768
+ "",
1769
+ "Known stablecoin mints (mainnet-beta):",
1770
+ n,
1771
+ "",
1772
+ "Double-check your token mint address before deploying to production."
1773
+ ].join(`
1774
+ `)
1775
+ } : {
1776
+ isValid: !1,
1777
+ isKnownStablecoin: !1,
1778
+ error: [
1779
+ `SAFETY ERROR: Unrecognized token mint address in ${e}`,
1780
+ ` Provided: ${a}`,
1781
+ "",
1782
+ "This token mint does not match any known stablecoin addresses.",
1783
+ "Using an unknown token mint can result in PERMANENT LOSS OF FUNDS if it's a typo.",
1784
+ "",
1785
+ "Known stablecoin mints (mainnet-beta):",
1786
+ n,
1787
+ "",
1788
+ "If you are CERTAIN this is the correct mint address (custom token, testnet, or new stablecoin),",
1789
+ "set dangerouslyAllowUnknownMint={true} in your CedrosProvider config:",
1790
+ "",
1791
+ " <CedrosProvider",
1792
+ " config={{",
1793
+ " ...",
1794
+ ' tokenMint: "' + a + '",',
1795
+ " dangerouslyAllowUnknownMint: true, // ⚠️ I have verified this mint address",
1796
+ " }}",
1797
+ " />",
1798
+ "",
1799
+ "⚠️ WARNING: Only enable dangerouslyAllowUnknownMint if you have TRIPLE-CHECKED the mint address."
1800
+ ].join(`
1801
+ `)
1802
+ };
1803
+ }
1804
+ function Ft(t, e = "unknown", r = !1) {
1805
+ return De(t, `X402Requirement (resource: ${e})`, r);
1806
+ }
1807
+ const Et = [
1808
+ "stripePublicKey"
1809
+ ], ue = /* @__PURE__ */ new Set(["mainnet-beta", "devnet", "testnet"]);
1810
+ function Ct() {
1811
+ if (typeof window < "u" && window.location)
1812
+ return window.location.origin;
1813
+ throw new Error(
1814
+ "serverUrl is required in SSR/Node environments. In browser environments, it defaults to window.location.origin"
1815
+ );
1816
+ }
1817
+ function St(t) {
1818
+ const e = [];
1819
+ Et.forEach((a) => {
1820
+ const n = t[a];
1821
+ (typeof n != "string" || n.trim().length === 0) && e.push({
1822
+ field: a,
1823
+ message: "must be a non-empty string"
1824
+ });
1825
+ });
1826
+ let r;
1827
+ if (t.serverUrl !== void 0)
1828
+ typeof t.serverUrl != "string" || t.serverUrl.trim().length === 0 ? (e.push({
1829
+ field: "serverUrl",
1830
+ message: "must be a non-empty string when provided"
1831
+ }), r = "") : r = t.serverUrl;
1832
+ else
1833
+ try {
1834
+ r = Ct();
1835
+ } catch (a) {
1836
+ e.push({
1837
+ field: "serverUrl",
1838
+ message: a instanceof Error ? a.message : "failed to determine default"
1839
+ }), r = "";
1840
+ }
1841
+ if (ue.has(t.solanaCluster) || e.push({
1842
+ field: "solanaCluster",
1843
+ message: `must be one of ${Array.from(ue).join(", ")}`
1844
+ }), t.solanaEndpoint !== void 0 && (typeof t.solanaEndpoint != "string" ? e.push({
1845
+ field: "solanaEndpoint",
1846
+ message: "must be a string when provided"
1847
+ }) : t.solanaEndpoint.trim().length === 0 ? e.push({
1848
+ field: "solanaEndpoint",
1849
+ message: 'must be a non-empty string when provided (e.g., "https://api.mainnet-beta.solana.com")'
1850
+ }) : !t.solanaEndpoint.startsWith("http://") && !t.solanaEndpoint.startsWith("https://") && e.push({
1851
+ field: "solanaEndpoint",
1852
+ message: 'must start with "http://" or "https://" (e.g., "https://api.mainnet-beta.solana.com")'
1853
+ })), t.tokenMint && typeof t.tokenMint != "string" && e.push({
1854
+ field: "tokenMint",
1855
+ message: "must be a string when provided"
1856
+ }), e.length > 0) {
1857
+ const a = e.map((n) => `- ${n.field} ${n.message}`).join(`
1858
+ `);
1859
+ throw new Error(`Invalid Cedros configuration:
1860
+ ${a}`);
1861
+ }
1862
+ if (t.tokenMint) {
1863
+ const a = t.dangerouslyAllowUnknownMint === !0, n = De(t.tokenMint, "CedrosConfig.tokenMint", a);
1864
+ if (!n.isValid && n.error)
1865
+ throw new Error(n.error);
1866
+ n.warning && c().warn(n.warning);
1867
+ }
1868
+ return {
1869
+ ...t,
1870
+ serverUrl: r
1871
+ };
1872
+ }
1873
+ const xt = Object.freeze({
1874
+ surfaceBackground: "rgba(255, 255, 255, 0)",
1875
+ surfaceText: "#111827",
1876
+ surfaceBorder: "rgba(15, 23, 42, 0.08)",
1877
+ stripeBackground: "linear-gradient(135deg, #635bff 0%, #4f46e5 100%)",
1878
+ stripeText: "#ffffff",
1879
+ stripeShadow: "rgba(79, 70, 229, 0.25)",
1880
+ cryptoBackground: "linear-gradient(135deg, #14f195 0%, #9945ff 100%)",
1881
+ cryptoText: "#ffffff",
1882
+ cryptoShadow: "rgba(99, 102, 241, 0.25)",
1883
+ errorBackground: "#fee2e2",
1884
+ errorBorder: "#fca5a5",
1885
+ errorText: "#b91c1c",
1886
+ successBackground: "#dcfce7",
1887
+ successBorder: "#86efac",
1888
+ successText: "#166534",
1889
+ modalOverlay: "rgba(0, 0, 0, 0.5)",
1890
+ modalBackground: "#ffffff",
1891
+ modalBorder: "rgba(15, 23, 42, 0.08)",
1892
+ buttonBorderRadius: "8px",
1893
+ buttonPadding: "0.75rem 1.5rem",
1894
+ buttonFontSize: "1rem",
1895
+ buttonFontWeight: "600"
1896
+ }), Pt = Object.freeze({
1897
+ surfaceBackground: "rgba(17, 24, 39, 0.6)",
1898
+ surfaceText: "#f9fafb",
1899
+ surfaceBorder: "rgba(148, 163, 184, 0.25)",
1900
+ stripeBackground: "linear-gradient(135deg, #4f46e5 0%, #3730a3 100%)",
1901
+ stripeText: "#f5f3ff",
1902
+ stripeShadow: "rgba(99, 102, 241, 0.35)",
1903
+ cryptoBackground: "linear-gradient(135deg, #1dd4a6 0%, #6d28d9 100%)",
1904
+ cryptoText: "#ecfeff",
1905
+ cryptoShadow: "rgba(75, 85, 99, 0.35)",
1906
+ errorBackground: "#7f1d1d",
1907
+ errorBorder: "#fca5a5",
1908
+ errorText: "#fecaca",
1909
+ successBackground: "#14532d",
1910
+ successBorder: "#4ade80",
1911
+ successText: "#bbf7d0",
1912
+ modalOverlay: "rgba(0, 0, 0, 0.75)",
1913
+ modalBackground: "#1f2937",
1914
+ modalBorder: "rgba(148, 163, 184, 0.25)",
1915
+ buttonBorderRadius: "8px",
1916
+ buttonPadding: "0.75rem 1.5rem",
1917
+ buttonFontSize: "1rem",
1918
+ buttonFontWeight: "600"
1919
+ }), Tt = {
1920
+ surfaceBackground: "--cedros-surface-bg",
1921
+ surfaceText: "--cedros-surface-text",
1922
+ surfaceBorder: "--cedros-surface-border",
1923
+ stripeBackground: "--cedros-stripe-bg",
1924
+ stripeText: "--cedros-stripe-text",
1925
+ stripeShadow: "--cedros-stripe-shadow",
1926
+ cryptoBackground: "--cedros-crypto-bg",
1927
+ cryptoText: "--cedros-crypto-text",
1928
+ cryptoShadow: "--cedros-crypto-shadow",
1929
+ errorBackground: "--cedros-error-bg",
1930
+ errorBorder: "--cedros-error-border",
1931
+ errorText: "--cedros-error-text",
1932
+ successBackground: "--cedros-success-bg",
1933
+ successBorder: "--cedros-success-border",
1934
+ successText: "--cedros-success-text",
1935
+ modalOverlay: "--cedros-modal-overlay",
1936
+ modalBackground: "--cedros-modal-bg",
1937
+ modalBorder: "--cedros-modal-border",
1938
+ buttonBorderRadius: "--cedros-button-radius",
1939
+ buttonPadding: "--cedros-button-padding",
1940
+ buttonFontSize: "--cedros-button-font-size",
1941
+ buttonFontWeight: "--cedros-button-font-weight"
1942
+ }, te = le(null);
1943
+ function Rt(t, e) {
1944
+ return {
1945
+ ...t === "dark" ? Pt : xt,
1946
+ ...e
1947
+ };
1948
+ }
1949
+ function kt(t) {
1950
+ const e = Object.entries(t).map(([r, a]) => [
1951
+ Tt[r],
1952
+ a
1953
+ ]);
1954
+ return Object.fromEntries(e);
1955
+ }
1956
+ function Mt({
1957
+ initialMode: t = "light",
1958
+ overrides: e,
1959
+ unstyled: r = !1,
1960
+ children: a
1961
+ }) {
1962
+ const [n, i] = U(t), [o, s] = U(e), l = de(e);
1963
+ k(() => {
1964
+ if (e === l.current)
1965
+ return;
1966
+ (!e || !l.current ? e !== l.current : Object.keys({ ...e, ...l.current }).some(
1967
+ (u) => e[u] !== l.current?.[u]
1968
+ )) && (l.current = e, s(e));
1969
+ }, [e]);
1970
+ const A = K(() => {
1971
+ const f = Rt(n, o), u = r ? {} : kt(f), d = r ? "" : `cedros-theme-root cedros-theme cedros-theme--${n}`;
1972
+ return {
1973
+ mode: n,
1974
+ setMode: i,
1975
+ tokens: f,
1976
+ className: d,
1977
+ style: u,
1978
+ unstyled: r
1979
+ };
1980
+ }, [n, o, r]);
1981
+ return /* @__PURE__ */ J(te.Provider, { value: A, children: a });
1982
+ }
1983
+ function Lt() {
1984
+ const t = _(te);
1985
+ if (!t)
1986
+ throw new Error("useCedrosTheme must be used within CedrosProvider");
1987
+ return t;
1988
+ }
1989
+ function It() {
1990
+ return _(te);
1991
+ }
1992
+ const W = {
1993
+ getAdapters: () => [],
1994
+ cleanup: async () => {
1995
+ },
1996
+ isInitialized: () => !1,
1997
+ getId: () => "stub"
1998
+ };
1999
+ function Dt() {
2000
+ return typeof process < "u" && process.env.NODE_ENV === "development" ? 0 : 2;
2001
+ }
2002
+ const Oe = le(null);
2003
+ function jt({ config: t, children: e }) {
2004
+ const r = K(() => St(t), [t]), [a, n] = U(W), i = de(W);
2005
+ k(() => {
2006
+ let u = !1;
2007
+ return import("./walletPool-BR6etEiq.mjs").then(({ createWalletPool: d }) => {
2008
+ if (u) return;
2009
+ const y = d();
2010
+ i.current = y, n(y);
2011
+ }), () => {
2012
+ u = !0;
2013
+ };
2014
+ }, []);
2015
+ const [o, s] = U(null);
2016
+ k(() => {
2017
+ let u = !1;
2018
+ return import("./solanaCheck-IlYsbXDd.mjs").then(
2019
+ ({ checkSolanaAvailability: d }) => d()
2020
+ ).then((d) => {
2021
+ u || (d.available ? s(void 0) : s(d.error || "Solana dependencies not available"));
2022
+ }), () => {
2023
+ u = !0;
2024
+ };
2025
+ }, []), k(() => {
2026
+ const u = r.logLevel ?? Dt(), d = Ve({
2027
+ level: u,
2028
+ prefix: "[CedrosPay]"
2029
+ });
2030
+ He(d);
2031
+ }, [r.logLevel]), k(() => () => {
2032
+ const u = i.current;
2033
+ u && u !== W && u.cleanup().catch((d) => {
2034
+ c().warn("[CedrosProvider] Wallet pool cleanup failed:", d);
2035
+ });
2036
+ }, []);
2037
+ const [l, A] = U(null);
2038
+ k(() => {
2039
+ let u = !1;
2040
+ const d = r.stripePublicKey, y = r.serverUrl ?? "", E = r.solanaCluster, v = r.solanaEndpoint, R = r.dangerouslyAllowUnknownMint;
2041
+ return ht(d, y, E, v, R).then((V) => {
2042
+ u || A(V);
2043
+ }), () => {
2044
+ u = !0, pt(d, y, E, v, R);
2045
+ };
2046
+ }, [
2047
+ r.stripePublicKey,
2048
+ r.serverUrl,
2049
+ r.solanaCluster,
2050
+ r.solanaEndpoint,
2051
+ r.dangerouslyAllowUnknownMint
2052
+ ]);
2053
+ const f = K(() => l ? {
2054
+ config: r,
2055
+ ...l,
2056
+ walletPool: a,
2057
+ solanaError: o
2058
+ } : null, [r, l, a, o]);
2059
+ return f ? /* @__PURE__ */ J(Oe.Provider, { value: f, children: /* @__PURE__ */ J(
2060
+ Mt,
2061
+ {
2062
+ initialMode: r.theme ?? "light",
2063
+ overrides: r.themeOverrides,
2064
+ unstyled: r.unstyled ?? !1,
2065
+ children: e
2066
+ }
2067
+ ) }) : null;
2068
+ }
2069
+ function Qt() {
2070
+ const t = _(Oe);
2071
+ if (!t)
2072
+ throw new Error("useCedrosContext must be used within CedrosProvider");
2073
+ return t;
2074
+ }
2075
+ export {
2076
+ jt as C,
2077
+ Z as K,
2078
+ ze as L,
2079
+ T as R,
2080
+ bt as S,
2081
+ Lt as a,
2082
+ F as b,
2083
+ P as c,
2084
+ Je as d,
2085
+ m as e,
2086
+ Ut as f,
2087
+ g,
2088
+ ye as h,
2089
+ c as i,
2090
+ Ve as j,
2091
+ Ft as k,
2092
+ ce as l,
2093
+ x as m,
2094
+ De as n,
2095
+ h as o,
2096
+ It as p,
2097
+ w as r,
2098
+ Qt as u,
2099
+ St as v
2100
+ };