@cedros/pay-react 1.0.3 → 1.0.5

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