@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.
- package/dist/CedrosContext-C2v_s8cc.js +6 -0
- package/dist/CedrosContext-D7nh5-Zh.mjs +2100 -0
- package/dist/WalletManager-B5KLZK2D.js +1 -0
- package/dist/WalletManager-oEjZhaFk.mjs +219 -0
- package/dist/components/CedrosPay.d.ts.map +1 -1
- package/dist/context/CedrosContext.d.ts +9 -3
- package/dist/context/CedrosContext.d.ts.map +1 -1
- package/dist/crypto-only.d.ts +9 -19
- package/dist/crypto-only.d.ts.map +1 -1
- package/dist/crypto-only.js +1 -1
- package/dist/crypto-only.mjs +766 -32
- package/dist/index-BFt38o8Q.mjs +88 -0
- package/dist/{index-CUoeIbXT.mjs → index-DjnqYAvN.mjs} +10300 -9055
- package/dist/index-WcOlBYZJ.js +1 -0
- package/dist/index-cW1q6Jp0.js +136 -0
- package/dist/index.d.ts +1 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +68 -75
- package/dist/managers/ManagerCache.d.ts +2 -2
- package/dist/managers/ManagerCache.d.ts.map +1 -1
- package/dist/pay-react.css +1 -1
- package/dist/{sections-TiollkCu.mjs → sections-DN09osp3.mjs} +2 -2
- package/dist/{sections-D7gSCYck.js → sections-DT8Vsm7s.js} +1 -1
- package/dist/solanaCheck-BS3QTE63.js +6 -0
- package/dist/solanaCheck-IlYsbXDd.mjs +27 -0
- package/dist/stripe-only.d.ts +4 -21
- package/dist/stripe-only.d.ts.map +1 -1
- package/dist/stripe-only.js +1 -1
- package/dist/stripe-only.mjs +71 -29
- package/dist/testing/index.js +1 -1
- package/dist/testing/index.mjs +1 -1
- package/dist/types/componentOptions.d.ts +15 -2
- package/dist/types/componentOptions.d.ts.map +1 -1
- package/dist/utils/index.d.ts +0 -1
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/walletPool-BR6etEiq.mjs +67 -0
- package/dist/walletPool-BZyAG4YS.js +1 -0
- package/package.json +6 -1
- package/dist/CedrosContext-DUT3cLZg.mjs +0 -2474
- package/dist/CedrosContext-efFL4kQz.js +0 -11
- package/dist/index-CWbWPgXt.js +0 -136
- package/dist/styles-C4-_hbgr.js +0 -1
- package/dist/styles-QcAsIVWl.mjs +0 -1909
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"use strict";const J=require("react/jsx-runtime"),y=require("react"),S=require("./uuid-C5B8o31X.js");var ue="https://js.stripe.com/v3",Ue=/^https:\/\/js\.stripe\.com\/v3\/?(\?.*)?$/;var Ne=function(){for(var e=document.querySelectorAll('script[src^="'.concat(ue,'"]')),r=0;r<e.length;r++){var a=e[r];if(Ue.test(a.src))return a}return null},re=function(e){var r="",a=document.createElement("script");a.src="".concat(ue).concat(r);var n=document.head||document.body;if(!n)throw new Error("Expected document.body not to be null. Stripe.js requires a <body> element.");return n.appendChild(a),a},Ie=function(e,r){!e||!e._registerWrapper||e._registerWrapper({name:"stripe-js",version:"4.6.0",startTime:r})},B=null,L=null,F=null,Le=function(e){return function(){e(new Error("Failed to load Stripe.js"))}},Fe=function(e,r){return function(){window.Stripe?e(window.Stripe):r(new Error("Stripe.js not available"))}},je=function(e){return B!==null?B:(B=new Promise(function(r,a){if(typeof window>"u"||typeof document>"u"){r(null);return}if(window.Stripe){r(window.Stripe);return}try{var n=Ne();if(!(n&&e)){if(!n)n=re(e);else if(n&&F!==null&&L!==null){var i;n.removeEventListener("load",F),n.removeEventListener("error",L),(i=n.parentNode)===null||i===void 0||i.removeChild(n),n=re(e)}}F=Fe(r,a),L=Le(a),n.addEventListener("load",F),n.addEventListener("error",L)}catch(o){a(o);return}}),B.catch(function(r){return B=null,Promise.reject(r)}))},Qe=function(e,r,a){if(e===null)return null;var n=e.apply(void 0,r);return Ie(n,a),n},U,le=!1,de=function(){return U||(U=je(null).catch(function(e){return U=null,Promise.reject(e)}),U)};Promise.resolve().then(function(){return de()}).catch(function(t){le||console.warn(t)});var fe=function(){for(var e=arguments.length,r=new Array(e),a=0;a<e;a++)r[a]=arguments[a];le=!0;var n=Date.now();return de().then(function(i){return Qe(i,r,n)})},Ae=(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))(Ae||{});class Z{config;constructor(e){this.config=e}setLevel(e){this.config.level=e}getLevel(){return this.config.level}debug(...e){this.config.level<=0&&this.log("DEBUG",console.log,e)}info(...e){this.config.level<=1&&this.log("INFO",console.info,e)}warn(...e){this.config.level<=2&&this.log("WARN",console.warn,e)}error(...e){this.config.level<=3&&this.log("ERROR",console.error,e)}log(e,r,a){const n=this.config.prefix?`${this.config.prefix} `:"",i=new Date().toISOString();r(`[${i}] ${n}[${e}]`,...a)}}const qe=()=>typeof process<"u"&&process.env.NODE_ENV==="development"?0:2;let Q=null;function c(){return Q||(Q=new Z({level:qe(),prefix:"[CedrosPay]"})),Q}function ze(t){Q=t}function he(t){return new Z(t)}function x(t,e){return t instanceof Error?t.message:typeof t=="string"?t:e}const He={service_unavailable:"Service temporarily unavailable. Please try again later or contact support.",server_insufficient_funds:"Service temporarily unavailable. Please try again later or contact support.",insufficient_funds_token:"Insufficient token balance in your wallet. Please add more tokens and try again.",insufficient_funds_sol:"Insufficient SOL for transaction fees. Please add some SOL to your wallet and try again.",insufficient_amount:"Payment amount is insufficient. Please check the required amount.",invalid_signature:"Transaction signature is invalid. Please try again.",send_failed:"Failed to send transaction. Please try again or contact support.",timeout:"Transaction timed out. Please check the blockchain explorer or try again."};async function p(t,e,r=!1){try{const a=await t.json();if(r&&a.verificationError){c().debug(`Payment verification failed: ${a.verificationError.code}`);const n=a.verificationError.code;return He[n]||a.verificationError.message||e}return typeof a.error=="string"?a.error:a.error&&typeof a.error=="object"&&"message"in a.error?a.error.message:e}catch{return await t.text()||e}}const We=15e3;async function h(t,e={},r=We){const a=new AbortController,n=e.signal;if(n?.aborted)throw a.abort(),new DOMException("The operation was aborted","AbortError");const i=setTimeout(()=>a.abort(),r);let o=null;n&&(o=()=>a.abort(),n.addEventListener("abort",o));try{return await fetch(t,{...e,signal:a.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?n?.aborted?s:new Error(`Request timeout after ${r}ms`):s}finally{clearTimeout(i),n&&o&&n.removeEventListener("abort",o)}}function T(t){const{maxRequests:e,windowMs:r}=t;let a=e,n=Date.now();const i=e/r;function o(){const u=Date.now(),d=u-n;if(d>0){const w=d*i;a=Math.min(e,a+w),n=u}}function s(){return o(),a>=1?(a-=1,!0):!1}function l(){return o(),Math.floor(a)}function A(){if(o(),a>=1)return 0;const d=(1-a)/i;return Math.ceil(d)}function f(){a=e,n=Date.now()}return{tryConsume:s,getAvailableTokens:l,getTimeUntilRefill:A,reset:f}}const P={PAYMENT:{maxRequests:10,windowMs:6e4},QUOTE:{maxRequests:30,windowMs:6e4},STRICT:{maxRequests:5,windowMs:6e4},PERMISSIVE:{maxRequests:100,windowMs:6e4}};var ye=(t=>(t.CLOSED="CLOSED",t.OPEN="OPEN",t.HALF_OPEN="HALF_OPEN",t))(ye||{});class m extends Error{constructor(e){super(e),this.name="CircuitBreakerOpenError"}}function D(t){const{failureThreshold:e,timeout:r,name:a="circuit-breaker"}=t;let n="CLOSED",i=0,o=0,s=0,l=null,A=null,f=null;function u(){n==="OPEN"&&f!==null&&Date.now()>=f&&(c().debug(`[CircuitBreaker:${a}] Transitioning OPEN → HALF_OPEN (timeout expired)`),n="HALF_OPEN",f=null)}function d(){A=Date.now(),o++,n==="HALF_OPEN"?(c().debug(`[CircuitBreaker:${a}] Success in HALF_OPEN → CLOSED`),n="CLOSED",i=0):n==="CLOSED"&&(i=0)}function w(I){l=Date.now(),i++,c().warn(`[CircuitBreaker:${a}] Failure recorded (${i}/${e}):`,I.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)}async function C(I){if(u(),n==="OPEN"){s++;const R=f?Math.ceil((f-Date.now())/1e3):0;throw new m(`Circuit breaker is OPEN. Service is unavailable. Retry in ${R}s.`)}try{const R=await I();return d(),R}catch(R){throw w(R instanceof Error?R:new Error(String(R))),R}}function E(){return u(),n}function k(){return u(),{state:n,failures:i,successes:o,rejections:s,lastFailureTime:l,lastSuccessTime:A}}function W(){c().debug(`[CircuitBreaker:${a}] Manual reset → CLOSED`),n="CLOSED",i=0,o=0,s=0,l=null,A=null,f=null}function Be(){c().warn(`[CircuitBreaker:${a}] Manual trip → OPEN`),n="OPEN",f=Date.now()+r}return{execute:C,getState:E,getStats:k,reset:W,trip:Be}}const Ve={STRICT:{failureThreshold:3,timeout:6e4},STANDARD:{failureThreshold:5,timeout:3e4},LENIENT:{failureThreshold:10,timeout:15e3}};function Ge(t,e){if(e>=3)return!1;const r=t.message.toLowerCase();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)}function Je(t,e,r,a,n){const i=e*Math.pow(r,t),o=Math.min(i,a);if(n){const s=Math.random()*o;return Math.floor(s)}return Math.floor(o)}function Ke(t){return new Promise(e=>setTimeout(e,t))}async function g(t,e={}){const{maxRetries:r=3,initialDelayMs:a=1e3,backoffFactor:n=2,maxDelayMs:i=3e4,jitter:o=!0,shouldRetry:s=Ge,name:l="retry"}=e;let A=null,f=0;for(let u=0;u<=r;u++)try{const d=await t();return u>0&&c().debug(`[Retry:${l}] Succeeded on attempt ${u+1}/${r+1} after ${f}ms`),d}catch(d){A=d instanceof Error?d:new Error(String(d));const w=u===r,C=s(A,u);if(w||!C)throw c().warn(`[Retry:${l}] Failed on attempt ${u+1}/${r+1}. ${w?"No more retries.":"Error not retryable."}`),A;const E=Je(u,a,n,i,o);f+=E,c().warn(`[Retry:${l}] Attempt ${u+1}/${r+1} failed: ${A.message}. Retrying in ${E}ms...`),await Ke(E)}throw A||new Error("Retry failed with no error")}const b={QUICK:{maxRetries:3,initialDelayMs:1e3,backoffFactor:2,maxDelayMs:1e4},STANDARD:{maxRetries:3,initialDelayMs:2e3,backoffFactor:2,maxDelayMs:3e4},AGGRESSIVE:{maxRetries:5,initialDelayMs:500,backoffFactor:1.5,maxDelayMs:15e3},PATIENT:{maxRetries:5,initialDelayMs:5e3,backoffFactor:2,maxDelayMs:6e4}};class Ye{stripe=null;publicKey;routeDiscovery;rateLimiter=T(P.PAYMENT);circuitBreaker=D({failureThreshold:5,timeout:1e4,name:"stripe-manager"});constructor(e,r){this.publicKey=e,this.routeDiscovery=r}async initialize(){if(!this.stripe&&(this.stripe=await fe(this.publicKey),!this.stripe))throw new Error("Failed to initialize Stripe")}async createSession(e){if(!this.rateLimiter.tryConsume())throw new Error("Rate limit exceeded for Stripe session creation. Please try again later.");try{return await this.circuitBreaker.execute(async()=>await g(async()=>{const r=await this.routeDiscovery.buildUrl("/paywall/v1/stripe-session");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");const a=await h(r,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":S.generateUUID()},body:JSON.stringify(e)});if(!a.ok){const n=await p(a,"Failed to create Stripe session");throw new Error(n)}return await a.json()},{...b.STANDARD,name:"stripe-create-session"}))}catch(r){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}}async redirectToCheckout(e){if(this.stripe||await this.initialize(),!this.stripe)return{success:!1,error:"Stripe not initialized"};const r=await this.stripe.redirectToCheckout({sessionId:e});return r.error?{success:!1,error:r.error.message}:{success:!0}}async processPayment(e){try{const r=await this.createSession(e);return await this.redirectToCheckout(r.sessionId)}catch(r){return{success:!1,error:x(r,"Unknown error")}}}async processCartCheckout(e){const{items:r,successUrl:a,cancelUrl:n,metadata:i,customerEmail:o,couponCode:s}=e;if(!this.rateLimiter.tryConsume())return{success:!1,error:"Rate limit exceeded for cart checkout. Please try again later."};try{const l=await this.circuitBreaker.execute(async()=>await g(async()=>{const A=await this.routeDiscovery.buildUrl("/paywall/v1/cart/checkout"),f={items:r,successUrl:a,cancelUrl:n,metadata:i,customerEmail:o,coupon:s,couponCode:s},u=await h(A,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":S.generateUUID()},body:JSON.stringify(f)});if(!u.ok){const d=await p(u,"Failed to create cart checkout session");throw new Error(d)}return await u.json()},{...b.STANDARD,name:"stripe-cart-checkout"}));return await this.redirectToCheckout(l.sessionId)}catch(l){return l instanceof m?{success:!1,error:"Stripe payment service is temporarily unavailable. Please try again in a few moments."}:{success:!1,error:x(l,"Cart checkout failed")}}}}const pe="3.7.8",Xe=pe,O=typeof Buffer=="function",ae=typeof TextDecoder=="function"?new TextDecoder:void 0,ne=typeof TextEncoder=="function"?new TextEncoder:void 0,Ze="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",N=Array.prototype.slice.call(Ze),j=(t=>{let e={};return t.forEach((r,a)=>e[r]=a),e})(N),_e=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,v=String.fromCharCode.bind(String),ie=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):t=>new Uint8Array(Array.prototype.slice.call(t,0)),me=t=>t.replace(/=/g,"").replace(/[+\/]/g,e=>e=="+"?"-":"_"),we=t=>t.replace(/[^A-Za-z0-9\+\/]/g,""),ge=t=>{let e,r,a,n,i="";const o=t.length%3;for(let s=0;s<t.length;){if((r=t.charCodeAt(s++))>255||(a=t.charCodeAt(s++))>255||(n=t.charCodeAt(s++))>255)throw new TypeError("invalid character found");e=r<<16|a<<8|n,i+=N[e>>18&63]+N[e>>12&63]+N[e>>6&63]+N[e&63]}return o?i.slice(0,o-3)+"===".substring(o):i},_=typeof btoa=="function"?t=>btoa(t):O?t=>Buffer.from(t,"binary").toString("base64"):ge,K=O?t=>Buffer.from(t).toString("base64"):t=>{let r=[];for(let a=0,n=t.length;a<n;a+=4096)r.push(v.apply(null,t.subarray(a,a+4096)));return _(r.join(""))},q=(t,e=!1)=>e?me(K(t)):K(t),$e=t=>{if(t.length<2){var e=t.charCodeAt(0);return e<128?t:e<2048?v(192|e>>>6)+v(128|e&63):v(224|e>>>12&15)+v(128|e>>>6&63)+v(128|e&63)}else{var e=65536+(t.charCodeAt(0)-55296)*1024+(t.charCodeAt(1)-56320);return v(240|e>>>18&7)+v(128|e>>>12&63)+v(128|e>>>6&63)+v(128|e&63)}},et=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,be=t=>t.replace(et,$e),oe=O?t=>Buffer.from(t,"utf8").toString("base64"):ne?t=>K(ne.encode(t)):t=>_(be(t)),M=(t,e=!1)=>e?me(oe(t)):oe(t),se=t=>M(t,!0),tt=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,rt=t=>{switch(t.length){case 4:var e=(7&t.charCodeAt(0))<<18|(63&t.charCodeAt(1))<<12|(63&t.charCodeAt(2))<<6|63&t.charCodeAt(3),r=e-65536;return v((r>>>10)+55296)+v((r&1023)+56320);case 3:return v((15&t.charCodeAt(0))<<12|(63&t.charCodeAt(1))<<6|63&t.charCodeAt(2));default:return v((31&t.charCodeAt(0))<<6|63&t.charCodeAt(1))}},ve=t=>t.replace(tt,rt),Ee=t=>{if(t=t.replace(/\s+/g,""),!_e.test(t))throw new TypeError("malformed base64.");t+="==".slice(2-(t.length&3));let e,r,a,n=[];for(let i=0;i<t.length;)e=j[t.charAt(i++)]<<18|j[t.charAt(i++)]<<12|(r=j[t.charAt(i++)])<<6|(a=j[t.charAt(i++)]),r===64?n.push(v(e>>16&255)):a===64?n.push(v(e>>16&255,e>>8&255)):n.push(v(e>>16&255,e>>8&255,e&255));return n.join("")},$=typeof atob=="function"?t=>atob(we(t)):O?t=>Buffer.from(t,"base64").toString("binary"):Ee,Ce=O?t=>ie(Buffer.from(t,"base64")):t=>ie($(t).split("").map(e=>e.charCodeAt(0))),Se=t=>Ce(xe(t)),at=O?t=>Buffer.from(t,"base64").toString("utf8"):ae?t=>ae.decode(Ce(t)):t=>ve($(t)),xe=t=>we(t.replace(/[-_]/g,e=>e=="-"?"+":"/")),Y=t=>at(xe(t)),nt=t=>{if(typeof t!="string")return!1;const e=t.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(e)||!/[^\s0-9a-zA-Z\-_]/.test(e)},Te=t=>({value:t,enumerable:!1,writable:!0,configurable:!0}),Pe=function(){const t=(e,r)=>Object.defineProperty(String.prototype,e,Te(r));t("fromBase64",function(){return Y(this)}),t("toBase64",function(e){return M(this,e)}),t("toBase64URI",function(){return M(this,!0)}),t("toBase64URL",function(){return M(this,!0)}),t("toUint8Array",function(){return Se(this)})},Re=function(){const t=(e,r)=>Object.defineProperty(Uint8Array.prototype,e,Te(r));t("toBase64",function(e){return q(this,e)}),t("toBase64URI",function(){return q(this,!0)}),t("toBase64URL",function(){return q(this,!0)})},it=()=>{Pe(),Re()},X={version:pe,VERSION:Xe,atob:$,atobPolyfill:Ee,btoa:_,btoaPolyfill:ge,fromBase64:Y,toBase64:M,encode:M,encodeURI:se,encodeURL:se,utob:be,btou:ve,decode:Y,isValid:nt,fromUint8Array:q,toUint8Array:Se,extendString:Pe,extendUint8Array:Re,extendBuiltins:it};class ot{routeDiscovery;quoteRateLimiter=T(P.QUOTE);verifyRateLimiter=T(P.PAYMENT);circuitBreaker=D({failureThreshold:5,timeout:1e4,name:"x402-manager"});constructor(e){this.routeDiscovery=e}async requestQuote(e){const{resource:r,couponCode:a}=e;if(!this.quoteRateLimiter.tryConsume())throw new Error("Rate limit exceeded for quote requests. Please try again later.");try{return await this.circuitBreaker.execute(async()=>await g(async()=>{const n="/paywall/v1/quote";c().debug("[X402Manager] Requesting quote",a?"with coupon":"without coupon");const i=await this.routeDiscovery.buildUrl(n),o=await h(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({resource:r,couponCode:a||null})});if(o.status!==402)throw new Error(`Expected 402 status, got ${o.status}`);const s=await o.json();if(s.crypto)return s.crypto;if(s.accepts&&s.accepts.length>0)return s.accepts[0];throw new Error("Invalid x402 response: missing crypto or accepts field")},{...b.QUICK,name:"x402-quote"}))}catch(n){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}}async requestCartQuote(e){const{items:r,metadata:a,couponCode:n}=e;if(!this.quoteRateLimiter.tryConsume())throw new Error("Rate limit exceeded for cart quote requests. Please try again later.");try{return await this.circuitBreaker.execute(async()=>await g(async()=>{const i=await this.routeDiscovery.buildUrl("/paywall/v1/cart/quote"),o={items:r,metadata:a,coupon:n,couponCode:n},s=await h(i,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":S.generateUUID()},body:JSON.stringify(o)});if(s.status!==402&&!s.ok){const l=await p(s,"Failed to get cart quote");throw new Error(l)}return await s.json()},{...b.QUICK,name:"x402-cart-quote"}))}catch(i){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}}buildPaymentHeader(e){const r=JSON.stringify(e);return X.encode(r)}parseSettlementResponse(e){const r=e.headers.get("X-PAYMENT-RESPONSE");if(!r)return null;try{const a=X.decode(r),n=JSON.parse(a);return typeof n.success!="boolean"?(c().error("Invalid settlement response: missing success field"),null):n}catch(a){return c().error("Failed to parse settlement response:",a),null}}async submitPayment(e){const{resource:r,payload:a,couponCode:n,metadata:i,resourceType:o="regular"}=e;if(!this.verifyRateLimiter.tryConsume())return{success:!1,error:"Rate limit exceeded for payment verification. Please try again later."};try{return await this.circuitBreaker.execute(async()=>await g(async()=>{const l={...a,payload:{...a.payload,resource:r,resourceType:o,metadata:{...a.payload.metadata||{},...i||{},...n?{couponCode:n}:{}}}},A=this.buildPaymentHeader(l),f="/paywall/v1/verify";c().debug("[X402Manager] Submitting payment",{resourceType:o,hasCoupon:!!n,hasMetadata:!!i});const u=await this.routeDiscovery.buildUrl(f),d=await h(u,{method:"POST",headers:{"Content-Type":"application/json","X-PAYMENT":A,"Idempotency-Key":S.generateUUID()}});if(d.ok){const{settlement:C,transactionId:E}=await this.handlePaymentVerification(d,a.payload.signature);return{success:!0,transactionId:E,settlement:C||void 0}}return{success:!1,error:await p(d,"Payment verification failed",!0)}},{...b.STANDARD,name:"x402-verify"}))}catch(s){return s instanceof m?{success:!1,error:"Payment verification service is temporarily unavailable. Please try again in a few moments."}:{success:!1,error:x(s,"Unknown error")}}}async buildGaslessTransaction(e){const{resourceId:r,userWallet:a,feePayer:n,couponCode:i}=e;if(!this.quoteRateLimiter.tryConsume())throw new Error("Rate limit exceeded for gasless transaction requests. Please try again later.");try{return await this.circuitBreaker.execute(async()=>await g(async()=>{const o=await this.routeDiscovery.buildUrl("/paywall/v1/gasless-transaction"),s=await h(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({resourceId:r,userWallet:a,feePayer:n,couponCode:i})});if(!s.ok){const l=await p(s,"Failed to build gasless transaction");throw new Error(l)}return await s.json()},{...b.QUICK,name:"x402-gasless-build"}))}catch(o){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}}async submitGaslessTransaction(e){const{resource:r,partialTx:a,couponCode:n,metadata:i,resourceType:o="regular",requirement:s}=e;if(!this.verifyRateLimiter.tryConsume())return{success:!1,error:"Rate limit exceeded for gasless transaction verification. Please try again later."};try{return await this.circuitBreaker.execute(async()=>await g(async()=>{const A={x402Version:0,scheme:s?.scheme||"solana-spl-transfer",network:s?.network||"mainnet-beta",payload:{signature:"",transaction:a,feePayer:s?.extra?.feePayer||"",resource:r,resourceType:o,metadata:{...i||{},...n?{couponCode:n}:{}}}},f=this.buildPaymentHeader(A),d=await this.routeDiscovery.buildUrl("/paywall/v1/verify"),w=await h(d,{method:"POST",headers:{"Content-Type":"application/json","X-PAYMENT":f,"Idempotency-Key":S.generateUUID()}});if(w.ok){const{settlement:E,transactionId:k}=await this.handlePaymentVerification(w,"gasless-tx");return{success:!0,transactionId:k,settlement:E||void 0}}return{success:!1,error:await p(w,"Gasless transaction failed",!0)}},{...b.STANDARD,name:"x402-gasless-verify"}))}catch(l){return l instanceof m?{success:!1,error:"Gasless transaction verification service is temporarily unavailable. Please try again in a few moments."}:{success:!1,error:x(l,"Unknown error")}}}async handlePaymentVerification(e,r){const a=this.parseSettlementResponse(e),n=e.headers.get("Content-Type")||"";let i=r;if(n.includes("application/json"))try{i=(await e.json()).signature||r}catch(o){c().warn("Failed to parse JSON response body:",o)}return{settlement:a,transactionId:i}}validateRequirement(e){return!!(e.scheme&&e.network&&e.maxAmountRequired&&e.resource&&e.payTo&&e.asset&&e.maxTimeoutSeconds>0)}}class st{stripe=null;publicKey;routeDiscovery;sessionRateLimiter=T(P.PAYMENT);statusRateLimiter=T(P.QUOTE);circuitBreaker=D({failureThreshold:5,timeout:1e4,name:"subscription-manager"});constructor(e,r){this.publicKey=e,this.routeDiscovery=r}async initialize(){if(!this.stripe&&(this.stripe=await fe(this.publicKey),!this.stripe))throw new Error("Failed to initialize Stripe")}async executeWithResilience(e,r,a,n){if(!e.tryConsume())throw new Error("Rate limit exceeded. Please try again later.");try{return await this.circuitBreaker.execute(()=>g(r,{...b.STANDARD,name:a}))}catch(i){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}}async createSubscriptionSession(e){if(!this.sessionRateLimiter.tryConsume())throw new Error("Rate limit exceeded for subscription session creation. Please try again later.");try{return await this.circuitBreaker.execute(async()=>await g(async()=>{const r=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/stripe-session");c().debug("[SubscriptionManager] Creating subscription session:",{resource:e.resource,interval:e.interval,trialDays:e.trialDays});const a=await h(r,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":S.generateUUID()},body:JSON.stringify(e)});if(!a.ok){const n=await p(a,"Failed to create subscription session");throw new Error(n)}return await a.json()},{...b.STANDARD,name:"subscription-create-session"}))}catch(r){throw r instanceof m?(c().error("[SubscriptionManager] Circuit breaker is OPEN - service unavailable"),new Error("Subscription service is temporarily unavailable. Please try again in a few moments.")):r}}async redirectToCheckout(e){if(this.stripe||await this.initialize(),!this.stripe)return{success:!1,error:"Stripe not initialized"};const r=await this.stripe.redirectToCheckout({sessionId:e});return r.error?{success:!1,error:r.error.message}:{success:!0,transactionId:e}}async processSubscription(e){try{const r=await this.createSubscriptionSession(e);return await this.redirectToCheckout(r.sessionId)}catch(r){return{success:!1,error:x(r,"Subscription failed")}}}async checkSubscriptionStatus(e){if(!this.statusRateLimiter.tryConsume())throw new Error("Rate limit exceeded for subscription status check. Please try again later.");try{return await this.circuitBreaker.execute(async()=>await g(async()=>{const r=new URLSearchParams({resource:e.resource,userId:e.userId}),a=await this.routeDiscovery.buildUrl(`/paywall/v1/subscription/status?${r.toString()}`);c().debug("[SubscriptionManager] Checking subscription status:",e);const n=await h(a,{method:"GET",headers:{"Content-Type":"application/json"}});if(!n.ok){const i=await p(n,"Failed to check subscription status");throw new Error(i)}return await n.json()},{...b.STANDARD,name:"subscription-status-check"}))}catch(r){throw r instanceof m?(c().error("[SubscriptionManager] Circuit breaker is OPEN for status check"),new Error("Subscription status service is temporarily unavailable. Please try again in a few moments.")):r}}async requestSubscriptionQuote(e,r,a){if(!this.statusRateLimiter.tryConsume())throw new Error("Rate limit exceeded for subscription quote. Please try again later.");try{return await this.circuitBreaker.execute(async()=>await g(async()=>{const n=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/quote"),i={resource:e,interval:r,couponCode:a?.couponCode,intervalDays:a?.intervalDays};c().debug("[SubscriptionManager] Requesting subscription quote:",i);const o=await h(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(o.status!==402&&!o.ok){const s=await p(o,"Failed to get subscription quote");throw new Error(s)}return await o.json()},{...b.STANDARD,name:"subscription-quote"}))}catch(n){throw n instanceof m?(c().error("[SubscriptionManager] Circuit breaker is OPEN for quote"),new Error("Subscription quote service is temporarily unavailable. Please try again in a few moments.")):n}}async cancelSubscription(e){return this.executeWithResilience(this.sessionRateLimiter,async()=>{const r=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/cancel");c().debug("[SubscriptionManager] Canceling subscription:",e);const a=await h(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!a.ok)throw new Error(await p(a,"Failed to cancel"));return await a.json()},"subscription-cancel","cancellation")}async getBillingPortalUrl(e){return this.executeWithResilience(this.statusRateLimiter,async()=>{const r=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/portal");c().debug("[SubscriptionManager] Getting billing portal URL:",e);const a=await h(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!a.ok)throw new Error(await p(a,"Failed to get portal"));return await a.json()},"subscription-portal","portal")}async activateX402Subscription(e){return this.executeWithResilience(this.sessionRateLimiter,async()=>{const r=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/x402/activate");c().debug("[SubscriptionManager] Activating x402 subscription:",e);const a=await h(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!a.ok)throw new Error(await p(a,"Failed to activate"));return await a.json()},"subscription-activate","activation")}}class ct{routeDiscovery;rateLimiter=T(P.PAYMENT);queryRateLimiter=T(P.QUOTE);circuitBreaker=D({failureThreshold:5,timeout:1e4,name:"subscription-change-manager"});constructor(e){this.routeDiscovery=e}async executeWithResilience(e,r,a,n){if(!e.tryConsume())throw new Error("Rate limit exceeded. Please try again later.");try{return await this.circuitBreaker.execute(()=>g(r,{...b.STANDARD,name:a}))}catch(i){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}}async changeSubscription(e){return this.executeWithResilience(this.rateLimiter,async()=>{const r=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/change");c().debug("[SubscriptionChangeManager] Changing subscription:",e);const a=await h(r,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":S.generateUUID()},body:JSON.stringify(e)});if(!a.ok)throw new Error(await p(a,"Failed to change subscription"));return await a.json()},"subscription-change","plan change")}async previewChange(e){return this.executeWithResilience(this.queryRateLimiter,async()=>{const r=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/change/preview");c().debug("[SubscriptionChangeManager] Previewing subscription change:",e);const a=await h(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!a.ok)throw new Error(await p(a,"Failed to preview change"));return await a.json()},"subscription-preview","change preview")}async getDetails(e,r){return this.executeWithResilience(this.queryRateLimiter,async()=>{const a=new URLSearchParams({resource:e,userId:r}),n=await this.routeDiscovery.buildUrl(`/paywall/v1/subscription/details?${a}`);c().debug("[SubscriptionChangeManager] Getting subscription details:",{resource:e,userId:r});const i=await h(n,{method:"GET",headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(await p(i,"Failed to get subscription details"));return await i.json()},"subscription-details","details")}async cancel(e){return this.executeWithResilience(this.rateLimiter,async()=>{const r=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/cancel");c().debug("[SubscriptionChangeManager] Canceling subscription:",e);const a=await h(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!a.ok)throw new Error(await p(a,"Failed to cancel subscription"));return await a.json()},"subscription-cancel","cancellation")}async getBillingPortalUrl(e){return this.executeWithResilience(this.queryRateLimiter,async()=>{const r=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/portal");c().debug("[SubscriptionChangeManager] Getting billing portal URL:",e);const a=await h(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!a.ok)throw new Error(await p(a,"Failed to get billing portal URL"));return await a.json()},"subscription-portal","portal")}}class ut{routeDiscovery;rateLimiter=T(P.PAYMENT);circuitBreaker=D({failureThreshold:5,timeout:1e4,name:"credits-manager"});constructor(e){this.routeDiscovery=e}async requestQuote(e,r){if(!this.rateLimiter.tryConsume())throw new Error("Rate limit exceeded for credits quote. Please try again later.");try{return await this.circuitBreaker.execute(async()=>await g(async()=>{const a=await this.routeDiscovery.buildUrl("/paywall/v1/quote");c().debug("[CreditsManager] Requesting quote for resource:",e);const n=await h(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({resource:e,couponCode:r})});if(n.status===402)return(await n.json()).credits||null;if(!n.ok){const i=await p(n,"Failed to get credits quote");throw new Error(i)}return null},{...b.STANDARD,name:"credits-quote"}))}catch(a){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}}async requestCartQuote(e,r){if(!this.rateLimiter.tryConsume())throw new Error("Rate limit exceeded for cart credits quote. Please try again later.");try{return await this.circuitBreaker.execute(async()=>await g(async()=>{const a=await this.routeDiscovery.buildUrl("/paywall/v1/cart/quote");c().debug("[CreditsManager] Requesting cart quote for items:",e.length);const n=await h(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({items:e,couponCode:r})});if(!n.ok){const o=await p(n,"Failed to get cart credits quote");throw new Error(o)}const i=await n.json();return i.credits?{cartId:i.cartId,credits:i.credits}:null},{...b.STANDARD,name:"credits-cart-quote"}))}catch(a){throw a instanceof m?new Error("Credits service is temporarily unavailable. Please try again in a few moments."):a}}async createHold(e){const{resource:r,couponCode:a,authToken:n}=e;if(!this.rateLimiter.tryConsume())throw new Error("Rate limit exceeded for credits hold. Please try again later.");try{return await this.circuitBreaker.execute(async()=>await g(async()=>{const i=await this.routeDiscovery.buildUrl("/paywall/v1/credits/hold");c().debug("[CreditsManager] Creating hold for resource:",r);const o=await h(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,"Idempotency-Key":S.generateUUID()},body:JSON.stringify({resource:r,couponCode:a})});if(!o.ok){const s=await p(o,"Failed to create credits hold");throw new Error(s)}return await o.json()},{...b.STANDARD,name:"credits-create-hold"}))}catch(i){throw i instanceof m?new Error("Credits service is temporarily unavailable. Please try again in a few moments."):i}}async createCartHold(e){const{cartId:r,authToken:a}=e;if(!this.rateLimiter.tryConsume())throw new Error("Rate limit exceeded for cart credits hold. Please try again later.");try{return await this.circuitBreaker.execute(async()=>await g(async()=>{const n=await this.routeDiscovery.buildUrl(`/paywall/v1/cart/${r}/credits/hold`);c().debug("[CreditsManager] Creating cart hold for cart:",r);const i=await h(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`,"Idempotency-Key":S.generateUUID()},body:JSON.stringify({})});if(!i.ok){const o=await p(i,"Failed to create cart credits hold");throw new Error(o)}return await i.json()},{...b.STANDARD,name:"credits-create-cart-hold"}))}catch(n){throw n instanceof m?new Error("Credits service is temporarily unavailable. Please try again in a few moments."):n}}async authorizePayment(e){const{resource:r,holdId:a,couponCode:n,authToken:i,metadata:o}=e;if(!this.rateLimiter.tryConsume())return{success:!1,error:"Rate limit exceeded for credits authorization. Please try again later.",errorCode:"rate_limit_exceeded"};try{return await this.circuitBreaker.execute(async()=>await g(async()=>{const s=await this.routeDiscovery.buildUrl("/paywall/v1/credits/authorize");c().debug("[CreditsManager] Authorizing payment for resource:",r);const l=await h(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`,"Idempotency-Key":S.generateUUID()},body:JSON.stringify({resource:r,holdId:a,couponCode:n,...o&&{metadata:o}})});if(!l.ok){const f=await l.json().catch(()=>({}));return{success:!1,error:f.error?.message||"Credits authorization failed",errorCode:f.error?.code||"authorization_failed"}}return{success:!0,transactionId:(await l.json()).transactionId}},{...b.STANDARD,name:"credits-authorize"}))}catch(s){return s instanceof m?{success:!1,error:"Credits service is temporarily unavailable. Please try again in a few moments.",errorCode:"service_unavailable"}:{success:!1,error:x(s,"Credits authorization failed"),errorCode:"authorization_failed"}}}async authorizeCartPayment(e){const{cartId:r,holdId:a,authToken:n,metadata:i}=e;if(!this.rateLimiter.tryConsume())return{success:!1,error:"Rate limit exceeded for cart credits authorization. Please try again later.",errorCode:"rate_limit_exceeded"};try{return await this.circuitBreaker.execute(async()=>await g(async()=>{const o=await this.routeDiscovery.buildUrl(`/paywall/v1/cart/${r}/credits/authorize`);c().debug("[CreditsManager] Authorizing cart payment for cart:",r);const s=await h(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,"Idempotency-Key":S.generateUUID()},body:JSON.stringify({holdId:a,...i&&{metadata:i}})});if(!s.ok){const A=await s.json().catch(f=>(c().error("[CreditsManager] Failed to parse error response JSON:",f,{cartId:r,status:s.status,statusText:s.statusText}),{}));return{success:!1,error:A.error?.message||"Cart credits authorization failed",errorCode:A.error?.code||"authorization_failed"}}return{success:!0,transactionId:(await s.json()).transactionId}},{...b.STANDARD,name:"credits-cart-authorize"}))}catch(o){return o instanceof m?{success:!1,error:"Credits service is temporarily unavailable. Please try again in a few moments.",errorCode:"service_unavailable"}:{success:!1,error:x(o,"Cart credits authorization failed"),errorCode:"authorization_failed"}}}async processPayment(e,r,a,n){try{const i=await this.createHold({resource:e,couponCode:a,authToken:r}),o=await this.authorizePayment({resource:e,holdId:i.holdId,couponCode:a,authToken:r,metadata:n});return{success:o.success,transactionId:o.transactionId,error:o.error}}catch(i){return{success:!1,error:x(i,"Credits payment failed")}}}}class lt{serverUrl;routePrefix=null;discoveryPromise=null;maxRetries=3;baseDelayMs=1e3;constructor(e){this.serverUrl=e}async discoverPrefix(){if(this.routePrefix!==null)return this.routePrefix;if(this.discoveryPromise)return this.discoveryPromise;const e=(async()=>{let r=0;for(;r<this.maxRetries;)try{const a=await h(`${this.serverUrl}/cedros-health`);if(!a.ok){if(a.status>=400&&a.status<500)return c().warn(`Route discovery received ${a.status} - not retrying client error`),this.routePrefix="","";throw new Error(`Health check returned ${a.status}`)}const i=(await a.json()).routePrefix||"";return this.routePrefix=i,c().debug("Route discovery successful, prefix:",i||"(empty)"),i}catch(a){if(r++,r>=this.maxRetries)return c().warn(`Route discovery failed after ${r} attempts, using empty prefix for this request:`,a),"";const n=this.baseDelayMs*Math.pow(2,r-1);c().warn(`Route discovery failed (attempt ${r}/${this.maxRetries}), retrying in ${n}ms:`,a),await new Promise(i=>setTimeout(i,n))}return""})();this.discoveryPromise=e;try{return await this.discoveryPromise}finally{this.discoveryPromise===e&&(this.discoveryPromise=null)}}async buildUrl(e){const r=await this.discoverPrefix(),a=e.startsWith("/")?e:`/${e}`;return`${this.serverUrl}${r}${a}`}reset(){this.routePrefix=null,this.discoveryPromise=null}}let V=null;async function dt(){return V||(V=(await Promise.resolve().then(()=>require("./WalletManager-B5KLZK2D.js"))).WalletManager),V}const z=new Map;function ke(t,e,r,a,n){return JSON.stringify({stripePublicKey:t,serverUrl:e,solanaCluster:r,solanaEndpoint:a||"",dangerouslyAllowUnknownMint:n||!1})}async function ft(t,e,r,a,n){const i=ke(t,e,r,a,n);let o=z.get(i);if(o)return o.refCount++,c().debug(`[ManagerCache] Reusing cached managers (refCount: ${o.refCount}):`,{stripePublicKey:t.slice(0,10)+"...",serverUrl:e}),o;c().debug("[ManagerCache] Creating new manager instances:",{stripePublicKey:t.slice(0,10)+"...",serverUrl:e});const s=new lt(e),l=new Ye(t,s),A=new ot(s),f=await dt(),u=new f(r,a,n??!1),d=new st(t,s),w=new ct(s),C=new ut(s);return o={stripeManager:l,x402Manager:A,walletManager:u,subscriptionManager:d,subscriptionChangeManager:w,creditsManager:C,routeDiscovery:s,refCount:1},z.set(i,o),o}function At(t,e,r,a,n){const i=ke(t,e,r,a,n),o=z.get(i);if(!o){c().warn("[ManagerCache] Attempted to release non-existent managers:",{cacheKey:i});return}o.refCount--,c().debug(`[ManagerCache] Released manager reference (refCount: ${o.refCount}):`,{stripePublicKey:t.slice(0,10)+"...",serverUrl:e}),o.refCount<=0&&(z.delete(i),c().debug("[ManagerCache] Removed managers from cache (refCount reached 0)"))}const ht="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/ZS7tG917rPgI3Q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zKd7d3ohUz8Ra08WYKlAuMQD08bF4+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==",yt="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",pt="data:image/webp;base64,UklGRqwEAABXRUJQVlA4WAoAAAAYAAAAOwAAOwAAQUxQSL8BAAABkGvbtmlLc5997yvbmW19gBnbDm2kjF5UmW3bthXZVZFdZ+81r+87Z1XlEaHIbSNlMstwos4XUBSTLAFQo/u01Zdf/yLDDze3zB/YwADJEoOoJAKg7oTdH4SF+XxiZlMgSESzwAJdVn2iUJzzOUMiLhQKf+/va2FtBLMBuu1zpHcsincUXhtoTKLsCTVX/KF3wrLhPLm/OWzZtjQWfZ7RhYyAC/lxMowpSzJYJAyFkZDQc21FBMUT7BqGjpHxf3m+XlEPUHE/f3vGgPzmw4awRUaTexkyJhwfNShctVgZXyJDXq4CUyjNy6Y4fVOB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AaADAAEAAAD//wAAAqAEAAEAAAA8AAAAA6AEAAEAAAA8AAAAAAAAAA==",Me={EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v:{symbol:"USDC",decimals:6,icon:ht},Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB:{symbol:"USDT",decimals:6,icon:yt},"2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo":{symbol:"PYUSD",decimals:6,icon:pt},CASHx9KJUStyftLFWGvEVf59SGeG9sh5FfcnZMVPCASH:{symbol:"CASH",decimals:6,icon:mt}},H=Object.fromEntries(Object.entries(Me).map(([t,e])=>[t,e.symbol]));function wt(t){return t in H}function ee(t,e="token mint",r=!1){if(!t||t.trim().length===0)return{isValid:!0,isKnownStablecoin:!1};const a=t.trim();if(wt(a))return{isValid:!0,isKnownStablecoin:!0,symbol:H[a]};const n=Object.entries(H).map(([i,o])=>` ${o}: ${i}`).join(`
|
|
2
|
+
`);return r?{isValid:!0,isKnownStablecoin:!1,warning:[`Warning: Unrecognized token mint address in ${e}`,` Provided: ${a}`,"","This token mint does not match any known stablecoin addresses.","You have set dangerouslyAllowUnknownMint=true, so this will proceed.","If this is a typo, payments will be sent to the wrong token and funds will be PERMANENTLY LOST.","","Known stablecoin mints (mainnet-beta):",n,"","Double-check your token mint address before deploying to production."].join(`
|
|
3
|
+
`)}:{isValid:!1,isKnownStablecoin:!1,error:[`SAFETY ERROR: Unrecognized token mint address in ${e}`,` Provided: ${a}`,"","This token mint does not match any known stablecoin addresses.","Using an unknown token mint can result in PERMANENT LOSS OF FUNDS if it's a typo.","","Known stablecoin mints (mainnet-beta):",n,"","If you are CERTAIN this is the correct mint address (custom token, testnet, or new stablecoin),","set dangerouslyAllowUnknownMint={true} in your CedrosProvider config:",""," <CedrosProvider"," config={{"," ...",' tokenMint: "'+a+'",'," dangerouslyAllowUnknownMint: true, // ⚠️ I have verified this mint address"," }}"," />","","⚠️ WARNING: Only enable dangerouslyAllowUnknownMint if you have TRIPLE-CHECKED the mint address."].join(`
|
|
4
|
+
`)}}function gt(t,e="unknown",r=!1){return ee(t,`X402Requirement (resource: ${e})`,r)}const bt=["stripePublicKey"],ce=new Set(["mainnet-beta","devnet","testnet"]);function vt(){if(typeof window<"u"&&window.location)return window.location.origin;throw new Error("serverUrl is required in SSR/Node environments. In browser environments, it defaults to window.location.origin")}function De(t){const e=[];bt.forEach(a=>{const n=t[a];(typeof n!="string"||n.trim().length===0)&&e.push({field:a,message:"must be a non-empty string"})});let r;if(t.serverUrl!==void 0)typeof t.serverUrl!="string"||t.serverUrl.trim().length===0?(e.push({field:"serverUrl",message:"must be a non-empty string when provided"}),r=""):r=t.serverUrl;else try{r=vt()}catch(a){e.push({field:"serverUrl",message:a instanceof Error?a.message:"failed to determine default"}),r=""}if(ce.has(t.solanaCluster)||e.push({field:"solanaCluster",message:`must be one of ${Array.from(ce).join(", ")}`}),t.solanaEndpoint!==void 0&&(typeof t.solanaEndpoint!="string"?e.push({field:"solanaEndpoint",message:"must be a string when provided"}):t.solanaEndpoint.trim().length===0?e.push({field:"solanaEndpoint",message:'must be a non-empty string when provided (e.g., "https://api.mainnet-beta.solana.com")'}):!t.solanaEndpoint.startsWith("http://")&&!t.solanaEndpoint.startsWith("https://")&&e.push({field:"solanaEndpoint",message:'must start with "http://" or "https://" (e.g., "https://api.mainnet-beta.solana.com")'})),t.tokenMint&&typeof t.tokenMint!="string"&&e.push({field:"tokenMint",message:"must be a string when provided"}),e.length>0){const a=e.map(n=>`- ${n.field} ${n.message}`).join(`
|
|
5
|
+
`);throw new Error(`Invalid Cedros configuration:
|
|
6
|
+
${a}`)}if(t.tokenMint){const a=t.dangerouslyAllowUnknownMint===!0,n=ee(t.tokenMint,"CedrosConfig.tokenMint",a);if(!n.isValid&&n.error)throw new Error(n.error);n.warning&&c().warn(n.warning)}return{...t,serverUrl:r}}const Et=Object.freeze({surfaceBackground:"rgba(255, 255, 255, 0)",surfaceText:"#111827",surfaceBorder:"rgba(15, 23, 42, 0.08)",stripeBackground:"linear-gradient(135deg, #635bff 0%, #4f46e5 100%)",stripeText:"#ffffff",stripeShadow:"rgba(79, 70, 229, 0.25)",cryptoBackground:"linear-gradient(135deg, #14f195 0%, #9945ff 100%)",cryptoText:"#ffffff",cryptoShadow:"rgba(99, 102, 241, 0.25)",errorBackground:"#fee2e2",errorBorder:"#fca5a5",errorText:"#b91c1c",successBackground:"#dcfce7",successBorder:"#86efac",successText:"#166534",modalOverlay:"rgba(0, 0, 0, 0.5)",modalBackground:"#ffffff",modalBorder:"rgba(15, 23, 42, 0.08)",buttonBorderRadius:"8px",buttonPadding:"0.75rem 1.5rem",buttonFontSize:"1rem",buttonFontWeight:"600"}),Ct=Object.freeze({surfaceBackground:"rgba(17, 24, 39, 0.6)",surfaceText:"#f9fafb",surfaceBorder:"rgba(148, 163, 184, 0.25)",stripeBackground:"linear-gradient(135deg, #4f46e5 0%, #3730a3 100%)",stripeText:"#f5f3ff",stripeShadow:"rgba(99, 102, 241, 0.35)",cryptoBackground:"linear-gradient(135deg, #1dd4a6 0%, #6d28d9 100%)",cryptoText:"#ecfeff",cryptoShadow:"rgba(75, 85, 99, 0.35)",errorBackground:"#7f1d1d",errorBorder:"#fca5a5",errorText:"#fecaca",successBackground:"#14532d",successBorder:"#4ade80",successText:"#bbf7d0",modalOverlay:"rgba(0, 0, 0, 0.75)",modalBackground:"#1f2937",modalBorder:"rgba(148, 163, 184, 0.25)",buttonBorderRadius:"8px",buttonPadding:"0.75rem 1.5rem",buttonFontSize:"1rem",buttonFontWeight:"600"}),St={surfaceBackground:"--cedros-surface-bg",surfaceText:"--cedros-surface-text",surfaceBorder:"--cedros-surface-border",stripeBackground:"--cedros-stripe-bg",stripeText:"--cedros-stripe-text",stripeShadow:"--cedros-stripe-shadow",cryptoBackground:"--cedros-crypto-bg",cryptoText:"--cedros-crypto-text",cryptoShadow:"--cedros-crypto-shadow",errorBackground:"--cedros-error-bg",errorBorder:"--cedros-error-border",errorText:"--cedros-error-text",successBackground:"--cedros-success-bg",successBorder:"--cedros-success-border",successText:"--cedros-success-text",modalOverlay:"--cedros-modal-overlay",modalBackground:"--cedros-modal-bg",modalBorder:"--cedros-modal-border",buttonBorderRadius:"--cedros-button-radius",buttonPadding:"--cedros-button-padding",buttonFontSize:"--cedros-button-font-size",buttonFontWeight:"--cedros-button-font-weight"},te=y.createContext(null);function xt(t,e){return{...t==="dark"?Ct:Et,...e}}function Tt(t){const e=Object.entries(t).map(([r,a])=>[St[r],a]);return Object.fromEntries(e)}function Pt({initialMode:t="light",overrides:e,unstyled:r=!1,children:a}){const[n,i]=y.useState(t),[o,s]=y.useState(e),l=y.useRef(e);y.useEffect(()=>{if(e===l.current)return;(!e||!l.current?e!==l.current:Object.keys({...e,...l.current}).some(u=>e[u]!==l.current?.[u]))&&(l.current=e,s(e))},[e]);const A=y.useMemo(()=>{const f=xt(n,o),u=r?{}:Tt(f),d=r?"":`cedros-theme-root cedros-theme cedros-theme--${n}`;return{mode:n,setMode:i,tokens:f,className:d,style:u,unstyled:r}},[n,o,r]);return J.jsx(te.Provider,{value:A,children:a})}function Rt(){const t=y.useContext(te);if(!t)throw new Error("useCedrosTheme must be used within CedrosProvider");return t}function kt(){return y.useContext(te)}const G={getAdapters:()=>[],cleanup:async()=>{},isInitialized:()=>!1,getId:()=>"stub"};function Mt(){return typeof process<"u"&&process.env.NODE_ENV==="development"?0:2}const Oe=y.createContext(null);function Dt({config:t,children:e}){const r=y.useMemo(()=>De(t),[t]),[a,n]=y.useState(G),i=y.useRef(G);y.useEffect(()=>{let u=!1;return Promise.resolve().then(()=>require("./walletPool-BZyAG4YS.js")).then(({createWalletPool:d})=>{if(u)return;const w=d();i.current=w,n(w)}),()=>{u=!0}},[]);const[o,s]=y.useState(null);y.useEffect(()=>{let u=!1;return Promise.resolve().then(()=>require("./solanaCheck-BS3QTE63.js")).then(({checkSolanaAvailability:d})=>d()).then(d=>{u||(d.available?s(void 0):s(d.error||"Solana dependencies not available"))}),()=>{u=!0}},[]),y.useEffect(()=>{const u=r.logLevel??Mt(),d=he({level:u,prefix:"[CedrosPay]"});ze(d)},[r.logLevel]),y.useEffect(()=>()=>{const u=i.current;u&&u!==G&&u.cleanup().catch(d=>{c().warn("[CedrosProvider] Wallet pool cleanup failed:",d)})},[]);const[l,A]=y.useState(null);y.useEffect(()=>{let u=!1;const d=r.stripePublicKey,w=r.serverUrl??"",C=r.solanaCluster,E=r.solanaEndpoint,k=r.dangerouslyAllowUnknownMint;return ft(d,w,C,E,k).then(W=>{u||A(W)}),()=>{u=!0,At(d,w,C,E,k)}},[r.stripePublicKey,r.serverUrl,r.solanaCluster,r.solanaEndpoint,r.dangerouslyAllowUnknownMint]);const f=y.useMemo(()=>l?{config:r,...l,walletPool:a,solanaError:o}:null,[r,l,a,o]);return f?J.jsx(Oe.Provider,{value:f,children:J.jsx(Pt,{initialMode:r.theme??"light",overrides:r.themeOverrides,unstyled:r.unstyled??!1,children:e})}):null}function Ot(){const t=y.useContext(Oe);if(!t)throw new Error("useCedrosContext must be used within CedrosProvider");return t}exports.CIRCUIT_BREAKER_PRESETS=Ve;exports.CedrosProvider=Dt;exports.CircuitBreakerOpenError=m;exports.CircuitState=ye;exports.KNOWN_STABLECOINS=H;exports.LogLevel=Ae;exports.Logger=Z;exports.RATE_LIMITER_PRESETS=P;exports.RETRY_PRESETS=b;exports.STABLECOIN_METADATA=Me;exports.createCircuitBreaker=D;exports.createLogger=he;exports.createRateLimiter=T;exports.fetchWithTimeout=h;exports.formatError=x;exports.gBase64=X;exports.getLogger=c;exports.retryWithBackoff=g;exports.useCedrosContext=Ot;exports.useCedrosTheme=Rt;exports.useCedrosThemeOptional=kt;exports.validateConfig=De;exports.validateTokenMint=ee;exports.validateX402Asset=gt;
|