@paypercut/checkout-js 1.2.18 → 1.2.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +669 -396
- package/dist/index.cjs +4733 -185
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +300 -2
- package/dist/index.mjs +4733 -186
- package/dist/index.mjs.map +1 -1
- package/dist/paypercut-checkout.iife.min.js +1 -1
- package/dist/paypercut-checkout.iife.min.js.map +1 -1
- package/licenses/Geist-OFL-1.1.txt +92 -0
- package/package.json +14 -4
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var PaypercutCheckout=function(){"use strict";class e{constructor(){this.handlers=new Map}on(e,t){return this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t),()=>this.off(e,t)}once(e,t){const i=(...n)=>{t(...n),this.off(e,i)};return this.on(e,i)}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,...t){this.handlers.get(e)?.forEach(i=>{try{i(...t)}catch(t){console.error(`[Emitter] Error in ${e} handler:`,t)}})}hasListeners(e){const t=this.handlers.get(e);return!!t&&t.size>0}clear(){this.handlers.clear()}}const t={version:"1.2.18",defaultCheckoutOrigin:"https://buy.paypercut.io",defaultApiOrigin:"https://api.paypercut.io",defaultVaultApiUrl:"https://api.basistheory.com",allowedOrigins:["https://buy.paypercut.io"]};function i(e){return t.allowedOrigins.includes(e)}function n(e){return t.defaultCheckoutOrigin}function a(e){return t.defaultApiOrigin}function s(){return t.defaultVaultApiUrl}function o(){const e="undefined"!=typeof window?window.visualViewport:void 0,t="undefined"!=typeof document?document.documentElement:void 0;return{width:e?.width||window.innerWidth||t?.clientWidth||window.screen?.width||460,height:e?.height||window.innerHeight||t?.clientHeight||window.screen?.height||680}}function r(e,t,i){const n=Math.min(t,i);return Math.min(Math.max(e,n),i)}class l{constructor(e){this.options=e,this.modal=null,this.shell=null,this.iframe=null,this.frameSize={},this.resizeHandler=null,this.pendingData=null}show(e){this.close(),this.modal=function(e){const t=document.createElement("div"),i=o();return t.id=e,Object.assign(t.style,{position:"fixed",top:"0",left:"0",width:`${i.width}px`,height:`${i.height}px`,minHeight:`${i.height}px`,display:"flex",alignItems:"center",justifyContent:"center",zIndex:"999999",background:"rgba(0, 0, 0, 0.56)",padding:"16px",boxSizing:"border-box",overflow:"hidden"}),t}(this.options.modalId),this.shell=function(e){const t=document.createElement("div");Object.assign(t.style,{position:"relative",borderRadius:"6px",background:"transparent",boxShadow:"0 24px 64px rgba(0, 0, 0, 0.36), 0 2px 10px rgba(0, 0, 0, 0.18)",overflow:"visible"});const i=document.createElement("iframe");i.allow="payment *",i.setAttribute("frameborder","0"),Object.assign(i.style,{border:"none",outline:"none",borderRadius:"6px",display:"block",background:"transparent",maxWidth:"100%",maxHeight:"100%"});const n=document.createElement("button");n.type="button",n.textContent="Cancel",n.setAttribute("aria-label","Cancel 3D Secure authentication"),Object.assign(n.style,{position:"absolute",top:"-40px",right:"0",zIndex:"2",height:"28px",padding:"0 10px",border:"0",borderRadius:"999px",background:"rgba(17, 24, 39, 0.56)",color:"#ffffff",font:'600 11px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',letterSpacing:"0.04em",textTransform:"uppercase",cursor:"pointer",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.24)",transform:"translateY(0) scale(1)",transition:window.matchMedia?.("(prefers-reduced-motion: reduce)").matches?"none":"transform 300ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow 300ms cubic-bezier(0.22, 1, 0.36, 1), background 300ms cubic-bezier(0.22, 1, 0.36, 1)",willChange:"transform"});const a=()=>{n.style.background="rgba(17, 24, 39, 0.56)",n.style.boxShadow="0 4px 16px rgba(0, 0, 0, 0.24)",n.style.transform="translateY(0) scale(1)"},s=()=>{n.style.background="rgba(17, 24, 39, 0.68)",n.style.boxShadow="0 8px 22px rgba(0, 0, 0, 0.26)",n.style.transform="translateY(-1px) scale(1.025)"};return n.addEventListener("mouseenter",s),n.addEventListener("focus",s),n.addEventListener("mouseleave",a),n.addEventListener("blur",a),n.addEventListener("mouseup",s),n.addEventListener("mousedown",()=>{n.style.background="rgba(17, 24, 39, 0.72)",n.style.boxShadow="0 3px 12px rgba(0, 0, 0, 0.22)",n.style.transform="translateY(0) scale(0.985)"}),n.addEventListener("click",e),t.appendChild(i),t.appendChild(n),{shell:t,iframe:i,cancelButton:n}}(()=>this.options.onCancel()),this.iframe=this.shell.iframe,this.iframe.src=this.options.buildUrl(e),this.frameSize={},this.applySize(),this.modal.appendChild(this.shell.shell),document.body.appendChild(this.modal),this.resizeHandler=()=>this.applySize(),window.addEventListener("resize",this.resizeHandler),window.addEventListener("orientationchange",this.resizeHandler),window.visualViewport?.addEventListener("resize",this.resizeHandler),this.pendingData=e}handleFrameResize(e,t){if(!this.iframe?.contentWindow||e.source!==this.iframe.contentWindow)return;const i=function(e){if(!e||"object"!=typeof e)return null;const t=e,i={};return"number"==typeof t.width&&Number.isFinite(t.width)&&t.width>0&&(i.width=t.width),"number"==typeof t.height&&Number.isFinite(t.height)&&t.height>0&&(i.height=t.height),i.width||i.height?i:null}(t);i&&(this.frameSize={...this.frameSize,...i},this.applySize())}handleReady(){return!(!this.pendingData||!this.iframe?.contentWindow)&&(this.options.onReady(this.iframe,this.pendingData),!0)}close(){this.resizeHandler&&(window.removeEventListener("resize",this.resizeHandler),window.removeEventListener("orientationchange",this.resizeHandler),window.visualViewport?.removeEventListener("resize",this.resizeHandler),this.resizeHandler=null),this.modal&&(this.modal.remove(),this.modal=null),this.shell=null,this.iframe=null,this.frameSize={},this.pendingData=null}applySize(){!function(e,t,i={},n){if(!e||!t)return i;const a=o(),s=Math.min(860,Math.max(0,a.width-32)),l=Math.min(860,Math.max(0,a.height-112)),p=i.width??460,h=i.height??680,d=r(p,320,s),c=r(h,300,l);e.style.width=`${a.width}px`,e.style.height=`${a.height}px`,e.style.minHeight=`${a.height}px`,t.style.width=`${Math.round(d)}px`,t.style.height=`${Math.round(c)}px`,n&&(n.style.width=`${Math.round(d)}px`,n.style.height=`${Math.round(c)}px`)}(this.modal,this.iframe,this.frameSize,this.shell?.shell)}}const p=new Set(["bg","bg-BG","en","en-GB","el","el-GR","ro","ro-RO","hr","hr-HR","pl","pl-PL","cs","cs-CZ","sl","sl-SI","sk","sk-SK","hu","hu-HU"]);function h(e){return e&&"auto"!==e?p.has(e)?e:(console.warn(`[PaypercutCheckout] Locale "${e}" is not supported. Falling back to "en".`),"en"):"en"}var d,c,u,y;function m(e){return Object.values(c).includes(e)}function g(e){return Object.values(u).includes(e)}function P(e){var t;if(e)return t=e,Object.values(d).includes(t)?e:void console.warn(`[PaypercutCheckout] Invalid ui_mode: "${e}". Valid options: ${Object.values(d).join(", ")}`)}!function(e){e.EMBEDDED="embedded"}(d||(d={})),function(e){e.CARD="card"}(c||(c={})),function(e){e.APPLE_PAY="apple_pay",e.GOOGLE_PAY="google_pay"}(u||(u={})),function(e){e.Loaded="loaded",e.Processing="processing",e.Success="success",e.Error="error",e.Expired="expired",e.Resize="resize",e.ThreeDSComplete="threeds_complete",e.ThreeDSError="threeds_error",e.ThreeDSCanceled="threeds_canceled",e.ThreeDSStarted="threeds_started",e.Cancel="cancel",e.FormValidation="form_validation"}(y||(y={}));const f="SDK_CAPABILITIES",S="APPLE_PAY_START",C="APPLE_PAY_VALIDATE_MERCHANT",b="APPLE_PAY_MERCHANT_SESSION",w="APPLE_PAY_MERCHANT_ERROR",E="APPLE_PAY_PAYMENT_DATA",A="APPLE_PAY_PAYMENT_RESULT",I="APPLE_PAY_CANCELLED",v="APPLE_PAY_SESSION_ERROR",k=new Set(["ar","bg","ca","cs","da","de","el","en","es","et","fi","fr","hr","id","it","ja","ko","ms","nl","no","pl","pt","ru","sk","sl","sr","sv","th","tr","uk","zh"]);function T(e){return e||"en"}function D(e){const t=e.split("-")[0].toLowerCase();return k.has(t)?t:"en"}var _;function x(){return"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function R(e){return e.startsWith("pk_live_")}!function(e){e.Ready="ready",e.Click="click",e.SessionStart="session_start",e.ShippingOptionsRequired="shipping_options_required",e.ShippingAddressChange="shipping_address_change",e.ShippingOptionChange="shipping_option_change",e.PaymentMethodCreated="payment_method_created",e.PaymentMethodFailed="payment_method_failed",e.Cancel="cancel",e.Error="error"}(_||(_={}));let O=null;function M(){return O||(O=new Promise(e=>{if("undefined"==typeof window)return void e();if(customElements?.get("apple-pay-button"))return void e();const t=document.createElement("script");t.src="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",t.async=!0,t.onload=()=>e(),t.onerror=()=>e(),document.head.appendChild(t)}),O)}let L=null;function G(){return L||(L=new Promise((e,t)=>{if("undefined"==typeof window)return void t(new Error("No window"));if(globalThis.google?.payments?.api?.PaymentsClient)return void e();const i=document.createElement("script");i.src="https://pay.google.com/gp/p/js/pay.js",i.async=!0,i.onload=()=>e(),i.onerror=()=>t(new Error("Failed to load Google Pay script")),document.head.appendChild(i)}),L)}function z(e,t,i="DE"){const n={};return void 0!==e.amount&&(n.newTransactionInfo={totalPriceStatus:"FINAL",totalPriceLabel:"Total",totalPrice:(e.amount/100).toFixed(2),currencyCode:t,countryCode:i}),e.shippingOptions?.length&&(n.newShippingOptionParameters={defaultSelectedOptionId:e.shippingOptions[0].id,shippingOptions:e.shippingOptions.map(e=>({id:e.id,label:e.label,description:e.detail??`${(e.amount/100).toFixed(2)} ${t}`}))}),"invalid_shipping_address"===e.status?n.error={reason:"SHIPPING_ADDRESS_UNSERVICEABLE",message:"Cannot ship to this address.",intent:"SHIPPING_ADDRESS"}:"invalid_shipping_option"===e.status&&(n.error={reason:"SHIPPING_OPTION_INVALID",message:"This shipping option is not available.",intent:"SHIPPING_OPTION"}),n}function U(e){return"checkout"===e?"check-out":e}class N{constructor(t){this.options=t,this.emitter=new e,this.mounted=!1,this.destroyed=!1,this.sessionActive=!1,this.tokenizeIframe=null,this.wrapper=null,this.applePayContainer=null,this.applePayButtonEl=null,this.gpayContainer=null,this.gpayClient=null,this.gpayPaymentRequest=null,this.gpayCurrentAmount=0,this.preferredLayout="row",this.layoutResizeObserver=null,this.instanceId=x(),this.idempotencyKey=x(),this.pending3DSAfterGpay=null,this.applePaySession=null,this.applePayCurrentAmount=0,this.currentLineItems=[],this.applePayCurrentShippingOptions=[],this.applePayPendingShippingOption=null,this.applePayPendingCallback=null,this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.expressConfig=null,this.pendingGpayResolve=null,this.pendingGpayReject=null,this.pendingGpayBillingDetails=null,this.pendingGpayShippingDetails=null,this.pendingGpayShippingOption=void 0,this.currentShippingOptions=t.shippingOptions??[],this.messageHandler=this.onMessage.bind(this),this.threeDSModal=new l({modalId:"paypercut-express-3ds-modal",buildUrl:e=>this.buildThreeDSUrl(e),onCancel:()=>this.handle3DSShellCancel(),onReady:e=>this.postThreeDSInit(e)}),window.addEventListener("message",this.messageHandler)}buildTokenizeSrc(){const e=n(this.options.hostedCheckoutUrl),t=new URL("/express/tokenize",e);return t.searchParams.set("instanceId",this.instanceId),t.searchParams.set("liveMode",String(R(this.options.publishableKey))),t.toString()}async fetchExpressConfig(){const e=a(this.options.apiUrl),t=new URL("/v1/elements/sessions",e),{amount:i}=this.options;t.searchParams.set("type","deferred_intent"),t.searchParams.set("key",this.options.publishableKey),t.searchParams.set("deferred_intent[mode]","payment"),t.searchParams.set("deferred_intent[currency]",this.options.currency),null!=i&&t.searchParams.set("deferred_intent[amount]",`${i}`),t.searchParams.set("referrer_host",window.location.hostname);try{const e=await fetch(t.toString(),{cache:"no-store"});if(!e.ok)throw new Error(`Config fetch failed: HTTP ${e.status}`);const i=await e.json(),n=R(this.options.publishableKey),a="BCR2DN5T735375Y7",o=i.payment_domain?.wallets?.google_pay?.merchant_ref??"",r=i.payment_domain?.wallets?.google_pay?.status??"inactive";this.expressConfig={tenantId:i.payment_domain?.wallet_provider?.tenant_id??"",publicKey:i.payment_domain?.wallet_provider?.public_key??"",vaultApiUrl:s(),googlePayMerchantId:n?"active"===r?o:a:o||a,googlePayStatus:r,applePayStatus:i.payment_domain?.wallets?.apple_pay?.status??"inactive",displayName:i.merchant?.name??"",merchantMid:i.merchant?.mid??"",merchantMcc:i.merchant?.mcc??"",merchantCountry:i.merchant?.country??"",merchantUrl:i.merchant?.business_url??""}}catch(e){console.error("[PaypercutExpressCheckout] Failed to fetch express config:",e)}}onMessage(e){if(!i(e.origin))return void(e.origin.includes("localhost")&&console.warn("[PaypercutExpressCheckout] Message blocked — origin not allowed:",e.origin));const t=e.data;if(t&&"object"==typeof t&&"type"in t&&(!t.instanceId||t.instanceId===this.instanceId))switch(t.type){case"TOKENIZE_RESPONSE":if("apple_pay"===t.wallet)t.success?this.createPaymentMethod({btTokenId:t.btTokenId,cardPayload:t.cardPayload,billingDetails:t.billingDetails,csessId:t.csessId,walletType:"apple_pay"}).then(e=>{this.completeApplePaySession(!0),this.emitter.emit(_.PaymentMethodCreated,{paymentMethodId:e,wallet:"apple_pay",billingDetails:this.applePayPendingBillingDetails??void 0,shippingDetails:this.applePayPendingShippingDetails??void 0,selectedShippingOption:this.applePayPendingShippingOption??void 0}),this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.applePayPendingShippingOption=null}).catch(e=>{this.completeApplePaySession(!1),this.emitter.emit(_.Error,new Error(e?.message??"Payment method creation failed")),this.emitter.emit(_.PaymentMethodFailed,{error:e?.message??"Payment method creation failed"}),this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.applePayPendingShippingOption=null}):(this.completeApplePaySession(!1),this.emitter.emit(_.Error,new Error(t.error??"Apple Pay payment failed")),this.emitter.emit(_.PaymentMethodFailed,{error:t.error??"Apple Pay payment failed"}),this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.applePayPendingShippingOption=null);else if(t.success)this.pendingGpayResolve?(this.pendingGpayResolve(t),this.pendingGpayResolve=null,this.pendingGpayReject=null):this.createPaymentMethod({btTokenId:t.btTokenId,cardPayload:t.cardPayload,billingDetails:t.billingDetails,csessId:t.csessId,walletType:"google_pay"}).then(e=>{this.emitter.emit(_.PaymentMethodCreated,{paymentMethodId:e,wallet:"google_pay",billingDetails:this.pendingGpayBillingDetails??void 0,shippingDetails:this.pendingGpayShippingDetails??void 0,selectedShippingOption:this.pendingGpayShippingOption})}).catch(e=>{this.emitter.emit(_.Error,new Error(e?.message??"Payment method creation failed")),this.emitter.emit(_.PaymentMethodFailed,{error:e?.message??"Payment method creation failed"})}).finally(()=>{this.pendingGpayBillingDetails=null,this.pendingGpayShippingDetails=null,this.pendingGpayShippingOption=void 0});else if(this.pendingGpayReject)this.pendingGpayReject(new Error(t.error??"Tokenization failed")),this.pendingGpayResolve=null,this.pendingGpayReject=null;else{const e=t.error??"Google Pay payment failed";e.toLowerCase().includes("cancel")?this.emitter.emit(_.Cancel):(this.emitter.emit(_.Error,new Error(e)),this.emitter.emit(_.PaymentMethodFailed,{error:e})),this.pendingGpayBillingDetails=null,this.pendingGpayShippingDetails=null,this.pendingGpayShippingOption=void 0}break;case"PAYPERCUT_THREEDS_FRAME_RESIZE":this.threeDSModal.handleFrameResize(e,t);break;case"THREEDS_START_FLOW":this.pendingGpayResolve?(this.pending3DSAfterGpay=t,this.pendingGpayResolve({__closeSheet:!0}),this.pendingGpayResolve=null,this.pendingGpayReject=null):this.threeDSModal.show(t);break;case"THREEDS_READY":this.handle3DSReady();break;case"THREEDS_COMPLETE":case"THREEDS_CANCELED":case"THREEDS_ERROR":this.postToTokenizeIframe(t),this.threeDSModal.close()}}mount(e){if(this.mounted)return void console.warn("[PaypercutExpressCheckout] mount() called but already mounted — ignoring");const t="string"==typeof e?document.querySelector(e):e;if(!t)throw new Error(`[PaypercutExpressCheckout] Container not found: ${e}`);const i=this.options.walletOptions?.length?this.options.walletOptions:[u.APPLE_PAY,u.GOOGLE_PAY],n=i.includes(u.APPLE_PAY),a=i.includes(u.GOOGLE_PAY),s=this.options.layout??"auto";this.preferredLayout="auto"===s?"row":s;const o=document.createElement("div");this.wrapper=o,Object.assign(o.style,{display:"flex",flexDirection:"row"===this.preferredLayout?"row":"column",gap:"8px",width:"100%"}),a&&(this.gpayContainer=document.createElement("div"),this.applyLayoutToContainers(this.preferredLayout,this.gpayContainer),o.appendChild(this.gpayContainer),G().catch(e=>{console.error("[PaypercutExpressCheckout] Failed to load Google Pay script:",e)})),n&&(this.applePayContainer=document.createElement("div"),this.applyLayoutToContainers(this.preferredLayout,this.applePayContainer),o.appendChild(this.applePayContainer),M()),t.appendChild(o),"auto"===s&&"undefined"!=typeof ResizeObserver&&(this.layoutResizeObserver=new ResizeObserver(e=>{const i=e[0]?.contentRect.width??t.offsetWidth;this.applyLayout(i<=540?"column":"row")}),this.layoutResizeObserver.observe(t));const r=this.buildTokenizeSrc();this.tokenizeIframe=document.createElement("iframe"),this.tokenizeIframe.id="paypercut-express-tokenize-iframe",this.tokenizeIframe.src=r,this.tokenizeIframe.setAttribute("frameborder","0"),this.tokenizeIframe.setAttribute("sandbox","allow-scripts allow-forms allow-same-origin"),Object.assign(this.tokenizeIframe.style,{position:"absolute",top:"-9999px",left:"-9999px",width:"1px",height:"1px",border:"none",visibility:"hidden"}),document.body.appendChild(this.tokenizeIframe),this.mounted=!0,this.fetchExpressConfig().then(async()=>{if(this.destroyed)return;const e=this.expressConfig;n&&this.applePayContainer&&"active"===e?.applePayStatus?await this.mountApplePayButton(this.applePayContainer):this.applePayContainer&&this.removeApplePayContainer(),a&&e&&this.mountGooglePayFromConfig(),this.emitter.emit(_.Ready)})}applyLayoutToContainers(e,...t){for(const i of t)i&&(i.style.flex="row"===e?"1":"",i.style.minWidth="row"===e?"0":"",i.style.width="row"===e?"":"100%")}applyLayout(e){this.wrapper&&(this.wrapper.style.flexDirection="row"===e?"row":"column",this.applyLayoutToContainers(e,this.applePayContainer,this.gpayContainer))}setLayout(e){this.preferredLayout=e,this.applyLayout(e)}setLocale(e){this.options.locale=e,this.applePayButtonEl&&this.applePayButtonEl.setAttribute("locale",T(e)),this.gpayClient&&this.gpayContainer&&this.gpayPaymentRequest&&this.setButtonOptions({})}setButtonOptions(e){this.options.buttonOptions={...this.options.buttonOptions,...e};const t=this.options.buttonOptions;if(this.applePayButtonEl&&(void 0!==e.applePayStyle&&this.applePayButtonEl.setAttribute("buttonstyle",e.applePayStyle),void 0!==e.type&&this.applePayButtonEl.setAttribute("type",U(e.type)),void 0!==e.borderRadius&&this.applePayButtonEl.style.setProperty("--apple-pay-button-border-radius",e.borderRadius)),this.gpayClient&&this.gpayContainer&&this.gpayPaymentRequest){this.gpayContainer.innerHTML="";const e=this.gpayClient.createButton({onClick:()=>this.startGooglePay(this.gpayPaymentRequest),buttonSizeMode:"fill",buttonType:t?.type??"plain",buttonColor:t?.googlePayColor??"default",...this.options.locale&&{buttonLocale:D(this.options.locale)}}),i=t?.borderRadius??"0.5rem";e.style.width="100%",this.injectGpayInnerStyles(e,i),this.gpayContainer.appendChild(e)}}async mountApplePayButton(e){await M();const t=window.ApplePaySession;if(!t)return void console.log("[PaypercutExpressCheckout] ApplePaySession not available");if(!t.canMakePayments?.())return void console.log("[PaypercutExpressCheckout] ApplePaySession.canMakePayments() returned false — hiding Apple Pay button");const i=this.options.locale?T(this.options.locale):"en",n=this.options.buttonOptions,a=document.createElement("apple-pay-button");a.setAttribute("buttonstyle",n?.applePayStyle??"black"),a.setAttribute("type",U(n?.type??"plain")),a.setAttribute("locale",i),a.style.setProperty("--apple-pay-button-width","100%"),a.style.setProperty("--apple-pay-button-height","48px"),a.style.setProperty("--apple-pay-button-border-radius",n?.borderRadius??"0.5rem"),a.style.display="block",a.style.cursor="pointer",a.addEventListener("click",()=>this.startApplePay());const s=()=>{this.applePayButtonEl=a,e.appendChild(a);const t=a.shadowRoot;if(t){const e=document.createElement("style");e.textContent="span svg { height: 75% !important; width: auto !important; }",t.appendChild(e)}};customElements?.get("apple-pay-button")?s():customElements?.whenDefined("apple-pay-button").then(s).catch(()=>s())}async startApplePay(){if(this.sessionActive)return;if("undefined"==typeof window)return;const e=window.ApplePaySession;if(!e)return void console.error("[PaypercutExpressCheckout] ApplePaySession not available");this.idempotencyKey=x(),this.setSessionActive(!0),this.emitter.emit(_.Click);const t=await new Promise(e=>{if(!this.emitter.hasListeners(_.SessionStart))return void e(null);const t=setTimeout(()=>e(null),3e3);this.emitter.emit(_.SessionStart,{wallet:"apple_pay",updateWith:i=>{clearTimeout(t),e(i)}})});if(!t)return console.error("[PaypercutExpressCheckout] Apple Pay: no session_start response — aborting"),this.setSessionActive(!1),void this.emitter.emit(_.ShippingOptionsRequired,{wallet:"apple_pay"});"number"==typeof t.amount?this.applePayCurrentAmount=t.amount:this.applePayCurrentAmount=this.options.amount,Array.isArray(t.lineItems)?this.currentLineItems=t.lineItems:this.currentLineItems=this.options.lineItems??[],Array.isArray(t.shippingOptions)?this.applePayCurrentShippingOptions=t.shippingOptions:this.applePayCurrentShippingOptions=this.currentShippingOptions,this.applePayPendingShippingOption=null;const i=this.expressConfig?.displayName||"Checkout",n=(this.applePayCurrentAmount/100).toFixed(2),a=this.currentLineItems.map(e=>({label:e.label,amount:(e.amount/100).toFixed(2),type:e.type??"final"})),o={countryCode:this.options.countryCode??"DE",currencyCode:this.options.currency,merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],supportedNetworks:["visa","masterCard"],lineItems:a,total:{label:i,amount:n,type:"final"},requiredBillingContactFields:["postalAddress","name","email"],requiredShippingContactFields:["postalAddress","name","email"]};this.applePayCurrentShippingOptions.length&&(o.shippingMethods=this.applePayCurrentShippingOptions.map(e=>({label:e.label,detail:e.detail??"",amount:(e.amount/100).toFixed(2),identifier:e.id}))),o.shippingType="shipping",this.abortApplePaySession();const r=e.supportsVersion?.(14)?14:3;try{const t=new e(r,o);this.applePaySession=t,t.onvalidatemerchant=async e=>{const n=this.expressConfig?.vaultApiUrl??s(),a=this.expressConfig?.publicKey??"";try{const s={"Content-Type":"application/json","BT-API-KEY":a};this.idempotencyKey&&(s["Idempotency-Key"]=this.idempotencyKey);const o=await fetch(`${n}/apple-pay/session`,{method:"POST",headers:s,body:JSON.stringify({display_name:i,domain:window.location.host,validation_url:e.validationURL})});if(!o.ok){const e=await o.json().catch(()=>({}));throw new Error(e?.message??`Merchant validation failed: HTTP ${o.status}`)}const r=await o.json();t.completeMerchantValidation(r)}catch(e){console.error("[PaypercutExpressCheckout] Apple Pay merchant validation failed"),this.abortApplePaySession(),this.emitter.emit(_.Error,new Error(e?.message??"Apple Pay merchant validation failed")),this.emitter.emit(_.Cancel)}},t.onshippingcontactselected=async n=>{const a=n.shippingContact,s=await new Promise(e=>{this.applePayPendingCallback={type:"contact",resolve:e},this.emitter.emit(_.ShippingAddressChange,{address:{country:a.countryCode??"",state:a.administrativeArea,city:a.locality,postalCode:a.postalCode},updateWith:e=>this.update(e)}),setTimeout(()=>e({}),3e4)});this.applePayPendingCallback=null,"number"==typeof s.amount&&(this.applePayCurrentAmount=s.amount),Array.isArray(s.lineItems)&&(this.currentLineItems=s.lineItems),Array.isArray(s.shippingOptions)&&(this.applePayCurrentShippingOptions=s.shippingOptions);const o="invalid_shipping_address"===s.status?e.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS:e.STATUS_SUCCESS;try{t.completeShippingContactSelection(o,this.applePayCurrentShippingOptions.map(e=>({label:e.label,detail:e.detail??"",amount:(e.amount/100).toFixed(2),identifier:e.id})),{label:i,amount:(this.applePayCurrentAmount/100).toFixed(2),type:"final"},this.currentLineItems.map(e=>({label:e.label,amount:(e.amount/100).toFixed(2),type:e.type??"final"})))}catch(e){console.error("[PaypercutExpressCheckout] completeShippingContactSelection failed",e)}},t.onshippingmethodselected=async n=>{const a=n.shippingMethod,s={id:a.identifier,label:a.label,detail:a.detail,amount:Math.round(100*parseFloat(a.amount))};this.applePayPendingShippingOption=s;const o=await new Promise(e=>{this.applePayPendingCallback={type:"method",resolve:e},this.emitter.emit(_.ShippingOptionChange,{shippingOption:s,updateWith:e=>this.update(e)}),setTimeout(()=>e({}),3e4)});this.applePayPendingCallback=null,"number"==typeof o.amount&&(this.applePayCurrentAmount=o.amount),Array.isArray(o.lineItems)&&(this.currentLineItems=o.lineItems);try{t.completeShippingMethodSelection(e.STATUS_SUCCESS,{label:i,amount:(this.applePayCurrentAmount/100).toFixed(2),type:"final"},this.currentLineItems.map(e=>({label:e.label,amount:(e.amount/100).toFixed(2),type:e.type??"final"})))}catch(e){console.error("[PaypercutExpressCheckout] completeShippingMethodSelection failed",e)}},t.onpaymentauthorized=e=>{const t=e.payment?.billingContact,i=e.payment?.shippingContact;this.applePayPendingBillingDetails=t?{name:[t.givenName,t.familyName].filter(Boolean).join(" ")||void 0,email:t.emailAddress,address:{line1:t.addressLines?.[0],line2:t.addressLines?.[1],city:t.locality,state:t.administrativeArea,postalCode:t.postalCode,country:t.countryCode}}:null,this.applePayPendingShippingDetails=i?{name:[i.givenName,i.familyName].filter(Boolean).join(" ")||void 0,address:{line1:i.addressLines?.[0],line2:i.addressLines?.[1],city:i.locality,state:i.administrativeArea,postalCode:i.postalCode,country:i.countryCode}}:null,this.postToTokenizeIframe({type:"TOKENIZE_REQUEST",instanceId:this.instanceId,wallet:"apple_pay",applePaymentData:e.payment.token,idemKey:this.idempotencyKey,publishableKey:this.options.publishableKey,billingDetails:this.applePayPendingBillingDetails,amount:this.applePayCurrentAmount,currency:this.options.currency,merchantInfo:{name:this.expressConfig?.displayName??"",mid:this.expressConfig?.merchantMid??"",mcc:this.expressConfig?.merchantMcc??"",country:this.expressConfig?.merchantCountry??"",url:this.expressConfig?.merchantUrl??""}})},t.oncancel=()=>{this.applePaySession=null,this.applePayPendingCallback=null,this.applePayPendingShippingOption=null,this.emitter.emit(_.Cancel)},t.begin()}catch(e){this.applePaySession=null,console.error("[PaypercutExpressCheckout] Failed to create ApplePaySession",{name:e?.name,message:e?.message,hint:"SecurityError"===e?.name?"Page is not HTTPS or merchant domain is not registered for Apple Pay":"Check isSecureContext and that ApplePaySession.canMakePayments() returns true"})}}removeGpayContainer(){this.gpayContainer?.remove(),this.gpayContainer=null}removeApplePayContainer(){this.applePayContainer?.remove(),this.applePayContainer=null,this.applePayButtonEl=null}mountGooglePayFromConfig(){const e=this.expressConfig;if(!e)return;const t=R(this.options.publishableKey),i=e.tenantId,n=e.googlePayMerchantId,a=e.displayName||"Checkout";return i?n?(console.log({liveMode:t}),!t||e.merchantMcc&&e.merchantUrl?void G().then(()=>{this.mountGooglePayButton(i,n,a,t)}).catch(e=>{console.error("[PaypercutExpressCheckout] Failed to load Google Pay script:",e)}):(console.warn("[PaypercutExpressCheckout] Google Pay disabled!"),void this.removeGpayContainer())):(console.warn("[PaypercutExpressCheckout] googlePayMerchantId is empty — Google Pay will not be mounted (merchant may not have Google Pay active)."),void this.removeGpayContainer()):(console.error("[PaypercutExpressCheckout] tenantId is empty — Google Pay cannot be mounted without a valid gatewayMerchantId."),void this.removeGpayContainer())}mountGooglePayButton(e,t,i,n){if(!this.gpayContainer)return void console.error("[PaypercutExpressCheckout] gpayContainer is null");const a=globalThis.google;if(!a?.payments?.api?.PaymentsClient)return void console.error("[PaypercutExpressCheckout] google.payments.api.PaymentsClient not available");const s=n?"PRODUCTION":"TEST",o=this.options.countryCode;o||console.warn('[PaypercutExpressCheckout] countryCode is not set. This is required for Google Pay in production. Pass it via options.countryCode (e.g. "DE").');const r={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["CRYPTOGRAM_3DS","PAN_ONLY"],allowedCardNetworks:["MASTERCARD","VISA"],billingAddressRequired:!0,billingAddressParameters:{format:"FULL",phoneNumberRequired:!1}},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:"basistheory",gatewayMerchantId:e}}}],merchantInfo:{merchantId:t,merchantName:i},transactionInfo:{totalPriceStatus:"FINAL",totalPriceLabel:"Total",totalPrice:(this.options.amount/100).toFixed(2),currencyCode:this.options.currency,countryCode:o},callbackIntents:["PAYMENT_AUTHORIZATION","SHIPPING_ADDRESS","SHIPPING_OPTION"],shippingAddressRequired:!0,shippingOptionRequired:!0};this.options.allowedCountries?.length&&(r.shippingAddressParameters={allowedCountryCodes:this.options.allowedCountries,phoneNumberRequired:!1}),this.options.shippingOptions?.length&&(r.shippingOptionParameters={defaultSelectedOptionId:this.options.shippingOptions[0].id,shippingOptions:this.options.shippingOptions.map(e=>({id:e.id,label:e.label,description:e.detail??`${(e.amount/100).toFixed(2)} ${this.options.currency}`}))}),this.gpayPaymentRequest=r,this.gpayClient=new a.payments.api.PaymentsClient({environment:s,paymentDataCallbacks:{onPaymentAuthorized:e=>this.handleGooglePayAuthorized(e),onPaymentDataChanged:e=>this.handleGooglePayDataChanged(e)}});const l=this.options.buttonOptions,p=this.gpayClient.createButton({onClick:()=>this.startGooglePay(r),buttonSizeMode:"fill",buttonType:l?.type??"plain",buttonColor:l?.googlePayColor??"default",...this.options.locale&&{buttonLocale:D(this.options.locale)}}),h=l?.borderRadius??"0.5rem";p.style.width="100%",this.injectGpayInnerStyles(p,h),this.gpayContainer.appendChild(p)}injectGpayInnerStyles(e,t){const i=document.createElement("style");i.textContent=`.gpay-button { height: 48px !important; border-radius: ${t} !important; background-size: auto 60% !important; } .gpay-card-info-container { border-radius: ${t} !important; } .gpay-card-info-container-fill, .gpay-card-info-container-fill > .gpay-card-info-container { height: 48px !important; }`,e.prepend(i)}async startGooglePay(e){if(this.gpayClient&&!this.sessionActive){if(this.idempotencyKey=x(),this.setSessionActive(!0),this.emitter.emit(_.Click),this.emitter.hasListeners(_.SessionStart)){const t=await new Promise(e=>{const t=setTimeout(()=>e(null),3e3);this.emitter.emit(_.SessionStart,{wallet:"google_pay",updateWith:i=>{clearTimeout(t),e(i)}})});if(!t)return this.setSessionActive(!1),void this.emitter.emit(_.ShippingOptionsRequired,{wallet:"google_pay"});t.shippingOptions&&(this.currentShippingOptions=t.shippingOptions,e.shippingOptionParameters={defaultSelectedOptionId:t.shippingOptions[0]?.id,shippingOptions:t.shippingOptions.map(e=>({id:e.id,label:e.label,description:e.detail??`${(e.amount/100).toFixed(2)} ${this.options.currency}`}))}),null!=t.amount&&(this.gpayCurrentAmount=t.amount,e.transactionInfo={...e.transactionInfo,totalPrice:(t.amount/100).toFixed(2)})}this.gpayCurrentAmount||(this.gpayCurrentAmount=this.options.amount);try{if(await this.gpayClient.loadPaymentData(e),this.pending3DSAfterGpay){const e=this.pending3DSAfterGpay;this.pending3DSAfterGpay=null,this.threeDSModal.show(e)}}catch(e){"CANCELED"===e?.statusCode||e?.message?.toLowerCase?.().includes("cancel")?this.emitter.emit(_.Cancel):this.emitter.emit(_.Error,new Error(e?.message??"Google Pay failed"))}finally{this.setSessionActive(!1)}}}async handleGooglePayAuthorized(e){try{const t=e.paymentMethodData.tokenizationData.token,i=e.paymentMethodData?.info?.cardNetwork??"",n=e.paymentMethodData?.info?.billingAddress,a=e.shippingAddress,s=e.shippingOptionData,o=n?{name:n.name,address:{line1:n.address1,city:n.locality,state:n.administrativeArea,postalCode:n.postalCode,country:n.countryCode}}:null,r=a?{name:a.name||void 0,address:{line1:a.address1,city:a.locality,state:a.administrativeArea,postalCode:a.postalCode,country:a.countryCode}}:void 0,l=s?this.currentShippingOptions.find(e=>e.id===s.id)??{id:s.id,label:s.label??s.id,amount:0}:void 0;this.pendingGpayBillingDetails=o,this.pendingGpayShippingDetails=r,this.pendingGpayShippingOption=l;const p=await new Promise((e,n)=>{const a=setTimeout(()=>{this.pendingGpayResolve=null,this.pendingGpayReject=null,n(new Error("Tokenization timed out"))},3e4);this.pendingGpayResolve=t=>{clearTimeout(a),e(t)},this.pendingGpayReject=e=>{clearTimeout(a),n(e)},this.postToTokenizeIframe({type:"TOKENIZE_REQUEST",instanceId:this.instanceId,wallet:"google_pay",encryptedToken:t,cardNetwork:i,idemKey:this.idempotencyKey,publishableKey:this.options.publishableKey,billingDetails:o,amount:this.options.amount,currency:this.options.currency,merchantInfo:{name:this.expressConfig?.displayName??"",mid:this.expressConfig?.merchantMid??"",mcc:this.expressConfig?.merchantMcc??"",country:this.expressConfig?.merchantCountry??"",url:this.expressConfig?.merchantUrl??""}})});if(p.__closeSheet)return{transactionState:"SUCCESS"};if(!p.success){const e=p.error??"Tokenization failed";return this.emitter.emit(_.Error,new Error(e)),this.emitter.emit(_.PaymentMethodFailed,{error:e}),{transactionState:"ERROR"}}const h=await this.createPaymentMethod({btTokenId:p.btTokenId,cardPayload:p.cardPayload,billingDetails:p.billingDetails,csessId:p.csessId,walletType:"google_pay"});return this.emitter.emit(_.PaymentMethodCreated,{paymentMethodId:h,wallet:"google_pay",billingDetails:o??void 0,shippingDetails:r,selectedShippingOption:l}),this.pendingGpayBillingDetails=null,this.pendingGpayShippingDetails=null,this.pendingGpayShippingOption=void 0,{transactionState:"SUCCESS"}}catch(e){return console.error("[PaypercutExpressCheckout] handleGooglePayAuthorized error:",e?.message??e),this.emitter.emit(_.Error,new Error(e?.message??"Google Pay authorization failed")),this.emitter.emit(_.PaymentMethodFailed,{error:e?.message??"Google Pay authorization failed"}),{transactionState:"ERROR"}}}async handleGooglePayDataChanged(e){const{callbackTrigger:t,shippingAddress:i,shippingOptionData:n}=e;if("INITIALIZE"===t)return z({amount:this.gpayCurrentAmount||this.options.amount,shippingOptions:this.currentShippingOptions},this.options.currency,this.options.countryCode);if("SHIPPING_ADDRESS"===t){return z(await new Promise(e=>{this.emitter.emit(_.ShippingAddressChange,{address:{country:i?.countryCode??"",state:i?.administrativeArea,city:i?.locality,postalCode:i?.postalCode},updateWith:t=>{t.shippingOptions&&(this.currentShippingOptions=t.shippingOptions),null!=t.amount&&(this.gpayCurrentAmount=t.amount),e(t)}})}),this.options.currency,this.options.countryCode)}if("SHIPPING_OPTION"===t){const e=n?.id,t=this.currentShippingOptions.find(t=>t.id===e);return z(await new Promise(i=>{this.emitter.emit(_.ShippingOptionChange,{shippingOption:{id:e??"",label:t?.label??e??"",detail:t?.detail,amount:t?.amount??0},updateWith:e=>{null!=e.amount&&(this.gpayCurrentAmount=e.amount),i(e)}})}),this.options.currency,this.options.countryCode)}return{}}update(e){this.mounted?this.applePayPendingCallback&&this.applePayPendingCallback.resolve(e):console.warn("[PaypercutExpressCheckout] Cannot update: not mounted")}on(e,t){return this.emitter.on(e,t)}destroy(){if(!this.destroyed){if(this.tokenizeIframe){try{this.tokenizeIframe.remove()}catch{}this.tokenizeIframe=null}if(this.gpayContainer){try{this.gpayContainer.remove()}catch{}this.gpayContainer=null}if(this.applePayContainer)try{this.removeApplePayContainer()}catch{}this.gpayPaymentRequest=null,this.layoutResizeObserver&&(this.layoutResizeObserver.disconnect(),this.layoutResizeObserver=null),this.threeDSModal.close(),this.abortApplePaySession(),this.sessionActive=!1,this.mounted=!1,this.destroyed=!0,window.removeEventListener("message",this.messageHandler),this.emitter.clear()}}setSessionActive(e){this.sessionActive=e;const t=e?"0.5":"",i=e?"none":"";this.applePayContainer&&(this.applePayContainer.style.opacity=t,this.applePayContainer.style.pointerEvents=i),this.gpayContainer&&(this.gpayContainer.style.opacity=t,this.gpayContainer.style.pointerEvents=i)}completeApplePaySession(e){try{if(this.applePaySession){const t=window.ApplePaySession,i=e?t.STATUS_SUCCESS:t.STATUS_FAILURE;this.applePaySession.completePayment(i)}}catch{}this.applePaySession=null,this.applePayPendingCallback=null,this.applePayPendingShippingOption=null,this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.setSessionActive(!1)}abortApplePaySession(){try{this.applePaySession?.abort()}catch{}this.applePaySession=null,this.applePayPendingCallback=null,this.applePayPendingShippingOption=null,this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.setSessionActive(!1)}async createPaymentMethod(e){const{btTokenId:t,cardPayload:i,billingDetails:n,csessId:s,walletType:o}=e;if(!i||!t)throw new Error("[createPaymentMethod] Missing required tokenization data.");const r=new URL("/v1/payment_methods",a(this.options.apiUrl)),l={type:"card",key:this.options.publishableKey,card:{token:s??"",brand:i.brand??"",exp_month:i.exp_month??1,exp_year:i.exp_year??1,funding:i.funding??"",last4:i.last4??"",iin:i.bin??"",issuer:i.issuer??null,fingerprint:i.fingerprint??null,segment:i.segment??"",wallet:{type:o,dynamic_last4:null},three_d_secure_usage:{supported:!0}},billing_details:{name:n?.name??null,email:n?.email??null,phone:n?.phone??null,address:{city:n?.address?.city??null,country:n?.address?.country??null,line1:n?.address?.line1??null,line2:n?.address?.line2??null,postal_code:n?.address?.postalCode??null,state:n?.address?.state??null}},confirmation_token:{token_id:t}},p=await fetch(r.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l),cache:"no-store"});if(!p.ok){const e=await p.text().catch(()=>`HTTP ${p.status}`);throw new Error(`Payment method creation failed (${p.status}): ${e}`)}return(await p.json()).id}postToTokenizeIframe(e){if(!this.tokenizeIframe?.contentWindow)return;const t=n(this.options.hostedCheckoutUrl);this.tokenizeIframe.contentWindow.postMessage(e,t)}buildThreeDSUrl(e){const t=n(this.options.hostedCheckoutUrl),i=new URL("/express/threeds",t);return i.searchParams.set("instanceId",this.instanceId),i.searchParams.set("sessionId",e.sessionId),i.searchParams.set("step",e.step),e.challengeUrl&&i.searchParams.set("challengeUrl",e.challengeUrl),e.acsTransactionId&&i.searchParams.set("acsTransactionId",e.acsTransactionId),e.threeDSVersion&&i.searchParams.set("threeDSVersion",e.threeDSVersion),i.searchParams.set("liveMode",String(e.liveMode??!1)),i.toString()}handle3DSShellCancel(){this.postToTokenizeIframe({type:"THREEDS_CANCELED",instanceId:this.instanceId,error:"User canceled 3DS authentication"}),this.threeDSModal.close(),this.emitter.emit(_.Cancel)}handle3DSReady(){this.threeDSModal.handleReady()||console.error("[PaypercutExpressCheckout] No pending 3DS data or iframe not ready")}postThreeDSInit(e){const t=n(this.options.hostedCheckoutUrl);e.contentWindow?.postMessage({type:"THREEDS_INIT",instanceId:this.instanceId},t)}}const H=function(e){return new N(e)};let F=!1;const B=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,j=/^(0|(\d+(\.\d+)?(px|rem|em)))$/;function $(e){e&&(void 0===e.brandColor||B.test(e.brandColor)||console.warn(`[PaypercutCheckout] Invalid appearance.variables.brandColor: "${e.brandColor}". Expected a hex color (#RGB or #RRGGBB). Value ignored.`),void 0===e.fontFamily||e.fontFamily.trim()||console.warn("[PaypercutCheckout] Invalid appearance.variables.fontFamily: value is empty. Value ignored."),void 0===e.logoUrl||/^https:\/\//.test(e.logoUrl)||console.warn(`[PaypercutCheckout] Invalid appearance.variables.logoUrl: "${e.logoUrl}". Must start with https://. Value ignored.`),void 0===e.borderRadius||j.test(e.borderRadius.trim())||console.warn(`[PaypercutCheckout] Invalid appearance.variables.borderRadius: "${e.borderRadius}". Expected a CSS length like "8px", "0.5rem", or "0". Value ignored.`))}class V{constructor(t){this.options=t,this.emitter=new e,this.mounted=!1,this.destroyed=!1,this.iframe=null,this.applePaySession=null,this.applePayBridgeTimeout=null,this.messageHandler=this.onMessage.bind(this),this.threeDSModal=new l({modalId:"paypercut-3ds-modal",buildUrl:e=>this.buildThreeDSUrl(e),onCancel:()=>this.handle3DSShellCancel(),onReady:e=>this.postThreeDSInit(e)}),window.addEventListener("message",this.messageHandler),P(t.ui_mode??d.EMBEDDED)===d.EMBEDDED&&function(){if("undefined"==typeof window)return;if(window.ApplePaySession)return;if(F)return;F=!0;const e=document.createElement("script");e.src="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",e.crossOrigin="anonymous",e.async=!0,document.head.appendChild(e)}()}buildSrc(){const e=n(this.options.hostedCheckoutUrl),t=new URL(`/c/${this.options.id}`,e);if(this.options.locale){const e=h(this.options.locale);t.searchParams.set("locale",e)}if(this.options.lang){const e=h(this.options.lang);t.searchParams.set("lang",e)}{const e=P(this.options.ui_mode??d.EMBEDDED);e&&t.searchParams.set("ui_mode",e)}if(this.options.payment_methods&&this.options.payment_methods.length>0){(function(e){const t=[];for(const i of e)m(i)?t.push(i):console.warn(`[PaypercutCheckout] Invalid payment method: "${i}". Skipping.`);return 0===t.length&&(console.warn('[PaypercutCheckout] No valid payment methods provided. Defaulting to "card".'),t.push(c.CARD)),t})(this.options.payment_methods).forEach(e=>{t.searchParams.append("payment_methods",e)})}if(void 0!==this.options.wallet_options)if(0===this.options.wallet_options.length)t.searchParams.set("wallet_options",null);else{(function(e){const t=[];for(const i of e)g(i)?t.push(i):console.warn(`[PaypercutCheckout] Invalid wallet option: "${i}". Skipping.`);return t})(this.options.wallet_options).forEach(e=>{t.searchParams.append("wallet_options",e)})}return this.options.appearance?.preset&&t.searchParams.set("preset",this.options.appearance.preset),this.options.appearance?.theme&&t.searchParams.set("theme",this.options.appearance.theme),this.options.appearance?.variables&&Object.keys(this.options.appearance.variables).length>0&&($(this.options.appearance.variables),t.searchParams.set("appearance_vars",JSON.stringify(this.options.appearance.variables))),void 0!==this.options.form_only&&t.searchParams.set("form_only",String(this.options.form_only)),void 0!==this.options.validate_form&&t.searchParams.set("validate_form",String(this.options.validate_form)),t.toString()}getContainer(){const e="string"==typeof this.options.containerId?document.querySelector(this.options.containerId):this.options.containerId;if(!e)throw new Error(`Container not found: ${this.options.containerId}`);return e}onMessage(e){if(!i(e.origin))return;const t=e.data;if(t&&"object"==typeof t&&"type"in t&&(!t.checkoutId||t.checkoutId===this.options.id))switch(t.type){case"CHECKOUT_LOADED":this.emitter.emit(y.Loaded),this.postToIframe({type:f,checkoutId:this.options.id,applePayBridge:!0});break;case"CHECKOUT_PROCESSING":this.emitter.emit(y.Processing,{checkoutId:t.checkoutId});break;case"CHECKOUT_SUCCESS":const{payment_method:i={},payment:n=null}=t;this.emitter.emit(y.Success,{payment_method:i,payment:n});break;case"CHECKOUT_ERROR":this.emitter.emit(y.Error,(t&&t.error)??t);break;case"CHECKOUT_CANCEL":this.emitter.emit(y.Cancel,{checkoutId:t.checkoutId,wallet:t.wallet});break;case"CHECKOUT_EXPIRED":this.emitter.emit(y.Expired);break;case"CHECKOUT_RESIZE":this.emitter.emit(y.Resize,t.height),this.handleResize(t.height);break;case"PAYPERCUT_THREEDS_FRAME_RESIZE":this.threeDSModal.handleFrameResize(e,t);break;case"THREEDS_START_FLOW":this.threeDSModal.show(t),this.emitter.emit(y.ThreeDSStarted);break;case"THREEDS_READY":this.handle3DSReady();break;case"THREEDS_COMPLETE":this.postToIframe(t),this.threeDSModal.close(),this.emitter.emit(y.ThreeDSComplete);break;case"THREEDS_CANCELED":this.postToIframe(t),this.threeDSModal.close(),this.emitter.emit(y.ThreeDSCanceled);break;case"THREEDS_ERROR":this.postToIframe(t),this.threeDSModal.close(),this.emitter.emit(y.ThreeDSError,t.error);break;case"FORM_VALIDATION":this.emitter.emit(y.FormValidation,{checkoutId:t.checkoutId,wallet:t.wallet});break;case S:this.handleApplePayStart(t);break;case b:this.handleApplePayMerchantSession(t.merchantSession);break;case w:this.abortApplePaySession();break;case A:this.handleApplePayPaymentResult(!0===t.success)}}render(){if(!this.mounted)try{const e=this.getContainer();this.iframe=document.createElement("iframe"),this.iframe.id="paypercut-checkout-iframe",this.iframe.src=this.buildSrc(),this.iframe.allow="payment *; clipboard-write",this.iframe.setAttribute("frameborder","0"),this.iframe.setAttribute("allowpaymentrequest","true"),this.iframe.setAttribute("sandbox","allow-scripts allow-forms allow-same-origin allow-popups allow-popups-to-escape-sandbox"),Object.assign(this.iframe.style,{width:"100%",height:"100%",border:"none",display:"block"}),e.appendChild(this.iframe),this.mounted=!0}catch(e){throw console.error("[PaypercutCheckout] Failed to render:",e),e}}submit(){if(this.mounted)try{this.postToIframe({type:"START_PROCESSING",checkoutId:this.options.id})}catch(e){throw console.error("[PaypercutCheckout] Failed to submit payment:",e),e}}postToIframe(e){if(!this.iframe?.contentWindow)return void console.error("[PaypercutCheckout] Cannot post message: iframe not mounted");const t=n(this.options.hostedCheckoutUrl);this.iframe.contentWindow.postMessage(e,t)}handleResize(e){!this.iframe||"number"!=typeof e||e<=0||(this.iframe.style.height=`${e}px`)}buildThreeDSUrl(e){const t=n(this.options.hostedCheckoutUrl),i=new URL(`/c/${this.options.id}/threeds`,t);return i.searchParams.set("sessionId",e.sessionId),i.searchParams.set("step",e.step),e.challengeUrl&&i.searchParams.set("challengeUrl",e.challengeUrl),e.acsTransactionId&&i.searchParams.set("acsTransactionId",e.acsTransactionId),e.threeDSVersion&&i.searchParams.set("threeDSVersion",e.threeDSVersion),i.searchParams.set("liveMode",String(e.liveMode??!1)),i.toString()}handle3DSShellCancel(){this.postToIframe({type:"THREEDS_CANCELED",checkoutId:this.options.id,reason:"sdk_shell_cancel"}),this.threeDSModal.close(),this.emitter.emit(y.ThreeDSCanceled)}handle3DSReady(){this.threeDSModal.handleReady()||console.error("[PaypercutCheckout] No pending 3DS data or iframe not ready")}postThreeDSInit(e){const t=n(this.options.hostedCheckoutUrl);e.contentWindow?.postMessage({type:"THREEDS_INIT",checkoutId:this.options.id},t)}handleApplePayStart(e){this.abortApplePaySession();const t=window.ApplePaySession;if(!t)return void this.postToIframe({type:v,checkoutId:this.options.id});const i=t.supportsVersion?.(14)?14:3;let n;try{n=new t(i,e.request)}catch(e){return console.error("SecurityError"===e?.name?'[PaypercutCheckout] Apple Pay blocked — parent page missing allow="payment" on iframe':"[PaypercutCheckout] Failed to create ApplePaySession",e),void this.postToIframe({type:v,checkoutId:this.options.id})}this.applePaySession=n,n.onvalidatemerchant=e=>{this.applePayBridgeTimeout=setTimeout(()=>this.abortApplePaySession(),15e3),this.postToIframe({type:C,checkoutId:this.options.id,validationURL:e.validationURL})},n.onpaymentauthorized=e=>{this.postToIframe({type:E,checkoutId:this.options.id,payment:e.payment})},n.oncancel=()=>{this.applePaySession=null,this.postToIframe({type:I,checkoutId:this.options.id})},n.begin()}handleApplePayMerchantSession(e){if(this.applePayBridgeTimeout&&(clearTimeout(this.applePayBridgeTimeout),this.applePayBridgeTimeout=null),this.applePaySession)try{this.applePaySession.completeMerchantValidation(e)}catch(e){console.error("[PaypercutCheckout] completeMerchantValidation failed",e),this.abortApplePaySession(),this.postToIframe({type:v,checkoutId:this.options.id})}}handleApplePayPaymentResult(e){if(!this.applePaySession)return;const t=window.ApplePaySession;try{this.applePaySession.completePayment(e?t.STATUS_SUCCESS:t.STATUS_FAILURE)}catch(e){console.error("[PaypercutCheckout] completePayment failed",e)}this.applePaySession=null}abortApplePaySession(){this.applePayBridgeTimeout&&(clearTimeout(this.applePayBridgeTimeout),this.applePayBridgeTimeout=null);try{this.applePaySession?.abort()}catch{}this.applePaySession=null}destroy(){if(!this.destroyed){if(this.iframe)try{this.iframe.remove(),this.iframe=null}catch(e){console.error("[PaypercutCheckout] Error removing iframe:",e)}this.threeDSModal.close(),this.abortApplePaySession(),this.mounted=!1,this.destroyed=!0,window.removeEventListener("message",this.messageHandler),this.emitter.clear()}}on(e,t){return this.emitter.on(e,t)}once(e,t){return this.emitter.once(e,t)}off(e,t){this.emitter.off(e,t)}isMounted(){return this.mounted}completeFormValidation(e){this.mounted?this.postToIframe({type:"FORM_VALIDATION_COMPLETED",checkoutId:this.options.id,wallet:e,status:"success"}):console.warn("[PaypercutCheckout] Cannot complete form validation: not mounted")}updateAppearance(e){this.mounted?($(e.variables),this.postToIframe({type:"UPDATE_APPEARANCE",checkoutId:this.options.id,appearance:e})):console.warn("[PaypercutCheckout] Cannot update appearance: not mounted")}failFormValidation(e,t){this.mounted?this.postToIframe({type:"FORM_VALIDATION_COMPLETED",checkoutId:this.options.id,wallet:e,status:"failed",errors:t}):console.warn("[PaypercutCheckout] Cannot fail form validation: not mounted")}}const K=function(e){return new V(e)};return K.version=t.version,"undefined"!=typeof window&&(window.PaypercutExpressCheckout=H),K}();
|
|
1
|
+
var PaypercutCheckout=function(){"use strict";class e{constructor(){this.handlers=new Map}on(e,t){return this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t),()=>this.off(e,t)}once(e,t){const n=(...i)=>{t(...i),this.off(e,n)};return this.on(e,n)}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,...t){this.handlers.get(e)?.forEach(n=>{try{n(...t)}catch(t){console.error(`[Emitter] Error in ${e} handler:`,t)}})}emitAndThrow(e,...t){let n;if(this.handlers.get(e)?.forEach(e=>{try{e(...t)}catch(e){void 0===n&&(n=e)}}),void 0!==n){if(n instanceof Error)throw n;throw new Error(String(n))}}hasListeners(e){const t=this.handlers.get(e);return!!t&&t.size>0}clear(){this.handlers.clear()}}const t={version:"1.2.19",mode:"production",defaultCheckoutOrigin:"https://buy.paypercut.io",defaultApiOrigin:"https://api.paypercut.io",defaultVaultApiUrl:"https://api.basistheory.com",allowedOrigins:["https://buy.paypercut.io"]};function n(e){return!!t.allowedOrigins.includes(e)}function i(e){return t.defaultCheckoutOrigin}function o(e){return t.defaultApiOrigin}function s(){return t.defaultVaultApiUrl}function a(){const e="undefined"!=typeof window?window.visualViewport:void 0,t="undefined"!=typeof document?document.documentElement:void 0;return{width:e?.width||window.innerWidth||t?.clientWidth||window.screen?.width||460,height:e?.height||window.innerHeight||t?.clientHeight||window.screen?.height||680}}function r(e,t,n){const i=Math.min(t,n);return Math.min(Math.max(e,i),n)}class l{constructor(e){this.options=e,this.modal=null,this.shell=null,this.iframe=null,this.frameSize={},this.resizeHandler=null,this.pendingData=null}show(e){this.close(),this.modal=function(e){const t=document.createElement("div"),n=a();return t.id=e,Object.assign(t.style,{position:"fixed",top:"0",left:"0",width:`${n.width}px`,height:`${n.height}px`,minHeight:`${n.height}px`,display:"flex",alignItems:"center",justifyContent:"center",zIndex:"999999",background:"rgba(0, 0, 0, 0.56)",padding:"16px",boxSizing:"border-box",overflow:"hidden"}),t}(this.options.modalId),this.shell=function(e){const t=document.createElement("div");Object.assign(t.style,{position:"relative",borderRadius:"6px",background:"transparent",boxShadow:"0 24px 64px rgba(0, 0, 0, 0.36), 0 2px 10px rgba(0, 0, 0, 0.18)",overflow:"visible"});const n=document.createElement("iframe");n.allow="payment *",n.setAttribute("frameborder","0"),Object.assign(n.style,{border:"none",outline:"none",borderRadius:"6px",display:"block",background:"transparent",maxWidth:"100%",maxHeight:"100%"});const i=document.createElement("button");i.type="button",i.textContent="Cancel",i.setAttribute("aria-label","Cancel 3D Secure authentication"),Object.assign(i.style,{position:"absolute",top:"-40px",right:"0",zIndex:"2",height:"28px",padding:"0 10px",border:"0",borderRadius:"999px",background:"rgba(17, 24, 39, 0.56)",color:"#ffffff",font:'600 11px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',letterSpacing:"0.04em",textTransform:"uppercase",cursor:"pointer",boxShadow:"0 4px 16px rgba(0, 0, 0, 0.24)",transform:"translateY(0) scale(1)",transition:window.matchMedia?.("(prefers-reduced-motion: reduce)").matches?"none":"transform 300ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow 300ms cubic-bezier(0.22, 1, 0.36, 1), background 300ms cubic-bezier(0.22, 1, 0.36, 1)",willChange:"transform"});const o=()=>{i.style.background="rgba(17, 24, 39, 0.56)",i.style.boxShadow="0 4px 16px rgba(0, 0, 0, 0.24)",i.style.transform="translateY(0) scale(1)"},s=()=>{i.style.background="rgba(17, 24, 39, 0.68)",i.style.boxShadow="0 8px 22px rgba(0, 0, 0, 0.26)",i.style.transform="translateY(-1px) scale(1.025)"};return i.addEventListener("mouseenter",s),i.addEventListener("focus",s),i.addEventListener("mouseleave",o),i.addEventListener("blur",o),i.addEventListener("mouseup",s),i.addEventListener("mousedown",()=>{i.style.background="rgba(17, 24, 39, 0.72)",i.style.boxShadow="0 3px 12px rgba(0, 0, 0, 0.22)",i.style.transform="translateY(0) scale(0.985)"}),i.addEventListener("click",e),t.appendChild(n),t.appendChild(i),{shell:t,iframe:n,cancelButton:i}}(()=>this.options.onCancel()),this.iframe=this.shell.iframe,this.iframe.src=this.options.buildUrl(e),this.frameSize={},this.applySize(),this.modal.appendChild(this.shell.shell),document.body.appendChild(this.modal),this.resizeHandler=()=>this.applySize(),window.addEventListener("resize",this.resizeHandler),window.addEventListener("orientationchange",this.resizeHandler),window.visualViewport?.addEventListener("resize",this.resizeHandler),this.pendingData=e}handleFrameResize(e,t){if(!this.iframe?.contentWindow||e.source!==this.iframe.contentWindow)return;const n=function(e){if(!e||"object"!=typeof e)return null;const t=e,n={};return"number"==typeof t.width&&Number.isFinite(t.width)&&t.width>0&&(n.width=t.width),"number"==typeof t.height&&Number.isFinite(t.height)&&t.height>0&&(n.height=t.height),n.width||n.height?n:null}(t);n&&(this.frameSize={...this.frameSize,...n},this.applySize())}handleReady(){return!(!this.pendingData||!this.iframe?.contentWindow)&&(this.options.onReady(this.iframe,this.pendingData),!0)}close(){this.resizeHandler&&(window.removeEventListener("resize",this.resizeHandler),window.removeEventListener("orientationchange",this.resizeHandler),window.visualViewport?.removeEventListener("resize",this.resizeHandler),this.resizeHandler=null),this.modal&&(this.modal.remove(),this.modal=null),this.shell=null,this.iframe=null,this.frameSize={},this.pendingData=null}applySize(){!function(e,t,n={},i){if(!e||!t)return n;const o=a(),s=Math.min(860,Math.max(0,o.width-32)),l=Math.min(860,Math.max(0,o.height-112)),p=n.width??460,c=n.height??680,h=r(p,320,s),d=r(c,300,l);e.style.width=`${o.width}px`,e.style.height=`${o.height}px`,e.style.minHeight=`${o.height}px`,t.style.width=`${Math.round(h)}px`,t.style.height=`${Math.round(d)}px`,i&&(i.style.width=`${Math.round(h)}px`,i.style.height=`${Math.round(d)}px`)}(this.modal,this.iframe,this.frameSize,this.shell?.shell)}}const p=new Set(["bg","bg-BG","en","en-GB","el","el-GR","ro","ro-RO","hr","hr-HR","pl","pl-PL","cs","cs-CZ","sl","sl-SI","sk","sk-SK","hu","hu-HU"]);function c(e){return e&&"auto"!==e?p.has(e)?e:(console.warn(`[PaypercutCheckout] Locale "${e}" is not supported. Falling back to "en".`),"en"):"en"}var h,d,u,m;function y(e){return Object.values(d).includes(e)}function g(e){return Object.values(u).includes(e)}function f(e){var t;if(e)return t=e,Object.values(h).includes(t)?e:void console.warn(`[PaypercutCheckout] Invalid ui_mode: "${e}". Valid options: ${Object.values(h).join(", ")}`)}!function(e){e.EMBEDDED="embedded"}(h||(h={})),function(e){e.CARD="card"}(d||(d={})),function(e){e.APPLE_PAY="apple_pay",e.GOOGLE_PAY="google_pay"}(u||(u={})),function(e){e.Loaded="loaded",e.Processing="processing",e.Success="success",e.Error="error",e.Expired="expired",e.Resize="resize",e.ThreeDSComplete="threeds_complete",e.ThreeDSError="threeds_error",e.ThreeDSCanceled="threeds_canceled",e.ThreeDSStarted="threeds_started",e.Cancel="cancel",e.FormValidation="form_validation"}(m||(m={}));const b="SDK_CAPABILITIES",P="APPLE_PAY_START",w="APPLE_PAY_VALIDATE_MERCHANT",v="APPLE_PAY_MERCHANT_SESSION",E="APPLE_PAY_MERCHANT_ERROR",C="APPLE_PAY_PAYMENT_DATA",A="APPLE_PAY_PAYMENT_RESULT",S="APPLE_PAY_CANCELLED",I="APPLE_PAY_SESSION_ERROR",_=new Set(["ar","bg","ca","cs","da","de","el","en","es","et","fi","fr","hr","id","it","ja","ko","ms","nl","no","pl","pt","ru","sk","sl","sr","sv","th","tr","uk","zh"]);function T(e){return e||"en"}function O(e){const t=e.split("-")[0].toLowerCase();return _.has(t)?t:"en"}var R;!function(e){e.Ready="ready",e.Click="click",e.SessionStart="session_start",e.ShippingOptionsRequired="shipping_options_required",e.ShippingAddressChange="shipping_address_change",e.ShippingOptionChange="shipping_option_change",e.PaymentMethodCreated="payment_method_created",e.PaymentMethodFailed="payment_method_failed",e.Cancel="cancel",e.Error="error"}(R||(R={}));const k=14,x=3,M=15e3,L=10;function D(e){return e.supportsVersion?.(k)?k:x}const N=16,q=16,G=3,U=8;function z(){return"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.floor(Math.random()*q);return("x"===e?t:t&G|U).toString(N)})}const B=100,H=2;function j(e){return(e/B).toFixed(H)}function F(e){return e.startsWith("pk_live_")}let W=null;function Y(){return W||(W=new Promise(e=>{if("undefined"==typeof window)return void e();if(customElements?.get("apple-pay-button"))return void e();const t=document.createElement("script");t.src="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",t.async=!0,t.onload=()=>e(),t.onerror=()=>e(),document.head.appendChild(t)}),W)}let $=null;function V(){return $||($=new Promise((e,t)=>{if("undefined"==typeof window)return void t(new Error("No window"));if(globalThis.google?.payments?.api?.PaymentsClient)return void e();const n=document.createElement("script");n.src="https://pay.google.com/gp/p/js/pay.js",n.async=!0,n.onload=()=>e(),n.onerror=()=>t(new Error("Failed to load Google Pay script")),document.head.appendChild(n)}),$)}function K(e,t,n="DE"){const i={};return void 0!==e.amount&&(i.newTransactionInfo={totalPriceStatus:"FINAL",totalPriceLabel:"Total",totalPrice:j(e.amount),currencyCode:t,countryCode:n}),e.shippingOptions?.length&&(i.newShippingOptionParameters={defaultSelectedOptionId:e.shippingOptions[0].id,shippingOptions:e.shippingOptions.map(e=>({id:e.id,label:e.label,description:e.detail??`${j(e.amount)} ${t}`}))}),"invalid_shipping_address"===e.status?i.error={reason:"SHIPPING_ADDRESS_UNSERVICEABLE",message:"Cannot ship to this address.",intent:"SHIPPING_ADDRESS"}:"invalid_shipping_option"===e.status&&(i.error={reason:"SHIPPING_OPTION_INVALID",message:"This shipping option is not available.",intent:"SHIPPING_OPTION"}),i}const J=540,Z=3e3,X=3e4;function Q(e){return"checkout"===e?"check-out":e}class ee{constructor(t){this.options=t,this.emitter=new e,this.mounted=!1,this.destroyed=!1,this.sessionActive=!1,this.tokenizeIframe=null,this.wrapper=null,this.applePayContainer=null,this.applePayButtonEl=null,this.gpayContainer=null,this.gpayClient=null,this.gpayPaymentRequest=null,this.gpayCurrentAmount=0,this.preferredLayout="row",this.layoutResizeObserver=null,this.layoutResizeFrame=null,this.pendingObservedLayout=null,this.instanceId=z(),this.idempotencyKey=z(),this.pending3DSAfterGpay=null,this.applePaySession=null,this.applePayCurrentAmount=0,this.currentLineItems=[],this.applePayCurrentShippingOptions=[],this.applePayPendingShippingOption=null,this.applePayPendingCallback=null,this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.expressConfig=null,this.pendingGpayResolve=null,this.pendingGpayReject=null,this.pendingGpayBillingDetails=null,this.pendingGpayShippingDetails=null,this.pendingGpayShippingOption=void 0,this.currentShippingOptions=t.shippingOptions??[],this.messageHandler=this.onMessage.bind(this),this.threeDSModal=new l({modalId:"paypercut-express-3ds-modal",buildUrl:e=>this.buildThreeDSUrl(e),onCancel:()=>this.handle3DSShellCancel(),onReady:e=>this.postThreeDSInit(e)}),window.addEventListener("message",this.messageHandler)}buildTokenizeSrc(){const e=i(this.options.hostedCheckoutUrl),t=new URL("/express/tokenize",e);return t.searchParams.set("instanceId",this.instanceId),t.searchParams.set("liveMode",String(F(this.options.publishableKey))),t.toString()}async fetchExpressConfig(){const e=o(this.options.apiUrl),t=new URL("/v1/elements/sessions",e),{amount:n}=this.options;t.searchParams.set("type","deferred_intent"),t.searchParams.set("key",this.options.publishableKey),t.searchParams.set("deferred_intent[mode]","payment"),t.searchParams.set("deferred_intent[currency]",this.options.currency),null!=n&&t.searchParams.set("deferred_intent[amount]",`${n}`),t.searchParams.set("referrer_host",window.location.hostname);try{const e=await fetch(t.toString(),{cache:"no-store"});if(!e.ok)throw new Error(`Config fetch failed: HTTP ${e.status}`);const n=await e.json(),i=F(this.options.publishableKey),o="BCR2DN5T735375Y7",a=n.payment_domain?.wallets?.google_pay?.merchant_ref??"",r=n.payment_domain?.wallets?.google_pay?.status??"inactive";this.expressConfig={tenantId:n.payment_domain?.wallet_provider?.tenant_id??"",publicKey:n.payment_domain?.wallet_provider?.public_key??"",vaultApiUrl:s(),googlePayMerchantId:i?"active"===r?a:o:a||o,googlePayStatus:r,applePayStatus:n.payment_domain?.wallets?.apple_pay?.status??"inactive",displayName:n.merchant?.name??"",merchantMid:n.merchant?.mid??"",merchantMcc:n.merchant?.mcc??"",merchantCountry:n.merchant?.country??"",merchantUrl:n.merchant?.business_url??""}}catch(e){console.error("[PaypercutExpressCheckout] Failed to fetch express config:",e)}}onMessage(e){if(!n(e.origin))return void(e.origin.includes("localhost")&&console.warn("[PaypercutExpressCheckout] Message blocked — origin not allowed:",e.origin));const t=e.data;if(t&&"object"==typeof t&&"type"in t&&(!t.instanceId||t.instanceId===this.instanceId))switch(t.type){case"TOKENIZE_RESPONSE":if("apple_pay"===t.wallet)t.success?this.createPaymentMethod({btTokenId:t.btTokenId,cardPayload:t.cardPayload,billingDetails:t.billingDetails,csessId:t.csessId,walletType:"apple_pay"}).then(e=>{this.completeApplePaySession(!0),this.emitter.emit(R.PaymentMethodCreated,{paymentMethodId:e,wallet:"apple_pay",billingDetails:this.applePayPendingBillingDetails??void 0,shippingDetails:this.applePayPendingShippingDetails??void 0,selectedShippingOption:this.applePayPendingShippingOption??void 0}),this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.applePayPendingShippingOption=null}).catch(e=>{this.completeApplePaySession(!1),this.emitter.emit(R.Error,new Error(e?.message??"Payment method creation failed")),this.emitter.emit(R.PaymentMethodFailed,{error:e?.message??"Payment method creation failed"}),this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.applePayPendingShippingOption=null}):(this.completeApplePaySession(!1),this.emitter.emit(R.Error,new Error(t.error??"Apple Pay payment failed")),this.emitter.emit(R.PaymentMethodFailed,{error:t.error??"Apple Pay payment failed"}),this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.applePayPendingShippingOption=null);else if(t.success)this.pendingGpayResolve?(this.pendingGpayResolve(t),this.pendingGpayResolve=null,this.pendingGpayReject=null):this.createPaymentMethod({btTokenId:t.btTokenId,cardPayload:t.cardPayload,billingDetails:t.billingDetails,csessId:t.csessId,walletType:"google_pay"}).then(e=>{this.emitter.emit(R.PaymentMethodCreated,{paymentMethodId:e,wallet:"google_pay",billingDetails:this.pendingGpayBillingDetails??void 0,shippingDetails:this.pendingGpayShippingDetails??void 0,selectedShippingOption:this.pendingGpayShippingOption})}).catch(e=>{this.emitter.emit(R.Error,new Error(e?.message??"Payment method creation failed")),this.emitter.emit(R.PaymentMethodFailed,{error:e?.message??"Payment method creation failed"})}).finally(()=>{this.pendingGpayBillingDetails=null,this.pendingGpayShippingDetails=null,this.pendingGpayShippingOption=void 0});else if(this.pendingGpayReject)this.pendingGpayReject(new Error(t.error??"Tokenization failed")),this.pendingGpayResolve=null,this.pendingGpayReject=null;else{const e=t.error??"Google Pay payment failed";e.toLowerCase().includes("cancel")?this.emitter.emit(R.Cancel):(this.emitter.emit(R.Error,new Error(e)),this.emitter.emit(R.PaymentMethodFailed,{error:e})),this.pendingGpayBillingDetails=null,this.pendingGpayShippingDetails=null,this.pendingGpayShippingOption=void 0}break;case"PAYPERCUT_THREEDS_FRAME_RESIZE":this.threeDSModal.handleFrameResize(e,t);break;case"THREEDS_START_FLOW":this.pendingGpayResolve?(this.pending3DSAfterGpay=t,this.pendingGpayResolve({__closeSheet:!0}),this.pendingGpayResolve=null,this.pendingGpayReject=null):this.threeDSModal.show(t);break;case"THREEDS_READY":this.handle3DSReady();break;case"THREEDS_COMPLETE":case"THREEDS_CANCELED":case"THREEDS_ERROR":this.postToTokenizeIframe(t),this.threeDSModal.close()}}mount(e){if(this.mounted)return void console.warn("[PaypercutExpressCheckout] mount() called but already mounted — ignoring");const t="string"==typeof e?document.querySelector(e):e;if(!t)throw new Error(`[PaypercutExpressCheckout] Container not found: ${e}`);const n=this.options.walletOptions?.length?this.options.walletOptions:[u.APPLE_PAY,u.GOOGLE_PAY],i=n.includes(u.APPLE_PAY),o=n.includes(u.GOOGLE_PAY),s=this.options.layout??"auto";this.preferredLayout="auto"===s?"row":s;const a=document.createElement("div");this.wrapper=a,Object.assign(a.style,{display:"flex",flexDirection:"row"===this.preferredLayout?"row":"column",gap:"8px",width:"100%"}),o&&(this.gpayContainer=document.createElement("div"),this.applyLayoutToContainers(this.preferredLayout,this.gpayContainer),a.appendChild(this.gpayContainer),V().catch(e=>{console.error("[PaypercutExpressCheckout] Failed to load Google Pay script:",e)})),i&&(this.applePayContainer=document.createElement("div"),this.applyLayoutToContainers(this.preferredLayout,this.applePayContainer),a.appendChild(this.applePayContainer),Y()),t.appendChild(a),"auto"===s&&"undefined"!=typeof ResizeObserver&&(this.layoutResizeObserver=new ResizeObserver(e=>{const n=e[0]?.contentRect.width??t.offsetWidth;this.pendingObservedLayout=n<=J?"column":"row",null===this.layoutResizeFrame&&(this.layoutResizeFrame=window.requestAnimationFrame(()=>{this.layoutResizeFrame=null;const e=this.pendingObservedLayout;this.pendingObservedLayout=null,e&&this.applyLayout(e)}))}),this.layoutResizeObserver.observe(t));const r=this.buildTokenizeSrc();this.tokenizeIframe=document.createElement("iframe"),this.tokenizeIframe.id="paypercut-express-tokenize-iframe",this.tokenizeIframe.src=r,this.tokenizeIframe.setAttribute("frameborder","0"),this.tokenizeIframe.setAttribute("sandbox","allow-scripts allow-forms allow-same-origin"),Object.assign(this.tokenizeIframe.style,{position:"absolute",top:"-9999px",left:"-9999px",width:"1px",height:"1px",border:"none",visibility:"hidden"}),document.body.appendChild(this.tokenizeIframe),this.mounted=!0,this.fetchExpressConfig().then(async()=>{if(this.destroyed)return;const e=this.expressConfig;i&&this.applePayContainer&&"active"===e?.applePayStatus?await this.mountApplePayButton(this.applePayContainer):this.applePayContainer&&this.removeApplePayContainer(),o&&e&&this.mountGooglePayFromConfig(),this.emitter.emit(R.Ready)})}applyLayoutToContainers(e,...t){for(const n of t)n&&(n.style.flex="row"===e?"1":"",n.style.minWidth="row"===e?"0":"",n.style.width="row"===e?"":"100%")}applyLayout(e){this.wrapper&&(this.wrapper.style.flexDirection="row"===e?"row":"column",this.applyLayoutToContainers(e,this.applePayContainer,this.gpayContainer))}setLayout(e){this.preferredLayout=e,this.applyLayout(e)}setLocale(e){this.options.locale=e,this.applePayButtonEl&&this.applePayButtonEl.setAttribute("locale",T(e)),this.gpayClient&&this.gpayContainer&&this.gpayPaymentRequest&&this.setButtonOptions({})}setButtonOptions(e){this.options.buttonOptions={...this.options.buttonOptions,...e};const t=this.options.buttonOptions;if(this.applePayButtonEl&&(void 0!==e.applePayStyle&&this.applePayButtonEl.setAttribute("buttonstyle",e.applePayStyle),void 0!==e.type&&this.applePayButtonEl.setAttribute("type",Q(e.type)),void 0!==e.borderRadius&&this.applePayButtonEl.style.setProperty("--apple-pay-button-border-radius",e.borderRadius)),this.gpayClient&&this.gpayContainer&&this.gpayPaymentRequest){this.gpayContainer.innerHTML="";const e=this.gpayClient.createButton({onClick:()=>this.startGooglePay(this.gpayPaymentRequest),buttonSizeMode:"fill",buttonType:t?.type??"plain",buttonColor:t?.googlePayColor??"default",...this.options.locale&&{buttonLocale:O(this.options.locale)}}),n=t?.borderRadius??"0.5rem";e.style.width="100%",this.injectGpayInnerStyles(e,n),this.gpayContainer.appendChild(e)}}async mountApplePayButton(e){await Y();const t=window.ApplePaySession;if(!t)return void console.log("[PaypercutExpressCheckout] ApplePaySession not available");if(!t.canMakePayments?.())return void console.log("[PaypercutExpressCheckout] ApplePaySession.canMakePayments() returned false — hiding Apple Pay button");const n=this.options.locale?T(this.options.locale):"en",i=this.options.buttonOptions,o=document.createElement("apple-pay-button");o.setAttribute("buttonstyle",i?.applePayStyle??"black"),o.setAttribute("type",Q(i?.type??"plain")),o.setAttribute("locale",n),o.style.setProperty("--apple-pay-button-width","100%"),o.style.setProperty("--apple-pay-button-height","48px"),o.style.setProperty("--apple-pay-button-border-radius",i?.borderRadius??"0.5rem"),o.style.display="block",o.style.cursor="pointer",o.addEventListener("click",()=>this.startApplePay());const s=()=>{this.applePayButtonEl=o,e.appendChild(o);const t=o.shadowRoot;if(t){const e=document.createElement("style");e.textContent="span svg { height: 75% !important; width: auto !important; }",t.appendChild(e)}};customElements?.get("apple-pay-button")?s():customElements?.whenDefined("apple-pay-button").then(s).catch(()=>s())}async startApplePay(){if(this.sessionActive)return;if("undefined"==typeof window)return;const e=window.ApplePaySession;if(!e)return void console.error("[PaypercutExpressCheckout] ApplePaySession not available");this.idempotencyKey=z(),this.setSessionActive(!0),this.emitter.emit(R.Click);const t=await new Promise(e=>{if(!this.emitter.hasListeners(R.SessionStart))return void e(null);const t=setTimeout(()=>e(null),Z);this.emitter.emit(R.SessionStart,{wallet:"apple_pay",updateWith:n=>{clearTimeout(t),e(n)}})});if(!t)return console.error("[PaypercutExpressCheckout] Apple Pay: no session_start response — aborting"),this.setSessionActive(!1),void this.emitter.emit(R.ShippingOptionsRequired,{wallet:"apple_pay"});"number"==typeof t.amount?this.applePayCurrentAmount=t.amount:this.applePayCurrentAmount=this.options.amount,Array.isArray(t.lineItems)?this.currentLineItems=t.lineItems:this.currentLineItems=this.options.lineItems??[],Array.isArray(t.shippingOptions)?this.applePayCurrentShippingOptions=t.shippingOptions:this.applePayCurrentShippingOptions=this.currentShippingOptions,this.applePayPendingShippingOption=null;const n=this.expressConfig?.displayName||"Checkout",i=j(this.applePayCurrentAmount),o=this.currentLineItems.map(e=>({label:e.label,amount:j(e.amount),type:e.type??"final"})),a={countryCode:this.options.countryCode??"DE",currencyCode:this.options.currency,merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],supportedNetworks:["visa","masterCard"],lineItems:o,total:{label:n,amount:i,type:"final"},requiredBillingContactFields:["postalAddress","name","email"],requiredShippingContactFields:["postalAddress","name","email"]};this.applePayCurrentShippingOptions.length&&(a.shippingMethods=this.applePayCurrentShippingOptions.map(e=>({label:e.label,detail:e.detail??"",amount:j(e.amount),identifier:e.id}))),a.shippingType="shipping",this.abortApplePaySession();const r=D(e);try{const t=new e(r,a);this.applePaySession=t,t.onvalidatemerchant=async e=>{const i=this.expressConfig?.vaultApiUrl??s(),o=this.expressConfig?.publicKey??"";try{const s={"Content-Type":"application/json","BT-API-KEY":o};this.idempotencyKey&&(s["Idempotency-Key"]=this.idempotencyKey);const a=await fetch(`${i}/apple-pay/session`,{method:"POST",headers:s,body:JSON.stringify({display_name:n,domain:window.location.host,validation_url:e.validationURL})});if(!a.ok){const e=await a.json().catch(()=>({}));throw new Error(e?.message??`Merchant validation failed: HTTP ${a.status}`)}const r=await a.json();t.completeMerchantValidation(r)}catch(e){console.error("[PaypercutExpressCheckout] Apple Pay merchant validation failed"),this.abortApplePaySession(),this.emitter.emit(R.Error,new Error(e?.message??"Apple Pay merchant validation failed")),this.emitter.emit(R.Cancel)}},t.onshippingcontactselected=async i=>{const o=i.shippingContact,s=await new Promise(e=>{this.applePayPendingCallback={type:"contact",resolve:e},this.emitter.emit(R.ShippingAddressChange,{address:{country:o.countryCode??"",state:o.administrativeArea,city:o.locality,postalCode:o.postalCode},updateWith:e=>this.update(e)}),setTimeout(()=>e({}),X)});this.applePayPendingCallback=null,"number"==typeof s.amount&&(this.applePayCurrentAmount=s.amount),Array.isArray(s.lineItems)&&(this.currentLineItems=s.lineItems),Array.isArray(s.shippingOptions)&&(this.applePayCurrentShippingOptions=s.shippingOptions);const a="invalid_shipping_address"===s.status?e.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS:e.STATUS_SUCCESS;try{t.completeShippingContactSelection(a,this.applePayCurrentShippingOptions.map(e=>({label:e.label,detail:e.detail??"",amount:j(e.amount),identifier:e.id})),{label:n,amount:j(this.applePayCurrentAmount),type:"final"},this.currentLineItems.map(e=>({label:e.label,amount:j(e.amount),type:e.type??"final"})))}catch(e){console.error("[PaypercutExpressCheckout] completeShippingContactSelection failed",e)}},t.onshippingmethodselected=async i=>{const o=i.shippingMethod,s={id:o.identifier,label:o.label,detail:o.detail,amount:(a=o.amount,Math.round(Number.parseFloat(a)*B))};var a;this.applePayPendingShippingOption=s;const r=await new Promise(e=>{this.applePayPendingCallback={type:"method",resolve:e},this.emitter.emit(R.ShippingOptionChange,{shippingOption:s,updateWith:e=>this.update(e)}),setTimeout(()=>e({}),X)});this.applePayPendingCallback=null,"number"==typeof r.amount&&(this.applePayCurrentAmount=r.amount),Array.isArray(r.lineItems)&&(this.currentLineItems=r.lineItems);try{t.completeShippingMethodSelection(e.STATUS_SUCCESS,{label:n,amount:j(this.applePayCurrentAmount),type:"final"},this.currentLineItems.map(e=>({label:e.label,amount:j(e.amount),type:e.type??"final"})))}catch(e){console.error("[PaypercutExpressCheckout] completeShippingMethodSelection failed",e)}},t.onpaymentauthorized=e=>{const t=e.payment?.billingContact,n=e.payment?.shippingContact;this.applePayPendingBillingDetails=t?{name:[t.givenName,t.familyName].filter(Boolean).join(" ")||void 0,email:t.emailAddress,address:{line1:t.addressLines?.[0],line2:t.addressLines?.[1],city:t.locality,state:t.administrativeArea,postalCode:t.postalCode,country:t.countryCode}}:null,this.applePayPendingShippingDetails=n?{name:[n.givenName,n.familyName].filter(Boolean).join(" ")||void 0,address:{line1:n.addressLines?.[0],line2:n.addressLines?.[1],city:n.locality,state:n.administrativeArea,postalCode:n.postalCode,country:n.countryCode}}:null,this.postToTokenizeIframe({type:"TOKENIZE_REQUEST",instanceId:this.instanceId,wallet:"apple_pay",applePaymentData:e.payment.token,idemKey:this.idempotencyKey,publishableKey:this.options.publishableKey,billingDetails:this.applePayPendingBillingDetails,amount:this.applePayCurrentAmount,currency:this.options.currency,merchantInfo:{name:this.expressConfig?.displayName??"",mid:this.expressConfig?.merchantMid??"",mcc:this.expressConfig?.merchantMcc??"",country:this.expressConfig?.merchantCountry??"",url:this.expressConfig?.merchantUrl??""}})},t.oncancel=()=>{this.applePaySession=null,this.applePayPendingCallback=null,this.applePayPendingShippingOption=null,this.emitter.emit(R.Cancel)},t.begin()}catch(e){this.applePaySession=null,console.error("[PaypercutExpressCheckout] Failed to create ApplePaySession",{name:e?.name,message:e?.message,hint:"SecurityError"===e?.name?"Page is not HTTPS or merchant domain is not registered for Apple Pay":"Check isSecureContext and that ApplePaySession.canMakePayments() returns true"})}}removeGpayContainer(){this.gpayContainer?.remove(),this.gpayContainer=null}removeApplePayContainer(){this.applePayContainer?.remove(),this.applePayContainer=null,this.applePayButtonEl=null}mountGooglePayFromConfig(){const e=this.expressConfig;if(!e)return;const t=F(this.options.publishableKey),n=e.tenantId,i=e.googlePayMerchantId,o=e.displayName||"Checkout";return n?i?(console.log({liveMode:t}),!t||e.merchantMcc&&e.merchantUrl?void V().then(()=>{this.mountGooglePayButton(n,i,o,t)}).catch(e=>{console.error("[PaypercutExpressCheckout] Failed to load Google Pay script:",e)}):(console.warn("[PaypercutExpressCheckout] Google Pay disabled!"),void this.removeGpayContainer())):(console.warn("[PaypercutExpressCheckout] googlePayMerchantId is empty — Google Pay will not be mounted (merchant may not have Google Pay active)."),void this.removeGpayContainer()):(console.error("[PaypercutExpressCheckout] tenantId is empty — Google Pay cannot be mounted without a valid gatewayMerchantId."),void this.removeGpayContainer())}mountGooglePayButton(e,t,n,i){if(!this.gpayContainer)return void console.error("[PaypercutExpressCheckout] gpayContainer is null");const o=globalThis.google;if(!o?.payments?.api?.PaymentsClient)return void console.error("[PaypercutExpressCheckout] google.payments.api.PaymentsClient not available");const s=i?"PRODUCTION":"TEST",a=this.options.countryCode;a||console.warn('[PaypercutExpressCheckout] countryCode is not set. This is required for Google Pay in production. Pass it via options.countryCode (e.g. "DE").');const r={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["CRYPTOGRAM_3DS","PAN_ONLY"],allowedCardNetworks:["MASTERCARD","VISA"],billingAddressRequired:!0,billingAddressParameters:{format:"FULL",phoneNumberRequired:!1}},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:"basistheory",gatewayMerchantId:e}}}],merchantInfo:{merchantId:t,merchantName:n},transactionInfo:{totalPriceStatus:"FINAL",totalPriceLabel:"Total",totalPrice:j(this.options.amount),currencyCode:this.options.currency,countryCode:a},callbackIntents:["PAYMENT_AUTHORIZATION","SHIPPING_ADDRESS","SHIPPING_OPTION"],shippingAddressRequired:!0,shippingOptionRequired:!0};this.options.allowedCountries?.length&&(r.shippingAddressParameters={allowedCountryCodes:this.options.allowedCountries,phoneNumberRequired:!1}),this.options.shippingOptions?.length&&(r.shippingOptionParameters={defaultSelectedOptionId:this.options.shippingOptions[0].id,shippingOptions:this.options.shippingOptions.map(e=>({id:e.id,label:e.label,description:e.detail??`${j(e.amount)} ${this.options.currency}`}))}),this.gpayPaymentRequest=r,this.gpayClient=new o.payments.api.PaymentsClient({environment:s,paymentDataCallbacks:{onPaymentAuthorized:e=>this.handleGooglePayAuthorized(e),onPaymentDataChanged:e=>this.handleGooglePayDataChanged(e)}});const l=this.options.buttonOptions,p=this.gpayClient.createButton({onClick:()=>this.startGooglePay(r),buttonSizeMode:"fill",buttonType:l?.type??"plain",buttonColor:l?.googlePayColor??"default",...this.options.locale&&{buttonLocale:O(this.options.locale)}}),c=l?.borderRadius??"0.5rem";p.style.width="100%",this.injectGpayInnerStyles(p,c),this.gpayContainer.appendChild(p)}injectGpayInnerStyles(e,t){const n=document.createElement("style");n.textContent=`.gpay-button { height: 48px !important; border-radius: ${t} !important; background-size: auto 60% !important; } .gpay-card-info-container { border-radius: ${t} !important; } .gpay-card-info-container-fill, .gpay-card-info-container-fill > .gpay-card-info-container { height: 48px !important; }`,e.prepend(n)}async startGooglePay(e){if(this.gpayClient&&!this.sessionActive){if(this.idempotencyKey=z(),this.setSessionActive(!0),this.emitter.emit(R.Click),this.emitter.hasListeners(R.SessionStart)){const t=await new Promise(e=>{const t=setTimeout(()=>e(null),Z);this.emitter.emit(R.SessionStart,{wallet:"google_pay",updateWith:n=>{clearTimeout(t),e(n)}})});if(!t)return this.setSessionActive(!1),void this.emitter.emit(R.ShippingOptionsRequired,{wallet:"google_pay"});t.shippingOptions&&(this.currentShippingOptions=t.shippingOptions,e.shippingOptionParameters={defaultSelectedOptionId:t.shippingOptions[0]?.id,shippingOptions:t.shippingOptions.map(e=>({id:e.id,label:e.label,description:e.detail??`${j(e.amount)} ${this.options.currency}`}))}),null!=t.amount&&(this.gpayCurrentAmount=t.amount,e.transactionInfo={...e.transactionInfo,totalPrice:j(t.amount)})}this.gpayCurrentAmount||(this.gpayCurrentAmount=this.options.amount);try{if(await this.gpayClient.loadPaymentData(e),this.pending3DSAfterGpay){const e=this.pending3DSAfterGpay;this.pending3DSAfterGpay=null,this.threeDSModal.show(e)}}catch(e){"CANCELED"===e?.statusCode||e?.message?.toLowerCase?.().includes("cancel")?this.emitter.emit(R.Cancel):this.emitter.emit(R.Error,new Error(e?.message??"Google Pay failed"))}finally{this.setSessionActive(!1)}}}async handleGooglePayAuthorized(e){try{const t=e.paymentMethodData.tokenizationData.token,n=e.paymentMethodData?.info?.cardNetwork??"",i=e.paymentMethodData?.info?.billingAddress,o=e.shippingAddress,s=e.shippingOptionData,a=i?{name:i.name,address:{line1:i.address1,city:i.locality,state:i.administrativeArea,postalCode:i.postalCode,country:i.countryCode}}:null,r=o?{name:o.name||void 0,address:{line1:o.address1,city:o.locality,state:o.administrativeArea,postalCode:o.postalCode,country:o.countryCode}}:void 0,l=s?this.currentShippingOptions.find(e=>e.id===s.id)??{id:s.id,label:s.label??s.id,amount:0}:void 0;this.pendingGpayBillingDetails=a,this.pendingGpayShippingDetails=r,this.pendingGpayShippingOption=l;const p=await new Promise((e,i)=>{const o=setTimeout(()=>{this.pendingGpayResolve=null,this.pendingGpayReject=null,i(new Error("Tokenization timed out"))},X);this.pendingGpayResolve=t=>{clearTimeout(o),e(t)},this.pendingGpayReject=e=>{clearTimeout(o),i(e)},this.postToTokenizeIframe({type:"TOKENIZE_REQUEST",instanceId:this.instanceId,wallet:"google_pay",encryptedToken:t,cardNetwork:n,idemKey:this.idempotencyKey,publishableKey:this.options.publishableKey,billingDetails:a,amount:this.options.amount,currency:this.options.currency,merchantInfo:{name:this.expressConfig?.displayName??"",mid:this.expressConfig?.merchantMid??"",mcc:this.expressConfig?.merchantMcc??"",country:this.expressConfig?.merchantCountry??"",url:this.expressConfig?.merchantUrl??""}})});if(p.__closeSheet)return{transactionState:"SUCCESS"};if(!p.success){const e=p.error??"Tokenization failed";return this.emitter.emit(R.Error,new Error(e)),this.emitter.emit(R.PaymentMethodFailed,{error:e}),{transactionState:"ERROR"}}const c=await this.createPaymentMethod({btTokenId:p.btTokenId,cardPayload:p.cardPayload,billingDetails:p.billingDetails,csessId:p.csessId,walletType:"google_pay"});return this.emitter.emit(R.PaymentMethodCreated,{paymentMethodId:c,wallet:"google_pay",billingDetails:a??void 0,shippingDetails:r,selectedShippingOption:l}),this.pendingGpayBillingDetails=null,this.pendingGpayShippingDetails=null,this.pendingGpayShippingOption=void 0,{transactionState:"SUCCESS"}}catch(e){return console.error("[PaypercutExpressCheckout] handleGooglePayAuthorized error:",e?.message??e),this.emitter.emit(R.Error,new Error(e?.message??"Google Pay authorization failed")),this.emitter.emit(R.PaymentMethodFailed,{error:e?.message??"Google Pay authorization failed"}),{transactionState:"ERROR"}}}async handleGooglePayDataChanged(e){const{callbackTrigger:t,shippingAddress:n,shippingOptionData:i}=e;if("INITIALIZE"===t)return K({amount:this.gpayCurrentAmount||this.options.amount,shippingOptions:this.currentShippingOptions},this.options.currency,this.options.countryCode);if("SHIPPING_ADDRESS"===t){return K(await new Promise(e=>{this.emitter.emit(R.ShippingAddressChange,{address:{country:n?.countryCode??"",state:n?.administrativeArea,city:n?.locality,postalCode:n?.postalCode},updateWith:t=>{t.shippingOptions&&(this.currentShippingOptions=t.shippingOptions),null!=t.amount&&(this.gpayCurrentAmount=t.amount),e(t)}})}),this.options.currency,this.options.countryCode)}if("SHIPPING_OPTION"===t){const e=i?.id,t=this.currentShippingOptions.find(t=>t.id===e);return K(await new Promise(n=>{this.emitter.emit(R.ShippingOptionChange,{shippingOption:{id:e??"",label:t?.label??e??"",detail:t?.detail,amount:t?.amount??0},updateWith:e=>{null!=e.amount&&(this.gpayCurrentAmount=e.amount),n(e)}})}),this.options.currency,this.options.countryCode)}return{}}update(e){this.mounted?this.applePayPendingCallback&&this.applePayPendingCallback.resolve(e):console.warn("[PaypercutExpressCheckout] Cannot update: not mounted")}on(e,t){return this.emitter.on(e,t)}destroy(){if(!this.destroyed){if(this.tokenizeIframe){try{this.tokenizeIframe.remove()}catch{}this.tokenizeIframe=null}if(this.gpayContainer){try{this.gpayContainer.remove()}catch{}this.gpayContainer=null}if(this.applePayContainer)try{this.removeApplePayContainer()}catch{}this.gpayPaymentRequest=null,this.layoutResizeObserver&&(this.layoutResizeObserver.disconnect(),this.layoutResizeObserver=null),null!==this.layoutResizeFrame&&(window.cancelAnimationFrame(this.layoutResizeFrame),this.layoutResizeFrame=null),this.pendingObservedLayout=null,this.threeDSModal.close(),this.abortApplePaySession(),this.sessionActive=!1,this.mounted=!1,this.destroyed=!0,window.removeEventListener("message",this.messageHandler),this.emitter.clear()}}setSessionActive(e){this.sessionActive=e;const t=e?"0.5":"",n=e?"none":"";this.applePayContainer&&(this.applePayContainer.style.opacity=t,this.applePayContainer.style.pointerEvents=n,this.applePayContainer.inert=e,this.applePayContainer.setAttribute("aria-busy",String(e))),this.gpayContainer&&(this.gpayContainer.style.opacity=t,this.gpayContainer.style.pointerEvents=n,this.gpayContainer.inert=e,this.gpayContainer.setAttribute("aria-busy",String(e)))}completeApplePaySession(e){try{if(this.applePaySession){const t=window.ApplePaySession,n=e?t.STATUS_SUCCESS:t.STATUS_FAILURE;this.applePaySession.completePayment(n)}}catch{}this.applePaySession=null,this.applePayPendingCallback=null,this.applePayPendingShippingOption=null,this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.setSessionActive(!1)}abortApplePaySession(){try{this.applePaySession?.abort()}catch{}this.applePaySession=null,this.applePayPendingCallback=null,this.applePayPendingShippingOption=null,this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.setSessionActive(!1)}async createPaymentMethod(e){const{btTokenId:t,cardPayload:n,billingDetails:i,csessId:s,walletType:a}=e;if(!n||!t)throw new Error("[createPaymentMethod] Missing required tokenization data.");const r=new URL("/v1/payment_methods",o(this.options.apiUrl)),l={type:"card",key:this.options.publishableKey,card:{token:s??"",brand:n.brand??"",exp_month:n.exp_month??1,exp_year:n.exp_year??1,funding:n.funding??"",last4:n.last4??"",iin:n.bin??"",issuer:n.issuer??null,fingerprint:n.fingerprint??null,segment:n.segment??"",wallet:{type:a,dynamic_last4:null},three_d_secure_usage:{supported:!0}},billing_details:{name:i?.name??null,email:i?.email??null,phone:i?.phone??null,address:{city:i?.address?.city??null,country:i?.address?.country??null,line1:i?.address?.line1??null,line2:i?.address?.line2??null,postal_code:i?.address?.postalCode??null,state:i?.address?.state??null}},confirmation_token:{token_id:t}},p=await fetch(r.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l),cache:"no-store"});if(!p.ok){const e=await p.text().catch(()=>`HTTP ${p.status}`);throw new Error(`Payment method creation failed (${p.status}): ${e}`)}return(await p.json()).id}postToTokenizeIframe(e){if(!this.tokenizeIframe?.contentWindow)return;const t=i(this.options.hostedCheckoutUrl);this.tokenizeIframe.contentWindow.postMessage(e,t)}buildThreeDSUrl(e){const t=i(this.options.hostedCheckoutUrl),n=new URL("/express/threeds",t);return n.searchParams.set("instanceId",this.instanceId),n.searchParams.set("sessionId",e.sessionId),n.searchParams.set("step",e.step),e.challengeUrl&&n.searchParams.set("challengeUrl",e.challengeUrl),e.acsTransactionId&&n.searchParams.set("acsTransactionId",e.acsTransactionId),e.threeDSVersion&&n.searchParams.set("threeDSVersion",e.threeDSVersion),n.searchParams.set("liveMode",String(e.liveMode??!1)),n.toString()}handle3DSShellCancel(){this.postToTokenizeIframe({type:"THREEDS_CANCELED",instanceId:this.instanceId,error:"User canceled 3DS authentication"}),this.threeDSModal.close(),this.emitter.emit(R.Cancel)}handle3DSReady(){this.threeDSModal.handleReady()||console.error("[PaypercutExpressCheckout] No pending 3DS data or iframe not ready")}postThreeDSInit(e){const t=i(this.options.hostedCheckoutUrl);e.contentWindow?.postMessage({type:"THREEDS_INIT",instanceId:this.instanceId},t)}}const te=function(e){return new ee(e)},ne=128,ie=1024,oe=/[\u0000-\u001f\u007f]/u,se=e=>oe.test(e),ae=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),re=(e,t)=>Object.keys(e).every(e=>t.includes(e))&&t.every(t=>Object.prototype.hasOwnProperty.call(e,t)),le=(e,t)=>"string"==typeof e&&e.length>0&&e.length<=t&&e===e.trim()&&!se(e),pe=new Set(["colorPrimary","colorPrimaryText","colorBackground","colorSurface","colorText","colorTextSecondary","colorTextPlaceholder","colorDanger","colorSuccess","colorWarning","colorBorder","colorFocus","colorMuted","fontFamily","fontSizeBase","fontWeightNormal","fontWeightMedium","lineHeight","spacingUnit","gridColumnSpacing","gridRowSpacing","labelSpacing","borderRadius","buttonBorderRadius","buttonExpressCheckoutBorderRadius","buttonPadding"]),ce=new Set([".Input",".Input--invalid",".Input:focus",".Label",".Error",".Text",".WalletButton",".WalletButton--applePay",".WalletButton--googlePay",".ActionShell"]),he=new Set(["backgroundColor","borderColor","borderRadius","borderStyle","borderWidth","borderTopColor","borderTopLeftRadius","borderTopRightRadius","borderTopStyle","borderTopWidth","borderRightColor","borderRightStyle","borderRightWidth","borderBottomColor","borderBottomLeftRadius","borderBottomRightRadius","borderBottomStyle","borderBottomWidth","borderLeftColor","borderLeftStyle","borderLeftWidth","boxShadow","color","fontFamily","fontSize","fontWeight","letterSpacing","lineHeight","opacity","outline","outlineOffset","padding","paddingTop","paddingRight","paddingBottom","paddingLeft","textDecoration","textShadow","textTransform","transition"]),de=/[{};]|<\/style|@import|expression\s*\(|javascript\s*:|url\s*\(/i,ue=/var\(\s*--([A-Za-z][A-Za-z0-9]*)\s*\)/gi;function me(e){return"string"==typeof e&&e.length>0&&e.length<=512&&e===e.trim()&&!se(e)&&!de.test(e)&&function(e){const t=e.replace(ue,(e,t)=>pe.has(t)?"":"var(invalid)");return!/var\s*\(/i.test(t)}(e)}function ye(e){if(!be(e)||0===Object.keys(e).length)throw new Error("[Paypercut Elements] Appearance details are required.");const t=new Set(["theme","inputs","labels","variables","rules","disableAnimations"]);if(Object.keys(e).some(e=>!t.has(e)))throw new Error("[Paypercut Elements] Appearance contains an unsupported field.");if(void 0!==e.theme&&"light"!==e.theme&&"dark"!==e.theme)throw new Error("[Paypercut Elements] Appearance theme must be light or dark.");if(void 0!==e.inputs&&"condensed"!==e.inputs&&"spaced"!==e.inputs)throw new Error("[Paypercut Elements] Appearance inputs must be condensed or spaced.");if(void 0!==e.labels&&"auto"!==e.labels&&"above"!==e.labels&&"floating"!==e.labels)throw new Error("[Paypercut Elements] Appearance labels must be auto, above, or floating.");if(void 0!==e.disableAnimations&&"boolean"!=typeof e.disableAnimations)throw new Error("[Paypercut Elements] Appearance disableAnimations must be a boolean.");if(void 0!==e.variables){if(!be(e.variables))throw new Error("[Paypercut Elements] Appearance variables are invalid.");for(const[t,n]of Object.entries(e.variables))if(!pe.has(t)||!me(n))throw new Error(`[Paypercut Elements] Appearance variable ${t} is invalid.`)}if(void 0!==e.rules){if(!be(e.rules))throw new Error("[Paypercut Elements] Appearance rules are invalid.");for(const[t,n]of Object.entries(e.rules)){if(!ce.has(t)||!be(n))throw new Error(`[Paypercut Elements] Appearance rule ${t} is invalid.`);for(const[e,i]of Object.entries(n))if(!he.has(e)||!me(i))throw new Error(`[Paypercut Elements] Appearance rule ${t}.${e} is invalid.`)}}}function ge(e){if(e)return{...e.theme?{theme:e.theme}:{},...e.inputs?{inputs:e.inputs}:{},...e.labels?{labels:e.labels}:{},...void 0!==e.disableAnimations?{disableAnimations:e.disableAnimations}:{},...e.variables?{variables:{...e.variables}}:{},...e.rules?{rules:Object.fromEntries(Object.entries(e.rules).map(([e,t])=>[e,{...t}]))}:{}}}function fe(e){return Array.isArray(e)?`[${e.map(fe).join(",")}]`:be(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${fe(e[t])}`).join(",")}}`:JSON.stringify(e)}function be(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const Pe="paypercut.elements.controller",we="paypercut.elements.component.bootstrap",ve="paypercut.elements.component",Ee="PAYPERCUT_ELEMENTS_CONTROLLER_FRAME_READY",Ce="PAYPERCUT_ELEMENTS_CONTROLLER_INIT",Ae="PAYPERCUT_ELEMENTS_CONTROLLER_INITIALIZED",Se="PAYPERCUT_ELEMENTS_CONTROLLER_ERROR",Ie="PAYPERCUT_ELEMENTS_CONTROLLER_ATTACH_COMPONENT",_e="PAYPERCUT_ELEMENTS_CONTROLLER_DETACH_COMPONENT",Te="PAYPERCUT_ELEMENTS_CONTROLLER_SUBMIT_COMPONENT",Oe="PAYPERCUT_ELEMENTS_CONTROLLER_CANCEL_COMPONENT_SUBMISSION",Re="PAYPERCUT_ELEMENTS_CONTROLLER_ATTACH_ACTION_CHANNEL",ke="PAYPERCUT_ELEMENTS_CONTROLLER_UPDATE_OPTIONS",xe="PAYPERCUT_ELEMENTS_CONTROLLER_APPLY_DEVELOPER_PRESET",Me="PAYPERCUT_ELEMENTS_CONTROLLER_APPLE_PAY_CAPABILITIES",Le="PAYPERCUT_ELEMENTS_CONTROLLER_APPLE_PAY_VALIDATE_MERCHANT",De="PAYPERCUT_ELEMENTS_CONTROLLER_APPLE_PAY_AUTHORIZED",Ne="PAYPERCUT_ELEMENTS_CONTROLLER_APPLE_PAY_CANCELED",qe="PAYPERCUT_ELEMENTS_CONTROLLER_GOOGLE_PAY_CLICK",Ge="PAYPERCUT_ELEMENTS_CONTROLLER_GOOGLE_PAY_CAPABILITIES",Ue="PAYPERCUT_ELEMENTS_CONTROLLER_GOOGLE_PAY_DATA_CHANGED",ze="PAYPERCUT_ELEMENTS_CONTROLLER_GOOGLE_PAY_AUTHORIZED",Be="PAYPERCUT_ELEMENTS_CONTROLLER_GOOGLE_PAY_PAYMENT_DATA",He="PAYPERCUT_ELEMENTS_CONTROLLER_GOOGLE_PAY_CANCELED",je="PAYPERCUT_ELEMENTS_CONTROLLER_GOOGLE_PAY_ERROR",Fe="PAYPERCUT_ELEMENTS_CONTROLLER_RESOLVE_WALLET_CLICK",We="PAYPERCUT_ELEMENTS_CONTROLLER_RESOLVE_WALLET_UPDATE",Ye="PAYPERCUT_ELEMENTS_CONTROLLER_RESOLVE_WALLET_CONFIRMATION",$e="PAYPERCUT_ELEMENTS_CONTROLLER_UPDATE_COMPONENT_OPTIONS",Ve="PAYPERCUT_ELEMENTS_CONTROLLER_COMPONENT_EVENT",Ke="PAYPERCUT_ELEMENTS_COMPONENT_FRAME_READY",Je="PAYPERCUT_ELEMENTS_COMPONENT_CONNECT",Ze=8192,Xe=16,Qe=64,et=80,tt=160,nt=64,it=256,ot=320,st=200,at=32768,rt=65536,lt=16384,pt=1024,ct=8192,ht=4,dt=2,ut=3,mt=1,yt=12,gt=2e3,ft=["applePay","googlePay"],bt=["channel","type"],Pt=["channel","type","controllerId","payload"],wt=["sessionId"],vt=["channel","type","controllerId","payload"],Et=["code","message","recoverable"],Ct=["x","y","width","height"],At=e=>ae(e)&&re(e,ft)&&"boolean"==typeof e.applePay&&"boolean"==typeof e.googlePay,St=e=>ae(e)&&re(e,bt)&&e.channel===we&&e.type===Ke,It=e=>"payment"===e||"express_checkout"===e,_t=e=>"apple_pay"===e||"google_pay"===e,Tt=e=>ae(e)&&Object.keys(e).every(e=>["type","brand","displayBrand","last4","expMonth","expYear","wallet"].includes(e))&&"card"===e.type&&le(e.brand,nt)&&le(e.displayBrand,nt)&&"string"==typeof e.last4&&/^\d{4}$/.test(e.last4)&&(void 0===e.expMonth||Number.isSafeInteger(e.expMonth)&&e.expMonth>=mt&&e.expMonth<=yt)&&(void 0===e.expYear||Number.isSafeInteger(e.expYear)&&e.expYear>=gt)&&_t(e.wallet),Ot=e=>"TEST"===e||"PRODUCTION"===e,Rt=e=>"string"==typeof e&&["book","buy","checkout","donate","order","pay","plain","short","subscribe"].includes(e),kt=e=>ae(e)&&re(e,Ct)&&Ct.every(t=>Number.isFinite(e[t]))&&e.x>=-8192&&e.x<=ct&&e.y>=-8192&&e.y<=ct&&e.width>0&&e.width<=Ze&&e.height>0&&e.height<=Ze,xt=(e,t)=>{if(!le(e,t))return!1;try{const t=JSON.parse(e);return ae(t)}catch{return!1}},Mt=e=>ae(e)&&Object.keys(e).every(e=>"name"===e||"address"===e)&&(void 0===e.name||le(e.name,it))&&(void 0===e.address||Dt(e.address)),Lt=e=>!(!ae(e)||!ae(e.total))&&(le(e.countryCode,dt)&&le(e.currencyCode,ut)&&Array.isArray(e.merchantCapabilities)&&e.merchantCapabilities.every(e=>"supports3DS"===e)&&Array.isArray(e.supportedNetworks)&&e.supportedNetworks.length>0&&e.supportedNetworks.every(e=>["amex","discover","masterCard","visa"].includes(String(e)))&&le(e.total.label,ne)&&/^\d+(?:\.\d{1,3})?$/.test(String(e.total.amount))&&["final","pending"].includes(String(e.total.type))),Dt=e=>{if(!ae(e))return!1;const t=new Set(["name","line1","line2","city","state","postalCode","country"]);return Object.entries(e).every(([e,n])=>t.has(e)&&le(n,"country"===e?dt:it))},Nt=e=>{if(!ae(e))return!1;const t=new Set(["recipient","addressLine","city","state","postalCode","country"]);return Object.entries(e).every(([e,n])=>!!t.has(e)&&("addressLine"===e?Array.isArray(n)&&n.length<=ht&&n.every(e=>le(e,it)):le(n,"country"===e?dt:it)))},qt=e=>ae(e)&&Object.keys(e).every(e=>["id","displayName","amount","detail"].includes(e))&&le(e.id,ne)&&le(e.displayName,it)&&Number.isSafeInteger(e.amount)&&e.amount>=0,Gt=e=>{if(!ae(e))return!1;const t=new Set(["name","email","phone","address"]);return Object.entries(e).every(([e,n])=>!!t.has(e)&&("address"===e?Dt(n):le(n,"email"===e?ot:it)))},Ut=e=>!!ae(e)&&("succeeded"===e.status?ae(e.paymentMethod)&&le(e.paymentMethod.id,ne)&&"card"===e.paymentMethod.type:"failed"===e.status&&le(e.code,ne)&&le(e.message,ie)&&"boolean"==typeof e.recoverable),zt=e=>ae(e)&&le(e.id,Qe)&&le(e.label,et)&&le(e.description,tt)&&"string"==typeof e.last4&&/^\d{4}$/.test(e.last4)&&["success","challenge","warning","danger"].includes(String(e.tone)),Bt="paypercut.elements.action",Ht="PAYPERCUT_ELEMENTS_ACTION_FRAME_READY",jt="PAYPERCUT_ELEMENTS_ACTION_INIT",Ft="PAYPERCUT_ELEMENTS_ACTION_PHASE",Wt="PAYPERCUT_ELEMENTS_ACTION_RESULT",Yt="PAYPERCUT_ELEMENTS_ACTION_ERROR",$t=["channel","type","requestId","payload"],Vt=["channel","type"],Kt=["phase"],Jt=["status"],Zt=["code","message","recoverable"],Xt=(e,t)=>ae(e)&&re(e,$t)&&e.channel===Bt&&e.type===t&&le(e.requestId,ne)&&void 0!==e.payload,Qt=e=>Xt(e,Ft)&&ae(e.payload)&&re(e.payload,Kt)&&["loading","content_ready","completing"].includes(String(e.payload.phase)),en=e=>Xt(e,Wt)&&ae(e.payload)&&re(e.payload,Jt)&&"canceled"===e.payload.status,tn=e=>Xt(e,Yt)&&ae(e.payload)&&re(e.payload,Zt)&&le(e.payload.code,ne)&&le(e.payload.message,ie)&&"boolean"==typeof e.payload.recoverable,nn=15e3,on=220,sn=400,an=2147483647,rn="rgb(40 40 40 / 0%)",ln="rgb(40 40 40 / 75%)",pn="transparent";let cn=0,hn="",dn="";const un=(e,t,n)=>{null===n?e.removeAttribute(t):e.setAttribute(t,n)};class mn{constructor(){this.host=null,this.active=!1,this.isolatedSiblings=new Map,this.isolationObserver=null}open(){const e=this.ensureHost();if(document.body.prepend(e),e.hidden=!1,e.style.display="block",this.active||(this.active=!0,0===cn&&(hn=document.body.style.overflow,dn=document.documentElement.style.overflow,document.body.style.overflow="hidden",document.documentElement.style.overflow="hidden"),cn+=1,this.isolateMerchantPage(e)),"function"==typeof e.showPopover&&!e.matches(":popover-open"))try{e.showPopover()}catch{e.removeAttribute("popover")}return window.requestAnimationFrame(()=>{this.active&&(e.style.background=ln)}),e}beginClose(){this.host&&(this.host.style.background=rn)}finishClose(){const e=this.host;if(e){try{e.hidePopover?.()}catch{}e.hidden=!0,e.style.display="none",e.style.background=rn,this.active&&(this.active=!1,this.restoreMerchantPage(),0!==cn&&(cn-=1,0===cn&&(document.body.style.overflow=hn,document.documentElement.style.overflow=dn)))}}destroy(){this.finishClose(),this.host?.remove(),this.host=null}ensureHost(){if(this.host)return this.host;const e=document.createElement("div");return e.dataset.paypercutElementsActionHost="",e.tabIndex=-1,e.setAttribute("popover","manual"),e.hidden=!0,Object.assign(e.style,{position:"fixed",inset:"0",width:"100%",height:"100%",minWidth:"100%",minHeight:"100%",maxWidth:"none",maxHeight:"none",margin:"0",padding:"0",border:"0",display:"none",overflow:"hidden",background:rn,colorScheme:"light only",transition:`background ${sn}ms ease-in-out`,willChange:"background",zIndex:String(an)}),this.host=e,e}isolateMerchantPage(e){const t=t=>{t===e||this.isolatedSiblings.has(t)||(this.isolatedSiblings.set(t,{element:t,inert:t.inert,ariaHidden:t.getAttribute("aria-hidden"),tabIndex:t.getAttribute("tabindex")}),t.inert=!0,t.setAttribute("aria-hidden","true"),t.setAttribute("tabindex","-1"))};for(const e of Array.from(document.body.children))e instanceof HTMLElement&&t(e);this.isolationObserver=new MutationObserver(e=>{for(const n of e)for(const e of Array.from(n.addedNodes))e instanceof HTMLElement&&t(e)}),this.isolationObserver.observe(document.body,{childList:!0})}restoreMerchantPage(){this.isolationObserver?.disconnect(),this.isolationObserver=null;for(const e of this.isolatedSiblings.values())e.element.isConnected&&(e.element.inert=e.inert,un(e.element,"aria-hidden",e.ariaHidden),un(e.element,"tabindex",e.tabIndex));this.isolatedSiblings.clear()}}class yn{constructor(e,t,n,i=nn){this.hostedOrigin=e,this.onCancel=t,this.onError=n,this.bootstrapTimeoutMs=i,this.host=new mn,this.frame=null,this.action=null,this.bootstrapTimeout=null,this.removalTimeout=null,this.previouslyFocused=null,this.componentPort=null,this.onWindowMessage=e=>{const t=this.frame,n=this.action;if(t?.contentWindow&&n&&e.source===t.contentWindow&&e.origin===this.hostedOrigin){if(i=e.data,ae(i)&&re(i,Vt)&&i.channel===Bt&&i.type===Ht){this.clearBootstrapTimeout();const e={channel:Bt,type:jt,requestId:n.id,payload:{source:"component",actionId:n.id,actionType:n.type}},i=this.componentPort;return i?(t.contentWindow.postMessage(e,this.hostedOrigin,[i]),this.componentPort=null,void window.requestAnimationFrame(()=>{this.frame===t&&(t.style.opacity="1",t.focus({preventScroll:!0}))})):void this.onError("elements_action_channel_unavailable","The secure authentication channel is unavailable.",!0)}var i;(Qt(e.data)||en(e.data)||tn(e.data))&&e.data.requestId!==n.id||(Qt(e.data)?t.dataset.paypercutActionPhase=e.data.payload.phase:en(e.data)?"canceled"===e.data.payload.status&&this.onCancel():tn(e.data)&&this.onError(e.data.payload.code,e.data.payload.message,e.data.payload.recoverable))}}}isOpen(){return null!==this.frame}show(e,t){if(this.action?.id===e.id&&this.frame)return;this.removeFrame(!1,!1),this.action=e,this.componentPort=t,this.previouslyFocused=document.activeElement instanceof HTMLElement?document.activeElement:null;const n=document.createElement("iframe");n.id=`paypercut-elements-action-frame-${e.id}`,n.title="3D Secure authentication",n.referrerPolicy="origin",n.src=new URL("/elements/actions/three-d-secure",this.hostedOrigin).toString(),n.allow="payment *; publickey-credentials-get *",n.setAttribute("allowtransparency","true"),n.setAttribute("frameborder","0"),n.setAttribute("role","presentation"),n.setAttribute("scrolling","no"),Object.assign(n.style,{position:"absolute",inset:"0",width:"100%",height:"100%",minWidth:"100%",minHeight:"100%",maxWidth:"none",maxHeight:"none",margin:"0",padding:"0",border:"0",display:"block",overflow:"hidden",background:pn,colorScheme:"light only",opacity:"0",transition:`opacity ${on}ms ease-in-out`,willChange:"opacity"}),this.frame=n,window.addEventListener("message",this.onWindowMessage);this.host.open().replaceChildren(n),this.bootstrapTimeout=window.setTimeout(()=>{this.frame===n&&this.onError("elements_action_shell_timeout","The secure authentication window could not be loaded.",!0)},this.bootstrapTimeoutMs)}close(){const e=this.frame;e&&(e.style.opacity="0",this.host.beginClose(),this.clearRemovalTimeout(),this.removalTimeout=window.setTimeout(()=>{this.frame===e&&this.removeFrame()},sn))}destroy(){this.removeFrame(!0)}removeFrame(e=!1,t=!0){const n=this.frame;this.frame=null,this.action=null,this.componentPort?.close(),this.componentPort=null,this.clearBootstrapTimeout(),this.clearRemovalTimeout(),window.removeEventListener("message",this.onWindowMessage),n?.remove(),e?this.host.destroy():this.host.finishClose();const i=this.previouslyFocused;if(this.previouslyFocused=null,t&&i?.isConnected)try{i.focus({preventScroll:!0})}catch{i.focus()}}clearBootstrapTimeout(){null!==this.bootstrapTimeout&&(window.clearTimeout(this.bootstrapTimeout),this.bootstrapTimeout=null)}clearRemovalTimeout(){null!==this.removalTimeout&&(window.clearTimeout(this.removalTimeout),this.removalTimeout=null)}}let gn=!1;function fn(e,t){var n;e.set("controllerId",t.controllerId),e.set("apiKey",t.clientOptions.publishableKey),e.set("keyMode",(n=t.clientOptions.publishableKey,/(?:^|_)live(?:_|$)/i.test(n)?"live":"test")),e.set("locale",t.elementsOptions.locale||("undefined"!=typeof navigator&&navigator.language?navigator.language:"en")),e.set("referrer",t.referrer),function(e,t){bn(e,"publicOptions[appearance][theme]",t?.theme),bn(e,"publicOptions[appearance][inputs]",t?.inputs),bn(e,"publicOptions[appearance][labels]",t?.labels),bn(e,"publicOptions[appearance][disableAnimations]",t?.disableAnimations);for(const[n,i]of Object.entries(t?.variables??{}).sort(([e],[t])=>e.localeCompare(t)))bn(e,`publicOptions[appearance][variables][${n}]`,i);for(const[n,i]of Object.entries(t?.rules??{}).sort(([e],[t])=>e.localeCompare(t)))for(const[t,o]of Object.entries(i??{}).sort(([e],[t])=>e.localeCompare(t)))bn(e,`publicOptions[appearance][rules][${n}][${t}]`,o)}(e,t.elementsOptions.appearance)}function bn(e,t,n){void 0!==n&&e.set(t,String(n))}function Pn(e,t,n){const i=new URL(e,t);i.hash=n.toString();const o=i.toString();return!gn&&o.length>4096&&(gn=!0,"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn(`[Paypercut Elements] Generated iframe URL is ${o.length} characters. Consider shortening appearance variables or rules to avoid URL length limits.`)),o}class wn{constructor(t){this.group=t,this.componentId=z(),this.componentType="payment",this.emitter=new e,this.iframe=null,this.mounted=!1,this.connected=!1,this.destroyed=!1,this.ready=!1,this.pendingSubmission=null,this.submissionIndeterminate=!1,this.completedReference=null,this.developerAssistant=null,this.pendingDeveloperPreset=null,this.actionShell=new yn(this.group.hostedOrigin,()=>this.cancelAction(),(e,t,n)=>this.failAction(e,t,n)),this.messageHandler=e=>this.onWindowMessage(e)}mount(e){if(this.destroyed)throw new Error("[Paypercut Elements] Cannot mount a destroyed Payment Element.");if(this.mounted)return;if("undefined"==typeof window||"undefined"==typeof document)throw new Error("[Paypercut Elements] Payment Element can only be mounted in a browser.");if(this.group.isDestroyed())throw new Error("[Paypercut Elements] Cannot mount an Element from a destroyed group.");const t=function(e){const t="string"==typeof e?document.querySelector(e):e;if(!(t instanceof HTMLElement))throw new Error(`[Paypercut Elements] Container not found: ${String(e)}`);return t}(e),n=document.createElement("iframe");n.id=`paypercut-payment-element-${this.componentId}`,n.title="Secure payment form",n.referrerPolicy="origin",n.src=function(e){const t=new URLSearchParams;return fn(t,e),t.set("componentName","payment"),t.set("elementId",e.componentId),t.set("mode",e.elementsOptions.mode),t.set("amount",String(e.elementsOptions.amount)),t.set("currency",e.elementsOptions.currency),Pn("/elements/components/payment",e.hostedOrigin,t)}({hostedOrigin:this.group.hostedOrigin,controllerId:this.group.controllerId,componentId:this.componentId,clientOptions:this.group.getClientOptions(),elementsOptions:this.group.getElementsOptions(),referrer:window.location.origin}),n.allow="payment *; publickey-credentials-get *; autofill *",n.setAttribute("allowtransparency","true"),n.setAttribute("frameborder","0"),n.setAttribute("role","presentation"),n.setAttribute("scrolling","no"),Object.assign(n.style,{width:"100%",maxWidth:"100%",minWidth:"0",height:"0",margin:"0",padding:"0",border:"0",display:"block",overflow:"hidden",colorScheme:"light dark",transition:"height 350ms ease-in-out, opacity 400ms ease-in-out 100ms",willChange:"height, opacity"}),this.iframe=n,this.mounted=!0,window.addEventListener("message",this.messageHandler),this.group.ensureController(),t.appendChild(n)}on(e,t){return this.emitter.on(e,t)}submit(){if(this.destroyed||this.group.isDestroyed())return Promise.reject(vn("elements_destroyed","The Payment Element has been destroyed.",!1));if(!this.mounted||!this.ready)return Promise.reject(vn("elements_not_ready","The Payment Element is not ready yet.",!0));if(this.completedReference)return Promise.resolve({...this.completedReference});if(this.submissionIndeterminate)return Promise.reject(vn("elements_submit_indeterminate","A previous submission has an unknown result. Reload the payment form before continuing.",!1));if(this.pendingDeveloperPreset)return Promise.reject(vn("elements_test_preset_in_progress","Wait for the test card preset to finish filling before submitting.",!0));if(this.pendingSubmission)return this.pendingSubmission.promise;const e=z();let t,n;const i=new Promise((e,i)=>{t=e,n=i}),o={requestId:e,promise:i,resolve:t,reject:n,timeoutId:window.setTimeout(()=>{this.pendingSubmission===o&&(this.submissionIndeterminate=!0,this.rejectPendingSubmission("elements_submit_timeout","Preparing the payment details timed out and the result is unknown.",!1))},6e5)};this.pendingSubmission=o,this.developerAssistant?.collapse(),this.developerAssistant?.refresh();try{this.group.submitComponent(this.componentId,e)}catch{this.rejectPendingSubmission("elements_submit_failed","Unable to submit the payment details.",!0)}return i}hasActiveSubmission(){return null!==this.pendingSubmission||this.submissionIndeterminate||null!==this.pendingDeveloperPreset}getComponentOptions(){return{}}handleControllerError(e){this.destroyed||(this.ready=!1,this.emitter.emit("error",e),this.rejectPendingSubmission(e.code,e.message,e.recoverable??!0))}handleControllerEvent(e){if(!this.destroyed)switch(e.event){case"ready":this.ready||(this.ready=!0,this.emitter.emit("ready"),this.group.discoverDeveloperPresets(this.componentId));break;case"resize":this.resize(e.height);break;case"error":this.actionShell.close(),this.handleControllerError(e);break;case"phase":"ready"===e.phase&&this.actionShell.close(),this.developerAssistant?.refresh();break;case"action_required":if(this.pendingSubmission?.requestId!==e.requestId)break;const t=new MessageChannel;this.group.attachActionChannel(this.componentId,e.requestId,e.action.id,t.port1),this.developerAssistant?.collapse(),this.actionShell.show(e.action,t.port2),this.developerAssistant?.refresh();break;case"submit_result":this.handleSubmitResult(e);break;case"developer_catalog":this.registerDeveloperPresets(e.presets);break;case"developer_apply_result":this.handleDeveloperApplyResult(e)}}destroy(){this.destroyed||(this.destroyed=!0,this.ready=!1,this.rejectPendingSubmission("elements_destroyed","The Payment Element was destroyed before submission completed.",!1),this.clearDeveloperAssistant("The payment form was destroyed."),this.actionShell.destroy(),"undefined"!=typeof window&&window.removeEventListener("message",this.messageHandler),this.iframe?.remove(),this.iframe=null,this.mounted=!1,this.emitter.clear(),this.group.remove(this))}onWindowMessage(e){if(this.destroyed||this.connected||!this.iframe?.contentWindow||e.source!==this.iframe.contentWindow||e.origin!==this.group.hostedOrigin||!St(e.data))return;this.connected=!0;const t=new MessageChannel,n={channel:we,type:Je,controllerId:this.group.controllerId,componentId:this.componentId,componentType:this.componentType};try{this.iframe.contentWindow.postMessage(n,this.group.hostedOrigin,[t.port2]),this.group.attachComponent(this,t.port1)}catch{t.port1.close(),t.port2.close(),this.handleControllerError({code:"elements_component_connect_failed",message:"The secure payment form could not be connected.",recoverable:!0})}}resize(e){if(!this.iframe||!Number.isFinite(e)||e<=0||e>8192)return;const t=Math.ceil(e);this.iframe.style.height=`${t}px`,this.emitter.emit("resize",{height:t})}handleSubmitResult(e){const t=this.pendingSubmission;if(t&&e.requestId===t.requestId){if(this.pendingSubmission=null,window.clearTimeout(t.timeoutId),this.actionShell.close(),"succeeded"===e.result.status){const n={type:"payment_method",id:e.result.paymentMethod.id};this.completedReference=n,t.resolve({...n})}else t.reject(vn(e.result.code,e.result.message,e.result.recoverable));this.developerAssistant?.refresh()}}rejectPendingSubmission(e,t,n){const i=this.pendingSubmission;i&&(this.pendingSubmission=null,window.clearTimeout(i.timeoutId),this.actionShell.close(),i.reject(vn(e,t,n)),this.developerAssistant?.refresh())}cancelAction(){const e=this.pendingSubmission;if(e){try{this.group.cancelComponentSubmission(this.componentId,e.requestId)}catch{}this.rejectPendingSubmission("elements_action_canceled","3D Secure authentication was canceled.",!0)}}failAction(e,t,n){const i=this.pendingSubmission;if(i){try{this.group.cancelComponentSubmission(this.componentId,i.requestId)}catch{}this.rejectPendingSubmission(e,t,n)}}registerDeveloperPresets(e){}canApplyDeveloperPreset(){return"internal"===t.mode}applyDeveloperPreset(e){if(!this.canApplyDeveloperPreset())return Promise.reject(new Error("Test card presets are unavailable right now."));const t=z();return new Promise((n,i)=>{const o={requestId:t,presetId:e,resolve:n,reject:i,timeoutId:window.setTimeout(()=>{this.pendingDeveloperPreset===o&&(this.pendingDeveloperPreset=null,i(new Error("The secure card frame did not acknowledge the test preset.")),this.developerAssistant?.refresh())},5e3)};this.pendingDeveloperPreset=o,this.developerAssistant?.refresh();try{this.group.applyDeveloperPreset(this.componentId,t,e)}catch{this.pendingDeveloperPreset=null,window.clearTimeout(o.timeoutId),i(new Error("Unable to contact the secure card frame.")),this.developerAssistant?.refresh()}})}handleDeveloperApplyResult(e){const t=this.pendingDeveloperPreset;t&&e.requestId===t.requestId&&e.presetId===t.presetId&&(this.pendingDeveloperPreset=null,window.clearTimeout(t.timeoutId),e.ok?t.resolve():t.reject(new Error("The secure card frame rejected the test preset.")),this.developerAssistant?.refresh())}clearDeveloperAssistant(e){this.developerAssistant?.unregister(),this.developerAssistant=null;const t=this.pendingDeveloperPreset;t&&(this.pendingDeveloperPreset=null,window.clearTimeout(t.timeoutId),t.reject(new Error(e)))}}function vn(e,t,n){const i=new Error(t);return i.name="PaymentElementSubmitError",i.code=e,i.recoverable=n,i}const En="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",Cn="apple-pay-modal",An="paypercut-apple-pay-modal-focus-style";let Sn=null,In=null,_n=0;function Tn(){"undefined"!=typeof window&&"undefined"!=typeof document&&(!function(){if(document.querySelectorAll(Cn).forEach(e=>{On(e)}),In||!document.documentElement)return;In=new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e instanceof Element&&(e.matches(Cn)&&On(e),e.querySelectorAll(Cn).forEach(e=>{On(e)}))})})}),In.observe(document.documentElement,{childList:!0,subtree:!0})}(),_n+=1)}function On(e,t=0){const n=e.shadowRoot;if(!n)return void(t<L&&requestAnimationFrame(()=>On(e,t+1)));if(n.getElementById(An))return;const i=document.createElement("style");i.id=An,i.textContent="[data-modal-element-overlay]:focus, [data-modal-element-overlay]:focus-visible, .modal-overlay:focus, .modal-overlay:focus-visible { outline: none !important; }",n.appendChild(i)}const Rn=6e4,kn=3e4,xn=.5,Mn=40,Ln=64,Dn=24,Nn=4,qn=64,Gn=256,Un=2,zn=10,Bn={transform:"none",filter:"none",perspective:"none","backdrop-filter":"none","-webkit-backdrop-filter":"none",contain:"none","container-type":"normal","will-change":"auto","clip-path":"none",mask:"none","-webkit-mask":"none",overflow:"visible",isolation:"auto","mix-blend-mode":"normal",opacity:"1","z-index":"auto","pointer-events":"auto"};class Hn{constructor(t,n={}){this.group=t,this.componentId=z(),this.componentType="express_checkout",this.emitter=new e,this.componentRevision=0,this.iframe=null,this.mounted=!1,this.connected=!1,this.destroyed=!1,this.ready=!1,this.activeAttempt=null,this.activeOptions=null,this.applePaySession=null,this.walletOverlayRestoreStyle=null,this.walletOverlayAncestorStyles=[],this.walletOverlayHeight=null,this.applePayTimeout=null,this.applePayModalObserverAcquired=!1,this.googlePayClient=null,this.googlePayEnvironment=null,this.googlePayRequestId=null,this.googlePayProcessingRequestId=null,this.googlePayUpdates=new Map,this.googlePayAuthorization=null,this.googlePayButtonTarget=null,this.googlePayButtonContainer=null,this.googlePayButtonGeneration=0,this.googlePayButtonPositionFrame=null,this.googlePayButtonResizeObserver=null,this.googlePayButtonPositionHandler=()=>{null===this.googlePayButtonPositionFrame&&(this.googlePayButtonPositionFrame=window.requestAnimationFrame(()=>{this.googlePayButtonPositionFrame=null,this.positionGooglePayButton()}))},this.actionShell=new yn(this.group.hostedOrigin,()=>this.cancelAction(),(e,t,n)=>this.failAction(e,t,n)),this.messageHandler=e=>this.onWindowMessage(e),this.walletOverlayKeyHandler=e=>{if("Escape"!==e.key||null===this.walletOverlayRestoreStyle)return;e.preventDefault(),e.stopPropagation();const t=this.activeAttempt;t&&this.group.cancelComponentSubmission(this.componentId,t.requestId),this.setWalletOverlay(!1)},this.options=Wn(n)}mount(e){if(this.destroyed)throw new Error("[Paypercut Elements] Cannot mount a destroyed Express Checkout Element.");if(this.mounted)return;if("undefined"==typeof window||"undefined"==typeof document)throw new Error("[Paypercut Elements] Express Checkout Element can only be mounted in a browser.");if(this.group.isDestroyed())throw new Error("[Paypercut Elements] Cannot mount an Element from a destroyed group.");this.applePayModalObserverAcquired||(Tn(),this.applePayModalObserverAcquired=!0);const t=document.createElement("iframe");t.id=`paypercut-express-checkout-element-${this.componentId}`,t.title="Express checkout",t.referrerPolicy="origin",t.src=function(e){const t=new URLSearchParams;return fn(t,e),t.set("componentName","expressCheckout"),t.set("elementId",e.componentId),t.set("mode",e.elementsOptions.mode),t.set("amount",String(e.elementsOptions.amount)),t.set("currency",e.elementsOptions.currency),bn(t,"publicOptions[paymentMethods][applePay]",e.options.paymentMethods?.applePay),bn(t,"publicOptions[paymentMethods][googlePay]",e.options.paymentMethods?.googlePay),bn(t,"publicOptions[layout][maxColumns]",e.options.layout?.maxColumns),bn(t,"publicOptions[layout][maxRows]",e.options.layout?.maxRows),bn(t,"publicOptions[layout][overflow]",e.options.layout?.overflow),bn(t,"publicOptions[buttonType][applePay]",e.options.buttonType?.applePay),bn(t,"publicOptions[buttonType][googlePay]",e.options.buttonType?.googlePay),bn(t,"publicOptions[buttonTheme][applePay]",e.options.buttonTheme?.applePay),bn(t,"publicOptions[buttonTheme][googlePay]",e.options.buttonTheme?.googlePay),bn(t,"publicOptions[buttonHeight]",e.options.buttonHeight),bn(t,"publicOptions[buttonRadius]",e.options.buttonRadius),bn(t,"publicOptions[emailRequired]",e.options.emailRequired),bn(t,"publicOptions[phoneNumberRequired]",e.options.phoneNumberRequired),bn(t,"publicOptions[billingAddressRequired]",e.options.billingAddressRequired),bn(t,"publicOptions[shippingAddressRequired]",e.options.shippingAddressRequired),e.options.allowedShippingCountries?.length&&t.set("publicOptions[allowedShippingCountries]",e.options.allowedShippingCountries.join(",")),Pn("/elements/components/express-checkout",e.hostedOrigin,t)}({hostedOrigin:this.group.hostedOrigin,controllerId:this.group.controllerId,componentId:this.componentId,clientOptions:this.group.getClientOptions(),elementsOptions:this.group.getElementsOptions(),options:this.options,referrer:window.location.origin}),t.allow="payment *",t.setAttribute("allowtransparency","true"),t.setAttribute("frameborder","0"),t.setAttribute("role","presentation"),t.setAttribute("scrolling","no"),Object.assign(t.style,{width:"100%",maxWidth:"100%",minWidth:"0",height:"0",margin:"0",padding:"0",border:"0",display:"block",overflow:"hidden",colorScheme:"light dark",transition:"height 250ms ease-in-out, opacity 250ms ease-in-out",willChange:"height, opacity"}),this.iframe=t,this.mounted=!0,window.addEventListener("message",this.messageHandler),this.group.ensureController(),function(e){const t="string"==typeof e?document.querySelector(e):e;if(!(t instanceof HTMLElement))throw new Error(`[Paypercut Elements] Container not found: ${String(e)}`);return t}(e).appendChild(t)}on(e,t){return this.emitter.on(e,t)}update(e){if(this.destroyed)throw new Error("[Paypercut Elements] Cannot update a destroyed Express Checkout Element.");if(this.activeAttempt)throw new Error("[Paypercut Elements] Cannot update Express Checkout while a wallet attempt is active.");const t=function(e){if(!Xn(e)||0===Object.keys(e).length)throw new Error("[Paypercut Elements] Express Checkout update options must contain checkout details.");return $n(e)}(e);if(this.options=Wn({...this.options,...t}),this.componentRevision===Number.MAX_SAFE_INTEGER)throw new Error("[Paypercut Elements] The component update revision limit has been reached.");this.componentRevision+=1,this.group.updateExpressCheckoutComponent(this.componentId,this.componentRevision,this.getComponentOptions())}getComponentOptions(){return ri(this.options)}hasActiveSubmission(){return!0===this.activeAttempt?.approved}handleControllerError(e){this.destroyed||(this.finalizeWalletAttempt({cancelSubmission:!0,skipApplePayCompletion:!1}),e.recoverable||(this.ready=!1),this.emitter.emit("error",e))}handleControllerEvent(e){if(!this.destroyed)switch(e.event){case"ready":this.ready||(this.ready=!0,this.emitter.emit("ready",{availablePaymentMethods:{...e.availablePaymentMethods}}));break;case"resize":this.resize(e.height);break;case"wallet_overlay":this.setWalletOverlay(e.open);break;case"error":this.handleControllerError(e);break;case"available_payment_methods_change":this.emitter.emit("availablepaymentmethodschange",{availablePaymentMethods:{...e.availablePaymentMethods}});break;case"apple_pay_capabilities_request":("undefined"==typeof window||"undefined"==typeof document||window.ApplePaySession?Promise.resolve():Sn||(Sn=new Promise(e=>{const t=Array.from(document.scripts).find(e=>e.src===En),n=t??document.createElement("script"),i=()=>e();n.addEventListener("load",i,{once:!0}),n.addEventListener("error",i,{once:!0}),t||(n.src=En,n.crossOrigin="anonymous",n.async=!0,n.dataset.paypercutApplePaySdk="true",document.head.appendChild(n))}),Sn)).then(()=>{this.destroyed||this.group.sendApplePayCapabilities(this.componentId,this.canMakeApplePayPayments())},()=>{this.destroyed||this.group.sendApplePayCapabilities(this.componentId,!1)});break;case"apple_pay_start":if(this.activeAttempt?.requestId!==e.requestId)break;this.startApplePay(e.requestId,e.request);break;case"apple_pay_merchant_session":if(this.activeAttempt?.requestId!==e.requestId||!this.applePaySession)break;this.clearApplePayTimeout();try{this.applePaySession.completeMerchantValidation(e.merchantSession)}catch{this.completeApplePay(!1),this.group.sendApplePayCanceled(this.componentId,e.requestId)}break;case"google_pay_capabilities_request":this.resolveGooglePayCapabilities(e.environment,e.requestJson);break;case"google_pay_button_target":this.configureGooglePayButton(e);break;case"google_pay_start":if(this.activeAttempt?.requestId!==e.requestId)break;this.startGooglePay(e.requestId,e.environment,e.requestJson);break;case"google_pay_data_changed_result":this.resolveGooglePayDataChanged(e.requestId,e.updateId,e.resultJson);break;case"google_pay_authorization_result":this.resolveGooglePayAuthorization(e.requestId,e.resultJson);break;case"wallet_click":if(!this.group.beginWalletAttempt(this.componentId,e.requestId,e.wallet,this.iframe)){this.group.cancelComponentSubmission(this.componentId,e.requestId);break}this.activeAttempt={requestId:e.requestId,wallet:e.wallet,approved:!1},"google_pay"===e.wallet&&this.googlePayProcessingRequestId===e.requestId&&this.group.markWalletAttemptProcessing(this.componentId,e.requestId,e.wallet),this.activeOptions=null,this.emitWalletClick(e.requestId,e.wallet);break;case"wallet_shipping_address_change":if(this.activeAttempt?.requestId!==e.requestId)break;this.emitShippingAddressChange(e.requestId,e.updateId,e.wallet,e.address);break;case"wallet_shipping_rate_change":if(this.activeAttempt?.requestId!==e.requestId)break;this.emitShippingRateChange(e.requestId,e.updateId,e.wallet,e.shippingRate);break;case"action_required":{if(this.activeAttempt?.requestId!==e.requestId)break;this.group.hideWalletAttemptOverlay(this.componentId,e.requestId);const t=new MessageChannel;this.group.attachActionChannel(this.componentId,e.requestId,e.action.id,t.port1),this.actionShell.show(e.action,t.port2);break}case"wallet_confirm":if(this.activeAttempt?.requestId!==e.requestId)break;this.emitWalletConfirm(e);break;case"wallet_cancel":if(this.activeAttempt?.requestId!==e.requestId)break;this.finalizeWalletAttempt({requestId:e.requestId}),this.emitter.emit("cancel",{wallet:e.wallet})}}emitWalletConfirm(e){const t=e.requestId;let n=!1;const i=(i,s)=>{if(!n&&!this.destroyed&&this.activeAttempt?.requestId===t){if(n=!0,window.clearTimeout(o),this.group.resolveWalletConfirmation(this.componentId,t,i,s),"apple_pay"===e.wallet)return this.completeApplePay(i),void this.finalizeWalletAttempt({requestId:t,skipApplePayCompletion:!0});this.finalizeWalletAttempt({requestId:t})}},o=window.setTimeout(()=>i(!1,{code:"merchant_confirmation_timeout",message:"The merchant did not finish the checkout in time."}),Rn),s={wallet:e.wallet,paymentMethod:{type:"payment_method",id:e.paymentMethod.id},...e.paymentMethodPreview?{paymentMethodPreview:e.paymentMethodPreview}:{},...e.billingDetails?{billingDetails:e.billingDetails}:{},...e.shippingAddress?{shippingAddress:e.shippingAddress}:{},...e.shippingRate?{shippingRate:e.shippingRate}:{},complete:()=>i(!0),paymentFailed:e=>i(!1,e)};if(!this.emitter.hasListeners("confirm")){const e={code:"merchant_confirmation_handler_missing",message:"The merchant did not register a confirmation handler."};return this.emitter.emit("error",{code:e.code,message:e.message,recoverable:!1}),void s.paymentFailed(e)}try{this.emitter.emitAndThrow("confirm",s)}catch{const e={code:"merchant_confirmation_handler_failed",message:"The merchant confirmation handler threw an error."};this.emitter.emit("error",{code:e.code,message:e.message,recoverable:!1}),s.paymentFailed(e)}}destroy(){this.destroyed||(this.destroyed=!0,this.ready=!1,this.activeAttempt&&this.finalizeWalletAttempt({cancelSubmission:!0}),this.activeOptions=null,this.actionShell.destroy(),this.setWalletOverlay(!1),this.abortApplePay(),this.clearGooglePayAttempt(),this.destroyGooglePayButton(),"undefined"!=typeof window&&window.removeEventListener("message",this.messageHandler),this.applePayModalObserverAcquired&&("undefined"!=typeof window&&"undefined"!=typeof document&&(_n<=0?_n=0:(_n-=1,0===_n&&(In?.disconnect(),In=null))),this.applePayModalObserverAcquired=!1),this.iframe?.remove(),this.iframe=null,this.mounted=!1,this.emitter.clear(),this.group.remove(this))}onWindowMessage(e){if(this.destroyed||this.connected||!this.iframe?.contentWindow||e.source!==this.iframe.contentWindow||e.origin!==this.group.hostedOrigin||!St(e.data))return;this.connected=!0;const t=new MessageChannel,n={channel:we,type:Je,controllerId:this.group.controllerId,componentId:this.componentId,componentType:this.componentType};try{this.iframe.contentWindow.postMessage(n,this.group.hostedOrigin,[t.port2]),this.group.attachComponent(this,t.port1)}catch{t.port1.close(),t.port2.close(),this.handleControllerError({code:"elements_component_connect_failed",message:"The express checkout component could not be connected.",recoverable:!0})}}resize(e){if(!this.iframe||!Number.isFinite(e)||e<0||e>4096)return;const t=Math.ceil(e);null===this.walletOverlayRestoreStyle?(this.iframe.style.height=`${t}px`,this.emitter.emit("resize",{height:t})):this.walletOverlayHeight=t}setWalletOverlay(e){const t=this.iframe;if(t){if(e){if(null!==this.walletOverlayRestoreStyle)return;this.walletOverlayRestoreStyle=t.style.cssText,document.addEventListener("keydown",this.walletOverlayKeyHandler,!0),this.walletOverlayAncestorStyles=[];for(let e=t.parentElement;e;e=e.parentElement){const t=Object.entries(Bn).map(([t,n])=>{const i={name:t,value:e.style.getPropertyValue(t),priority:e.style.getPropertyPriority(t)};return e.style.setProperty(t,n,"important"),i});this.walletOverlayAncestorStyles.push({element:e,properties:t})}const e={position:"fixed",inset:"0","z-index":"2147483647",width:"100vw","max-width":"none",height:CSS.supports("height","100dvh")?"100dvh":"100vh",margin:"0","box-sizing":"border-box",overflow:"visible",transition:"none",opacity:"1"};for(const[n,i]of Object.entries(e))t.style.setProperty(n,i,"important");const n=t.getBoundingClientRect();return void((Math.abs(n.left)>xn||Math.abs(n.top)>xn)&&t.style.setProperty("transform",`translate3d(${-n.left}px, ${-n.top}px, 0)`,"important"))}if(null!==this.walletOverlayRestoreStyle){t.style.cssText=this.walletOverlayRestoreStyle,this.walletOverlayRestoreStyle=null,document.removeEventListener("keydown",this.walletOverlayKeyHandler,!0);for(const{element:e,properties:t}of this.walletOverlayAncestorStyles.reverse())for(const{name:n,value:i,priority:o}of t)i?e.style.setProperty(n,i,o):e.style.removeProperty(n);if(this.walletOverlayAncestorStyles=[],null!==this.walletOverlayHeight){const e=this.walletOverlayHeight;this.walletOverlayHeight=null,this.resize(e)}}}}emitWalletClick(e,t){if(!this.emitter.hasListeners("click"))return this.activeAttempt?.requestId===e&&(this.activeAttempt.approved=!0),this.activeOptions=ri(this.options),void this.group.resolveWalletClick(this.componentId,e,!0,this.options);let n=!1;const i=(t,i)=>{if(n||this.destroyed||this.activeAttempt?.requestId!==e)return;const s=t?$n(i):void 0;n=!0,window.clearTimeout(o),t&&this.activeAttempt?.requestId===e&&(this.activeAttempt.approved=!0,this.activeOptions=ri({...this.options,...s??{}})),this.group.resolveWalletClick(this.componentId,e,t,s),t||(this.group.endWalletAttempt(this.componentId,e),this.activeAttempt=null,this.activeOptions=null)},o=window.setTimeout(()=>i(!1),kn),s=()=>{const e="merchant_click_handler_failed",t="The merchant click handler returned invalid data.";this.emitter.emit("error",{code:e,message:t,recoverable:!1}),i(!1)};try{this.emitter.emitAndThrow("click",{wallet:t,resolve:e=>{try{i(!0,e)}catch{s()}},reject:()=>i(!1)})}catch{const e={code:"merchant_click_handler_failed",message:"The merchant click handler threw an error."};this.emitter.emit("error",{code:e.code,message:e.message,recoverable:!1}),i(!1)}}emitShippingAddressChange(e,t,n,i,o){if(!this.emitter.hasListeners("shippingaddresschange"))return this.group.resolveWalletUpdate(this.componentId,e,t,!0),void o?.(this.walletUpdateSettlement(!0));this.emitShippingUpdate("shippingaddresschange",e,t,{wallet:n,address:i},o)}emitShippingRateChange(e,t,n,i,o){if(!this.emitter.hasListeners("shippingratechange"))return this.group.resolveWalletUpdate(this.componentId,e,t,!0),void o?.(this.walletUpdateSettlement(!0));this.emitShippingUpdate("shippingratechange",e,t,{wallet:n,shippingRate:i},o)}emitShippingUpdate(e,t,n,i,o){let s=!1;const a=(e,i)=>{if(s||this.destroyed||this.activeAttempt?.requestId!==t)return;const a=e?function(e){if(void 0===e)return;if(!Xn(e)||Object.keys(e).some(e=>!["amount","lineItems","shippingRates"].includes(e)))throw ai();const t=e.amount;if(void 0!==t&&("number"!=typeof t||!Number.isSafeInteger(t)||t<0))throw ai();return Yn(e.lineItems,"name"),Yn(e.shippingRates,"displayName",!0),ri(e)}(i):void 0;if(s=!0,window.clearTimeout(r),e&&a){const e=Object.prototype.hasOwnProperty.call(a,"lineItems"),t=Object.prototype.hasOwnProperty.call(a,"shippingRates");this.activeOptions=ri({...this.activeOptions??this.options,...e?{lineItems:a.lineItems}:{},...t?{shippingRates:a.shippingRates}:{}})}this.group.resolveWalletUpdate(this.componentId,t,n,e,a),o?.(this.walletUpdateSettlement(e,a))},r=window.setTimeout(()=>a(!1),kn),l=e=>{this.emitter.emit("error",{code:"merchant_shipping_update_handler_failed",message:e,recoverable:!1}),a(!1)};try{this.emitter.emitAndThrow(e,{...i,resolve:e=>{try{a(!0,e)}catch{l("The merchant shipping update handler returned invalid data.")}},reject:()=>a(!1)})}catch{const e={code:"merchant_shipping_update_handler_failed",message:"The merchant shipping update handler threw an error."};this.emitter.emit("error",{code:e.code,message:e.message,recoverable:!1}),a(!1)}}cancelAction(){const e=this.activeAttempt;e&&this.group.cancelComponentSubmission(this.componentId,e.requestId)}failAction(e,t,n){this.activeAttempt&&this.finalizeWalletAttempt({cancelSubmission:!0}),this.emitter.emit("error",{code:e,message:t,recoverable:n})}finalizeWalletAttempt(e={}){const t=this.activeAttempt;!t||void 0!==e.requestId&&t.requestId!==e.requestId||(this.group.endWalletAttempt(this.componentId,t.requestId),e.cancelSubmission&&this.group.cancelComponentSubmission(this.componentId,t.requestId),e.skipApplePayCompletion||"apple_pay"!==t.wallet||this.completeApplePay(!1),"google_pay"===t.wallet&&this.clearGooglePayAttempt(t.requestId),this.activeAttempt=null,this.activeOptions=null,this.actionShell.close())}canMakeApplePayPayments(){if("undefined"==typeof window||!window.isSecureContext)return!1;const e=window.ApplePaySession;try{return Boolean(e?.canMakePayments?.())}catch{return!1}}async resolveGooglePayCapabilities(e,t){try{if(await V(),this.destroyed)return;const n=Qn(t),i=this.createGooglePayClient(e),o=await i.isReadyToPay(n);if(this.destroyed)return;this.googlePayClient=i,this.googlePayEnvironment=e,this.group.sendGooglePayCapabilities(this.componentId,!0===o?.result)}catch{this.destroyed||this.group.sendGooglePayCapabilities(this.componentId,!1)}}async configureGooglePayButton(e){const t=++this.googlePayButtonGeneration;if(this.googlePayButtonTarget=e,!e.visible)return this.removeGooglePayButton(),void this.group.sendGooglePayCapabilities(this.componentId,!1);try{if(await V(),this.destroyed||t!==this.googlePayButtonGeneration)return;const n=Qn(e.requestJson),i=n.allowedPaymentMethods;if(!Array.isArray(i))throw new Error("Invalid Google Pay request.");const o=this.createGooglePayClient(e.environment),s=await o.isReadyToPay({apiVersion:n.apiVersion,apiVersionMinor:n.apiVersionMinor,allowedPaymentMethods:i});if(this.destroyed||t!==this.googlePayButtonGeneration)return;const a=!0===s?.result;if(this.googlePayClient=o,this.googlePayEnvironment=e.environment,this.group.sendGooglePayCapabilities(this.componentId,a),!a)return void this.removeGooglePayButton();this.mountGooglePayButton(o,e,n,i)}catch{if(this.destroyed||t!==this.googlePayButtonGeneration)return;this.removeGooglePayButton(),this.group.sendGooglePayCapabilities(this.componentId,!1)}}mountGooglePayButton(e,t,n,i){this.removeGooglePayButton();const o=document.createElement("div");o.dataset.paypercutElementsGooglePayButton=this.componentId,Object.assign(o.style,{position:"fixed",margin:"0",padding:"0",border:"0",overflow:"hidden",zIndex:"2147483000",pointerEvents:"auto",visibility:"hidden"});const s=e.createButton({buttonColor:t.buttonColor,buttonType:t.buttonType,buttonRadius:t.buttonRadius,buttonSizeMode:"fill",allowedPaymentMethods:i,onClick:()=>{if(this.destroyed||this.googlePayRequestId||this.activeAttempt)return;const e=z();o.style.visibility="hidden",o.style.pointerEvents="none",this.group.sendGooglePayClick(this.componentId,e),this.startGooglePay(e,t.environment,ei(n))}});Object.assign(s.style,{width:"100%",height:"100%",margin:"0"}),o.appendChild(s),document.body.appendChild(o),this.googlePayButtonContainer=o,window.addEventListener("resize",this.googlePayButtonPositionHandler),window.addEventListener("scroll",this.googlePayButtonPositionHandler,!0),"undefined"!=typeof ResizeObserver&&this.iframe&&(this.googlePayButtonResizeObserver=new ResizeObserver(this.googlePayButtonPositionHandler),this.googlePayButtonResizeObserver.observe(this.iframe)),this.positionGooglePayButton()}positionGooglePayButton(){const e=this.googlePayButtonContainer,t=this.googlePayButtonTarget,n=this.iframe;if(!e||!t?.visible||!n||this.googlePayRequestId)return;const i=n.getBoundingClientRect(),o=i.left+t.target.x,s=i.top+t.target.y;Object.assign(e.style,{left:`${o}px`,top:`${s}px`,width:`${t.target.width}px`,height:`${t.target.height}px`,borderRadius:`${t.buttonRadius}px`,visibility:i.width>0&&i.height>0&&t.target.width>0&&t.target.height>0?"visible":"hidden",pointerEvents:"auto"})}removeGooglePayButton(){null!==this.googlePayButtonPositionFrame&&(window.cancelAnimationFrame(this.googlePayButtonPositionFrame),this.googlePayButtonPositionFrame=null),window.removeEventListener("resize",this.googlePayButtonPositionHandler),window.removeEventListener("scroll",this.googlePayButtonPositionHandler,!0),this.googlePayButtonResizeObserver?.disconnect(),this.googlePayButtonResizeObserver=null,this.googlePayButtonContainer?.remove(),this.googlePayButtonContainer=null}destroyGooglePayButton(){this.googlePayButtonGeneration+=1,this.googlePayButtonTarget=null,this.removeGooglePayButton()}startGooglePay(e,t,n){let i;this.clearGooglePayAttempt(),this.googlePayButtonContainer&&(this.googlePayButtonContainer.style.visibility="hidden",this.googlePayButtonContainer.style.pointerEvents="none");try{i=Qn(n)}catch{return void this.group.sendGooglePayError(this.componentId,e,"elements_google_pay_request_invalid","Google Pay could not be opened because its request was invalid.")}const o=globalThis.google?.payments?.api?.PaymentsClient;if(o&&this.googlePayEnvironment===t){this.googlePayRequestId=e;try{const n=new Set(Array.isArray(i.callbackIntents)?i.callbackIntents.filter(e=>"string"==typeof e):[]),o={};(n.has("OFFER")||n.has("SHIPPING_ADDRESS")||n.has("SHIPPING_OPTION"))&&(o.onPaymentDataChanged=t=>this.requestGooglePayDataChanged(e,t)),n.has("PAYMENT_AUTHORIZATION")&&(o.onPaymentAuthorized=t=>this.requestGooglePayAuthorization(e,t)),this.googlePayClient=this.createGooglePayClient(t,Object.keys(o).length>0?o:void 0);const s=this.googlePayClient.loadPaymentData(i);Promise.resolve(s).then(t=>{this.googlePayRequestId!==e||this.destroyed||(this.googlePayProcessingRequestId=e,this.group.markWalletAttemptProcessing(this.componentId,e,"google_pay"),this.group.sendGooglePayPaymentData(this.componentId,e,ei(t)))},t=>{this.googlePayRequestId!==e||this.destroyed||(!function(e){return Xn(e)&&("CANCELED"===e.statusCode||"CANCELED"===e.code)}(t)?this.group.sendGooglePayError(this.componentId,e,ii(t),oi(t)):this.group.sendGooglePayCanceled(this.componentId,e),this.clearGooglePayAttempt(e))})}catch(t){this.group.sendGooglePayError(this.componentId,e,ii(t),oi(t)),this.clearGooglePayAttempt(e)}}else this.group.sendGooglePayError(this.componentId,e,"elements_google_pay_unavailable","Google Pay is not available in this browser.")}createGooglePayClient(e,t){const n=globalThis.google?.payments?.api?.PaymentsClient;if(!n)throw new Error("Google Pay is unavailable.");return new n({environment:e,...t?{paymentDataCallbacks:t}:{}})}requestGooglePayDataChanged(e,t){if(this.googlePayRequestId!==e)return Promise.resolve(ti("OTHER_ERROR","The payment attempt is stale."));const n=z();return new Promise(i=>{const o=setTimeout(()=>{this.googlePayUpdates.delete(n),i(ti("OTHER_ERROR","The merchant update timed out."))},kn);this.googlePayUpdates.set(n,{requestId:e,resolve:i,timeout:o});try{this.group.sendGooglePayDataChanged(this.componentId,e,n,ei(t))}catch{clearTimeout(o),this.googlePayUpdates.delete(n),i(ti("OTHER_ERROR","The merchant update was invalid."))}})}requestGooglePayAuthorization(e,t){return this.googlePayRequestId!==e||this.googlePayAuthorization?Promise.resolve(ni("The payment attempt is stale.")):new Promise(n=>{const i=setTimeout(()=>{this.googlePayAuthorization=null,n(ni("The merchant authorization timed out."))},kn);this.googlePayAuthorization={requestId:e,resolve:n,timeout:i};try{this.group.sendGooglePayAuthorized(this.componentId,e,ei(t))}catch{clearTimeout(i),this.googlePayAuthorization=null,n(ni("The merchant authorization was invalid."))}})}resolveGooglePayDataChanged(e,t,n){const i=this.googlePayUpdates.get(t);if(i&&i.requestId===e&&this.googlePayRequestId===e){this.googlePayUpdates.delete(t),clearTimeout(i.timeout);try{i.resolve(Qn(n))}catch{i.resolve(ti("OTHER_ERROR","The merchant update was invalid."))}}}resolveGooglePayAuthorization(e,t){const n=this.googlePayAuthorization;if(n&&n.requestId===e&&this.googlePayRequestId===e){this.googlePayAuthorization=null,clearTimeout(n.timeout);try{n.resolve(Qn(t))}catch{n.resolve(ni("The merchant authorization was invalid."))}}}clearGooglePayAttempt(e){if(!e||this.googlePayRequestId===e){this.googlePayRequestId=null,this.googlePayProcessingRequestId=null;for(const e of this.googlePayUpdates.values())clearTimeout(e.timeout),e.resolve(ti("OTHER_ERROR","The payment attempt was canceled."));this.googlePayUpdates.clear(),this.googlePayAuthorization&&(clearTimeout(this.googlePayAuthorization.timeout),this.googlePayAuthorization.resolve(ni("The payment attempt was canceled.")),this.googlePayAuthorization=null),this.positionGooglePayButton()}}startApplePay(e,t){this.abortApplePay();const n=window.ApplePaySession;if(!n||!this.canMakeApplePayPayments())return this.group.sendApplePayCanceled(this.componentId,e),void this.emitter.emit("error",{code:"elements_apple_pay_unavailable",message:"Apple Pay is not available in this browser.",recoverable:!0});let i;try{const e=D(n);i=new n(e,this.prepareApplePayRequest(t))}catch{return this.group.sendApplePayCanceled(this.componentId,e),void this.emitter.emit("error",{code:"elements_apple_pay_start_failed",message:"Apple Pay could not be opened.",recoverable:!0})}this.applePaySession=i,i.onvalidatemerchant=t=>{this.applePayTimeout=setTimeout(()=>{this.abortApplePay(),this.group.sendApplePayCanceled(this.componentId,e)},M),this.group.sendApplePayValidateMerchant(this.componentId,e,t.validationURL)},i.onpaymentauthorized=t=>{this.group.sendApplePayAuthorized(this.componentId,e,t.payment)},i.onshippingcontactselected=n=>{const o=function(e){if(!Xn(e))return;const t=Array.isArray(e.addressLines)?e.addressLines.filter(e=>"string"==typeof e&&""!==e):[],n=[e.givenName,e.familyName].filter(e=>"string"==typeof e&&""!==e).join(" "),i={...n?{recipient:n}:{},...t.length?{addressLine:t}:{},..."string"==typeof e.locality&&e.locality?{city:e.locality}:{},..."string"==typeof e.administrativeArea&&e.administrativeArea?{state:e.administrativeArea}:{},..."string"==typeof e.postalCode&&e.postalCode?{postalCode:e.postalCode}:{},..."string"==typeof e.countryCode&&e.countryCode?{country:e.countryCode.toUpperCase()}:{}};return Object.keys(i).length?i:void 0}(n.shippingContact);o?this.emitShippingAddressChange(e,z(),"apple_pay",o,e=>this.completeApplePayShippingContactSelection(i,t,e)):this.completeApplePayShippingContactSelection(i,t,{accepted:!1,amount:this.group.getUpdateSnapshot().options.amount,currency:this.group.getUpdateSnapshot().options.currency})},i.onshippingmethodselected=n=>{const o=(this.activeOptions?.shippingRates??this.options.shippingRates??[]).find(e=>e.id===n.shippingMethod?.identifier);o?this.emitShippingRateChange(e,z(),"apple_pay",o,e=>this.completeApplePayShippingMethodSelection(i,t,e)):this.completeApplePayShippingMethodSelection(i,t,{accepted:!1,amount:this.group.getUpdateSnapshot().options.amount,currency:this.group.getUpdateSnapshot().options.currency})},i.oncancel=()=>{this.clearApplePayTimeout(),this.applePaySession=null,this.activeOptions=null,this.group.sendApplePayCanceled(this.componentId,e)};try{i.begin()}catch{this.abortApplePay(),this.group.sendApplePayCanceled(this.componentId,e)}}completeApplePay(e){if(!this.applePaySession)return;const t=this.applePaySession,n=window.ApplePaySession;this.clearApplePayTimeout(),this.applePaySession=null;try{t.completePayment(e?n.STATUS_SUCCESS:n.STATUS_FAILURE)}catch{try{t.abort()}catch{}}}abortApplePay(){this.clearApplePayTimeout();try{this.applePaySession?.abort()}catch{}this.applePaySession=null}walletUpdateSettlement(e,t){const n=this.group.getUpdateSnapshot().options;return{accepted:e,...t?{update:t}:{},amount:t?.amount??n.amount,currency:n.currency}}prepareApplePayRequest(e){const t=this.group.getUpdateSnapshot().options,n=this.activeOptions??this.options,i=t.currency;return{...e,currencyCode:i.toUpperCase(),total:Kn(e.total.label,t.amount,i),...n.lineItems?.length?{lineItems:Jn(n.lineItems,i)}:{lineItems:void 0},...n.shippingAddressRequired?{requiredShippingContactFields:["name","postalAddress",...n.emailRequired?["email"]:[],...n.phoneNumberRequired?["phone"]:[]]}:{requiredShippingContactFields:void 0},...n.shippingAddressRequired&&n.shippingRates?.length?{shippingMethods:Zn(n.shippingRates,i)}:{shippingMethods:void 0}}}completeApplePayShippingContactSelection(e,t,n){if(e!==this.applePaySession)return;const i=n.update?.shippingRates??this.activeOptions?.shippingRates??[],o=window.ApplePayError;try{e.completeShippingContactSelection({newShippingMethods:n.accepted?Zn(i,n.currency):[],newTotal:Kn(t.total.label,n.amount,n.currency),newLineItems:Jn(n.update?.lineItems??this.activeOptions?.lineItems,n.currency),...!n.accepted&&o?{errors:[new o("shippingContactInvalid",void 0,"This address is not available for shipping.")]}:{}})}catch{const e=this.activeAttempt?.requestId;e&&this.group.sendApplePayCanceled(this.componentId,e),this.abortApplePay()}}completeApplePayShippingMethodSelection(e,t,n){if(e===this.applePaySession)try{e.completeShippingMethodSelection({newTotal:Kn(t.total.label,n.amount,n.currency),newLineItems:Jn(n.update?.lineItems??this.activeOptions?.lineItems,n.currency)})}catch{const e=this.activeAttempt?.requestId;e&&this.group.sendApplePayCanceled(this.componentId,e),this.abortApplePay()}}clearApplePayTimeout(){this.applePayTimeout&&(clearTimeout(this.applePayTimeout),this.applePayTimeout=null)}}const jn=new Set(["paymentMethods","layout","buttonType","buttonTheme","buttonHeight","buttonRadius","emailRequired","phoneNumberRequired","billingAddressRequired","shippingAddressRequired","allowedShippingCountries","lineItems","shippingRates"]),Fn=256;function Wn(e){const t=e;if(!Xn(t)||Object.keys(t).some(e=>!jn.has(e)))throw new Error("[Paypercut Elements] Express Checkout options are invalid.");if(void 0!==e.buttonHeight&&("number"!=typeof e.buttonHeight||!Number.isSafeInteger(e.buttonHeight)||e.buttonHeight<Mn||e.buttonHeight>Ln))throw new Error("[Paypercut Elements] Express Checkout button height must be 40–64 pixels.");if(void 0!==e.buttonRadius&&("number"!=typeof e.buttonRadius||!Number.isSafeInteger(e.buttonRadius)||e.buttonRadius<0||e.buttonRadius>Dn))throw new Error("[Paypercut Elements] Express Checkout button radius must be 0–24 pixels.");if(e.layout){if("object"!=typeof e.layout||Array.isArray(e.layout))throw ai();for(const t of["maxColumns","maxRows"]){const n=e.layout[t];if(void 0!==n&&("number"!=typeof n||!Number.isSafeInteger(n)||n<1||n>Nn))throw ai()}if(void 0!==e.layout.overflow&&!["auto","never"].includes(e.layout.overflow))throw ai()}if(e.paymentMethods)for(const t of Object.values(e.paymentMethods))if(void 0!==t&&!["auto","always","never"].includes(t))throw ai();if(e.buttonType){if(void 0!==e.buttonType.applePay&&!["plain","buy","check-out","donate","book","subscribe"].includes(e.buttonType.applePay))throw ai();if(void 0!==e.buttonType.googlePay&&!["plain","pay","buy","checkout","donate","book","subscribe"].includes(e.buttonType.googlePay))throw ai()}if(e.buttonTheme){if(void 0!==e.buttonTheme.applePay&&!["black","white","white-outline"].includes(e.buttonTheme.applePay))throw ai();if(void 0!==e.buttonTheme.googlePay&&!["black","white"].includes(e.buttonTheme.googlePay))throw ai()}if(e.allowedShippingCountries&&(!Array.isArray(e.allowedShippingCountries)||e.allowedShippingCountries.length>Fn||e.allowedShippingCountries.some(e=>!/^[A-Za-z]{2}$/.test(e))))throw ai();for(const t of[e.emailRequired,e.phoneNumberRequired,e.billingAddressRequired,e.shippingAddressRequired])if(void 0!==t&&"boolean"!=typeof t)throw ai();return Yn(e.lineItems,"name"),Yn(e.shippingRates,"displayName",!0),ri({...e,...e.allowedShippingCountries?{allowedShippingCountries:e.allowedShippingCountries.map(e=>e.toUpperCase())}:{}})}function Yn(e,t,n=!1){if(void 0!==e){if(!Array.isArray(e)||e.length>qn)throw ai();for(const i of e)if(!Xn(i)||"number"!=typeof i.amount||!Number.isSafeInteger(i.amount)||i.amount<0||!si(i[t],Gn)||n&&!si(i.id,ne))throw ai()}}function $n(e){if(void 0===e)return;const t=new Set(["lineItems","emailRequired","phoneNumberRequired","billingAddressRequired","shippingAddressRequired","allowedShippingCountries","shippingRates"]);if(!Xn(e)||Object.keys(e).some(e=>!t.has(e)))throw ai();Yn(e.lineItems,"name"),Yn(e.shippingRates,"displayName",!0);for(const t of[e.emailRequired,e.phoneNumberRequired,e.billingAddressRequired,e.shippingAddressRequired])if(void 0!==t&&"boolean"!=typeof t)throw ai();if(void 0!==e.allowedShippingCountries&&(!Array.isArray(e.allowedShippingCountries)||e.allowedShippingCountries.length>Fn||e.allowedShippingCountries.some(e=>!/^[A-Za-z]{2}$/.test(e))))throw ai();return ri({...e,...e.allowedShippingCountries?{allowedShippingCountries:e.allowedShippingCountries.map(e=>e.toUpperCase())}:{}})}function Vn(e,t){const n=function(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e.toUpperCase()}).resolvedOptions().maximumFractionDigits??Un}catch{return Un}}(t);return(e/zn**n).toFixed(n)}function Kn(e,t,n){return{label:e,amount:Vn(t,n),type:"final"}}function Jn(e,t){return(e??[]).map(e=>({label:e.name,amount:Vn(e.amount,t),type:"final"}))}function Zn(e,t){return e.map(e=>({identifier:e.id,label:e.displayName,detail:"",amount:Vn(e.amount,t)}))}function Xn(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Qn(e){const t=JSON.parse(e);if(!Xn(t))throw new Error("Expected a JSON object.");return t}function ei(e){if(!Xn(e))throw new Error("Expected an object.");return JSON.stringify(e)}function ti(e,t){return{error:{reason:e,message:t,intent:"PAYMENT_AUTHORIZATION"}}}function ni(e){return{transactionState:"ERROR",error:{intent:"PAYMENT_AUTHORIZATION",reason:"PAYMENT_DATA_INVALID",message:e}}}function ii(e){if(Xn(e)){const t=e.statusCode??e.code;if(le(t,ne))return t}return"elements_google_pay_failed"}function oi(e){if(Xn(e)){const t=e.statusMessage??e.message;if(le(t,ie))return t}return e instanceof Error&&e.message?e.message.slice(0,ie):"Google Pay could not be completed."}const si=le;function ai(){return new Error("[Paypercut Elements] Express Checkout options are invalid.")}function ri(e){return JSON.parse(JSON.stringify(e))}const li="16px",pi="1094 / 742",ci="http://www.w3.org/2000/svg";let hi=null;const di=(e,t,n)=>{null===n?e.removeAttribute(t):e.setAttribute(t,n)};class ui{constructor(){this.host=null,this.cancelButton=null,this.isolatedSiblings=new Map,this.isolationObserver=null,this.previousBodyOverflow="",this.previousDocumentOverflow="",this.previouslyFocused=null,this.providerElement=null,this.cancelAttempt=null,this.keyHandler=e=>{if(this.isActive())return"Tab"===e.key?(e.preventDefault(),e.stopPropagation(),void this.cancelButton?.focus({preventScroll:!0})):void("Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),this.cancel()))}}show(e,t,n,i,o){const s=hi;if(s)return s.owner===this&&s.componentId===e&&s.requestId===t;const a=this.ensureHost();return hi={owner:this,componentId:e,requestId:t},this.cancelAttempt=i,this.providerElement=o??null,this.previouslyFocused=document.activeElement instanceof HTMLElement?document.activeElement:null,this.updateCopy(n,"provider_open"),document.body.prepend(a),a.hidden=!1,a.style.display="flex",this.lockMerchantPage(a),document.addEventListener("keydown",this.keyHandler,!0),a.focus({preventScroll:!0}),!0}setPhase(e,t,n,i){this.matches(e,t)&&this.updateCopy(n,i)}hide(e,t){this.matches(e,t)&&this.hideHost()}close(e,t){this.matches(e,t)&&(hi=null,this.cancelAttempt=null,this.providerElement=null,this.hideHost())}destroy(){hi?.owner===this&&(hi=null),this.cancelAttempt=null,this.providerElement=null,this.hideHost(),this.host?.remove(),this.host=null,this.cancelButton=null}isActive(){return hi?.owner===this}matches(e,t){return hi?.owner===this&&hi.componentId===e&&hi.requestId===t}cancel(){this.isActive()&&this.cancelAttempt?.()}ensureHost(){if(this.host)return this.host;const e=document.createElement("div");e.dataset.paypercutElementsWalletOverlay="",e.hidden=!0,e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-labelledby","paypercut-wallet-overlay-title"),e.setAttribute("aria-describedby","paypercut-wallet-overlay-description"),e.tabIndex=-1,Object.assign(e.style,{position:"fixed",inset:"0",width:"100vw",height:"100vh",margin:"0",paddingTop:"max(20px, env(safe-area-inset-top))",paddingRight:"max(20px, env(safe-area-inset-right))",paddingBottom:"max(20px, env(safe-area-inset-bottom))",paddingLeft:"max(20px, env(safe-area-inset-left))",border:"0",outline:"none",boxSizing:"border-box",display:"none",alignItems:"center",justifyContent:"center",overflow:"auto",overscrollBehavior:"contain",background:"rgba(0, 0, 0, 0.85)",color:"#fff",colorScheme:"dark",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',zIndex:String(2147483646)});const t=document.createElement("div");Object.assign(t.style,{width:"min(430px, 100%)",display:"flex",flexDirection:"column",alignItems:"center",textAlign:"center"});const n=document.createElement("div");n.dataset.paypercutWalletBadge="",n.dataset.paypercutWalletOverlayTile="",Object.assign(n.style,{width:"min(165.52107px, 46vw)",aspectRatio:pi,padding:"0",border:"0",boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"center",overflow:"visible",background:"transparent",boxShadow:"none"});const i=document.createElement("h2");i.id="paypercut-wallet-overlay-title",Object.assign(i.style,{margin:"0",fontSize:"clamp(26px, 5vw, 30px)",lineHeight:"1.2",fontWeight:"650",letterSpacing:"-0.02em"});const o=document.createElement("p");o.id="paypercut-wallet-overlay-description",Object.assign(o.style,{maxWidth:"430px",margin:`${li} 0 0`,color:"rgba(255, 255, 255, 0.9)",fontSize:"clamp(16px, 3.6vw, 18px)",lineHeight:"1.45",fontWeight:"400"});const s=(()=>{const e=document.createElement("div");e.dataset.paypercutWalletProgress="",e.setAttribute("role","progressbar"),e.setAttribute("aria-label","Processing payment"),e.setAttribute("aria-valuetext","Processing"),Object.assign(e.style,{width:"28px",height:"28px",marginTop:"20px",display:"none",placeItems:"center"});const t=document.createElementNS(ci,"svg");t.dataset.paypercutWalletSpinner="",t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false"),Object.assign(t.style,{display:"block",width:"100%",height:"100%"});const n=document.createElementNS(ci,"circle");n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9"),n.setAttribute("fill","none"),n.setAttribute("stroke","rgba(255, 255, 255, 0.28)"),n.setAttribute("stroke-width","2.5");const i=document.createElementNS(ci,"circle");if(i.setAttribute("cx","12"),i.setAttribute("cy","12"),i.setAttribute("r","9"),i.setAttribute("fill","none"),i.setAttribute("stroke","#fff"),i.setAttribute("stroke-width","2.5"),i.setAttribute("stroke-linecap","round"),i.setAttribute("stroke-dasharray","18 39"),!("function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches)){const e=document.createElementNS(ci,"animateTransform");e.setAttribute("attributeName","transform"),e.setAttribute("type","rotate"),e.setAttribute("from","0 12 12"),e.setAttribute("to","360 12 12"),e.setAttribute("dur","0.85s"),e.setAttribute("repeatCount","indefinite"),i.append(e)}return t.append(n,i),e.append(t),e})(),a=document.createElement("button");return a.type="button",a.textContent="Cancel payment",a.addEventListener("click",()=>this.cancel()),a.addEventListener("focus",()=>{a.style.boxShadow=a.matches(":focus-visible")?"0 0 0 3px rgba(138, 188, 255, 0.9)":"none"}),a.addEventListener("blur",()=>{a.style.boxShadow="none"}),a.addEventListener("pointerenter",()=>{a.style.background="rgba(132, 132, 132, 0.42)"}),a.addEventListener("pointerleave",()=>{a.style.background="rgba(111, 111, 111, 0.32)"}),Object.assign(a.style,{width:"min(260px, 100%)",minHeight:"44px",marginTop:li,padding:"10px 18px",border:"0",borderRadius:"10px",background:"rgba(111, 111, 111, 0.32)",color:"#fff",font:"inherit",fontSize:"clamp(16px, 3.6vw, 18px)",lineHeight:"1.35",fontWeight:"400",cursor:"pointer",backdropFilter:"blur(8px)",WebkitBackdropFilter:"blur(8px)",transition:"background-color 120ms ease, box-shadow 120ms ease"}),t.append(n,i,o,s,a),e.append(t),this.host=e,this.cancelButton=a,e}updateCopy(e,t){const n=(e=>"apple_pay"===e?"Apple Pay":"Google Pay")(e),i=this.host?.querySelector("[data-paypercut-wallet-badge]"),o=this.host?.querySelector("[data-paypercut-wallet-progress]"),s=this.host?.querySelector("#paypercut-wallet-overlay-title"),a=this.host?.querySelector("#paypercut-wallet-overlay-description");if(this.host&&(this.host.dataset.paypercutWalletOverlayPhase=t,this.host.setAttribute("aria-busy","processing"===t?"true":"false")),i&&(i.replaceChildren((e=>{const t=document.createElement("template");t.innerHTML="apple_pay"===e?'<svg version="1.1" id="Artwork" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"\n\t width="165.52107px" height="105.9651px" viewBox="0 0 165.52107 105.9651" enable-background="new 0 0 165.52107 105.9651"\n\t xml:space="preserve">\n<g>\n\t<path id="XMLID_4_" d="M150.69807,0H14.82318c-0.5659,0-1.1328,0-1.69769,0.0033c-0.47751,0.0034-0.95391,0.0087-1.43031,0.0217\n\t\tc-1.039,0.0281-2.0869,0.0894-3.1129,0.2738c-1.0424,0.1876-2.0124,0.4936-2.9587,0.9754\n\t\tc-0.9303,0.4731-1.782,1.0919-2.52009,1.8303c-0.73841,0.7384-1.35721,1.5887-1.83021,2.52\n\t\tc-0.4819,0.9463-0.7881,1.9166-0.9744,2.9598c-0.18539,1.0263-0.2471,2.074-0.2751,3.1119\n\t\tc-0.0128,0.4764-0.01829,0.9528-0.0214,1.4291c-0.0033,0.5661-0.0022,1.1318-0.0022,1.6989V91.142\n\t\tc0,0.5671-0.0011,1.13181,0.0022,1.69901c0.00311,0.4763,0.0086,0.9527,0.0214,1.4291\n\t\tc0.028,1.03699,0.08971,2.08469,0.2751,3.11069c0.1863,1.0436,0.4925,2.0135,0.9744,2.9599\n\t\tc0.473,0.9313,1.0918,1.7827,1.83021,2.52c0.73809,0.7396,1.58979,1.3583,2.52009,1.8302\n\t\tc0.9463,0.4831,1.9163,0.7892,2.9587,0.9767c1.026,0.1832,2.0739,0.2456,3.1129,0.2737c0.4764,0.0108,0.9528,0.0172,1.43031,0.0194\n\t\tc0.56489,0.0044,1.13179,0.0044,1.69769,0.0044h135.87489c0.5649,0,1.13181,0,1.69659-0.0044\n\t\tc0.47641-0.0022,0.95282-0.0086,1.4314-0.0194c1.0368-0.0281,2.0845-0.0905,3.11301-0.2737\n\t\tc1.041-0.1875,2.0112-0.4936,2.9576-0.9767c0.9313-0.4719,1.7805-1.0906,2.52011-1.8302c0.7372-0.7373,1.35599-1.5887,1.8302-2.52\n\t\tc0.48299-0.9464,0.78889-1.9163,0.97429-2.9599c0.1855-1.026,0.2457-2.0737,0.2738-3.11069\n\t\tc0.013-0.4764,0.01941-0.9528,0.02161-1.4291c0.00439-0.5672,0.00439-1.1319,0.00439-1.69901V14.8242\n\t\tc0-0.5671,0-1.1328-0.00439-1.6989c-0.0022-0.4763-0.00861-0.9527-0.02161-1.4291c-0.02811-1.0379-0.0883-2.0856-0.2738-3.1119\n\t\tc-0.18539-1.0432-0.4913-2.0135-0.97429-2.9598c-0.47421-0.9313-1.093-1.7816-1.8302-2.52\n\t\tc-0.73961-0.7384-1.58881-1.3572-2.52011-1.8303c-0.9464-0.4818-1.9166-0.7878-2.9576-0.9754\n\t\tc-1.0285-0.1844-2.0762-0.2457-3.11301-0.2738c-0.47858-0.013-0.95499-0.0183-1.4314-0.0217C151.82988,0,151.26297,0,150.69807,0\n\t\tL150.69807,0z"/>\n\t<path id="XMLID_3_" fill="#FFFFFF" d="M150.69807,3.532l1.67149,0.0032c0.4528,0.0032,0.90561,0.0081,1.36092,0.0205\n\t\tc0.79201,0.0214,1.71849,0.0643,2.58209,0.2191c0.7507,0.1352,1.38029,0.3408,1.9845,0.6484\n\t\tc0.5965,0.3031,1.14301,0.7003,1.62019,1.1768c0.479,0.4797,0.87671,1.0271,1.18381,1.6302\n\t\tc0.30589,0.5995,0.51019,1.2261,0.64459,1.9823c0.1544,0.8542,0.1971,1.7832,0.21881,2.5801\n\t\tc0.01219,0.4498,0.01819,0.8996,0.0204,1.3601c0.00429,0.5569,0.0042,1.1135,0.0042,1.6715V91.142\n\t\tc0,0.558,0.00009,1.1136-0.0043,1.6824c-0.00211,0.4497-0.0081,0.8995-0.0204,1.3501c-0.02161,0.7957-0.0643,1.7242-0.2206,2.5885\n\t\tc-0.13251,0.7458-0.3367,1.3725-0.64429,1.975c-0.30621,0.6016-0.70331,1.1484-1.18022,1.6251\n\t\tc-0.47989,0.48-1.0246,0.876-1.62819,1.1819c-0.5997,0.3061-1.22821,0.51151-1.97151,0.6453\n\t\tc-0.88109,0.157-1.84639,0.2002-2.57339,0.2199c-0.4574,0.0103-0.9126,0.01649-1.37889,0.0187\n\t\tc-0.55571,0.0043-1.1134,0.0042-1.6692,0.0042H14.82318c-0.0074,0-0.0146,0-0.0221,0c-0.5494,0-1.0999,0-1.6593-0.0043\n\t\tc-0.4561-0.00211-0.9112-0.0082-1.3512-0.0182c-0.7436-0.0201-1.7095-0.0632-2.5834-0.2193\n\t\tc-0.74969-0.1348-1.3782-0.3402-1.9858-0.6503c-0.59789-0.3032-1.1422-0.6988-1.6223-1.1797\n\t\tc-0.4764-0.4756-0.8723-1.0207-1.1784-1.6232c-0.3064-0.6019-0.5114-1.2305-0.64619-1.9852\n\t\tc-0.15581-0.8626-0.19861-1.7874-0.22-2.5777c-0.01221-0.4525-0.01731-0.9049-0.02021-1.3547l-0.0022-1.3279l0.0001-0.3506V14.8242\n\t\tl-0.0001-0.3506l0.0021-1.3251c0.003-0.4525,0.0081-0.9049,0.02031-1.357c0.02139-0.7911,0.06419-1.7163,0.22129-2.5861\n\t\tc0.1336-0.7479,0.3385-1.3765,0.6465-1.9814c0.3037-0.5979,0.7003-1.1437,1.17921-1.6225\n\t\tc0.477-0.4772,1.02309-0.8739,1.62479-1.1799c0.6011-0.3061,1.2308-0.5116,1.9805-0.6465c0.8638-0.1552,1.7909-0.198,2.5849-0.2195\n\t\tc0.4526-0.0123,0.9052-0.0172,1.3544-0.0203l1.6771-0.0033H150.69807"/>\n\t<g>\n\t\t<g>\n\t\t\t<path d="M45.1862,35.64053c1.41724-1.77266,2.37897-4.15282,2.12532-6.58506c-2.07464,0.10316-4.60634,1.36871-6.07207,3.14276\n\t\t\t\tc-1.31607,1.5192-2.4809,3.99902-2.17723,6.3293C41.39111,38.72954,43.71785,37.36345,45.1862,35.64053"/>\n\t\t\t<path d="M47.28506,38.98252c-3.38211-0.20146-6.25773,1.91951-7.87286,1.91951c-1.61602,0-4.08931-1.81799-6.76438-1.76899\n\t\t\t\tc-3.48177,0.05114-6.71245,2.01976-8.4793,5.15079c-3.63411,6.2636-0.95904,15.55471,2.57494,20.65606\n\t\t\t\tc1.71618,2.5238,3.78447,5.30269,6.50976,5.20287c2.57494-0.10104,3.58421-1.66732,6.71416-1.66732\n\t\t\t\tc3.12765,0,4.03679,1.66732,6.76252,1.61681c2.82665-0.05054,4.59381-2.52506,6.30997-5.05132\n\t\t\t\tc1.96878-2.877,2.77473-5.65498,2.82542-5.80748c-0.0507-0.05051-5.45058-2.12204-5.50065-8.33358\n\t\t\t\tc-0.05098-5.20101,4.23951-7.6749,4.44144-7.82832C52.3832,39.4881,48.5975,39.08404,47.28506,38.98252"/>\n\t\t</g>\n\t\t<g>\n\t\t\t<path d="M76.73385,31.94381c7.35096,0,12.4697,5.06708,12.4697,12.44437c0,7.40363-5.22407,12.49704-12.65403,12.49704h-8.13892\n\t\t\t\tv12.94318h-5.88037v-37.8846H76.73385z M68.41059,51.9493h6.74732c5.11975,0,8.0336-2.75636,8.0336-7.53479\n\t\t\t\tc0-4.77792-2.91385-7.50845-8.00727-7.50845h-6.77365V51.9493z"/>\n\t\t\t<path d="M90.73997,61.97864c0-4.8311,3.70182-7.79761,10.26583-8.16526l7.56061-0.44614v-2.12639\n\t\t\t\tc0-3.07185-2.07423-4.90959-5.53905-4.90959c-3.28251,0-5.33041,1.57492-5.82871,4.04313h-5.35574\n\t\t\t\tc0.31499-4.98859,4.56777-8.66407,11.3941-8.66407c6.69466,0,10.97377,3.54432,10.97377,9.08388v19.03421h-5.43472v-4.54194\n\t\t\t\th-0.13065c-1.60125,3.07185-5.09341,5.01441-8.71623,5.01441C94.52078,70.30088,90.73997,66.94038,90.73997,61.97864z\n\t\t\t\t M108.56641,59.4846v-2.17905l-6.8,0.41981c-3.38683,0.23649-5.30306,1.73291-5.30306,4.09579\n\t\t\t\tc0,2.41504,1.99523,3.99046,5.04075,3.99046C105.46823,65.81161,108.56641,63.08108,108.56641,59.4846z"/>\n\t\t\t<path d="M119.34167,79.9889v-4.5946c0.4193,0.10483,1.36425,0.10483,1.83723,0.10483c2.6252,0,4.04313-1.10245,4.90908-3.9378\n\t\t\t\tc0-0.05267,0.49931-1.68025,0.49931-1.70658l-9.97616-27.64562h6.14268l6.98432,22.47371h0.10432l6.98433-22.47371h5.9857\n\t\t\t\tl-10.34483,29.06304c-2.36186,6.69517-5.0924,8.84789-10.81577,8.84789C121.17891,80.12006,119.76098,80.06739,119.34167,79.9889\n\t\t\t\tz"/>\n\t\t</g>\n\t</g>\n</g>\n<g>\n</g>\n<g>\n</g>\n<g>\n</g>\n<g>\n</g>\n<g>\n</g>\n<g>\n</g>\n</svg>':'<svg version="1.1" id="G_Pay_Acceptance_Mark" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"\n\t x="0px" y="0px" viewBox="0 0 1094 742" enable-background="new 0 0 1094 742" xml:space="preserve">\n<path id="Base_1_" fill="#FFFFFF" d="M722.7,170h-352c-110,0-200,90-200,200l0,0c0,110,90,200,200,200h352c110,0,200-90,200-200l0,0\n\tC922.7,260,832.7,170,722.7,170z"/>\n<path id="Outline" fill="#3C4043" d="M722.7,186.2c24.7,0,48.7,4.9,71.3,14.5c21.9,9.3,41.5,22.6,58.5,39.5\n\tc16.9,16.9,30.2,36.6,39.5,58.5c9.6,22.6,14.5,46.6,14.5,71.3s-4.9,48.7-14.5,71.3c-9.3,21.9-22.6,41.5-39.5,58.5\n\tc-16.9,16.9-36.6,30.2-58.5,39.5c-22.6,9.6-46.6,14.5-71.3,14.5h-352c-24.7,0-48.7-4.9-71.3-14.5c-21.9-9.3-41.5-22.6-58.5-39.5\n\tc-16.9-16.9-30.2-36.6-39.5-58.5c-9.6-22.6-14.5-46.6-14.5-71.3s4.9-48.7,14.5-71.3c9.3-21.9,22.6-41.5,39.5-58.5\n\tc16.9-16.9,36.6-30.2,58.5-39.5c22.6-9.6,46.6-14.5,71.3-14.5L722.7,186.2 M722.7,170h-352c-110,0-200,90-200,200l0,0\n\tc0,110,90,200,200,200h352c110,0,200-90,200-200l0,0C922.7,260,832.7,170,722.7,170L722.7,170z"/>\n<g id="G_Pay_Lockup_1_">\n\t<g id="Pay_Typeface_3_">\n\t\t<path id="Letter_p_3_" fill="#3C4043" d="M529.3,384.2v60.5h-19.2V295.3H561c12.9,0,23.9,4.3,32.9,12.9\n\t\t\tc9.2,8.6,13.8,19.1,13.8,31.5c0,12.7-4.6,23.2-13.8,31.7c-8.9,8.5-19.9,12.7-32.9,12.7h-31.7V384.2z M529.3,313.7v52.1h32.1\n\t\t\tc7.6,0,14-2.6,19-7.7c5.1-5.1,7.7-11.3,7.7-18.3c0-6.9-2.6-13-7.7-18.1c-5-5.3-11.3-7.9-19-7.9h-32.1V313.7z"/>\n\t\t<path id="Letter_a_3_" fill="#3C4043" d="M657.9,339.1c14.2,0,25.4,3.8,33.6,11.4c8.2,7.6,12.3,18,12.3,31.2v63h-18.3v-14.2h-0.8\n\t\t\tc-7.9,11.7-18.5,17.5-31.7,17.5c-11.3,0-20.7-3.3-28.3-10s-11.4-15-11.4-25c0-10.6,4-19,12-25.2c8-6.3,18.7-9.4,32-9.4\n\t\t\tc11.4,0,20.8,2.1,28.1,6.3v-4.4c0-6.7-2.6-12.3-7.9-17c-5.3-4.7-11.5-7-18.6-7c-10.7,0-19.2,4.5-25.4,13.6l-16.9-10.6\n\t\t\tC625.9,345.8,639.7,339.1,657.9,339.1z M633.1,413.3c0,5,2.1,9.2,6.4,12.5c4.2,3.3,9.2,5,14.9,5c8.1,0,15.3-3,21.6-9\n\t\t\ts9.5-13,9.5-21.1c-6-4.7-14.3-7.1-25-7.1c-7.8,0-14.3,1.9-19.5,5.6C635.7,403.1,633.1,407.8,633.1,413.3z"/>\n\t\t<path id="Letter_y_3_" fill="#3C4043" d="M808.2,342.4l-64,147.2h-19.8l23.8-51.5L706,342.4h20.9l30.4,73.4h0.4l29.6-73.4H808.2z"\n\t\t\t/>\n\t</g>\n\t<g id="G_Mark_1_">\n\t\t<path id="Blue_500" fill="#4285F4" d="M452.93,372c0-6.26-0.56-12.25-1.6-18.01h-80.48v33L417.2,387\n\t\t\tc-1.88,10.98-7.93,20.34-17.2,26.58v21.41h27.59C443.7,420.08,452.93,398.04,452.93,372z"/>\n\t\t<path id="Green_500_1_" fill="#34A853" d="M400.01,413.58c-7.68,5.18-17.57,8.21-29.14,8.21c-22.35,0-41.31-15.06-48.1-35.36\n\t\t\th-28.46v22.08c14.1,27.98,43.08,47.18,76.56,47.18c23.14,0,42.58-7.61,56.73-20.71L400.01,413.58z"/>\n\t\t<path id="Yellow_500_1_" fill="#FABB05" d="M320.09,370.05c0-5.7,0.95-11.21,2.68-16.39v-22.08h-28.46\n\t\t\tc-5.83,11.57-9.11,24.63-9.11,38.47s3.29,26.9,9.11,38.47l28.46-22.08C321.04,381.26,320.09,375.75,320.09,370.05z"/>\n\t\t<path id="Red_500" fill="#E94235" d="M370.87,318.3c12.63,0,23.94,4.35,32.87,12.85l24.45-24.43\n\t\t\tc-14.85-13.83-34.21-22.32-57.32-22.32c-33.47,0-62.46,19.2-76.56,47.18l28.46,22.08C329.56,333.36,348.52,318.3,370.87,318.3z"/>\n\t</g>\n</g>\n</svg>';const n=t.content.firstElementChild;if(!(n instanceof SVGElement))throw new Error("Unable to create the wallet provider mark.");return n.removeAttribute("style"),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false"),n.dataset.paypercutWalletMark=e,Object.assign(n.style,{display:"block",flex:"none",width:"apple_pay"===e?"68.74%":"100%",maxWidth:"100%",height:"apple_pay"===e?"auto":"100%"}),n})(e)),i.style.aspectRatio=pi,i.style.background="transparent",i.style.boxShadow="none",i.style.display="provider_open"===t?"flex":"none"),s&&(s.style.marginTop="processing"===t?"0":"apple_pay"===e?"8px":"2px"),o&&(o.style.display="processing"===t?"grid":"none"),"processing"===t)return s&&(s.textContent="Processing your payment"),void(a&&(a.textContent=`${n} returned your payment details. Please wait while we securely prepare the next step.`));s&&(s.textContent=`${n} is open`),a&&(a.textContent=`Complete your payment in the open ${n} window, or close ${n} to continue paying another way.`)}lockMerchantPage(e){this.previousBodyOverflow=document.body.style.overflow,this.previousDocumentOverflow=document.documentElement.style.overflow,document.body.style.overflow="hidden",document.documentElement.style.overflow="hidden";const t=this.getProtectedElements(e),n=e=>{this.isolatedSiblings.has(e)||t.has(e)||(this.isolatedSiblings.set(e,{element:e,inert:e.inert,ariaHidden:e.getAttribute("aria-hidden"),tabIndex:e.getAttribute("tabindex")}),e.inert=!0,e.setAttribute("aria-hidden","true"),e.setAttribute("tabindex","-1"))};for(const e of Array.from(document.body.children))e instanceof HTMLElement&&n(e);this.isolationObserver=new MutationObserver(e=>{for(const t of e)for(const e of Array.from(t.addedNodes))e instanceof HTMLElement&&n(e)}),this.isolationObserver.observe(document.body,{childList:!0})}getProtectedElements(e){const t=new Set([e]);if(!this.providerElement)return t;for(let e=this.providerElement;e;e=e.parentElement)t.add(e);return t}hideHost(){if("undefined"!=typeof document){document.removeEventListener("keydown",this.keyHandler,!0),this.isolationObserver?.disconnect(),this.isolationObserver=null;for(const e of this.isolatedSiblings.values())e.element.isConnected&&(e.element.inert=e.inert,di(e.element,"aria-hidden",e.ariaHidden),di(e.element,"tabindex",e.tabIndex));this.isolatedSiblings.clear(),document.body.style.overflow=this.previousBodyOverflow,document.documentElement.style.overflow=this.previousDocumentOverflow,this.host&&(this.host.hidden=!0,this.host.style.display="none"),this.previouslyFocused?.isConnected&&this.previouslyFocused.focus({preventScroll:!0}),this.previouslyFocused=null}}}class mi{constructor(e,t){if(this.clientOptions=e,this.elementsOptions=t,this.controllerId=z(),this.elements=new Map,this.pendingComponents=new Map,this.controllerIframe=null,this.controlPort=null,this.controllerInitialized=!1,this.controllerBootstrapped=!1,this.destroyed=!1,this.updateRevision=0,this.walletAttemptOverlay=new ui,this.windowMessageHandler=e=>this.onWindowMessage(e),this.hostedOrigin=function(){try{return new URL(i()).origin}catch{throw new Error("[Paypercut Elements] The configured hosted checkout URL is invalid.")}}(e.hostedCheckoutUrl),this.amount=t.amount,t.appearance&&ye(t.appearance),this.appearance=ge(t.appearance),!n(this.hostedOrigin))throw new Error(`[Paypercut Elements] Hosted checkout origin is not allowed: ${this.hostedOrigin}`)}create(e,t){if(this.destroyed)throw new Error("[Paypercut Elements] Cannot create an Element from a destroyed group.");if("payment"===e){const e=new wn(this);return this.elements.set(e.componentId,e),e}if("expressCheckout"===e){const e=new Hn(this,t);return this.elements.set(e.componentId,e),e}throw new Error(`[Paypercut Elements] Unsupported Element type: ${String(e)}`)}getClientOptions(){return{...this.clientOptions}}getElementsOptions(){return{...this.elementsOptions,amount:this.amount,...this.appearance?{appearance:ge(this.appearance)}:{}}}ensureController(){if(this.destroyed||this.controllerIframe)return;if("undefined"==typeof window||"undefined"==typeof document)throw new Error("[Paypercut Elements] Elements can only be mounted in a browser.");const e=document.createElement("iframe");e.id=`paypercut-elements-controller-${this.controllerId}`,e.title="Paypercut payment controller",e.referrerPolicy="origin",e.src=function(e){const t=new URLSearchParams;return fn(t,e),t.set("componentName","controller"),t.set("sdkVersion",e.sdkVersion),t.set("mode",e.elementsOptions.mode),t.set("amount",String(e.elementsOptions.amount)),t.set("currency",e.elementsOptions.currency),Pn("/elements/controller",e.hostedOrigin,t)}({hostedOrigin:this.hostedOrigin,controllerId:this.controllerId,clientOptions:this.clientOptions,elementsOptions:this.elementsOptions,sdkVersion:t.version,referrer:window.location.origin}),e.allow="payment *",e.setAttribute("allowtransparency","true"),e.setAttribute("aria-hidden","true"),e.setAttribute("frameborder","0"),e.setAttribute("role","presentation"),e.setAttribute("scrolling","no"),e.tabIndex=-1,Object.assign(e.style,{position:"fixed",width:"0",height:"0",minWidth:"0",margin:"0",padding:"0",border:"0",display:"block",overflow:"hidden",opacity:"0",pointerEvents:"none",userSelect:"none",visibility:"hidden"}),this.controllerIframe=e,window.addEventListener("message",this.windowMessageHandler),(document.body??document.documentElement).appendChild(e)}attachComponent(e,t){!this.destroyed&&this.elements.has(e.componentId)?(this.pendingComponents.set(e.componentId,{element:e,port:t}),this.ensureController(),this.flushPendingComponents()):t.close()}submitComponent(e,t){const n={channel:ve,type:Te,controllerId:this.controllerId,componentId:e,componentType:"payment",requestId:t};this.postControl(n)}cancelComponentSubmission(e,t){const n=this.elements.get(e);if(!n)return;const i={channel:ve,type:Oe,controllerId:this.controllerId,componentId:e,componentType:n.componentType,requestId:t};this.postControl(i)}beginWalletAttempt(e,t,n,i){const o=this.elements.get(e);return!(!o||"express_checkout"!==o.componentType)&&this.walletAttemptOverlay.show(e,t,n,()=>this.cancelComponentSubmission(e,t),i)}hideWalletAttemptOverlay(e,t){this.walletAttemptOverlay.hide(e,t)}markWalletAttemptProcessing(e,t,n){this.walletAttemptOverlay.setPhase(e,t,n,"processing")}endWalletAttempt(e,t){this.walletAttemptOverlay.close(e,t)}attachActionChannel(e,t,n,i){const o=this.elements.get(e);if(!o)return void i.close();const s={channel:ve,type:Re,controllerId:this.controllerId,componentId:e,componentType:o.componentType,requestId:t,actionId:n};this.postControl(s,[i])}sendApplePayCapabilities(e,t){const n={channel:ve,type:Me,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",available:t};this.postControl(n)}sendApplePayValidateMerchant(e,t,n){const i={channel:ve,type:Le,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,validationUrl:n};this.postControl(i)}sendApplePayAuthorized(e,t,n){const i={channel:ve,type:De,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,payment:n};this.postControl(i)}sendApplePayCanceled(e,t){const n={channel:ve,type:Ne,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t};this.postControl(n)}sendGooglePayCapabilities(e,t){const n={channel:ve,type:Ge,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",available:t};this.postControl(n)}sendGooglePayClick(e,t){const n={channel:ve,type:qe,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t};this.postControl(n)}sendGooglePayDataChanged(e,t,n,i){const o={channel:ve,type:Ue,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,updateId:n,dataJson:i};this.postControl(o)}sendGooglePayAuthorized(e,t,n){const i={channel:ve,type:ze,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,dataJson:n};this.postControl(i)}sendGooglePayPaymentData(e,t,n){const i={channel:ve,type:Be,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,dataJson:n};this.postControl(i)}sendGooglePayCanceled(e,t){const n={channel:ve,type:He,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t};this.postControl(n)}sendGooglePayError(e,t,n,i){const o={channel:ve,type:je,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,code:n,message:i};this.postControl(o)}resolveWalletClick(e,t,n,i){const o=this.getUpdateSnapshot().options,s={channel:ve,type:Fe,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,accepted:n,...i?{options:i}:{},amount:o.amount,currency:o.currency};this.postControl(s)}resolveWalletUpdate(e,t,n,i,o){const s=this.getUpdateSnapshot().options,{amount:a=s.amount,...r}=o??{},l=Object.keys(r).length>0,p={channel:ve,type:We,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,updateId:n,accepted:i,...l?{update:r}:{},amount:a,currency:s.currency};this.postControl(p)}resolveWalletConfirmation(e,t,n,i){const o={channel:ve,type:Ye,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,succeeded:n,...i?{error:i}:{}};this.postControl(o)}updateExpressCheckoutComponent(e,t,n){const i=this.elements.get(e);if(!i||"express_checkout"!==i.componentType)return;if(!this.controllerInitialized)return;const o={channel:ve,type:$e,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",componentRevision:t,componentOptions:n};this.postControl(o)}discoverDeveloperPresets(e){}applyDeveloperPreset(e,t,n){const i={channel:ve,type:xe,controllerId:this.controllerId,componentId:e,componentType:"payment",requestId:t,presetId:n};this.postControl(i)}getUpdateSnapshot(){return{updateRevision:this.updateRevision,options:Pi(this.elementsOptions,this.amount,this.customer,this.appearance)}}getAppearance(){return{theme:this.appearance?.theme??"light",inputs:this.appearance?.inputs??"condensed",labels:this.appearance?.labels??"auto",...void 0!==this.appearance?.disableAnimations?{disableAnimations:this.appearance.disableAnimations}:{},...this.appearance?.variables?{variables:{...this.appearance.variables}}:{},...this.appearance?.rules?{rules:Object.fromEntries(Object.entries(this.appearance.rules).map(([e,t])=>[e,{...t}]))}:{}}}updateAppearance(e){this.update({appearance:e})}update(e){if(this.destroyed)throw new Error("[Paypercut Elements] Cannot update a destroyed group.");if(Array.from(this.elements.values()).some(e=>e.hasActiveSubmission()))throw new Error("[Paypercut Elements] Cannot update Elements while payment details are being submitted.");const t=function(e,t,n,i=0){if(!ae(e)||0===Object.keys(e).length||Object.keys(e).some(e=>!gi.has(e)))throw new Error("[Paypercut Elements] Update options may contain only amount, customer, or appearance details.");const o=e.customer,s=e.appearance,a=e.amount;if(void 0!==a&&(!Number.isSafeInteger(a)||a<0))throw new Error("[Paypercut Elements] Updated amount must be a non-negative safe integer.");return{amount:a??i,customer:void 0===o?t:fi(o,t),appearance:void 0===s?n:bi(s,n)}}(e,this.customer,this.appearance,this.amount);if(t.amount===this.amount&&(n=t.customer,i=this.customer,n?.email===i?.email&&n?.name===i?.name)&&function(e,t){return fe(e??{})===fe(t??{})}(t.appearance,this.appearance))return;var n,i;if(this.updateRevision===Number.MAX_SAFE_INTEGER)throw new Error("[Paypercut Elements] The update revision limit has been reached.");if(this.amount=t.amount,this.customer=t.customer,this.appearance=t.appearance,this.updateRevision+=1,!this.controllerInitialized)return;const o=this.getUpdateSnapshot(),s={channel:ve,type:ke,controllerId:this.controllerId,updateRevision:o.updateRevision,options:o.options};this.postControl(s)}isDestroyed(){return this.destroyed}remove(e){this.elements.delete(e.componentId);const t=this.pendingComponents.get(e.componentId);if(t&&(t.port.close(),this.pendingComponents.delete(e.componentId)),this.controllerInitialized&&this.controlPort){const t={channel:ve,type:_e,controllerId:this.controllerId,componentId:e.componentId,componentType:e.componentType};this.controlPort.postMessage(t)}}destroy(){if(!this.destroyed){this.destroyed=!0;for(const e of Array.from(this.elements.values()))e.destroy();this.elements.clear();for(const e of this.pendingComponents.values())e.port.close();this.pendingComponents.clear(),this.walletAttemptOverlay.destroy(),this.controlPort?.close(),this.controlPort=null,this.controllerIframe?.remove(),this.controllerIframe=null,"undefined"!=typeof window&&window.removeEventListener("message",this.windowMessageHandler)}}onWindowMessage(e){if(this.destroyed||this.controllerBootstrapped||!this.controllerIframe?.contentWindow||e.source!==this.controllerIframe.contentWindow||e.origin!==this.hostedOrigin||(n=e.data,!ae(n)||!re(n,bt)||n.channel!==Pe||n.type!==Ee))return;var n;this.controllerBootstrapped=!0;const i=new MessageChannel;this.controlPort=i.port1,this.controlPort.onmessage=e=>this.onControlMessage(e),this.controlPort.start();const s={channel:Pe,type:Ce,controllerId:this.controllerId,payload:{publishableKey:this.clientOptions.publishableKey,apiUrl:o(this.clientOptions.apiUrl),sdkVersion:t.version,options:this.getUpdateSnapshot().options}};this.controllerIframe.contentWindow.postMessage(s,this.hostedOrigin,[i.port2])}onControlMessage(e){if(t=e.data,ae(t)&&re(t,Pt)&&t.channel===Pe&&t.type===Ae&&le(t.controllerId,ne)&&ae(t.payload)&&re(t.payload,wt)&&le(t.payload.sessionId,ne)){if(e.data.controllerId!==this.controllerId)return;if(this.controllerInitialized=!0,this.flushPendingComponents(),this.updateRevision>0){const e=this.getUpdateSnapshot(),t={channel:ve,type:ke,controllerId:this.controllerId,updateRevision:e.updateRevision,options:e.options};this.postControl(t)}return}var t;if((e=>ae(e)&&re(e,vt)&&e.channel===Pe&&e.type===Se&&le(e.controllerId,ne)&&ae(e.payload)&&re(e.payload,Et)&&le(e.payload.code,ne)&&le(e.payload.message,ie)&&"boolean"==typeof e.payload.recoverable)(e.data)){if(e.data.controllerId!==this.controllerId)return;for(const t of this.elements.values())t.handleControllerError(e.data.payload);return}if(!(e=>{if(!(ae(e)&&e.channel===ve&&e.type===Ve&&le(e.controllerId,ne)&&le(e.componentId,ne)&&It(e.componentType)&&ae(e.payload)))return!1;const t=e.payload;switch(t.event){case"ready":return"payment"===e.componentType||At(t.availablePaymentMethods);case"change":return"payment"===e.componentType;case"resize":return Number.isFinite(t.height)&&t.height>=0&&t.height<=Ze;case"phase":return"payment"===e.componentType&&["submitting","ready"].includes(String(t.phase));case"action_required":return le(t.requestId,ne)&&ae(t.action)&&le(t.action.id,ne)&&"three_d_secure"===t.action.type;case"error":return le(t.code,ne)&&le(t.message,ie)&&"boolean"==typeof t.recoverable;case"submit_result":return"payment"===e.componentType&&le(t.requestId,ne)&&Ut(t.result);case"developer_catalog":return"payment"===e.componentType&&Array.isArray(t.presets)&&t.presets.length>0&&t.presets.length<=Xe&&t.presets.every(zt);case"developer_apply_result":return"payment"===e.componentType&&le(t.requestId,ne)&&le(t.presetId,Qe)&&"boolean"==typeof t.ok&&(t.ok||le(t.errorCode,ne));case"available_payment_methods_change":return"express_checkout"===e.componentType&&At(t.availablePaymentMethods);case"wallet_overlay":return"express_checkout"===e.componentType&&"boolean"==typeof t.open;case"apple_pay_capabilities_request":return"express_checkout"===e.componentType;case"apple_pay_start":return"express_checkout"===e.componentType&&le(t.requestId,ne)&&Lt(t.request);case"apple_pay_merchant_session":return"express_checkout"===e.componentType&&le(t.requestId,ne)&&ae(t.merchantSession);case"google_pay_capabilities_request":return"express_checkout"===e.componentType&&Ot(t.environment)&&xt(t.requestJson,at);case"google_pay_button_target":return"express_checkout"===e.componentType&&"boolean"==typeof t.visible&&Ot(t.environment)&&xt(t.requestJson,rt)&&("black"===t.buttonColor||"white"===t.buttonColor)&&Rt(t.buttonType)&&Number.isFinite(t.buttonRadius)&&t.buttonRadius>=0&&t.buttonRadius<=pt&&kt(t.target);case"google_pay_start":return"express_checkout"===e.componentType&&le(t.requestId,ne)&&Ot(t.environment)&&xt(t.requestJson,rt);case"google_pay_data_changed_result":return"express_checkout"===e.componentType&&le(t.requestId,ne)&&le(t.updateId,ne)&&xt(t.resultJson,rt);case"google_pay_authorization_result":return"express_checkout"===e.componentType&&le(t.requestId,ne)&&xt(t.resultJson,lt);case"wallet_click":case"wallet_cancel":return"express_checkout"===e.componentType&&le(t.requestId,ne)&&_t(t.wallet);case"wallet_shipping_address_change":return"express_checkout"===e.componentType&&le(t.requestId,ne)&&le(t.updateId,ne)&&_t(t.wallet)&&Nt(t.address);case"wallet_shipping_rate_change":return"express_checkout"===e.componentType&&le(t.requestId,ne)&&le(t.updateId,ne)&&_t(t.wallet)&&qt(t.shippingRate);case"wallet_confirm":return"express_checkout"===e.componentType&&le(t.requestId,ne)&&_t(t.wallet)&&ae(t.paymentMethod)&&le(t.paymentMethod.id,ne)&&"card"===t.paymentMethod.type&&(void 0===t.paymentMethodPreview||Tt(t.paymentMethodPreview))&&(void 0===t.billingDetails||Gt(t.billingDetails))&&(void 0===t.shippingAddress||Mt(t.shippingAddress))&&(void 0===t.shippingRate||qt(t.shippingRate));default:return!1}})(e.data))return;const n=e.data;if(n.controllerId!==this.controllerId)return;if(0!==e.ports.length)return void e.ports.forEach(e=>e.close());const i=this.elements.get(n.componentId);i&&n.componentType===i.componentType?i.handleControllerEvent(n.payload):e.ports.forEach(e=>e.close())}flushPendingComponents(){if(this.controllerInitialized&&this.controlPort)for(const[e,t]of this.pendingComponents){const n={channel:ve,type:Ie,controllerId:this.controllerId,componentId:e,componentType:t.element.componentType,componentOptions:t.element.getComponentOptions()};try{this.controlPort.postMessage(n,[t.port]),this.pendingComponents.delete(e)}catch{t.element.handleControllerError({code:"elements_component_attach_failed",message:"The secure payment form could not be attached.",recoverable:!0})}}}postControl(e,t=[]){if(!this.controllerInitialized||!this.controlPort)throw new Error("[Paypercut Elements] The payment controller is not ready.");t.length>0?this.controlPort.postMessage(e,t):this.controlPort.postMessage(e)}}const yi=new Set(["email","name"]),gi=new Set(["amount","customer","appearance"]);function fi(e,t){if(!ae(e))throw new Error("[Paypercut Elements] Customer update details are required.");const n=Object.keys(e);if(0===n.length||n.some(e=>!yi.has(e)))throw new Error("[Paypercut Elements] Customer update must contain email or name.");const i={...t};for(const t of n){const n=e[t];if(null===n){delete i[t];continue}const o="email"===t?ot:st;if("string"!=typeof n||0===n.length||n.length>o||n!==n.trim()||se(n))throw new Error(`[Paypercut Elements] Customer ${t} is invalid.`);i[t]=n}return Object.keys(i).length>0?i:void 0}function bi(e,t){ye(e);const n={...t?.rules};for(const[t,i]of Object.entries(e.rules??{}))n[t]={...n[t],...i};return ge({...t,...e,...t?.variables||e.variables?{variables:{...t?.variables,...e.variables}}:{},...Object.keys(n).length>0?{rules:n}:{}})}function Pi(e,t,n,i){const o=ge(i);return{mode:e.mode,amount:t,currency:e.currency,...e.locale?{locale:String(e.locale)}:{},...n?{customer:{...n}}:{},...o?{appearance:o}:{}}}const wi=/^[A-Za-z]{3}$/;class vi{constructor(e){this.options=e}elements(e){return new mi(this.options,function(e){if(!e||"object"!=typeof e)throw new Error("[Paypercut Elements] Elements options are required.");if("payment"!==e.mode)throw new Error("[Paypercut Elements] Only payment mode is supported.");if(!Number.isSafeInteger(e.amount)||e.amount<0)throw new Error("[Paypercut Elements] Amount must be a non-negative integer in minor units.");if("string"!=typeof e.currency||!wi.test(e.currency))throw new Error("[Paypercut Elements] Currency must be a three-letter ISO 4217 code.");e.appearance&&ye(e.appearance);return{...e,currency:e.currency.toUpperCase(),...e.appearance?{appearance:ge(e.appearance)}:{}}}(e))}}const Ei=function(e){return new vi(function(e){if(!e||"object"!=typeof e)throw new Error("[Paypercut Elements] Client options are required.");const t=e.publishableKey;if("string"!=typeof t||0===t.length||t.length>512||t!==t.trim()||se(t))throw new Error("[Paypercut Elements] A valid publishable key is required.");if(void 0!==e.developerAssistant&&"boolean"!=typeof e.developerAssistant)throw new Error("[Paypercut Elements] Developer assistant access must be a boolean.");return{...e,publishableKey:t}}(e))};Ei.version=t.version;let Ci=!1;const Ai=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Si=/^(0|(\d+(\.\d+)?(px|rem|em)))$/;function Ii(e){e&&(void 0===e.brandColor||Ai.test(e.brandColor)||console.warn(`[PaypercutCheckout] Invalid appearance.variables.brandColor: "${e.brandColor}". Expected a hex color (#RGB or #RRGGBB). Value ignored.`),void 0===e.fontFamily||e.fontFamily.trim()||console.warn("[PaypercutCheckout] Invalid appearance.variables.fontFamily: value is empty. Value ignored."),void 0===e.logoUrl||/^https:\/\//.test(e.logoUrl)||console.warn(`[PaypercutCheckout] Invalid appearance.variables.logoUrl: "${e.logoUrl}". Must start with https://. Value ignored.`),void 0===e.borderRadius||Si.test(e.borderRadius.trim())||console.warn(`[PaypercutCheckout] Invalid appearance.variables.borderRadius: "${e.borderRadius}". Expected a CSS length like "8px", "0.5rem", or "0". Value ignored.`))}class _i{constructor(t){this.options=t,this.emitter=new e,this.mounted=!1,this.destroyed=!1,this.iframe=null,this.applePaySession=null,this.applePayBridgeTimeout=null,this.messageHandler=this.onMessage.bind(this),this.threeDSModal=new l({modalId:"paypercut-3ds-modal",buildUrl:e=>this.buildThreeDSUrl(e),onCancel:()=>this.handle3DSShellCancel(),onReady:e=>this.postThreeDSInit(e)}),window.addEventListener("message",this.messageHandler),f(t.ui_mode??h.EMBEDDED)===h.EMBEDDED&&function(){if("undefined"==typeof window)return;if(window.ApplePaySession)return;if(Ci)return;Ci=!0;const e=document.createElement("script");e.src="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",e.crossOrigin="anonymous",e.async=!0,document.head.appendChild(e)}()}buildSrc(){const e=i(this.options.hostedCheckoutUrl),t=new URL(`/c/${this.options.id}`,e);if(this.options.locale){const e=c(this.options.locale);t.searchParams.set("locale",e)}if(this.options.lang){const e=c(this.options.lang);t.searchParams.set("lang",e)}{const e=f(this.options.ui_mode??h.EMBEDDED);e&&t.searchParams.set("ui_mode",e)}if(this.options.payment_methods&&this.options.payment_methods.length>0){(function(e){const t=[];for(const n of e)y(n)?t.push(n):console.warn(`[PaypercutCheckout] Invalid payment method: "${n}". Skipping.`);return 0===t.length&&(console.warn('[PaypercutCheckout] No valid payment methods provided. Defaulting to "card".'),t.push(d.CARD)),t})(this.options.payment_methods).forEach(e=>{t.searchParams.append("payment_methods",e)})}if(void 0!==this.options.wallet_options)if(0===this.options.wallet_options.length)t.searchParams.set("wallet_options",null);else{(function(e){const t=[];for(const n of e)g(n)?t.push(n):console.warn(`[PaypercutCheckout] Invalid wallet option: "${n}". Skipping.`);return t})(this.options.wallet_options).forEach(e=>{t.searchParams.append("wallet_options",e)})}return this.options.appearance?.preset&&t.searchParams.set("preset",this.options.appearance.preset),this.options.appearance?.theme&&t.searchParams.set("theme",this.options.appearance.theme),this.options.appearance?.variables&&Object.keys(this.options.appearance.variables).length>0&&(Ii(this.options.appearance.variables),t.searchParams.set("appearance_vars",JSON.stringify(this.options.appearance.variables))),void 0!==this.options.form_only&&t.searchParams.set("form_only",String(this.options.form_only)),void 0!==this.options.validate_form&&t.searchParams.set("validate_form",String(this.options.validate_form)),t.toString()}getContainer(){const e="string"==typeof this.options.containerId?document.querySelector(this.options.containerId):this.options.containerId;if(!e)throw new Error(`Container not found: ${this.options.containerId}`);return e}onMessage(e){if(!n(e.origin))return;const t=e.data;if(t&&"object"==typeof t&&"type"in t&&(!t.checkoutId||t.checkoutId===this.options.id))switch(t.type){case"CHECKOUT_LOADED":this.emitter.emit(m.Loaded),this.postToIframe({type:b,checkoutId:this.options.id,applePayBridge:!0});break;case"CHECKOUT_PROCESSING":this.emitter.emit(m.Processing,{checkoutId:t.checkoutId});break;case"CHECKOUT_SUCCESS":const{payment_method:n={},payment:i=null}=t;this.emitter.emit(m.Success,{payment_method:n,payment:i});break;case"CHECKOUT_ERROR":this.emitter.emit(m.Error,(t&&t.error)??t);break;case"CHECKOUT_CANCEL":this.emitter.emit(m.Cancel,{checkoutId:t.checkoutId,wallet:t.wallet});break;case"CHECKOUT_EXPIRED":this.emitter.emit(m.Expired);break;case"CHECKOUT_RESIZE":this.emitter.emit(m.Resize,t.height),this.handleResize(t.height);break;case"PAYPERCUT_THREEDS_FRAME_RESIZE":this.threeDSModal.handleFrameResize(e,t);break;case"THREEDS_START_FLOW":this.threeDSModal.show(t),this.emitter.emit(m.ThreeDSStarted);break;case"THREEDS_READY":this.handle3DSReady();break;case"THREEDS_COMPLETE":this.postToIframe(t),this.threeDSModal.close(),this.emitter.emit(m.ThreeDSComplete);break;case"THREEDS_CANCELED":this.postToIframe(t),this.threeDSModal.close(),this.emitter.emit(m.ThreeDSCanceled);break;case"THREEDS_ERROR":this.postToIframe(t),this.threeDSModal.close(),this.emitter.emit(m.ThreeDSError,t.error);break;case"FORM_VALIDATION":this.emitter.emit(m.FormValidation,{checkoutId:t.checkoutId,wallet:t.wallet});break;case P:this.handleApplePayStart(t);break;case v:this.handleApplePayMerchantSession(t.merchantSession);break;case E:this.abortApplePaySession();break;case A:this.handleApplePayPaymentResult(!0===t.success)}}render(){if(!this.mounted)try{const e=this.getContainer();this.iframe=document.createElement("iframe"),this.iframe.id="paypercut-checkout-iframe",this.iframe.src=this.buildSrc(),this.iframe.allow="payment *; clipboard-write",this.iframe.setAttribute("frameborder","0"),this.iframe.setAttribute("scrolling","no"),this.iframe.setAttribute("allowpaymentrequest","true"),this.iframe.setAttribute("sandbox","allow-scripts allow-forms allow-same-origin allow-popups allow-popups-to-escape-sandbox"),Object.assign(this.iframe.style,{width:"100%",minWidth:"100%",height:"100%",border:"none",display:"block",overflow:"hidden"}),e.appendChild(this.iframe),this.mounted=!0}catch(e){throw console.error("[PaypercutCheckout] Failed to render:",e),e}}submit(){if(this.mounted)try{this.postToIframe({type:"START_PROCESSING",checkoutId:this.options.id})}catch(e){throw console.error("[PaypercutCheckout] Failed to submit payment:",e),e}}postToIframe(e){if(!this.iframe?.contentWindow)return void console.error("[PaypercutCheckout] Cannot post message: iframe not mounted");const t=i(this.options.hostedCheckoutUrl);this.iframe.contentWindow.postMessage(e,t)}handleResize(e){!this.iframe||"number"!=typeof e||e<=0||(this.iframe.style.height=`${e}px`)}buildThreeDSUrl(e){const t=i(this.options.hostedCheckoutUrl),n=new URL(`/c/${this.options.id}/threeds`,t);return n.searchParams.set("sessionId",e.sessionId),n.searchParams.set("step",e.step),e.challengeUrl&&n.searchParams.set("challengeUrl",e.challengeUrl),e.acsTransactionId&&n.searchParams.set("acsTransactionId",e.acsTransactionId),e.threeDSVersion&&n.searchParams.set("threeDSVersion",e.threeDSVersion),n.searchParams.set("liveMode",String(e.liveMode??!1)),n.toString()}handle3DSShellCancel(){this.postToIframe({type:"THREEDS_CANCELED",checkoutId:this.options.id,reason:"sdk_shell_cancel"}),this.threeDSModal.close(),this.emitter.emit(m.ThreeDSCanceled)}handle3DSReady(){this.threeDSModal.handleReady()||console.error("[PaypercutCheckout] No pending 3DS data or iframe not ready")}postThreeDSInit(e){const t=i(this.options.hostedCheckoutUrl);e.contentWindow?.postMessage({type:"THREEDS_INIT",checkoutId:this.options.id},t)}handleApplePayStart(e){this.abortApplePaySession();const t=window.ApplePaySession;if(!t)return void this.postToIframe({type:I,checkoutId:this.options.id});const n=D(t);let i;try{i=new t(n,e.request)}catch(e){return console.error("SecurityError"===e?.name?'[PaypercutCheckout] Apple Pay blocked — parent page missing allow="payment" on iframe':"[PaypercutCheckout] Failed to create ApplePaySession",e),void this.postToIframe({type:I,checkoutId:this.options.id})}this.applePaySession=i,i.onvalidatemerchant=e=>{this.applePayBridgeTimeout=setTimeout(()=>this.abortApplePaySession(),M),this.postToIframe({type:w,checkoutId:this.options.id,validationURL:e.validationURL})},i.onpaymentauthorized=e=>{this.postToIframe({type:C,checkoutId:this.options.id,payment:e.payment})},i.oncancel=()=>{this.applePaySession=null,this.postToIframe({type:S,checkoutId:this.options.id})},i.begin()}handleApplePayMerchantSession(e){if(this.applePayBridgeTimeout&&(clearTimeout(this.applePayBridgeTimeout),this.applePayBridgeTimeout=null),this.applePaySession)try{this.applePaySession.completeMerchantValidation(e)}catch(e){console.error("[PaypercutCheckout] completeMerchantValidation failed",e),this.abortApplePaySession(),this.postToIframe({type:I,checkoutId:this.options.id})}}handleApplePayPaymentResult(e){if(!this.applePaySession)return;const t=window.ApplePaySession;try{this.applePaySession.completePayment(e?t.STATUS_SUCCESS:t.STATUS_FAILURE)}catch(e){console.error("[PaypercutCheckout] completePayment failed",e)}this.applePaySession=null}abortApplePaySession(){this.applePayBridgeTimeout&&(clearTimeout(this.applePayBridgeTimeout),this.applePayBridgeTimeout=null);try{this.applePaySession?.abort()}catch{}this.applePaySession=null}destroy(){if(!this.destroyed){if(this.iframe)try{this.iframe.remove(),this.iframe=null}catch(e){console.error("[PaypercutCheckout] Error removing iframe:",e)}this.threeDSModal.close(),this.abortApplePaySession(),this.mounted=!1,this.destroyed=!0,window.removeEventListener("message",this.messageHandler),this.emitter.clear()}}on(e,t){return this.emitter.on(e,t)}once(e,t){return this.emitter.once(e,t)}off(e,t){this.emitter.off(e,t)}isMounted(){return this.mounted}completeFormValidation(e){this.mounted?this.postToIframe({type:"FORM_VALIDATION_COMPLETED",checkoutId:this.options.id,wallet:e,status:"success"}):console.warn("[PaypercutCheckout] Cannot complete form validation: not mounted")}updateAppearance(e){this.mounted?(Ii(e.variables),this.postToIframe({type:"UPDATE_APPEARANCE",checkoutId:this.options.id,appearance:e})):console.warn("[PaypercutCheckout] Cannot update appearance: not mounted")}failFormValidation(e,t){this.mounted?this.postToIframe({type:"FORM_VALIDATION_COMPLETED",checkoutId:this.options.id,wallet:e,status:"failed",errors:t}):console.warn("[PaypercutCheckout] Cannot fail form validation: not mounted")}}const Ti=function(e){return new _i(e)};return Ti.version=t.version,"undefined"!=typeof window&&(window.Paypercut=Ei,window.PaypercutExpressCheckout=te),Ti}();
|
|
2
2
|
//# sourceMappingURL=paypercut-checkout.iife.min.js.map
|