@paypercut/checkout-js 1.4.3 → 1.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- var PaypercutCheckout=function(){"use strict";var e="undefined"!=typeof document?document.currentScript:null;class t{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)}})}emitAndThrow(e,...t){let i;if(this.handlers.get(e)?.forEach(e=>{try{e(...t)}catch(e){void 0===i&&(i=e)}}),void 0!==i){if(i instanceof Error)throw i;throw new Error(String(i))}}hasListeners(e){const t=this.handlers.get(e);return!!t&&t.size>0}clear(){this.handlers.clear()}}const i="1.4.3",n={version:i,defaultCheckoutOrigin:"https://buy.paypercut.io",defaultApiOrigin:"https://api.paypercut.io",defaultVaultApiUrl:"https://api.basistheory.com",allowedOrigins:["https://buy.paypercut.io"]};function o(e){return!!n.allowedOrigins.includes(e)}function r(e){return n.defaultCheckoutOrigin}function s(e){return n.defaultApiOrigin}function a(){return n.defaultVaultApiUrl}function l(){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 c(e,t,i){const n=Math.min(t,i);return Math.min(Math.max(e,n),i)}class d{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=l();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 o=()=>{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)"},r=()=>{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",r),n.addEventListener("focus",r),n.addEventListener("mouseleave",o),n.addEventListener("blur",o),n.addEventListener("mouseup",r),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.ownsMessageSource(e.source))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())}ownsMessageSource(e){return Boolean(this.iframe?.contentWindow&&e===this.iframe.contentWindow)}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 o=l(),r=Math.min(860,Math.max(0,o.width-32)),s=Math.min(860,Math.max(0,o.height-112)),a=i.width??460,d=i.height??680,p=c(a,320,r),h=c(d,300,s);e.style.width=`${o.width}px`,e.style.height=`${o.height}px`,e.style.minHeight=`${o.height}px`,t.style.width=`${Math.round(p)}px`,t.style.height=`${Math.round(h)}px`,n&&(n.style.width=`${Math.round(p)}px`,n.style.height=`${Math.round(h)}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 u,m,y,g;function f(e){return Object.values(m).includes(e)}function b(e){return Object.values(y).includes(e)}function v(e){var t;if(e)return t=e,Object.values(u).includes(t)?e:void console.warn(`[PaypercutCheckout] Invalid ui_mode: "${e}". Valid options: ${Object.values(u).join(", ")}`)}!function(e){e.EMBEDDED="embedded"}(u||(u={})),function(e){e.CARD="card"}(m||(m={})),function(e){e.APPLE_PAY="apple_pay",e.GOOGLE_PAY="google_pay"}(y||(y={})),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"}(g||(g={}));const w="SDK_CAPABILITIES",P="APPLE_PAY_START",E="APPLE_PAY_VALIDATE_MERCHANT",A="APPLE_PAY_MERCHANT_SESSION",C="APPLE_PAY_MERCHANT_ERROR",S="APPLE_PAY_PAYMENT_DATA",_="APPLE_PAY_PAYMENT_RESULT",I="APPLE_PAY_CANCELLED",T="APPLE_PAY_SESSION_ERROR",R=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 k(e){return e||"en"}function O(e){const t=e.split("-")[0].toLowerCase();return R.has(t)?t:"en"}var x;!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"}(x||(x={}));const M=14,L=3,D=15e3,F=10;function N(e){return e.supportsVersion?.(M)?M:L}const z=16,U=16,q=3,B=8;function j(){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()*U);return("x"===e?t:t&q|B).toString(z)})}const G=100,H=2;function W(e){return(e/G).toFixed(H)}function V(e){return e.startsWith("pk_live_")}let $=null;function Y(){return $||($=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)}),$)}let K=null;function Z(){return K||(K=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)}),K)}function J(e,t,i="DE"){const n={};return void 0!==e.amount&&(n.newTransactionInfo={totalPriceStatus:"FINAL",totalPriceLabel:"Total",totalPrice:W(e.amount),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??`${W(e.amount)} ${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}const X=540,Q=3e3,ee=3e4;function te(e){return"checkout"===e?"check-out":e}class ie{constructor(e){this.options=e,this.emitter=new t,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=j(),this.idempotencyKey=j(),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=e.shippingOptions??[],this.messageHandler=this.onMessage.bind(this),this.threeDSModal=new d({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=r(this.options.hostedCheckoutUrl),t=new URL("/express/tokenize",e);return t.searchParams.set("instanceId",this.instanceId),t.searchParams.set("liveMode",String(V(this.options.publishableKey))),t.toString()}async fetchExpressConfig(){const e=s(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=V(this.options.publishableKey),o="BCR2DN5T735375Y7",r=i.payment_domain?.wallets?.google_pay?.merchant_ref??"",s=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:a(),googlePayMerchantId:n?"active"===s?r:o:r||o,googlePayStatus:s,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??"",threeDSecure:i.three_d_secure??null}}catch(e){console.error("[PaypercutExpressCheckout] Failed to fetch express config:",e)}}onMessage(e){if(!o(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))return;const i=Boolean(this.tokenizeIframe?.contentWindow&&e.source===this.tokenizeIframe.contentWindow),n=this.threeDSModal.ownsMessageSource(e.source),r=new Set(["PAYPERCUT_THREEDS_FRAME_RESIZE","THREEDS_READY","THREEDS_COMPLETE","THREEDS_CANCELED","THREEDS_ERROR"]);if((!r.has(t.type)||n)&&(r.has(t.type)||i)&&(!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(x.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(x.Error,new Error(e?.message??"Payment method creation failed")),this.emitter.emit(x.PaymentMethodFailed,{error:e?.message??"Payment method creation failed"}),this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.applePayPendingShippingOption=null}):(this.completeApplePaySession(!1),this.emitter.emit(x.Error,new Error(t.error??"Apple Pay payment failed")),this.emitter.emit(x.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(x.PaymentMethodCreated,{paymentMethodId:e,wallet:"google_pay",billingDetails:this.pendingGpayBillingDetails??void 0,shippingDetails:this.pendingGpayShippingDetails??void 0,selectedShippingOption:this.pendingGpayShippingOption})}).catch(e=>{this.emitter.emit(x.Error,new Error(e?.message??"Payment method creation failed")),this.emitter.emit(x.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(x.Cancel):(this.emitter.emit(x.Error,new Error(e)),this.emitter.emit(x.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:[y.APPLE_PAY,y.GOOGLE_PAY],n=i.includes(y.APPLE_PAY),o=i.includes(y.GOOGLE_PAY),r=this.options.layout??"auto";this.preferredLayout="auto"===r?"row":r;const s=document.createElement("div");this.wrapper=s,Object.assign(s.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),s.appendChild(this.gpayContainer),Z().catch(e=>{console.error("[PaypercutExpressCheckout] Failed to load Google Pay script:",e)})),n&&(this.applePayContainer=document.createElement("div"),this.applyLayoutToContainers(this.preferredLayout,this.applePayContainer),s.appendChild(this.applePayContainer),Y()),t.appendChild(s),"auto"===r&&"undefined"!=typeof ResizeObserver&&(this.layoutResizeObserver=new ResizeObserver(e=>{const i=e[0]?.contentRect.width??t.offsetWidth;this.pendingObservedLayout=i<=X?"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 a=this.buildTokenizeSrc();this.tokenizeIframe=document.createElement("iframe"),this.tokenizeIframe.id="paypercut-express-tokenize-iframe",this.tokenizeIframe.src=a,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(),o&&e&&this.mountGooglePayFromConfig(),this.emitter.emit(x.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",k(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",te(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)}}),i=t?.borderRadius??"0.5rem";e.style.width="100%",this.injectGpayInnerStyles(e,i),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 i=this.options.locale?k(this.options.locale):"en",n=this.options.buttonOptions,o=document.createElement("apple-pay-button");o.setAttribute("buttonstyle",n?.applePayStyle??"black"),o.setAttribute("type",te(n?.type??"plain")),o.setAttribute("locale",i),o.style.setProperty("--apple-pay-button-width","100%"),o.style.setProperty("--apple-pay-button-height","48px"),o.style.setProperty("--apple-pay-button-border-radius",n?.borderRadius??"0.5rem"),o.style.display="block",o.style.cursor="pointer",o.addEventListener("click",()=>this.startApplePay());const r=()=>{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")?r():customElements?.whenDefined("apple-pay-button").then(r).catch(()=>r())}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=j(),this.setSessionActive(!0),this.emitter.emit(x.Click);const t=await new Promise(e=>{if(!this.emitter.hasListeners(x.SessionStart))return void e(null);const t=setTimeout(()=>e(null),Q);this.emitter.emit(x.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(x.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=W(this.applePayCurrentAmount),o=this.currentLineItems.map(e=>({label:e.label,amount:W(e.amount),type:e.type??"final"})),r={countryCode:this.options.countryCode??"DE",currencyCode:this.options.currency,merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],supportedNetworks:["visa","masterCard"],lineItems:o,total:{label:i,amount:n,type:"final"},requiredBillingContactFields:["postalAddress","name","email"],requiredShippingContactFields:["postalAddress","name","email"]};this.applePayCurrentShippingOptions.length&&(r.shippingMethods=this.applePayCurrentShippingOptions.map(e=>({label:e.label,detail:e.detail??"",amount:W(e.amount),identifier:e.id}))),r.shippingType="shipping",this.abortApplePaySession();const s=N(e);try{const t=new e(s,r);this.applePaySession=t,t.onvalidatemerchant=async e=>{const n=this.expressConfig?.vaultApiUrl??a(),o=this.expressConfig?.publicKey??"";try{const r={"Content-Type":"application/json","BT-API-KEY":o};this.idempotencyKey&&(r["Idempotency-Key"]=this.idempotencyKey);const s=await fetch(`${n}/apple-pay/session`,{method:"POST",headers:r,body:JSON.stringify({display_name:i,domain:window.location.host,validation_url:e.validationURL})});if(!s.ok){const e=await s.json().catch(()=>({}));throw new Error(e?.message??`Merchant validation failed: HTTP ${s.status}`)}const a=await s.json();t.completeMerchantValidation(a)}catch(e){console.error("[PaypercutExpressCheckout] Apple Pay merchant validation failed"),this.abortApplePaySession(),this.emitter.emit(x.Error,new Error(e?.message??"Apple Pay merchant validation failed")),this.emitter.emit(x.Cancel)}},t.onshippingcontactselected=async n=>{const o=n.shippingContact,r=await new Promise(e=>{this.applePayPendingCallback={type:"contact",resolve:e},this.emitter.emit(x.ShippingAddressChange,{address:{country:o.countryCode??"",state:o.administrativeArea,city:o.locality,postalCode:o.postalCode},updateWith:e=>this.update(e)}),setTimeout(()=>e({}),ee)});this.applePayPendingCallback=null,"number"==typeof r.amount&&(this.applePayCurrentAmount=r.amount),Array.isArray(r.lineItems)&&(this.currentLineItems=r.lineItems),Array.isArray(r.shippingOptions)&&(this.applePayCurrentShippingOptions=r.shippingOptions);const s="invalid_shipping_address"===r.status?e.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS:e.STATUS_SUCCESS;try{t.completeShippingContactSelection(s,this.applePayCurrentShippingOptions.map(e=>({label:e.label,detail:e.detail??"",amount:W(e.amount),identifier:e.id})),{label:i,amount:W(this.applePayCurrentAmount),type:"final"},this.currentLineItems.map(e=>({label:e.label,amount:W(e.amount),type:e.type??"final"})))}catch(e){console.error("[PaypercutExpressCheckout] completeShippingContactSelection failed",e)}},t.onshippingmethodselected=async n=>{const o=n.shippingMethod,r={id:o.identifier,label:o.label,detail:o.detail,amount:(s=o.amount,Math.round(Number.parseFloat(s)*G))};var s;this.applePayPendingShippingOption=r;const a=await new Promise(e=>{this.applePayPendingCallback={type:"method",resolve:e},this.emitter.emit(x.ShippingOptionChange,{shippingOption:r,updateWith:e=>this.update(e)}),setTimeout(()=>e({}),ee)});this.applePayPendingCallback=null,"number"==typeof a.amount&&(this.applePayCurrentAmount=a.amount),Array.isArray(a.lineItems)&&(this.currentLineItems=a.lineItems);try{t.completeShippingMethodSelection(e.STATUS_SUCCESS,{label:i,amount:W(this.applePayCurrentAmount),type:"final"},this.currentLineItems.map(e=>({label:e.label,amount:W(e.amount),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??""},threeDSecure:this.expressConfig?.threeDSecure??null})},t.oncancel=()=>{this.applePaySession=null,this.applePayPendingCallback=null,this.applePayPendingShippingOption=null,this.emitter.emit(x.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=V(this.options.publishableKey),i=e.tenantId,n=e.googlePayMerchantId,o=e.displayName||"Checkout";return i?n?(console.log({liveMode:t}),!t||e.merchantMcc&&e.merchantUrl?void Z().then(()=>{this.mountGooglePayButton(i,n,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,i,n){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 r=n?"PRODUCTION":"TEST",s=this.options.countryCode;s||console.warn('[PaypercutExpressCheckout] countryCode is not set. This is required for Google Pay in production. Pass it via options.countryCode (e.g. "DE").');const a={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:W(this.options.amount),currencyCode:this.options.currency,countryCode:s},callbackIntents:["PAYMENT_AUTHORIZATION","SHIPPING_ADDRESS","SHIPPING_OPTION"],shippingAddressRequired:!0,shippingOptionRequired:!0};this.options.allowedCountries?.length&&(a.shippingAddressParameters={allowedCountryCodes:this.options.allowedCountries,phoneNumberRequired:!1}),this.options.shippingOptions?.length&&(a.shippingOptionParameters={defaultSelectedOptionId:this.options.shippingOptions[0].id,shippingOptions:this.options.shippingOptions.map(e=>({id:e.id,label:e.label,description:e.detail??`${W(e.amount)} ${this.options.currency}`}))}),this.gpayPaymentRequest=a,this.gpayClient=new o.payments.api.PaymentsClient({environment:r,paymentDataCallbacks:{onPaymentAuthorized:e=>this.handleGooglePayAuthorized(e),onPaymentDataChanged:e=>this.handleGooglePayDataChanged(e)}});const l=this.options.buttonOptions,c=this.gpayClient.createButton({onClick:()=>this.startGooglePay(a),buttonSizeMode:"fill",buttonType:l?.type??"plain",buttonColor:l?.googlePayColor??"default",...this.options.locale&&{buttonLocale:O(this.options.locale)}}),d=l?.borderRadius??"0.5rem";c.style.width="100%",this.injectGpayInnerStyles(c,d),this.gpayContainer.appendChild(c)}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=j(),this.setSessionActive(!0),this.emitter.emit(x.Click),this.emitter.hasListeners(x.SessionStart)){const t=await new Promise(e=>{const t=setTimeout(()=>e(null),Q);this.emitter.emit(x.SessionStart,{wallet:"google_pay",updateWith:i=>{clearTimeout(t),e(i)}})});if(!t)return this.setSessionActive(!1),void this.emitter.emit(x.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??`${W(e.amount)} ${this.options.currency}`}))}),null!=t.amount&&(this.gpayCurrentAmount=t.amount,e.transactionInfo={...e.transactionInfo,totalPrice:W(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(x.Cancel):this.emitter.emit(x.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,o=e.shippingAddress,r=e.shippingOptionData,s=n?{name:n.name,address:{line1:n.address1,city:n.locality,state:n.administrativeArea,postalCode:n.postalCode,country:n.countryCode}}:null,a=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=r?this.currentShippingOptions.find(e=>e.id===r.id)??{id:r.id,label:r.label??r.id,amount:0}:void 0;this.pendingGpayBillingDetails=s,this.pendingGpayShippingDetails=a,this.pendingGpayShippingOption=l;const c=await new Promise((e,n)=>{const o=setTimeout(()=>{this.pendingGpayResolve=null,this.pendingGpayReject=null,n(new Error("Tokenization timed out"))},ee);this.pendingGpayResolve=t=>{clearTimeout(o),e(t)},this.pendingGpayReject=e=>{clearTimeout(o),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:s,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??""},threeDSecure:this.expressConfig?.threeDSecure??null})});if(c.__closeSheet)return{transactionState:"SUCCESS"};if(!c.success){const e=c.error??"Tokenization failed";return this.emitter.emit(x.Error,new Error(e)),this.emitter.emit(x.PaymentMethodFailed,{error:e}),{transactionState:"ERROR"}}const d=await this.createPaymentMethod({btTokenId:c.btTokenId,cardPayload:c.cardPayload,billingDetails:c.billingDetails,csessId:c.csessId,walletType:"google_pay"});return this.emitter.emit(x.PaymentMethodCreated,{paymentMethodId:d,wallet:"google_pay",billingDetails:s??void 0,shippingDetails:a,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(x.Error,new Error(e?.message??"Google Pay authorization failed")),this.emitter.emit(x.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 J({amount:this.gpayCurrentAmount||this.options.amount,shippingOptions:this.currentShippingOptions},this.options.currency,this.options.countryCode);if("SHIPPING_ADDRESS"===t){return J(await new Promise(e=>{this.emitter.emit(x.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 J(await new Promise(i=>{this.emitter.emit(x.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),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":"",i=e?"none":"";this.applePayContainer&&(this.applePayContainer.style.opacity=t,this.applePayContainer.style.pointerEvents=i,this.applePayContainer.inert=e,this.applePayContainer.setAttribute("aria-busy",String(e))),this.gpayContainer&&(this.gpayContainer.style.opacity=t,this.gpayContainer.style.pointerEvents=i,this.gpayContainer.inert=e,this.gpayContainer.setAttribute("aria-busy",String(e)))}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:o,walletType:r}=e;if(!i||!t)throw new Error("[createPaymentMethod] Missing required tokenization data.");const a=new URL("/v1/payment_methods",s(this.options.apiUrl)),l={type:"card",key:this.options.publishableKey,card:{token:o??"",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:r,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}},c=await fetch(a.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l),cache:"no-store"});if(!c.ok){const e=await c.text().catch(()=>`HTTP ${c.status}`);throw new Error(`Payment method creation failed (${c.status}): ${e}`)}return(await c.json()).id}postToTokenizeIframe(e){if(!this.tokenizeIframe?.contentWindow)return;const t=r(this.options.hostedCheckoutUrl);this.tokenizeIframe.contentWindow.postMessage(e,t)}buildThreeDSUrl(e){const t=r(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(x.Cancel)}handle3DSReady(){this.threeDSModal.handleReady()||console.error("[PaypercutExpressCheckout] No pending 3DS data or iframe not ready")}postThreeDSInit(e){const t=r(this.options.hostedCheckoutUrl);e.contentWindow?.postMessage({type:"THREEDS_INIT",instanceId:this.instanceId},t)}}const ne=function(e){return new ie(e)},oe=128,re=1024,se=/[\u0000-\u001f\u007f]/u,ae=e=>se.test(e),le=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ce=(e,t)=>Object.keys(e).every(e=>t.includes(e))&&t.every(t=>Object.prototype.hasOwnProperty.call(e,t)),de=(e,t)=>"string"==typeof e&&e.length>0&&e.length<=t&&e===e.trim()&&!ae(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"]),he=new Set([".Input",".Input--invalid",".Input:focus",".Label",".Error",".Text",".WalletButton",".WalletButton--applePay",".WalletButton--googlePay",".ActionShell"]),ue=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"]),me=/[{};]|<\/style|@import|expression\s*\(|javascript\s*:|url\s*\(/i,ye=/var\(\s*--([A-Za-z][A-Za-z0-9]*)\s*\)/gi;function ge(e){return"string"==typeof e&&e.length>0&&e.length<=512&&e===e.trim()&&!ae(e)&&!me.test(e)&&function(e){const t=e.replace(ye,(e,t)=>pe.has(t)?"":"var(invalid)");return!/var\s*\(/i.test(t)}(e)}function fe(e){if(!Pe(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(!Pe(e.variables))throw new Error("[Paypercut Elements] Appearance variables are invalid.");for(const[t,i]of Object.entries(e.variables))if(!pe.has(t)||!ge(i))throw new Error(`[Paypercut Elements] Appearance variable ${t} is invalid.`)}if(void 0!==e.rules){if(!Pe(e.rules))throw new Error("[Paypercut Elements] Appearance rules are invalid.");for(const[t,i]of Object.entries(e.rules)){if(!he.has(t)||!Pe(i))throw new Error(`[Paypercut Elements] Appearance rule ${t} is invalid.`);for(const[e,n]of Object.entries(i))if(!ue.has(e)||!ge(n))throw new Error(`[Paypercut Elements] Appearance rule ${t}.${e} is invalid.`)}}}function be(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 ve(e,t){return we(e??{})===we(t??{})}function we(e){return Array.isArray(e)?`[${e.map(we).join(",")}]`:Pe(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${we(e[t])}`).join(",")}}`:JSON.stringify(e)}function Pe(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const Ee="paypercut.elements.controller",Ae="paypercut.elements.component.bootstrap",Ce="paypercut.elements.component",Se="PAYPERCUT_ELEMENTS_CONTROLLER_FRAME_READY",_e="PAYPERCUT_ELEMENTS_CONTROLLER_INIT",Ie="PAYPERCUT_ELEMENTS_CONTROLLER_INITIALIZED",Te="PAYPERCUT_ELEMENTS_CONTROLLER_ERROR",Re="PAYPERCUT_ELEMENTS_CONTROLLER_ATTACH_COMPONENT",ke="PAYPERCUT_ELEMENTS_CONTROLLER_DETACH_COMPONENT",Oe="PAYPERCUT_ELEMENTS_CONTROLLER_VALIDATE_COMPONENT",xe="PAYPERCUT_ELEMENTS_CONTROLLER_SUBMIT_COMPONENT",Me="PAYPERCUT_ELEMENTS_CONTROLLER_CARD_COLLECTION_TOKENIZATION_RESULT",Le="PAYPERCUT_ELEMENTS_CONTROLLER_CANCEL_COMPONENT_SUBMISSION",De="PAYPERCUT_ELEMENTS_CONTROLLER_ATTACH_ACTION_CHANNEL",Fe="PAYPERCUT_ELEMENTS_CONTROLLER_UPDATE_OPTIONS",Ne="PAYPERCUT_ELEMENTS_CONTROLLER_DISCOVER_DEVELOPER_PRESETS",ze="PAYPERCUT_ELEMENTS_CONTROLLER_APPLY_DEVELOPER_PRESET",Ue="PAYPERCUT_ELEMENTS_CONTROLLER_APPLE_PAY_CAPABILITIES",qe="PAYPERCUT_ELEMENTS_CONTROLLER_APPLE_PAY_VALIDATE_MERCHANT",Be="PAYPERCUT_ELEMENTS_CONTROLLER_APPLE_PAY_AUTHORIZED",je="PAYPERCUT_ELEMENTS_CONTROLLER_APPLE_PAY_CANCELED",Ge="PAYPERCUT_ELEMENTS_CONTROLLER_GOOGLE_PAY_CLICK",He="PAYPERCUT_ELEMENTS_CONTROLLER_GOOGLE_PAY_CAPABILITIES",We="PAYPERCUT_ELEMENTS_CONTROLLER_GOOGLE_PAY_DATA_CHANGED",Ve="PAYPERCUT_ELEMENTS_CONTROLLER_GOOGLE_PAY_AUTHORIZED",$e="PAYPERCUT_ELEMENTS_CONTROLLER_GOOGLE_PAY_PAYMENT_DATA",Ye="PAYPERCUT_ELEMENTS_CONTROLLER_GOOGLE_PAY_CANCELED",Ke="PAYPERCUT_ELEMENTS_CONTROLLER_GOOGLE_PAY_ERROR",Ze="PAYPERCUT_ELEMENTS_CONTROLLER_RESOLVE_WALLET_CLICK",Je="PAYPERCUT_ELEMENTS_CONTROLLER_RESOLVE_WALLET_UPDATE",Xe="PAYPERCUT_ELEMENTS_CONTROLLER_RESOLVE_WALLET_CONFIRMATION",Qe="PAYPERCUT_ELEMENTS_CONTROLLER_UPDATE_COMPONENT_OPTIONS",et="PAYPERCUT_ELEMENTS_CONTROLLER_COMPONENT_EVENT",tt="PAYPERCUT_ELEMENTS_COMPONENT_FRAME_READY",it="PAYPERCUT_ELEMENTS_COMPONENT_CONNECT";function nt(e){return"ready"===e.event||"resize"===e.event||"secure_field_surface_invalid"===e.event}const ot=8192,rt=16,st=64,at=80,lt=160,ct=64,dt=256,pt=320,ht=32768,ut=65536,mt=16384,yt=1024,gt=8192,ft=4,bt=2,vt=3,wt=1,Pt=12,Et=2e3,At=512,Ct=["applePay","googlePay"],St=["channel","type"],_t=["channel","type","controllerId","payload"],It=["sessionId","cardCollection"],Tt=["protocolVersion","driver","publicKey","livemode","expiresAt"],Rt=[...Tt,"locale","messages"],kt=[...Rt,"capabilities"],Ot=["paymentMethodSubmission"],xt=[...Tt,"error"],Mt=["card"],Lt=["cardNumber","cardNumberPlaceholder","expirationDate","expirationDatePlaceholder","securityCode","cvvPlaceholder","errors"],Dt=["number","expirationDate","cvv"],Ft=["incomplete","invalid"],Nt=["channel","type","controllerId","payload"],zt=["code","message","recoverable"],Ut=["channel","type","controllerId","componentId","componentType","payload"],qt=[...Ut,"componentGeneration"],Bt=["x","y","width","height"],jt=e=>le(e)&&ce(e,Ct)&&"boolean"==typeof e.applePay&&"boolean"==typeof e.googlePay,Gt=e=>le(e)&&ce(e,St)&&e.channel===Ae&&e.type===tt,Ht=e=>!!(le(e)&&"basis_theory_v2"===e.driver&&de(e.publicKey,At)&&"boolean"==typeof e.livemode&&"string"==typeof e.expiresAt&&Number.isFinite(Date.parse(e.expiresAt)))&&(1===e.protocolVersion?ce(e,Tt):(2===e.protocolVersion||3===e.protocolVersion)&&(2===e.protocolVersion&&ce(e,Rt)?de(e.locale,dt)&&Vt(e.messages):3===e.protocolVersion&&ce(e,kt)&&le(e.capabilities)&&ce(e.capabilities,Ot)?!0===e.capabilities.paymentMethodSubmission&&de(e.locale,dt)&&Vt(e.messages):ce(e,xt)&&Wt(e.error))),Wt=e=>le(e)&&ce(e,zt)&&de(e.code,oe)&&de(e.message,re)&&"boolean"==typeof e.recoverable,Vt=e=>{if(!le(e)||!ce(e,Mt)||!le(e.card))return!1;const t=e.card;if(!ce(t,Lt)||!le(t.errors))return!1;const i=t.errors;if(!ce(i,Dt))return!1;return!!Lt.filter(e=>"errors"!==e).every(e=>de(t[e],re))&&Dt.every(e=>{const t=i[e];return le(t)&&ce(t,Ft)&&Ft.every(e=>de(t[e],re))})},$t=e=>"card"===e||"express_checkout"===e||"card_collection"===e||Yt(e),Yt=e=>"card_number"===e||"card_expiry"===e||"card_cvc"===e,Kt=(e,t)=>{const i=new Set(["event","complete","empty","brand","error"]);return!(!Object.keys(e).every(e=>i.has(e))||"boolean"!=typeof e.complete||"boolean"!=typeof e.empty||"card_number"!==t&&void 0!==e.brand||void 0!==e.brand&&!de(e.brand,ct))&&(void 0===e.error||le(e.error)&&ce(e.error,["type","message"])&&("incomplete"===e.error.type||"invalid"===e.error.type)&&de(e.error.message,re))},Zt=e=>"apple_pay"===e||"google_pay"===e,Jt=e=>le(e)&&Object.keys(e).every(e=>["type","brand","displayBrand","last4","expMonth","expYear","wallet"].includes(e))&&"card"===e.type&&de(e.brand,ct)&&de(e.displayBrand,ct)&&"string"==typeof e.last4&&/^\d{4}$/.test(e.last4)&&(void 0===e.expMonth||Number.isSafeInteger(e.expMonth)&&e.expMonth>=wt&&e.expMonth<=Pt)&&(void 0===e.expYear||Number.isSafeInteger(e.expYear)&&e.expYear>=Et)&&Zt(e.wallet),Xt=e=>"TEST"===e||"PRODUCTION"===e,Qt=e=>"string"==typeof e&&["book","buy","checkout","donate","order","pay","plain","short","subscribe"].includes(e),ei=e=>le(e)&&ce(e,Bt)&&Bt.every(t=>Number.isFinite(e[t]))&&e.x>=-8192&&e.x<=gt&&e.y>=-8192&&e.y<=gt&&e.width>0&&e.width<=ot&&e.height>0&&e.height<=ot,ti=(e,t)=>{if(!de(e,t))return!1;try{const t=JSON.parse(e);return le(t)}catch{return!1}},ii=e=>le(e)&&Object.keys(e).every(e=>"name"===e||"address"===e)&&(void 0===e.name||de(e.name,dt))&&(void 0===e.address||oi(e.address)),ni=e=>!(!le(e)||!le(e.total))&&(de(e.countryCode,bt)&&de(e.currencyCode,vt)&&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)))&&de(e.total.label,oe)&&/^\d+(?:\.\d{1,3})?$/.test(String(e.total.amount))&&["final","pending"].includes(String(e.total.type))),oi=e=>{if(!le(e))return!1;const t=new Set(["name","line1","line2","city","state","postalCode","country"]);return Object.entries(e).every(([e,i])=>t.has(e)&&de(i,"country"===e?bt:dt))},ri=e=>{if(!le(e))return!1;const t=new Set(["recipient","addressLine","city","state","postalCode","country"]);return Object.entries(e).every(([e,i])=>!!t.has(e)&&("addressLine"===e?Array.isArray(i)&&i.length<=ft&&i.every(e=>de(e,dt)):de(i,"country"===e?bt:dt)))},si=e=>le(e)&&Object.keys(e).every(e=>["id","displayName","amount","detail"].includes(e))&&de(e.id,oe)&&de(e.displayName,dt)&&Number.isSafeInteger(e.amount)&&e.amount>=0,ai=e=>{if(!le(e))return!1;const t=new Set(["name","email","phone","address"]);return Object.entries(e).every(([e,i])=>!!t.has(e)&&("address"===e?oi(i):de(i,"email"===e?pt:dt)))},li=e=>!!le(e)&&("succeeded"===e.status?ce(e,["status","paymentMethod"])&&le(e.paymentMethod)&&ce(e.paymentMethod,["id","type"])&&de(e.paymentMethod.id,oe)&&de(e.paymentMethod.type,ct):"failed"===e.status&&ce(e,["status","code","message","recoverable"])&&de(e.code,oe)&&de(e.message,re)&&"boolean"==typeof e.recoverable),ci=e=>le(e)&&de(e.id,st)&&de(e.label,at)&&de(e.description,lt)&&"string"==typeof e.last4&&/^\d{4}$/.test(e.last4)&&["success","challenge","warning","danger"].includes(String(e.tone)),di="paypercut-developer-assistance.iife.min.js",pi=/\/paypercut-checkout(?:-dev)?\.iife\.min\.js$/,hi="string"==typeof __filename?function(e){const t=e.replace(/\\/g,"/");return new URL(`file://${t.startsWith("/")?"":"/"}${t}`).href}(__filename):e&&"SCRIPT"===e.tagName.toUpperCase()&&e.src||new URL("paypercut-checkout.iife.min.js",document.baseURI).href,ui="undefined"==typeof document?null:document.currentScript?.getAttribute("src")??null;let mi=!1;function yi(e){mi||e()||(mi=!0,"undefined"!=typeof document&&"function"==typeof document.createElement&&Boolean(document.head||document.documentElement)?Promise.resolve().then(fi).then(()=>{if(!e())throw new Error}).catch(gi):gi())}function gi(){console.warn("[Paypercut Elements] developer_assistance_load_failed: Developer Assistant is unavailable. The SDK and Elements continue to work.")}function fi(){if(ui||function(e){try{return pi.test(new URL(e).pathname)}catch{return!1}}(hi))return e=function(e){const t=new URL(e);if(pi.test(t.pathname)){const e=new URL(di,t);return e.search=t.search,e.hash="",e.href}return/\.js$/.test(t.pathname)?t.pathname=t.pathname.replace(/[^/]+$/,di):/\/cdn\/?$/.test(t.pathname)?t.pathname=t.pathname.replace(/\/cdn\/?$/,`/dist/${di}`):t.pathname=`${t.pathname.replace(/\/$/,"")}/dist/${di}`,t.hash="",t.href}(hi),new Promise((t,i)=>{const n=document.createElement("script");n.async=!0,n.src=e,n.addEventListener("load",()=>t(),{once:!0}),n.addEventListener("error",()=>i(new Error),{once:!0}),(document.head||document.documentElement).appendChild(n)});var e;const t=new URL("developer-assistance.mjs",hi).href;return import(t)}const bi=Symbol.for("paypercut.checkout-js.developer-assistance");function vi(){const e=globalThis;return e[bi]??(e[bi]={coreVersions:new Set,provider:null,registrations:new Set}),e[bi]}function wi(){const e=vi();if(e.provider&&e.provider.version!==i){for(const t of e.registrations)Pi(t);e.provider=null}e.coreVersions.add(i)}function Pi(e){try{e.delegate?.unregister()}catch{}e.delegate=null}function Ei(e,t){e.registered&&(function(e){try{return e.target.isVisible?.()??!0}catch{return!1}}(e)?t.provider?.version!==i?yi(()=>function(e){return e.provider?.version===i&&Array.from(e.registrations).some(e=>e.registered&&null!==e.delegate)}(t)):function(e,t){if(e.registered&&!e.delegate)try{e.delegate=t.register(e.target)}catch{}}(e,t.provider):Pi(e))}let Ai=null;function Ci(e){const t=vi();wi();const i={target:e,delegate:null,registered:!0};return t.registrations.add(i),function(e){!Ai&&"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&document.documentElement&&(Ai=new MutationObserver(()=>{for(const t of e.registrations)Ei(t,e)}),Ai.observe(document.documentElement,{attributes:!0,attributeFilter:["aria-hidden","class","hidden","style"],childList:!0,subtree:!0}))}(t),Ei(i,t),{unregister(){i.registered&&(i.registered=!1,t.registrations.delete(i),Pi(i),function(e){e.registrations.size>0||(Ai?.disconnect(),Ai=null)}(t))},refresh(){i.registered&&(Ei(i,t),i.delegate?.refresh())},collapse(){i.registered&&i.delegate?.collapse()}}}function Si(e){if(!e?.isConnected)return!1;for(let t=e;t;t=t.parentElement){if(t.hidden||t.inert||"true"===t.getAttribute("aria-hidden"))return!1;const e=t.ownerDocument.defaultView?.getComputedStyle(t);if("none"===e?.display||"hidden"===e?.visibility||"collapse"===e?.visibility||"hidden"===e?.contentVisibility)return!1}return!0}let _i=!1;function Ii(e,t){const i=new URL(e);return i.searchParams.set("__paypercut_navigation",t),i.toString()}function Ti(e,t,i=!0){var n;e.set("controllerId",t.controllerId),e.set("apiKey",t.clientOptions.publishableKey),Ri(e,"account",t.clientOptions.account),i&&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){Ri(e,"publicOptions[appearance][theme]",t?.theme),Ri(e,"publicOptions[appearance][inputs]",t?.inputs),Ri(e,"publicOptions[appearance][labels]",t?.labels),Ri(e,"publicOptions[appearance][disableAnimations]",t?.disableAnimations);for(const[i,n]of Object.entries(t?.variables??{}).sort(([e],[t])=>e.localeCompare(t)))Ri(e,`publicOptions[appearance][variables][${i}]`,n);for(const[i,n]of Object.entries(t?.rules??{}).sort(([e],[t])=>e.localeCompare(t)))for(const[t,o]of Object.entries(n??{}).sort(([e],[t])=>e.localeCompare(t)))Ri(e,`publicOptions[appearance][rules][${i}][${t}]`,o)}(e,t.elementsOptions.appearance)}function Ri(e,t,i){void 0!==i&&e.set(t,String(i))}function ki(e,t,i){const n=new URL(e,t);n.hash=i.toString();const o=n.toString();return!_i&&o.length>4096&&(_i=!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}const Oi=new Set(["name","email","phone","address"]),xi=new Set(["line1","line2","city","state","postal_code","country"]),Mi=200,Li=320,Di=64,Fi=256,Ni=64,zi=(e,t,i)=>{if("string"!=typeof e)throw new Error(`[Paypercut Elements] Billing ${t} must be a string.`);const n=e.trim();if(0===n.length||n.length>i||ae(n))throw new Error(`[Paypercut Elements] Billing ${t} is invalid.`);return n};function Ui(e,t){return e===t||!(!e||!t)&&(e.name===t.name&&e.email===t.email&&e.phone===t.phone&&e.address?.line1===t.address?.line1&&e.address?.line2===t.address?.line2&&e.address?.city===t.address?.city&&e.address?.state===t.address?.state&&e.address?.postal_code===t.address?.postal_code&&e.address?.country===t.address?.country)}const qi="paypercut.elements.action",Bi="PAYPERCUT_ELEMENTS_ACTION_FRAME_READY",ji="PAYPERCUT_ELEMENTS_ACTION_INIT",Gi="PAYPERCUT_ELEMENTS_ACTION_WAKE",Hi="PAYPERCUT_ELEMENTS_ACTION_PHASE",Wi="PAYPERCUT_ELEMENTS_ACTION_RESULT",Vi="PAYPERCUT_ELEMENTS_ACTION_ERROR",$i=["channel","type","requestId","payload"],Yi=["channel","type"],Ki=["phase"],Zi=["status"],Ji=["code","message","recoverable"],Xi=(e,t)=>le(e)&&ce(e,$i)&&e.channel===qi&&e.type===t&&de(e.requestId,oe)&&void 0!==e.payload,Qi=e=>Xi(e,Hi)&&le(e.payload)&&ce(e.payload,Ki)&&"string"==typeof e.payload.phase&&["loading","content_ready","completing"].includes(e.payload.phase),en=e=>Xi(e,Wi)&&le(e.payload)&&ce(e.payload,Zi)&&"canceled"===e.payload.status,tn=e=>Xi(e,Vi)&&le(e.payload)&&ce(e.payload,Ji)&&de(e.payload.code,oe)&&de(e.payload.message,re)&&"boolean"==typeof e.payload.recoverable,nn=15e3,on=220,rn=400,sn=2147483647,an="rgb(40 40 40 / 0%)",ln="rgb(40 40 40 / 75%)",cn="transparent";let dn=0,pn="",hn="";const un=(e,t,i)=>{null===i?e.removeAttribute(t):e.setAttribute(t,i)};class mn{constructor(){this.host=null,this.active=!1,this.isolatedSiblings=new Map,this.isolationObserver=null}mount(){const e=this.ensureHost();return e.parentElement!==document.body&&document.body.prepend(e),e.removeAttribute("popover"),e.hidden=!1,e.style.display="block",e.style.visibility="visible",e.style.opacity="0",e.style.pointerEvents="none",e}open(){const e=this.mount();if(e.style.opacity="1",e.style.pointerEvents="auto",this.active||(this.active=!0,0===dn&&(pn=document.body.style.overflow,hn=document.documentElement.style.overflow,document.body.style.overflow="hidden",document.documentElement.style.overflow="hidden"),dn+=1,this.isolateMerchantPage(e)),e.setAttribute("popover","manual"),"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=an,this.host.style.opacity="0",this.host.style.pointerEvents="none")}finishClose(){const e=this.host;if(e){try{e.hidePopover?.()}catch{}e.hidden=!0,e.style.display="none",e.style.visibility="visible",e.style.opacity="0",e.style.pointerEvents="none",e.style.background=an,this.active&&(this.active=!1,this.restoreMerchantPage(),0!==dn&&(dn-=1,0===dn&&(document.body.style.overflow=pn,document.documentElement.style.overflow=hn)))}}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.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",visibility:"visible",opacity:"0",pointerEvents:"none",overflow:"hidden",background:an,colorScheme:"light only",transition:`background ${rn}ms ease-in-out, opacity ${rn}ms ease-in-out`,willChange:"background, opacity",zIndex:String(sn)}),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 i of e)for(const e of Array.from(i.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,i,n=nn){this.hostedOrigin=e,this.onCancel=t,this.onError=i,this.bootstrapTimeoutMs=n,this.host=new mn,this.frame=null,this.action=null,this.bootstrapTimeout=null,this.removalTimeout=null,this.previouslyFocused=null,this.componentPort=null,this.actionFrameInitialized=!1,this.actionPresented=!1,this.lifecycleInterrupted=!1,this.returnWakeListenersAttached=!1,this.onWindowMessage=e=>{const t=this.frame,i=this.action;if(t?.contentWindow&&i&&e.source===t.contentWindow&&e.origin===this.hostedOrigin){if(n=e.data,le(n)&&ce(n,Yi)&&n.channel===qi&&n.type===Bi){if(this.actionFrameInitialized)return;this.clearBootstrapTimeout();const e={channel:qi,type:ji,requestId:i.id,payload:{source:i.source??"component",actionId:i.id,actionType:i.type}},n=this.componentPort;return n?(t.contentWindow.postMessage(e,this.hostedOrigin,[n]),this.componentPort=null,this.actionFrameInitialized=!0,this.attachReturnWakeListeners(),void window.requestAnimationFrame(()=>{this.frame===t&&(t.style.opacity="1")})):void this.onError(i.id,"elements_action_channel_unavailable","The secure authentication channel is unavailable.",!0)}var n;if(!(Qi(e.data)||en(e.data)||tn(e.data))||e.data.requestId===i.id)return Qi(e.data)?(t.dataset.paypercutActionPhase=e.data.payload.phase,void("content_ready"!==e.data.payload.phase||this.actionPresented||(this.actionPresented=!0,t.removeAttribute("aria-hidden"),t.tabIndex=0,this.host.open(),window.requestAnimationFrame(()=>{this.frame===t&&this.actionPresented&&t.focus({preventScroll:!0})})))):void(en(e.data)?"canceled"===e.data.payload.status&&this.onCancel(i.id):tn(e.data)&&this.onError(i.id,e.data.payload.code,e.data.payload.message,e.data.payload.recoverable))}},this.onVisibilityChange=()=>{"visible"===document.visibilityState?this.sendReturnWake("visibility"):this.lifecycleInterrupted=!0},this.onPageHide=()=>{this.lifecycleInterrupted=!0},this.onPageShow=()=>{this.sendReturnWake("pageshow")},this.onOffline=()=>{this.lifecycleInterrupted=!0},this.onOnline=()=>{this.sendReturnWake("online")},this.onWindowFocus=()=>{this.lifecycleInterrupted&&this.sendReturnWake("focus")}}isOpen(){return null!==this.frame}show(e,t){if(this.action?.id===e.id&&this.frame)return void t.close();this.removeFrame(!1,!1),this.action=e,this.componentPort=t,this.actionFrameInitialized=!1,this.actionPresented=!1,this.lifecycleInterrupted=!1,this.previouslyFocused=document.activeElement instanceof HTMLElement?document.activeElement:null;const i=document.createElement("iframe");i.id=`paypercut-elements-action-frame-${e.id}`,i.title="3D Secure authentication",i.referrerPolicy="origin",i.src=new URL("/elements/actions/three-d-secure",this.hostedOrigin).toString(),i.allow="payment *; publickey-credentials-get *",i.setAttribute("allowtransparency","true"),i.setAttribute("frameborder","0"),i.setAttribute("aria-hidden","true"),i.tabIndex=-1,i.setAttribute("scrolling","no"),Object.assign(i.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:cn,colorScheme:"light only",opacity:"0",transition:`opacity ${on}ms ease-in-out`,willChange:"opacity"}),this.frame=i,window.addEventListener("message",this.onWindowMessage);this.host.mount().replaceChildren(i),this.bootstrapTimeout=window.setTimeout(()=>{this.frame===i&&this.onError(e.id,"elements_action_shell_timeout","The secure authentication window could not be loaded.",!0)},this.bootstrapTimeoutMs);let n=0;i.addEventListener("load",()=>{this.frame===i&&(n+=1,1!==n&&this.onError(e.id,"elements_submit_indeterminate","The secure authentication window reloaded while its result was unknown.",!1))})}close(){const e=this.frame;e&&(e.setAttribute("aria-hidden","true"),e.tabIndex=-1,e.style.opacity="0",this.host.beginClose(),this.clearRemovalTimeout(),this.removalTimeout=window.setTimeout(()=>{this.frame===e&&this.removeFrame()},rn))}destroy(){this.removeFrame(!0)}sendReturnWake(e){const t=this.frame,i=this.action;if(!this.actionFrameInitialized||!t?.contentWindow||!i||"visible"!==document.visibilityState)return;const n=((e,t)=>({channel:qi,type:Gi,requestId:e,payload:{source:t}}))(i.id,e);t.contentWindow.postMessage(n,this.hostedOrigin),this.lifecycleInterrupted=!1}attachReturnWakeListeners(){this.returnWakeListenersAttached||(this.returnWakeListenersAttached=!0,document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("pagehide",this.onPageHide),window.addEventListener("pageshow",this.onPageShow),window.addEventListener("offline",this.onOffline),window.addEventListener("online",this.onOnline),window.addEventListener("focus",this.onWindowFocus))}detachReturnWakeListeners(){this.returnWakeListenersAttached&&(this.returnWakeListenersAttached=!1,document.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("pagehide",this.onPageHide),window.removeEventListener("pageshow",this.onPageShow),window.removeEventListener("offline",this.onOffline),window.removeEventListener("online",this.onOnline),window.removeEventListener("focus",this.onWindowFocus))}removeFrame(e=!1,t=!0){const i=this.frame;this.frame=null,this.action=null,this.componentPort?.close(),this.componentPort=null,this.actionFrameInitialized=!1,this.lifecycleInterrupted=!1,this.detachReturnWakeListeners(),this.clearBootstrapTimeout(),this.clearRemovalTimeout(),window.removeEventListener("message",this.onWindowMessage),i?.remove(),e?this.host.destroy():this.host.finishClose();const n=this.previouslyFocused;if(this.previouslyFocused=null,t&&n?.isConnected)try{n.focus({preventScroll:!0})}catch{n.focus()}}clearBootstrapTimeout(){null!==this.bootstrapTimeout&&(window.clearTimeout(this.bootstrapTimeout),this.bootstrapTimeout=null)}clearRemovalTimeout(){null!==this.removalTimeout&&(window.clearTimeout(this.removalTimeout),this.removalTimeout=null)}}const gn=6e5;class fn{constructor(e){this.hostedOrigin=e,this.pending=null,this.indeterminateAttempt=null,this.completed=null,this.destroyed=!1,this.actionShell=null,this.futureUsageSelected=!1,this.billingDetailsSelected=!1}submit(e,t,i){if(this.destroyed)return Promise.reject(vn("elements_destroyed","The Elements group has been destroyed.",!1));if(this.futureUsageSelected&&this.selectedFutureUsage!==t||this.billingDetailsSelected&&!Ui(this.selectedBillingDetails,i))return Promise.reject(bn());if(this.completed)return this.completed.futureUsage===t&&Ui(this.completed.billingDetails,i)?Promise.resolve({...this.completed.reference}):Promise.reject(bn());if(this.indeterminateAttempt)return Promise.reject(vn("elements_submit_indeterminate","A previous submission has an unknown result. Create a new Elements group before making a deliberate new attempt.",!1));if(this.pending)return this.pending.source.submissionSourceId===e.submissionSourceId?this.pending.futureUsage===t&&Ui(this.pending.billingDetails,i)?this.pending.promise:Promise.reject(bn()):Promise.reject(vn("elements_submit_in_progress","Another payment method is already being prepared.",!0));try{e.assertCanSubmitPaymentMethod()}catch(e){return Promise.reject(wn(e))}this.futureUsageSelected=!0,this.selectedFutureUsage=t,this.billingDetailsSelected=!0,this.selectedBillingDetails=i;const n=j(),o=Date.now()+gn;let r,s;const a=new Promise((e,t)=>{r=e,s=t}),l={source:e,requestId:n,...t?{futureUsage:t}:{},...i?{billingDetails:i}:{},actionId:null,promise:a,resolve:r,reject:s,timeoutId:window.setTimeout(()=>{this.pending===l&&(this.markIndeterminate(l),this.cancelPendingSource(l,"timed_out"),this.rejectPending("elements_submit_timeout","Preparing the payment details timed out and the result is unknown.",!1))},gn)};this.pending=l,e.onPaymentMethodSubmissionStateChange();try{i?e.beginPaymentMethodSubmission(n,o,t,i):t?e.beginPaymentMethodSubmission(n,o,t):e.beginPaymentMethodSubmission(n,o)}catch{this.rejectPending("elements_submit_failed","Unable to submit the payment details.",!0)}return a}handleSourceEvent(e,t){"error"!==t.event?"action_required"!==t.event&&"submit_result"!==t.event||this.handleSubmissionEvent(e,t):this.handleSourceError(e,t)}handleSourceError(e,t){const i=this.pending;i?.source.submissionSourceId===e&&(this.markIndeterminate(i),this.cancelPendingSource(i,"failed"),this.rejectPending("elements_submit_indeterminate","elements_submit_indeterminate"===t.code?t.message:"The payment form became unavailable while its submission result was unknown.",!1))}hasActiveSubmission(e){return void 0===e?null!==this.pending||null!==this.indeterminateAttempt:this.pending?.source.submissionSourceId===e||null!==this.indeterminateAttempt}getIndeterminateAttemptError(){return this.indeterminateAttempt?vn("elements_submit_indeterminate","A previous submission has an unknown result. Create a new Elements group before making a deliberate new attempt.",!1):null}hasCompletedSubmission(e){return null!==this.completed}ownsAttempt(e,t){return this.pending?.source.submissionSourceId===e&&this.pending.requestId===t}releaseSource(e){const t=this.pending;if(t?.source.submissionSourceId===e){this.markIndeterminate(t);try{t.source.cancelPaymentMethodSubmission(t.requestId,"destroyed")}catch{}this.rejectPending("elements_submit_indeterminate","The payment form was removed while its submission result was unknown.",!1)}}reinitializeSource(e){const t=this.pending;if(t&&t.source.submissionSourceId===e){this.markIndeterminate(t);try{t.source.cancelPaymentMethodSubmission(t.requestId,"destroyed")}catch{}this.rejectPending("elements_submit_indeterminate","The secure payment form reloaded while its submission result was unknown.",!1)}}destroy(){this.destroyed||(this.destroyed=!0,this.pending&&(this.markIndeterminate(this.pending),this.cancelPendingSource(this.pending,"destroyed"),this.rejectPending("elements_submit_indeterminate","The Elements group was destroyed while its submission result was unknown.",!1)),this.actionShell?.destroy(),this.actionShell=null)}handleSubmissionEvent(e,t){const i=this.pending;if(i&&i.source.submissionSourceId===e&&t.requestId===i.requestId){if("action_required"===t.event){i.actionId=t.action.id;const e=new MessageChannel;try{i.source.attachPaymentMethodActionChannel(t.requestId,t.action.id,e.port1),this.getActionShell().show(t.action,e.port2),i.source.onPaymentMethodSubmissionStateChange()}catch{e.port1.close(),e.port2.close(),this.cancelPendingSource(i,"failed"),this.rejectPending("elements_action_channel_unavailable","The required payment authentication could not be opened.",!0)}return}if(this.pending=null,window.clearTimeout(i.timeoutId),this.actionShell?.close(),"succeeded"===t.result.status){const n={type:"payment_method",id:t.result.paymentMethod.id};this.completed={sourceId:e,...i.futureUsage?{futureUsage:i.futureUsage}:{},...i.billingDetails?{billingDetails:i.billingDetails}:{},reference:n},i.resolve({...n})}else"elements_submit_indeterminate"===t.result.code&&(this.indeterminateAttempt={sourceId:e,requestId:i.requestId}),i.reject(vn(t.result.code,t.result.message,t.result.recoverable));i.source.onPaymentMethodSubmissionStateChange()}}cancelAction(e){const t=this.pending;if(t&&t.actionId===e){try{t.source.cancelPaymentMethodSubmission(t.requestId,"canceled")}catch{}this.rejectPending("elements_action_canceled","Payment authentication was canceled.",!0)}}failAction(e,t,i,n){const o=this.pending;if(o&&o.actionId===e){"elements_submit_indeterminate"===t&&this.markIndeterminate(o);try{o.source.cancelPaymentMethodSubmission(o.requestId,"failed")}catch{}this.rejectPending(t,i,n)}}rejectPending(e,t,i){const n=this.pending;n&&(this.pending=null,window.clearTimeout(n.timeoutId),this.actionShell?.close(),n.reject(vn(e,t,i)),n.source.onPaymentMethodSubmissionStateChange())}cancelPendingSource(e,t){try{e.source.cancelPaymentMethodSubmission(e.requestId,t)}catch{}}markIndeterminate(e){this.indeterminateAttempt={sourceId:e.source.submissionSourceId,requestId:e.requestId}}getActionShell(){return this.actionShell??(this.actionShell=new yn(this.hostedOrigin,e=>this.cancelAction(e),(e,t,i,n)=>this.failAction(e,t,i,n))),this.actionShell}}const bn=()=>vn("elements_component_configuration_invalid","This Elements group has already started Payment Method creation with different futureUsage or billing details. Create a new Elements group to change either value.",!1);function vn(e,t,i){const n=new Error(t);return n.name="ElementsSubmitError",n.code=e,n.recoverable=i,n}const wn=e=>e instanceof Error&&"code"in e&&"string"==typeof e.code&&"recoverable"in e&&"boolean"==typeof e.recoverable?e:vn("elements_submit_failed",e instanceof Error?e.message:"Unable to submit the payment details.",!0);function Pn(e,t){const i=e.parentNode;if(!i)throw new Error("The payment component is not mounted.");const n={pointerEvents:e.style.pointerEvents,inert:e.inert,ariaBusy:e.getAttribute("aria-busy")},o={position:i instanceof HTMLElement?i.style.position:"",establishesContainingBlock:i instanceof HTMLElement&&"function"==typeof window.getComputedStyle&&"static"!==window.getComputedStyle(i).position},r=t.style.transition,s=t.style.opacity,a=t.id;t.id=`${a}-appearance-preview`,t.dataset.paypercutAppearanceTransition="replacement",t.setAttribute("aria-hidden","true"),t.inert=!0,t.style.position="absolute",t.style.inset="0",t.style.opacity="0",t.style.pointerEvents="none",t.style.transition="none";try{i instanceof HTMLElement&&!o.establishesContainingBlock&&(i.style.position="relative"),i.appendChild(t),e.dataset.paypercutAppearanceTransition="previous",e.setAttribute("aria-busy","true"),e.inert=!0,e.style.pointerEvents="none"}catch(e){throw t.remove(),t.id=a,i instanceof HTMLElement&&!o.establishesContainingBlock&&(i.style.position=o.position),e}let l=!1;const c=()=>{i instanceof HTMLElement&&!o.establishesContainingBlock&&(i.style.position=o.position)};return{previous:e,replacement:t,commit(){l||(l=!0,e.remove(),t.id=a,delete t.dataset.paypercutAppearanceTransition,t.removeAttribute("aria-hidden"),t.inert=!1,t.style.position="",t.style.inset="",t.style.opacity=s,t.style.pointerEvents="",t.getBoundingClientRect(),t.style.transition=r,c())},rollback(){l||(l=!0,t.remove(),delete e.dataset.paypercutAppearanceTransition,null===n.ariaBusy?e.removeAttribute("aria-busy"):e.setAttribute("aria-busy",n.ariaBusy),e.inert=n.inert,e.style.pointerEvents=n.pointerEvents,c())}}}class En{constructor(e){this.group=e,this.componentId=j(),this.componentType="card",this.componentGeneration=0,this.submissionSourceId=this.componentId,this.emitter=new t,this.iframe=null,this.mounted=!1,this.connected=!1,this.destroyed=!1,this.ready=!1,this.developerAssistant=null,this.pendingDeveloperPreset=null,this.pendingValidation=null,this.initializationTimeoutId=null,this.initializationReloads=0,this.pendingAppearanceRemount=null,this.appearancePreviewError=null,this.messageHandler=e=>this.onWindowMessage(e)}mount(e){if(this.destroyed)throw new Error("[Paypercut Elements] Cannot mount a destroyed Card Element.");if(this.mounted)return;if("undefined"==typeof window||"undefined"==typeof document)throw new Error("[Paypercut Elements] Card 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),i=this.createFrame();this.iframe=i,this.mounted=!0,this.group.markComponentMounted(),window.addEventListener("message",this.messageHandler),this.group.ensureController(),t.appendChild(i),this.armInitializationWatch(i)}on(e,t){return this.emitter.on(e,t)}assertCanSubmitPaymentMethod(){if(this.destroyed||this.group.isDestroyed())throw vn("elements_destroyed","The Card Element has been destroyed.",!1);if(!this.mounted)throw vn("elements_not_mounted","The Card Element has not been mounted.",!0);if(!this.ready)throw vn("elements_not_ready","The Card Element is not ready yet.",!0);if(this.pendingDeveloperPreset)throw vn("elements_test_preset_in_progress","Wait for the test card preset to finish filling before submitting.",!0)}validatePaymentMethod(){try{this.assertCanSubmitPaymentMethod()}catch(e){return Promise.reject(e)}if(this.pendingValidation)return this.pendingValidation.promise;const e=j();let t,i;const n=new Promise((e,n)=>{t=e,i=n}),o={requestId:e,promise:n,resolve:t,reject:i,timeoutId:window.setTimeout(()=>{this.pendingValidation===o&&(this.pendingValidation=null,i(vn("elements_submit_timeout","Validating the payment details timed out. Please try again.",!0)))},15e3)};this.pendingValidation=o;try{this.group.validateComponent(this.componentId,e)}catch{this.settleValidation(vn("elements_submit_failed","The secure card form could not be validated.",!0))}return n}beginPaymentMethodSubmission(e,t,i,n){this.clearInitializationWatch(),this.developerAssistant?.collapse(),this.developerAssistant?.refresh(),this.group.submitComponent(this.componentId,e,t,n)}cancelPaymentMethodSubmission(e,t){try{this.group.cancelComponentSubmission(this.componentId,e,t)}catch{}}attachPaymentMethodActionChannel(e,t,i){this.group.attachActionChannel(this.componentId,e,t,i)}onPaymentMethodSubmissionStateChange(){this.developerAssistant?.collapse(),this.developerAssistant?.refresh()}hasActiveSubmission(){return this.group.hasPaymentMethodSubmissionState(this.componentId)||null!==this.pendingValidation||null!==this.pendingDeveloperPreset}getComponentOptions(){return{}}handleControllerError(e){this.destroyed||(this.clearInitializationWatch(),this.ready=!1,this.settleValidation(vn(e.code,e.message,e.recoverable??!0)),this.emitter.emit("error",e))}handleControllerEvent(e){if(this.destroyed)return;const t=this.pendingAppearanceRemount;if(!t||nt(e))switch(e.event){case"ready":if(!this.ready){if(this.ready=!0,this.clearInitializationWatch(),t&&t===this.pendingAppearanceRemount){t.resolve(this.prepareSettledAppearanceTransition(t));break}this.emitter.emit("ready"),this.group.discoverDeveloperPresets(this.componentId)}break;case"secure_field_surface_invalid":if(!t||t!==this.pendingAppearanceRemount)break;if(!t.automaticRecoveryAttempted){this.retryInvalidAppearanceGeometry(t);break}this.showAppearancePreviewFailure(),this.rejectAppearanceRemount(new Error("The replacement Card Element reported invalid secure-field geometry twice."));break;case"resize":this.resize(e.height);break;case"error":this.handleControllerError(e);break;case"phase":this.developerAssistant?.refresh();break;case"action_required":case"submit_result":break;case"validation_result":if(e.requestId!==this.pendingValidation?.requestId)break;"succeeded"===e.result.status?this.settleValidation():this.settleValidation(vn(e.result.code,e.result.message,e.result.recoverable));break;case"developer_catalog":this.registerDeveloperPresets(e.presets);break;case"developer_apply_result":this.handleDeveloperApplyResult(e);break;case"change":this.group.invalidateSubmissionValidation()}else"error"===e.event&&this.rejectAppearanceRemount(new Error("The replacement Card Element could not render its Appearance."))}destroy(){this.destroyed||(this.destroyed=!0,this.rejectAppearanceRemount(new Error("The Card Element was destroyed during Appearance Preview.")),this.ready=!1,this.clearInitializationWatch(),this.settleValidation(vn("elements_destroyed","The Card Element has been destroyed.",!1)),this.clearDeveloperAssistant("The card form was destroyed."),"undefined"!=typeof window&&window.removeEventListener("message",this.messageHandler),this.iframe?.remove(),this.appearancePreviewError?.remove(),this.appearancePreviewError=null,this.iframe=null,this.mounted=!1,this.emitter.clear(),this.group.remove(this))}remountAppearance(){this.rejectAppearanceRemount(new Error("A newer Appearance Preview superseded this one."));const e=this.iframe,t=e?.parentNode;if(this.destroyed||!this.mounted||!e||!t)return Promise.resolve({commit:()=>{},rollback:()=>{}});let i,n;const o=new Promise((e,t)=>{i=e,n=t}),r=this.ready,s=this.componentGeneration;this.ready=!1,this.componentGeneration+=1,this.initializationReloads=0,this.clearInitializationWatch(),this.group.invalidateSubmissionValidation(),this.settleValidation(vn("elements_not_ready","The Card Element is refreshing its Appearance.",!0));try{const t=this.createFrame(),o=Pn(e,t);this.pendingAppearanceRemount={resolve:i,reject:n,transition:o,wasReady:r,settled:!1,automaticRecoveryAttempted:!1},this.iframe=t,this.group.detachComponent(this),this.armInitializationWatch(t)}catch(t){this.iframe=e,this.ready=r,this.componentGeneration=s;const i=t instanceof Error?t:new Error("Unable to replace the Card Element frame.");return this.pendingAppearanceRemount?this.rejectAppearanceRemount(i):n(i),o}return o}cancelAppearanceRemount(e,t){this.componentGeneration===e&&this.rejectAppearanceRemount(t)}markAppearanceRecoveryFailed(){this.ready=!1,this.iframe&&(this.iframe.inert=!0,this.iframe.style.pointerEvents="none"),this.emitter.emit("error",{code:"elements_appearance_preview_recovery_failed",message:"The Card Element could not restore its last Appearance.",recoverable:!0})}clearAppearancePreviewFailure(){this.appearancePreviewError?.remove(),this.appearancePreviewError=null}isMounted(){return this.mounted&&!this.destroyed}onWindowMessage(e){if(this.destroyed||!this.iframe?.contentWindow||e.source!==this.iframe.contentWindow||e.origin!==this.group.hostedOrigin||!Gt(e.data))return;const t=this.connected;this.connected=!0,t&&(this.ready=!1,this.group.invalidateSubmissionValidation(),this.settleValidation(vn("elements_reinitialized","The secure card form reloaded while it was being validated.",!0)),this.hasActiveSubmission()||this.armInitializationWatch(this.iframe));const i=new MessageChannel,n={channel:Ae,type:it,controllerId:this.group.controllerId,componentId:this.componentId,componentType:this.componentType};try{this.iframe.contentWindow.postMessage(n,this.group.hostedOrigin,[i.port2]),t?this.group.reattachComponent(this,i.port1):this.group.attachComponent(this,i.port1)}catch{if(i.port1.close(),i.port2.close(),this.pendingAppearanceRemount)return void this.rejectAppearanceRemount(new Error("The replacement Card Element could not connect to its controller."));this.handleControllerError({code:"elements_component_connect_failed",message:"The secure card 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})}armInitializationWatch(e){this.clearInitializationWatch(),this.initializationTimeoutId=window.setTimeout(()=>{if(this.initializationTimeoutId=null,!this.destroyed&&this.mounted&&!this.ready&&this.iframe===e&&!this.hasActiveSubmission())if(this.pendingAppearanceRemount)this.handleInitializationTimeout();else{if(this.initializationReloads<1){this.initializationReloads+=1;const t=e.parentNode;if(!t)return void this.handleInitializationTimeout();const i=this.createFrame(),n=this.componentGeneration;this.componentGeneration+=1;try{this.iframe=i,t.replaceChild(i,e),this.armInitializationWatch(i)}catch{this.iframe=e,this.componentGeneration=n,this.handleInitializationTimeout()}return}this.handleInitializationTimeout()}},4e4)}createFrame(){const e=document.createElement("iframe");return e.id=`paypercut-card-element-${this.componentId}`,e.title="Secure card form",e.referrerPolicy="origin",e.src=Ii(function(e){const t=new URLSearchParams;return Ti(t,e),t.set("componentName","card"),t.set("elementId",e.componentId),t.set("mode",e.elementsOptions.mode),t.set("amount",String(e.elementsOptions.amount)),t.set("currency",e.elementsOptions.currency),ki("/elements/components/card",e.hostedOrigin,t)}({hostedOrigin:this.group.hostedOrigin,controllerId:this.group.controllerId,componentId:this.componentId,clientOptions:this.group.getClientOptions(),elementsOptions:this.group.getRenderableElementsOptions(),referrer:window.location.origin}),j()),e.allow="payment *; publickey-credentials-get *; autofill *",e.setAttribute("allowtransparency","true"),e.setAttribute("frameborder","0"),e.setAttribute("role","presentation"),e.setAttribute("scrolling","no"),Object.assign(e.style,{width:"100%",maxWidth:"100%",minWidth:"0",height:"0",margin:"0",padding:"0",border:"0",display:"block",overflow:"hidden",colorScheme:"normal",transition:"height 350ms ease-in-out, opacity 400ms ease-in-out 100ms",willChange:"height, opacity"}),e}clearInitializationWatch(){null!==this.initializationTimeoutId&&"undefined"!=typeof window&&window.clearTimeout(this.initializationTimeoutId),this.initializationTimeoutId=null}handleInitializationTimeout(){this.pendingAppearanceRemount?this.rejectAppearanceRemount(new Error("The replacement Card Element did not become ready in time.")):this.handleControllerError({code:"elements_component_initialization_timeout",message:"The secure card form did not become ready in time.",recoverable:!0})}retryInvalidAppearanceGeometry(e){if(e!==this.pendingAppearanceRemount||e.settled)return;const t=e.transition.previous;this.clearInitializationWatch(),e.transition.rollback(),this.iframe=t,this.componentGeneration+=1,this.initializationReloads=0,e.automaticRecoveryAttempted=!0;try{const i=this.createFrame();e.transition=Pn(t,i),this.iframe=i,this.group.detachComponent(this),this.armInitializationWatch(i)}catch(e){this.rejectAppearanceRemount(e instanceof Error?e:new Error("Unable to retry the Card Element Appearance Preview."))}}showAppearancePreviewFailure(){if(this.appearancePreviewError?.isConnected)return;const e=this.pendingAppearanceRemount?.transition.previous.parentNode;if(!(e instanceof HTMLElement))return;const t=document.createElement("div");t.dataset.paypercutAppearancePreviewError="true",t.setAttribute("role","alert"),t.setAttribute("aria-live","assertive"),t.textContent="Appearance Preview could not produce usable secure fields. Retry the Appearance update or restore a known-good Appearance.",Object.assign(t.style,{marginTop:"8px",padding:"10px 12px",border:"1px solid #f04438",borderRadius:"8px",color:"#b42318",background:"#fff1f0",font:"13px/1.4 system-ui, sans-serif"}),e.appendChild(t),this.appearancePreviewError=t}rejectAppearanceRemount(e){const t=this.pendingAppearanceRemount;t&&(this.pendingAppearanceRemount=null,t.settled||(t.settled=!0,t.transition.rollback(),this.iframe=t.transition.previous,this.ready=t.wasReady,t.reject(e)))}prepareSettledAppearanceTransition(e){return{commit:()=>{e.settled||(e.settled=!0,this.pendingAppearanceRemount===e&&(this.pendingAppearanceRemount=null),e.transition.commit(),queueMicrotask(()=>{this.destroyed||(this.emitter.emit("ready"),this.group.discoverDeveloperPresets(this.componentId))}))},rollback:()=>{e.settled||(e.settled=!0,this.pendingAppearanceRemount===e&&(this.pendingAppearanceRemount=null),e.transition.rollback(),this.iframe=e.transition.previous,this.ready=e.wasReady)}}}settleValidation(e){const t=this.pendingValidation;t&&(this.pendingValidation=null,window.clearTimeout(t.timeoutId),e?t.reject(e):t.resolve())}registerDeveloperPresets(e){!0===this.group.getClientOptions().developerAssistant&&(this.developerAssistant?this.developerAssistant.refresh():this.developerAssistant=Ci({id:`${this.group.controllerId}:${this.componentId}`,configurationIdentity:this.group.configurationIdentity,appearanceScopeId:this.group.controllerId,presets:e,isVisible:()=>Si(this.iframe?.parentElement??null),isAvailable:()=>this.canApplyDeveloperPreset(),isAppearanceAvailable:()=>this.isMounted(),appearancePreviewClearsTestData:()=>!0,canPreview:()=>this.group.isAppearancePreviewAvailable(),applyPreset:e=>this.applyDeveloperPreset(e),getAppearance:()=>this.group.getAppearance(),updateAppearance:e=>this.group.updateAppearance(e),replaceAppearance:e=>this.group.replaceAppearance(e),prepareAppearance:e=>this.group.prepareAppearance(e),prepareAppearanceReplacement:e=>this.group.prepareAppearanceReplacement(e)}))}canApplyDeveloperPreset(){return!0===this.group.getClientOptions().developerAssistant&&this.ready&&!this.destroyed&&!this.group.hasPaymentMethodSubmissionState(this.componentId)&&!this.group.hasCompletedPaymentMethodSubmission(this.componentId)&&!this.pendingDeveloperPreset}applyDeveloperPreset(e){if(!this.canApplyDeveloperPreset())return Promise.reject(new Error("Test card presets are unavailable right now."));const t=j();return new Promise((i,n)=>{const o={requestId:t,presetId:e,resolve:i,reject:n,timeoutId:window.setTimeout(()=>{this.pendingDeveloperPreset===o&&(this.pendingDeveloperPreset=null,n(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),n(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)))}}const An="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",Cn="apple-pay-modal",Sn="paypercut-apple-pay-modal-focus-style";let _n=null,In=null,Tn=0;function Rn(){"undefined"!=typeof window&&"undefined"!=typeof document&&(!function(){if(document.querySelectorAll(Cn).forEach(e=>{kn(e)}),In||!document.documentElement)return;In=new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e instanceof Element&&(e.matches(Cn)&&kn(e),e.querySelectorAll(Cn).forEach(e=>{kn(e)}))})})}),In.observe(document.documentElement,{childList:!0,subtree:!0})}(),Tn+=1)}function kn(e,t=0){const i=e.shadowRoot;if(!i)return void(t<F&&requestAnimationFrame(()=>kn(e,t+1)));if(i.getElementById(Sn))return;const n=document.createElement("style");n.id=Sn,n.textContent="[data-modal-element-overlay]:focus, [data-modal-element-overlay]:focus-visible, .modal-overlay:focus, .modal-overlay:focus-visible { outline: none !important; }",i.appendChild(n)}const On=250,xn=3500,Mn=["paymentMethods","layout","buttonType","buttonTheme","buttonHeight","buttonRadius"],Ln=6e4,Dn=3e4,Fn=.5,Nn=40,zn=64,Un=24,qn=4,Bn=64,jn=256,Gn=2,Hn=10,Wn={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 Vn{constructor(e,i={}){this.group=e,this.componentId=j(),this.componentType="express_checkout",this.componentGeneration=0,this.emitter=new t,this.componentRevision=0,this.iframe=null,this.mounted=!1,this.connectedFrame=null,this.destroyed=!1,this.ready=!1,this.developerAssistant=null,this.pendingPreview=null,this.previewTransitionActive=!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.googlePayPopupRecovery=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,e=>this.cancelAction(e),(e,t,i,n)=>this.failAction(e,t,i,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=Zn(i)}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.");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);this.applePayModalObserverAcquired||(Rn(),this.applePayModalObserverAcquired=!0);const i=this.createFrame();this.iframe=i,this.mounted=!0,this.group.markComponentMounted(),window.addEventListener("message",this.messageHandler),this.group.ensureController(),t.appendChild(i),this.registerDeveloperAssistant()}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(!no(e)||0===Object.keys(e).length||"amount"in e)throw new Error("[Paypercut Elements] Express Checkout update options must contain checkout details.");return Xn(e)}(e);if(this.options=Zn({...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 uo(this.pendingPreview?.nextOptions??this.options)}isMounted(){return this.mounted&&!this.destroyed}remountAppearance(){return this.preparePreviewFrame(this.options)}cancelAppearanceRemount(e,t){this.componentGeneration===e&&this.rejectPendingPreview(t)}markAppearanceRecoveryFailed(){this.ready=!1,this.previewTransitionActive=!1,this.iframe&&(this.iframe.inert=!0,this.iframe.style.pointerEvents="none"),this.googlePayButtonContainer&&(this.googlePayButtonContainer.style.visibility="hidden",this.googlePayButtonContainer.style.pointerEvents="none"),this.emitter.emit("error",{code:"elements_appearance_preview_recovery_failed",message:"Express Checkout could not restore its last Appearance.",recoverable:!0})}updateDeveloperDisplayOptions(e){const t=Zn(function(e,t){return{...e,...t,...t.paymentMethods?{paymentMethods:{...e.paymentMethods,...t.paymentMethods}}:{},...t.layout?{layout:{...e.layout,...t.layout}}:{},...t.buttonType?{buttonType:{...e.buttonType,...t.buttonType}}:{},...t.buttonTheme?{buttonTheme:{...e.buttonTheme,...t.buttonTheme}}:{}}}(this.options,e));return this.replacePreviewFrame(t,!0)}replaceDeveloperDisplayOptions(e){const t=uo(this.options);for(const e of Mn)delete t[e];return this.replacePreviewFrame(Zn({...t,...uo(e)}),!0)}hasActiveSubmission(){return null!==this.activeAttempt||null!==this.applePaySession||null!==this.googlePayRequestId}hasActiveProviderSubmission(){const e=null!==this.googlePayRequestId&&this.activeAttempt?.requestId===this.googlePayRequestId&&!1===this.activeAttempt.approved;return!0===this.activeAttempt?.approved||null!==this.applePaySession||null!==this.googlePayRequestId&&!e}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)return;const t=this.pendingPreview;if(!t||nt(e))switch(e.event){case"ready":if(!this.ready){if(this.ready=!0,t&&t===this.pendingPreview){window.clearTimeout(t.timeoutId),t.availablePaymentMethods={...e.availablePaymentMethods},t.resolve(this.prepareSettledPreviewTransition(t));break}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():_n||(_n=new Promise(e=>{const t=Array.from(document.scripts).find(e=>e.src===An),i=t??document.createElement("script"),n=()=>e();i.addEventListener("load",n,{once:!0}),i.addEventListener("error",n,{once:!0}),t||(i.src=An,i.crossOrigin="anonymous",i.async=!0,i.dataset.paypercutApplePaySdk="true",document.head.appendChild(i))}),_n)).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.activeAttempt.actionId=e.action.id,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})}else"error"===e.event&&this.failPendingPreview(new Error("The replacement Express Checkout frame could not render."))}emitWalletConfirm(e){const t=e.requestId;let i=!1;const n=(n,r)=>{if(!i&&!this.destroyed&&this.activeAttempt?.requestId===t){if(i=!0,window.clearTimeout(o),this.group.resolveWalletConfirmation(this.componentId,t,n,r),"apple_pay"===e.wallet)return this.completeApplePay(n),void this.finalizeWalletAttempt({requestId:t,skipApplePayCompletion:!0});this.finalizeWalletAttempt({requestId:t})}},o=window.setTimeout(()=>n(!1,{code:"merchant_confirmation_timeout",message:"The merchant did not finish the checkout in time."}),Ln),r={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:()=>n(!0),paymentFailed:e=>n(!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 r.paymentFailed(e)}try{this.emitter.emitAndThrow("confirm",r)}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}),r.paymentFailed(e)}}destroy(){this.destroyed||(this.destroyed=!0,this.rejectPendingPreview(new Error("Express Checkout was destroyed during Appearance Preview.")),this.developerAssistant?.unregister(),this.developerAssistant=null,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&&(Tn<=0?Tn=0:(Tn-=1,0===Tn&&(In?.disconnect(),In=null))),this.applePayModalObserverAcquired=!1),this.iframe?.remove(),this.iframe=null,this.connectedFrame=null,this.mounted=!1,this.emitter.clear(),this.group.remove(this))}createFrame(e=this.options){const t=document.createElement("iframe");return t.id=`paypercut-express-checkout-element-${this.componentId}`,t.title="Express checkout",t.referrerPolicy="origin",t.src=Ii(function(e){const t=new URLSearchParams;return Ti(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),Ri(t,"publicOptions[paymentMethods][applePay]",e.options.paymentMethods?.applePay),Ri(t,"publicOptions[paymentMethods][googlePay]",e.options.paymentMethods?.googlePay),Ri(t,"publicOptions[layout][maxColumns]",e.options.layout?.maxColumns),Ri(t,"publicOptions[layout][maxRows]",e.options.layout?.maxRows),Ri(t,"publicOptions[layout][overflow]",e.options.layout?.overflow),Ri(t,"publicOptions[buttonType][applePay]",e.options.buttonType?.applePay),Ri(t,"publicOptions[buttonType][googlePay]",e.options.buttonType?.googlePay),Ri(t,"publicOptions[buttonTheme][applePay]",e.options.buttonTheme?.applePay),Ri(t,"publicOptions[buttonTheme][googlePay]",e.options.buttonTheme?.googlePay),Ri(t,"publicOptions[buttonHeight]",e.options.buttonHeight),Ri(t,"publicOptions[buttonRadius]",e.options.buttonRadius),Ri(t,"publicOptions[emailRequired]",e.options.emailRequired),Ri(t,"publicOptions[phoneNumberRequired]",e.options.phoneNumberRequired),Ri(t,"publicOptions[billingAddressRequired]",e.options.billingAddressRequired),Ri(t,"publicOptions[shippingAddressRequired]",e.options.shippingAddressRequired),e.options.allowedShippingCountries?.length&&t.set("publicOptions[allowedShippingCountries]",e.options.allowedShippingCountries.join(",")),ki("/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.getRenderableElementsOptions(),options:e,referrer:window.location.origin}),j()),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"}),t}replacePreviewFrame(e,t=!1){const i=uo(this.options);return this.preparePreviewFrame(e,t).then(e=>e.commit(),async e=>{if(function(e){return no(e)&&!0===e.skipAppearanceRecovery||no(e)&&"elements_appearance_preview_refused"===e.code}(e))throw e;if(t&&!this.destroyed&&this.mounted)try{(await this.preparePreviewFrame(i)).commit()}catch{this.markAppearanceRecoveryFailed()}throw e})}preparePreviewFrame(e,t=!1){if(this.hasActiveSubmission()||!this.group.isAppearancePreviewAvailable())return Promise.reject(Object.assign(new Error("Express Checkout preview is unavailable while payment validation or a wallet attempt is active."),{code:"elements_appearance_preview_refused"}));this.rejectPendingPreview(Yn(new Error("A newer Express Checkout preview superseded this one.")));const i=this.iframe,n=i?.parentNode;if(this.destroyed||!this.mounted||!i||!n)return Promise.resolve({commit:()=>{},rollback:()=>{}});const o=this.ready;let r,s;this.ready=!1,this.componentGeneration+=1;const a=new Promise((e,t)=>{r=e,s=t});try{const n=this.createFrame(e),a=Pn(i,n),l={resolve:r,reject:s,timeoutId:0,nextOptions:uo(e),commitOptions:t,transition:a,wasReady:o,settled:!1};l.timeoutId=window.setTimeout(()=>{this.pendingPreview===l&&this.failPendingPreview(new Error("The replacement Express Checkout frame did not become ready."))},1e4),this.pendingPreview=l,this.previewTransitionActive=!0,this.iframe=n,this.googlePayButtonContainer&&(this.googlePayButtonContainer.style.pointerEvents="none"),this.group.detachComponent(this)}catch(e){this.iframe=i,this.ready=o,this.componentGeneration-=1,s(Yn(e instanceof Error?e:new Error("Unable to replace the Express Checkout frame.")))}return a}rejectPendingPreview(e){const t=this.pendingPreview;t&&(this.pendingPreview=null,window.clearTimeout(t.timeoutId),t.settled||(t.settled=!0,t.transition.rollback(),this.iframe=t.transition.previous,this.ready=t.wasReady,this.previewTransitionActive=!1,this.positionGooglePayButton(),t.reject(e)))}failPendingPreview(e){this.pendingPreview&&this.rejectPendingPreview(e)}prepareSettledPreviewTransition(e){return{commit:()=>{if(e.settled)return;e.settled=!0,this.pendingPreview===e&&(this.pendingPreview=null),e.transition.commit(),e.commitOptions&&(this.options=uo(e.nextOptions)),this.previewTransitionActive=!1,this.positionGooglePayButton();const t=e.availablePaymentMethods;queueMicrotask(()=>{!this.destroyed&&t&&this.emitter.emit("ready",{availablePaymentMethods:t})})},rollback:()=>{e.settled||(e.settled=!0,this.pendingPreview===e&&(this.pendingPreview=null),e.transition.rollback(),this.iframe=e.transition.previous,this.ready=e.wasReady,this.previewTransitionActive=!1,this.positionGooglePayButton())}}}registerDeveloperAssistant(){!0===this.group.getClientOptions().developerAssistant&&(this.developerAssistant=Ci({id:`${this.group.controllerId}:${this.componentId}:express-checkout`,configurationIdentity:this.group.configurationIdentity,appearanceScopeId:this.group.controllerId,componentDisplayScopeId:this.componentId,isVisible:()=>Si(this.iframe?.parentElement??null),isAvailable:()=>!0,isAppearanceAvailable:()=>this.isMounted(),canPreview:()=>this.group.isAppearancePreviewAvailable(),getAppearance:()=>this.group.getAppearance(),updateAppearance:e=>this.group.updateAppearance(e),replaceAppearance:e=>this.group.replaceAppearance(e),prepareAppearance:e=>this.group.prepareAppearance(e),prepareAppearanceReplacement:e=>this.group.prepareAppearanceReplacement(e),getComponentDisplayOptions:()=>{return uo({...(e=this.options).paymentMethods?{paymentMethods:e.paymentMethods}:{},...e.layout?{layout:e.layout}:{},...e.buttonType?{buttonType:e.buttonType}:{},...e.buttonTheme?{buttonTheme:e.buttonTheme}:{},...void 0!==e.buttonHeight?{buttonHeight:e.buttonHeight}:{},...void 0!==e.buttonRadius?{buttonRadius:e.buttonRadius}:{}});var e},updateComponentDisplayOptions:e=>this.updateDeveloperDisplayOptions(e),replaceComponentDisplayOptions:e=>this.replaceDeveloperDisplayOptions(e)}))}onWindowMessage(e){if(this.destroyed||!this.iframe?.contentWindow||e.source!==this.iframe.contentWindow||e.source===this.connectedFrame||e.origin!==this.group.hostedOrigin||!Gt(e.data))return;const t=this.connectedFrame,i=null!==t;this.connectedFrame=e.source;const n=new MessageChannel,o={channel:Ae,type:it,controllerId:this.group.controllerId,componentId:this.componentId,componentType:this.componentType};try{this.iframe.contentWindow.postMessage(o,this.group.hostedOrigin,[n.port2]),i?this.group.reattachComponent(this,n.port1):this.group.attachComponent(this,n.port1)}catch{this.connectedFrame=t,n.port1.close(),n.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(Wn).map(([t,i])=>{const n={name:t,value:e.style.getPropertyValue(t),priority:e.style.getPropertyPriority(t)};return e.style.setProperty(t,i,"important"),n});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[i,n]of Object.entries(e))t.style.setProperty(i,n,"important");const i=t.getBoundingClientRect();return void((Math.abs(i.left)>Fn||Math.abs(i.top)>Fn)&&t.style.setProperty("transform",`translate3d(${-i.left}px, ${-i.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:i,value:n,priority:o}of t)n?e.style.setProperty(i,n,o):e.style.removeProperty(i);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=uo(this.options),void this.group.resolveWalletClick(this.componentId,e,!0,this.options);let i=!1;const n=(n,r)=>{if(i||this.destroyed||this.activeAttempt?.requestId!==e)return;const s=n?Xn(r):void 0,{amount:a,...l}=s??{},c=Object.keys(l).length>0?l:void 0;i=!0,window.clearTimeout(o),n&&this.activeAttempt?.requestId===e&&(this.activeAttempt.approved=!0,this.activeOptions=uo({...this.options,...c??{}})),void 0===a?this.group.resolveWalletClick(this.componentId,e,n,c):this.group.resolveWalletClick(this.componentId,e,n,c,a),n||(this.group.endWalletAttempt(this.componentId,e),"google_pay"===t&&this.googlePayRequestId===e||(this.activeAttempt=null,this.activeOptions=null))},o=window.setTimeout(()=>n(!1),Dn),r=()=>{const e="merchant_click_handler_failed",t="The merchant click handler returned invalid data.";this.emitter.emit("error",{code:e,message:t,recoverable:!1}),n(!1)};try{this.emitter.emitAndThrow("click",{wallet:t,resolve:e=>{try{n(!0,e)}catch{r()}},reject:()=>n(!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}),n(!1)}}emitShippingAddressChange(e,t,i,n,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:i,address:n},o)}emitShippingRateChange(e,t,i,n,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:i,shippingRate:n},o)}emitShippingUpdate(e,t,i,n,o){let r=!1;const s=(e,n)=>{if(r||this.destroyed||this.activeAttempt?.requestId!==t)return;const s=e?function(e){if(void 0===e)return;if(!no(e)||Object.keys(e).some(e=>!["amount","lineItems","shippingRates"].includes(e)))throw ho();const t=e.amount;if(void 0!==t&&("number"!=typeof t||!Number.isSafeInteger(t)||t<0))throw ho();return Jn(e.lineItems,"name"),Jn(e.shippingRates,"displayName",!0),uo(e)}(n):void 0;if(r=!0,window.clearTimeout(a),e&&s){const e=Object.prototype.hasOwnProperty.call(s,"lineItems"),t=Object.prototype.hasOwnProperty.call(s,"shippingRates");this.activeOptions=uo({...this.activeOptions??this.options,...e?{lineItems:s.lineItems}:{},...t?{shippingRates:s.shippingRates}:{}})}this.group.resolveWalletUpdate(this.componentId,t,i,e,s),o?.(this.walletUpdateSettlement(e,s))},a=window.setTimeout(()=>s(!1),Dn),l=e=>{this.emitter.emit("error",{code:"merchant_shipping_update_handler_failed",message:e,recoverable:!1}),s(!1)};try{this.emitter.emitAndThrow(e,{...n,resolve:e=>{try{s(!0,e)}catch{l("The merchant shipping update handler returned invalid data.")}},reject:()=>s(!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}),s(!1)}}cancelAction(e){const t=this.activeAttempt;t&&t.actionId===e&&this.group.cancelComponentSubmission(this.componentId,t.requestId)}failAction(e,t,i,n){const o=this.activeAttempt;o&&o.actionId===e&&(o&&this.finalizeWalletAttempt({cancelSubmission:!0}),this.emitter.emit("error",{code:t,message:i,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 Z(),this.destroyed)return;const i=oo(t),n=this.createGooglePayClient(e),o=await n.isReadyToPay(i);if(this.destroyed)return;this.googlePayClient=n,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 Z(),this.destroyed||t!==this.googlePayButtonGeneration)return;const i=oo(e.requestJson),n=i.allowedPaymentMethods;if(!Array.isArray(n))throw new Error("Invalid Google Pay request.");const o=this.createGooglePayClient(e.environment),r=await o.isReadyToPay({apiVersion:i.apiVersion,apiVersionMinor:i.apiVersionMinor,allowedPaymentMethods:n});if(this.destroyed||t!==this.googlePayButtonGeneration)return;const s=!0===r?.result;if(this.googlePayClient=o,this.googlePayEnvironment=e.environment,this.group.sendGooglePayCapabilities(this.componentId,s),!s)return void this.removeGooglePayButton();this.mountGooglePayButton(o,e,i,n)}catch{if(this.destroyed||t!==this.googlePayButtonGeneration)return;this.removeGooglePayButton(),this.group.sendGooglePayCapabilities(this.componentId,!1)}}mountGooglePayButton(e,t,i,n){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 r=e.createButton({buttonColor:t.buttonColor,buttonType:t.buttonType,buttonRadius:t.buttonRadius,buttonSizeMode:"fill",allowedPaymentMethods:n,onClick:()=>{if(this.destroyed||this.previewTransitionActive||this.googlePayRequestId||this.activeAttempt)return;const e=j();o.style.visibility="hidden",o.style.pointerEvents="none",this.group.sendGooglePayClick(this.componentId,e),this.startGooglePay(e,t.environment,ro(i))}});Object.assign(r.style,{width:"100%",height:"100%",margin:"0"}),o.appendChild(r),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,i=this.iframe;if(!e||!t?.visible||!i||this.previewTransitionActive||this.googlePayRequestId)return;const n=i.getBoundingClientRect(),o=n.left+t.target.x,r=n.top+t.target.y;Object.assign(e.style,{left:`${o}px`,top:`${r}px`,width:`${t.target.width}px`,height:`${t.target.height}px`,borderRadius:`${t.buttonRadius}px`,visibility:n.width>0&&n.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,i){let n;this.clearGooglePayAttempt(),this.googlePayButtonContainer&&(this.googlePayButtonContainer.style.visibility="hidden",this.googlePayButtonContainer.style.pointerEvents="none");try{n=oo(i)}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 i=new Set(Array.isArray(n.callbackIntents)?n.callbackIntents.filter(e=>"string"==typeof e):[]),o={};(i.has("OFFER")||i.has("SHIPPING_ADDRESS")||i.has("SHIPPING_OPTION"))&&(o.onPaymentDataChanged=t=>this.requestGooglePayDataChanged(e,t)),i.has("PAYMENT_AUTHORIZATION")&&(o.onPaymentAuthorized=t=>this.requestGooglePayAuthorization(e,t)),this.googlePayClient=this.createGooglePayClient(t,Object.keys(o).length>0?o:void 0);const r=((e,t,i=window)=>{const n=i.open;let o=null,r=!1,s=!1,a=null,l=null;const c=(e,t,r)=>{const s=n.call(i,e,t,r);return!o&&s&&(o=s),s};try{i.open=c,r=i.open===c}catch{r=!1}let d;try{d=e()}finally{r&&i.open===c&&(i.open=n)}const p=()=>{s||(s=!0,null!==a&&i.clearTimeout(a),null!==l&&i.clearTimeout(l),a=null,l=null,o=null)},h=()=>{try{return i.document?.hasFocus()??!0}catch{return!1}},u=()=>{if(s||!o)return;let e=!1;try{e=o.closed}catch{return void p()}e&&h()?(a=null,l=i.setTimeout(()=>{s||(l=null,h()?(p(),t()):a=i.setTimeout(u,On))},xn)):a=i.setTimeout(u,On)};return o&&(a=i.setTimeout(u,On)),{result:d,stop:p}})(()=>this.googlePayClient.loadPaymentData(n),()=>{if(this.googlePayRequestId===e&&!this.destroyed)try{this.group.sendGooglePayCanceled(this.componentId,e)}finally{this.clearGooglePayAttempt(e)}});this.googlePayPopupRecovery=r;const s=r.result;Promise.resolve(s).then(t=>{this.googlePayRequestId!==e||this.destroyed||(this.clearGooglePayPopupRecovery(),this.googlePayProcessingRequestId=e,this.group.markWalletAttemptProcessing(this.componentId,e,"google_pay"),this.group.sendGooglePayPaymentData(this.componentId,e,ro(t)))},t=>{if(this.googlePayRequestId===e&&!this.destroyed)try{!function(e){return no(e)&&("CANCELED"===e.statusCode||"CANCELED"===e.code)}(t)?this.group.sendGooglePayError(this.componentId,e,lo(t),co(t)):this.group.sendGooglePayCanceled(this.componentId,e)}finally{this.clearGooglePayAttempt(e)}})}catch(t){this.group.sendGooglePayError(this.componentId,e,lo(t),co(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 i=globalThis.google?.payments?.api?.PaymentsClient;if(!i)throw new Error("Google Pay is unavailable.");return new i({environment:e,...t?{paymentDataCallbacks:t}:{}})}requestGooglePayDataChanged(e,t){if(this.googlePayRequestId!==e)return Promise.resolve(so("OTHER_ERROR","The payment attempt is stale."));const i=j();return new Promise(n=>{const o=setTimeout(()=>{this.googlePayUpdates.delete(i),n(so("OTHER_ERROR","The merchant update timed out."))},Dn);this.googlePayUpdates.set(i,{requestId:e,resolve:n,timeout:o});try{this.group.sendGooglePayDataChanged(this.componentId,e,i,ro(t))}catch{clearTimeout(o),this.googlePayUpdates.delete(i),n(so("OTHER_ERROR","The merchant update was invalid."))}})}requestGooglePayAuthorization(e,t){return this.googlePayRequestId!==e||this.googlePayAuthorization?Promise.resolve(ao("The payment attempt is stale.")):new Promise(i=>{const n=setTimeout(()=>{this.googlePayAuthorization=null,i(ao("The merchant authorization timed out."))},Dn);this.googlePayAuthorization={requestId:e,resolve:i,timeout:n};try{this.group.sendGooglePayAuthorized(this.componentId,e,ro(t))}catch{clearTimeout(n),this.googlePayAuthorization=null,i(ao("The merchant authorization was invalid."))}})}resolveGooglePayDataChanged(e,t,i){const n=this.googlePayUpdates.get(t);if(n&&n.requestId===e&&this.googlePayRequestId===e){this.googlePayUpdates.delete(t),clearTimeout(n.timeout);try{n.resolve(oo(i))}catch{n.resolve(so("OTHER_ERROR","The merchant update was invalid."))}}}resolveGooglePayAuthorization(e,t){const i=this.googlePayAuthorization;if(i&&i.requestId===e&&this.googlePayRequestId===e){this.googlePayAuthorization=null,clearTimeout(i.timeout);try{i.resolve(oo(t))}catch{i.resolve(ao("The merchant authorization was invalid."))}}}clearGooglePayAttempt(e){if(!e||this.googlePayRequestId===e){this.clearGooglePayPopupRecovery(),this.googlePayRequestId=null,this.googlePayProcessingRequestId=null;for(const e of this.googlePayUpdates.values())clearTimeout(e.timeout),e.resolve(so("OTHER_ERROR","The payment attempt was canceled."));this.googlePayUpdates.clear(),this.googlePayAuthorization&&(clearTimeout(this.googlePayAuthorization.timeout),this.googlePayAuthorization.resolve(ao("The payment attempt was canceled.")),this.googlePayAuthorization=null),this.positionGooglePayButton()}}clearGooglePayPopupRecovery(){this.googlePayPopupRecovery?.stop(),this.googlePayPopupRecovery=null}startApplePay(e,t){this.abortApplePay();const i=window.ApplePaySession;if(!i||!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 n;try{const e=N(i);n=new i(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=n,n.onvalidatemerchant=t=>{this.applePayTimeout=setTimeout(()=>{this.abortApplePay(),this.group.sendApplePayCanceled(this.componentId,e)},D),this.group.sendApplePayValidateMerchant(this.componentId,e,t.validationURL)},n.onpaymentauthorized=t=>{this.group.sendApplePayAuthorized(this.componentId,e,t.payment)},n.onshippingcontactselected=i=>{const o=function(e){if(!no(e))return;const t=Array.isArray(e.addressLines)?e.addressLines.filter(e=>"string"==typeof e&&""!==e):[],i=[e.givenName,e.familyName].filter(e=>"string"==typeof e&&""!==e).join(" "),n={...i?{recipient:i}:{},...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(n).length?n:void 0}(i.shippingContact);o?this.emitShippingAddressChange(e,j(),"apple_pay",o,e=>this.completeApplePayShippingContactSelection(n,t,e)):this.completeApplePayShippingContactSelection(n,t,{accepted:!1,amount:this.group.getUpdateSnapshot().options.amount,currency:this.group.getUpdateSnapshot().options.currency})},n.onshippingmethodselected=i=>{const o=(this.activeOptions?.shippingRates??this.options.shippingRates??[]).find(e=>e.id===i.shippingMethod?.identifier);o?this.emitShippingRateChange(e,j(),"apple_pay",o,e=>this.completeApplePayShippingMethodSelection(n,t,e)):this.completeApplePayShippingMethodSelection(n,t,{accepted:!1,amount:this.group.getUpdateSnapshot().options.amount,currency:this.group.getUpdateSnapshot().options.currency})},n.oncancel=()=>{this.clearApplePayTimeout(),this.applePaySession=null,this.activeOptions=null,this.group.sendApplePayCanceled(this.componentId,e)};try{n.begin()}catch{this.abortApplePay(),this.group.sendApplePayCanceled(this.componentId,e)}}completeApplePay(e){if(!this.applePaySession)return;const t=this.applePaySession,i=window.ApplePaySession;this.clearApplePayTimeout(),this.applePaySession=null;try{t.completePayment(e?i.STATUS_SUCCESS:i.STATUS_FAILURE)}catch{try{t.abort()}catch{}}}abortApplePay(){this.clearApplePayTimeout();try{this.applePaySession?.abort()}catch{}this.applePaySession=null}walletUpdateSettlement(e,t){const i=this.group.getUpdateSnapshot().options;return{accepted:e,...t?{update:t}:{},amount:t?.amount??i.amount,currency:i.currency}}prepareApplePayRequest(e){const t=this.group.getUpdateSnapshot().options,i=this.activeOptions??this.options,n=t.currency;return{...e,currencyCode:n.toUpperCase(),total:eo(e.total.label,t.amount,n),...i.lineItems?.length?{lineItems:to(i.lineItems,n)}:{lineItems:void 0},...i.shippingAddressRequired?{requiredShippingContactFields:["name","postalAddress",...i.emailRequired?["email"]:[],...i.phoneNumberRequired?["phone"]:[]]}:{requiredShippingContactFields:void 0},...i.shippingAddressRequired&&i.shippingRates?.length?{shippingMethods:io(i.shippingRates,n)}:{shippingMethods:void 0}}}completeApplePayShippingContactSelection(e,t,i){if(e!==this.applePaySession)return;const n=i.update?.shippingRates??this.activeOptions?.shippingRates??[],o=window.ApplePayError;try{e.completeShippingContactSelection({newShippingMethods:i.accepted?io(n,i.currency):[],newTotal:eo(t.total.label,i.amount,i.currency),newLineItems:to(i.update?.lineItems??this.activeOptions?.lineItems,i.currency),...!i.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,i){if(e===this.applePaySession)try{e.completeShippingMethodSelection({newTotal:eo(t.total.label,i.amount,i.currency),newLineItems:to(i.update?.lineItems??this.activeOptions?.lineItems,i.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 $n=new Set(["paymentMethods","layout","buttonType","buttonTheme","buttonHeight","buttonRadius","emailRequired","phoneNumberRequired","billingAddressRequired","shippingAddressRequired","allowedShippingCountries","lineItems","shippingRates"]);function Yn(e){return Object.assign(e,{skipAppearanceRecovery:!0})}const Kn=256;function Zn(e){const t=e;if(!no(t)||Object.keys(t).some(e=>!$n.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<Nn||e.buttonHeight>zn))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>Un))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 ho();for(const t of["maxColumns","maxRows"]){const i=e.layout[t];if(void 0!==i&&("number"!=typeof i||!Number.isSafeInteger(i)||i<1||i>qn))throw ho()}if(void 0!==e.layout.overflow&&!["auto","never"].includes(e.layout.overflow))throw ho()}if(e.paymentMethods)for(const t of Object.values(e.paymentMethods))if(void 0!==t&&!["auto","always","never"].includes(t))throw ho();if(e.buttonType){if(void 0!==e.buttonType.applePay&&!["plain","buy","check-out","donate","book","subscribe"].includes(e.buttonType.applePay))throw ho();if(void 0!==e.buttonType.googlePay&&!["plain","pay","buy","checkout","donate","book","subscribe"].includes(e.buttonType.googlePay))throw ho()}if(e.buttonTheme){if(void 0!==e.buttonTheme.applePay&&!["black","white","white-outline"].includes(e.buttonTheme.applePay))throw ho();if(void 0!==e.buttonTheme.googlePay&&!["black","white"].includes(e.buttonTheme.googlePay))throw ho()}if(e.allowedShippingCountries&&(!Array.isArray(e.allowedShippingCountries)||e.allowedShippingCountries.length>Kn||e.allowedShippingCountries.some(e=>!/^[A-Za-z]{2}$/.test(e))))throw ho();for(const t of[e.emailRequired,e.phoneNumberRequired,e.billingAddressRequired,e.shippingAddressRequired])if(void 0!==t&&"boolean"!=typeof t)throw ho();return Jn(e.lineItems,"name"),Jn(e.shippingRates,"displayName",!0),uo({...e,...e.allowedShippingCountries?{allowedShippingCountries:e.allowedShippingCountries.map(e=>e.toUpperCase())}:{}})}function Jn(e,t,i=!1){if(void 0!==e){if(!Array.isArray(e)||e.length>Bn)throw ho();for(const n of e)if(!no(n)||"number"!=typeof n.amount||!Number.isSafeInteger(n.amount)||n.amount<0||!po(n[t],jn)||i&&!po(n.id,oe))throw ho()}}function Xn(e){if(void 0===e)return;const t=new Set(["amount","lineItems","emailRequired","phoneNumberRequired","billingAddressRequired","shippingAddressRequired","allowedShippingCountries","shippingRates"]);if(!no(e)||Object.keys(e).some(e=>!t.has(e)))throw ho();if(void 0!==e.amount&&("number"!=typeof e.amount||!Number.isSafeInteger(e.amount)||e.amount<0))throw ho();Jn(e.lineItems,"name"),Jn(e.shippingRates,"displayName",!0);for(const t of[e.emailRequired,e.phoneNumberRequired,e.billingAddressRequired,e.shippingAddressRequired])if(void 0!==t&&"boolean"!=typeof t)throw ho();if(void 0!==e.allowedShippingCountries&&(!Array.isArray(e.allowedShippingCountries)||e.allowedShippingCountries.length>Kn||e.allowedShippingCountries.some(e=>!/^[A-Za-z]{2}$/.test(e))))throw ho();return uo({...e,...e.allowedShippingCountries?{allowedShippingCountries:e.allowedShippingCountries.map(e=>e.toUpperCase())}:{}})}function Qn(e,t){const i=function(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e.toUpperCase()}).resolvedOptions().maximumFractionDigits??Gn}catch{return Gn}}(t);return(e/Hn**i).toFixed(i)}function eo(e,t,i){return{label:e,amount:Qn(t,i),type:"final"}}function to(e,t){return(e??[]).map(e=>({label:e.name,amount:Qn(e.amount,t),type:"final"}))}function io(e,t){return e.map(e=>({identifier:e.id,label:e.displayName,detail:"",amount:Qn(e.amount,t)}))}function no(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function oo(e){const t=JSON.parse(e);if(!no(t))throw new Error("Expected a JSON object.");return t}function ro(e){if(!no(e))throw new Error("Expected an object.");return JSON.stringify(e)}function so(e,t){return{error:{reason:e,message:t,intent:"PAYMENT_AUTHORIZATION"}}}function ao(e){return{transactionState:"ERROR",error:{intent:"PAYMENT_AUTHORIZATION",reason:"PAYMENT_DATA_INVALID",message:e}}}function lo(e){if(no(e)){const t=e.statusCode??e.code;if(de(t,oe))return t}return"elements_google_pay_failed"}function co(e){if(no(e)){const t=e.statusMessage??e.message;if(de(t,re))return t}return e instanceof Error&&e.message?e.message.slice(0,re):"Google Pay could not be completed."}const po=de;function ho(){return new Error("[Paypercut Elements] Express Checkout options are invalid.")}function uo(e){return JSON.parse(JSON.stringify(e))}const mo="16px",yo="1094 / 742",go="http://www.w3.org/2000/svg";let fo=null;const bo=(e,t,i)=>{null===i?e.removeAttribute(t):e.setAttribute(t,i)};class vo{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,i,n,o){const r=fo;if(r)return r.owner===this&&r.componentId===e&&r.requestId===t;const s=this.ensureHost();return fo={owner:this,componentId:e,requestId:t},this.cancelAttempt=n,this.providerElement=o??null,this.previouslyFocused=document.activeElement instanceof HTMLElement?document.activeElement:null,this.updateCopy(i,"provider_open"),document.body.prepend(s),s.hidden=!1,s.style.display="flex",this.lockMerchantPage(s),document.addEventListener("keydown",this.keyHandler,!0),this.cancelButton?.focus({preventScroll:!0}),!0}setPhase(e,t,i,n){this.matches(e,t)&&this.updateCopy(i,n)}hide(e,t){this.matches(e,t)&&this.hideHost()}close(e,t){this.matches(e,t)&&(fo=null,this.cancelAttempt=null,this.providerElement=null,this.hideHost())}destroy(){fo?.owner===this&&(fo=null),this.cancelAttempt=null,this.providerElement=null,this.hideHost(),this.host?.remove(),this.host=null,this.cancelButton=null}isActive(){return fo?.owner===this}matches(e,t){return fo?.owner===this&&fo.componentId===e&&fo.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 i=document.createElement("div");i.dataset.paypercutWalletBadge="",i.dataset.paypercutWalletOverlayTile="",Object.assign(i.style,{width:"min(165.52107px, 46vw)",aspectRatio:yo,padding:"0",border:"0",boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"center",overflow:"visible",background:"transparent",boxShadow:"none"});const n=document.createElement("h2");n.id="paypercut-wallet-overlay-title",Object.assign(n.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:`${mo} 0 0`,color:"rgba(255, 255, 255, 0.9)",fontSize:"clamp(16px, 3.6vw, 18px)",lineHeight:"1.45",fontWeight:"400"});const r=(()=>{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(go,"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 i=document.createElementNS(go,"circle");i.setAttribute("cx","12"),i.setAttribute("cy","12"),i.setAttribute("r","9"),i.setAttribute("fill","none"),i.setAttribute("stroke","rgba(255, 255, 255, 0.28)"),i.setAttribute("stroke-width","2.5");const n=document.createElementNS(go,"circle");if(n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9"),n.setAttribute("fill","none"),n.setAttribute("stroke","#fff"),n.setAttribute("stroke-width","2.5"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-dasharray","18 39"),!("function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches)){const e=document.createElementNS(go,"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"),n.append(e)}return t.append(i,n),e.append(t),e})(),s=document.createElement("button");return s.type="button",s.textContent="Cancel payment",s.addEventListener("click",()=>this.cancel()),s.addEventListener("focus",()=>{s.style.boxShadow=s.matches(":focus-visible")?"0 0 0 3px rgba(138, 188, 255, 0.9)":"none"}),s.addEventListener("blur",()=>{s.style.boxShadow="none"}),s.addEventListener("pointerenter",()=>{s.style.background="rgba(132, 132, 132, 0.42)"}),s.addEventListener("pointerleave",()=>{s.style.background="rgba(111, 111, 111, 0.32)"}),Object.assign(s.style,{width:"min(260px, 100%)",minHeight:"44px",marginTop:mo,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(i,n,o,r,s),e.append(t),this.host=e,this.cancelButton=s,e}updateCopy(e,t){const i=(e=>"apple_pay"===e?"Apple Pay":"Google Pay")(e),n=this.host?.querySelector("[data-paypercut-wallet-badge]"),o=this.host?.querySelector("[data-paypercut-wallet-progress]"),r=this.host?.querySelector("#paypercut-wallet-overlay-title"),s=this.host?.querySelector("#paypercut-wallet-overlay-description");if(this.host&&(this.host.dataset.paypercutWalletOverlayPhase=t,this.host.setAttribute("aria-busy","processing"===t?"true":"false")),n&&(n.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 i=t.content.firstElementChild;if(!(i instanceof SVGElement))throw new Error("Unable to create the wallet provider mark.");return i.removeAttribute("style"),i.setAttribute("aria-hidden","true"),i.setAttribute("focusable","false"),i.dataset.paypercutWalletMark=e,Object.assign(i.style,{display:"block",flex:"none",width:"apple_pay"===e?"68.74%":"100%",maxWidth:"100%",height:"apple_pay"===e?"auto":"100%"}),i})(e)),n.style.aspectRatio=yo,n.style.background="transparent",n.style.boxShadow="none",n.style.display="provider_open"===t?"flex":"none"),r&&(r.style.marginTop="processing"===t?"0":"apple_pay"===e?"8px":"2px"),o&&(o.style.display="processing"===t?"grid":"none"),"processing"===t)return r&&(r.textContent="Processing your payment"),void(s&&(s.textContent=`${i} returned your payment details. Please wait while we securely prepare the next step.`));r&&(r.textContent=`${i} is open`),s&&(s.textContent=`Complete your payment in the open ${i} window, or close ${i} 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),i=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&&i(e);this.isolationObserver=new MutationObserver(e=>{for(const t of e)for(const e of Array.from(t.addedNodes))e instanceof HTMLElement&&i(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,bo(e.element,"aria-hidden",e.ariaHidden),bo(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}}}const wo={colorPrimary:"#0570de",colorPrimaryText:"#ffffff",colorBackground:"#ffffff",colorSurface:"#ffffff",colorText:"#2b2d2f",colorTextSecondary:"#6a6c6f",colorTextPlaceholder:"#737474",colorDanger:"#cc1818",colorSuccess:"#30b130",colorWarning:"#e69e2c",colorBorder:"#d7dde0",colorFocus:"#0570de",colorMuted:"#f2f4f5",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',fontSizeBase:"16px",fontWeightNormal:"400",fontWeightMedium:"500",lineHeight:"1.5",spacingUnit:"4px",gridColumnSpacing:"12px",gridRowSpacing:"12px",labelSpacing:"6px",borderRadius:"4px",buttonBorderRadius:"4px",buttonExpressCheckoutBorderRadius:"4px",buttonPadding:"12px"},Po={...wo,colorBackground:"#15171c",colorSurface:"#1d2027",colorText:"#f3f4f6",colorTextSecondary:"#aeb7c7",colorTextPlaceholder:"#8f99aa",colorBorder:"#3a404b",colorFocus:"#7db7ff",colorMuted:"#252932"},Eo=new Set(Object.keys(wo)),Ao=/var\(\s*--([A-Za-z][A-Za-z0-9]*)\s*\)/g;function Co(e){const t=e?.theme??"light",i="dark"===t?Po:wo,n=Object.fromEntries(Object.entries(e?.variables??{}).filter(([e,t])=>Eo.has(e)&&"string"==typeof t));return{theme:t,disableAnimations:e?.disableAnimations??!1,variables:{...i,...n}}}function So(e,t){const i=e?.rules?.[t];if(!i)return{};const n=Co(e).variables;return Object.fromEntries(Object.entries(i).flatMap(([e,t])=>"string"==typeof t&&ge(t)?[[e,t.replace(Ao,(e,t)=>t in n?n[t]:e)]]:[]))}function _o(e,t){const i=Co(e).variables,n=So(e,".Input"),o=So(e,".Input--invalid"),r=n.backgroundColor??i.colorSurface,s=n.color??i.colorText,a=o.backgroundColor??r,l=o.color??s,c="undefined"!=typeof navigator&&/\bCriOS\//.test(navigator.userAgent),d=e=>c?`${e} !important`:e;return{base:{backgroundColor:r,color:s,fontFamily:i.fontFamily,fontSize:i.fontSizeBase,fontWeight:i.fontWeightNormal,lineHeight:i.lineHeight,padding:t&&t.floatingLabels?t.floatingLabelActive?"23px 12px 9px 12px":"16px 12px 16px 12px":"12px","::placeholder":{color:i.colorTextPlaceholder},":disabled":{backgroundColor:r},...n},empty:{backgroundColor:d(r),color:d(s)},invalid:{...o,backgroundColor:d(a),color:d(l)},complete:{backgroundColor:d(r),color:d(s)}}}const Io=(e,t)=>Array.from({length:t},()=>e).join(" + "),To="http://www.w3.org/2000/svg",Ro=(e,t,i)=>{const n=document.createElementNS(To,"svg");return n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false"),n.setAttribute("width",String(e)),n.setAttribute("height",String(t)),n.setAttribute("viewBox",i),n.style.display="block",n.style.flex="none",n},ko=(e,t)=>{const i=document.createElementNS(To,"rect");for(const[e,n]of Object.entries(t))i.setAttribute(e,n);return e.appendChild(i),i},Oo=(e,t)=>{const i=document.createElementNS(To,"path");for(const[e,n]of Object.entries(t))i.setAttribute(e,n);return e.appendChild(i),i};class xo{constructor(e){this.labels=e,this.visa=(()=>{const e=Ro(48,28,"0 0 48 28");return ko(e,{x:"0.5",y:"0.5",width:"47",height:"27",rx:"3.5",fill:"#ffffff",stroke:"#d7dde0"}),Oo(e,{d:"M15.875 19.02h-2.726l-2.044-7.835c-.097-.36-.303-.679-.606-.829-.757-.378-1.59-.678-2.499-.829v-.302h4.392c.606 0 1.06.453 1.136.979l1.061 5.652 2.725-6.631h2.65l-4.089 9.795Zm5.604 0h-2.575l2.121-9.795h2.574l-2.12 9.795Zm5.451-7.08c.076-.528.53-.83 1.061-.83.833-.075 1.741.076 2.499.452l.454-2.109C30.187 9.152 29.353 9 28.597 9c-2.499 0-4.317 1.357-4.317 3.24 0 1.432 1.288 2.184 2.197 2.638.983.451 1.362.753 1.286 1.205 0 .678-.757.979-1.514.979-.909 0-1.818-.225-2.65-.603l-.454 2.11c.909.376 1.892.528 2.801.528 2.802.074 4.544-1.282 4.544-3.316 0-2.562-3.56-2.712-3.56-3.841ZM39.5 19.02l-2.044-9.795H35.26c-.455 0-.909.302-1.061.753L30.414 19.02h2.65l.529-1.431h3.257l.303 1.431H39.5Zm-3.861-7.157.756 3.692h-2.12l1.364-3.692Z",fill:"#172B85"}),e})(),this.mastercard=(()=>{const e=Ro(48,28,"0 0 48 28");return ko(e,{x:"0.5",y:"0.5",width:"47",height:"27",rx:"3.5",fill:"#ffffff",stroke:"#d7dde0"}),Oo(e,{d:"M23.1 7.7a8.1 8.1 0 1 0 0 12.6 8.1 8.1 0 0 1 0-12.6Z",fill:"#EB001B"}),Oo(e,{d:"M24 8.5a8.1 8.1 0 0 0 0 11 8.1 8.1 0 0 0 0-11Z",fill:"#FF5F00"}),Oo(e,{d:"M24.9 7.7a8.1 8.1 0 1 1 0 12.6 8.1 8.1 0 0 0 0-12.6Z",fill:"#F79E1B"}),e})(),this.invalid=(()=>{const e=Ro(36,28,"0 0 36 28");return e.style.color="currentColor",ko(e,{x:"1",y:"2",width:"27",height:"20",rx:"3",fill:"none",stroke:"currentColor","stroke-width":"2"}),Oo(e,{d:"M2 8h25",stroke:"currentColor","stroke-width":"2"}),Oo(e,{d:"M27.7 11.1a2 2 0 0 1 3.6 0l4.4 9a2 2 0 0 1-1.8 2.9h-8.8a2 2 0 0 1-1.8-2.9l4.4-9Z",fill:"currentColor"}),Oo(e,{d:"M29.5 14.4v3.4m0 2.3v.1",stroke:"#ffffff","stroke-linecap":"round","stroke-width":"1.8"}),e})(),this.root=document.createElement("div"),this.root.dataset.paypercutCardBrandBadges="",this.root.setAttribute("role","img"),this.root.append(this.visa,this.mastercard,this.invalid),this.setState("accepted")}setState(e){this.root.dataset.cardBrandState=e,this.root.setAttribute("aria-label",((e,t)=>t[e])(e,this.labels)),this.visa.style.display="accepted"===e||"visa"===e?"block":"none",this.mastercard.style.display="accepted"===e||"mastercard"===e?"block":"none",this.invalid.style.display="invalid"===e?"block":"none"}setVisible(e){this.root.hidden=!e,this.root.setAttribute("aria-hidden",e?"false":"true")}}const Mo=(e,t)=>{for(const[i,n]of Object.entries(t))e.style.setProperty(i.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`),n)},Lo=e=>{e.removeAttribute("style")},Do=e=>{const t=e?.inputs??"condensed",i=e?.labels??"auto";return{input:t,label:"auto"===i?"condensed"===t?"floating":"above":i}};class Fo{constructor(e,t){this.focused=!1,this.ready=!1,this.validation={empty:!0},this.visibleError=!1,this.submissionErrorVisible=!1,this.loadingAnimation=null,this.appearanceTransition=!1,this.destroyed=!1,this.type=t.type,this.copy=t.copy,this.appearance=t.appearance,this.showIcon="cardNumber"===this.type&&(t.showIcon??!0),this.root=document.createElement("div"),this.root.dataset.paypercutCardField="",this.root.dataset.field=this.type,this.root.lang=this.copy.locale,this.labelAbove=document.createElement("span"),this.labelAbove.dataset.paypercutCardFieldLabel="above",this.labelAbove.textContent=this.copy.ariaLabel,this.inputFrame=document.createElement("div"),this.inputFrame.dataset.paypercutCardFieldInput="",this.inputFrame.dataset.field=this.type,this.floatingLabel=document.createElement("span"),this.floatingLabel.dataset.paypercutCardFieldLabel="floating",this.floatingLabel.setAttribute("aria-hidden","true"),this.floatingLabel.textContent=this.copy.ariaLabel,this.providerMount=document.createElement("div"),this.providerMount.dataset.paypercutCardFieldProvider="",this.loadingIndicator=document.createElement("div"),this.loadingIndicator.dataset.paypercutCardFieldLoading="",this.loadingIndicator.setAttribute("aria-hidden","true"),this.loadingLabelLine=document.createElement("span"),this.loadingLabelLine.dataset.paypercutCardFieldLoadingLine="label",this.loadingValueLine=document.createElement("span"),this.loadingValueLine.dataset.paypercutCardFieldLoadingLine="value",this.loadingIndicator.append(this.loadingLabelLine,this.loadingValueLine),this.brandBadges="cardNumber"===this.type?new xo({accepted:`${this.copy.ariaLabel}: Visa, Mastercard`,invalid:this.copy.errors.invalid,visa:"Visa",mastercard:"Mastercard"}):null,this.brandLane="cardNumber"===this.type?document.createElement("div"):null,this.brandLane&&(this.brandLane.dataset.paypercutCardBrandLane=""),this.errorMessage=document.createElement("p"),this.errorMessage.dataset.paypercutCardFieldError="",this.errorMessage.setAttribute("role","alert"),this.errorMessage.setAttribute("aria-live","polite"),this.inputFrame.appendChild(this.floatingLabel),this.inputFrame.appendChild(this.providerMount),this.brandBadges&&this.brandLane&&(this.brandLane.appendChild(this.brandBadges.root),this.inputFrame.appendChild(this.brandLane)),this.inputFrame.appendChild(this.loadingIndicator),this.root.appendChild(this.labelAbove),this.root.appendChild(this.inputFrame),this.root.appendChild(this.errorMessage),e.appendChild(this.root),this.render()}getPresentation(){const e=Do(this.appearance),t=this.focused||!this.validation.empty;return{floatingLabels:"floating"===e.label,floatingLabelActive:t,placeholder:"floating"!==e.label||t?this.copy.placeholder:""}}updateAppearance(e){this.assertAlive(),this.appearance=e,this.render()}beginAppearanceTransition(){this.assertAlive(),this.appearanceTransition=!0,this.render()}handleReady(){this.assertAlive(),this.ready&&!this.appearanceTransition||(this.ready=!0,this.appearanceTransition=!1,this.render())}handleChange(e){this.assertAlive(),this.validation={empty:e.empty,...e.brand?{brand:e.brand}:{},...e.error?{error:{...e.error}}:{}},e.error||(this.submissionErrorVisible=!1),this.visibleError=Boolean(e.error)&&(this.submissionErrorVisible||!this.focused&&!e.empty),this.render()}handleFocus(){this.assertAlive(),this.focused=!0,this.visibleError=this.submissionErrorVisible&&Boolean(this.validation.error),this.render()}handleBlur(){this.assertAlive(),this.focused=!1,this.visibleError=Boolean(this.validation.error)&&(this.submissionErrorVisible||!this.validation.empty),this.render()}revealValidationError(e){this.assertAlive(),this.validation.error||(this.validation={...this.validation,error:{type:e,message:this.copy.errors[e]}}),this.submissionErrorVisible=Boolean(this.validation.error),this.visibleError=Boolean(this.validation.error),this.render()}destroy(){this.destroyed||(this.destroyed=!0,this.loadingAnimation?.cancel(),this.loadingAnimation=null,this.root.remove())}render(){const e=Co(this.appearance),t=Do(this.appearance),i=this.getPresentation(),n=this.visibleError,o=n?this.validation.error?.message??"":"",r=n?"invalid":(e=>{const t=e?.trim().toLowerCase().replace(/[ _-]+/g,"");return"visa"===t?"visa":"mastercard"===t?"mastercard":void 0})(this.validation.brand)??"accepted",s=((e,t="accepted")=>{const i="accepted"===t?96:"invalid"===t?36:48,n="accepted"===t?2:0;return{badgeGap:`calc(${Io(e,2)})`,endInset:`calc(${Io(e,3)})`,laneWidth:`calc(${i}px + ${Io(e,n+3)})`}})(e.variables.spacingUnit,r),a=!this.ready;this.root.dataset.focused=this.focused?"true":"false",this.root.dataset.invalid=n?"true":"false",this.root.dataset.loading=a?"true":"false",this.root.dataset.appearanceTransition=this.appearanceTransition?"updating":"idle",this.root.setAttribute("aria-busy",a||this.appearanceTransition?"true":"false"),this.root.dataset.theme=e.theme,this.root.dataset.inputLayout=t.input,this.root.dataset.labelLayout=t.label,this.inputFrame.dataset.focused=this.focused?"true":"false",this.inputFrame.dataset.invalid=n?"true":"false",this.inputFrame.inert=this.appearanceTransition,Lo(this.root),Mo(this.root,{display:"grid",width:"100%",minWidth:"0",gap:e.variables.labelSpacing,boxSizing:"border-box",color:e.variables.colorText,colorScheme:e.theme,fontFamily:e.variables.fontFamily,fontSize:e.variables.fontSizeBase,fontWeight:e.variables.fontWeightNormal,lineHeight:e.variables.lineHeight}),this.labelAbove.hidden="above"!==t.label,Lo(this.labelAbove),Mo(this.labelAbove,{display:"above"===t.label?"block":"none",color:e.variables.colorText,fontFamily:e.variables.fontFamily,fontSize:"0.875em",fontWeight:e.variables.fontWeightMedium,lineHeight:e.variables.lineHeight,...So(this.appearance,".Label")}),Lo(this.inputFrame),Mo(this.inputFrame,{position:"relative",width:"100%",minWidth:"0",height:"floating"===t.label?"56px":"48px",overflow:"hidden",boxSizing:"border-box",borderStyle:"solid",borderWidth:"1px",borderColor:this.focused?e.variables.colorFocus:n?e.variables.colorDanger:e.variables.colorBorder,borderRadius:e.variables.borderRadius,background:e.variables.colorSurface,color:e.variables.colorText,transition:e.disableAnimations?"none":"border-color 150ms ease, box-shadow 150ms ease",boxShadow:this.focused?`inset 0 0 0 1px ${e.variables.colorFocus}, 0 0 0 3px color-mix(in srgb, ${e.variables.colorFocus} 25%, transparent)`:n?`inset 0 0 0 1px ${e.variables.colorDanger}`:"none","--ppc-card-brand-lane-width":this.showIcon?s.laneWidth:"0px",pointerEvents:this.appearanceTransition?"none":"auto",...So(this.appearance,".Input"),...n?So(this.appearance,".Input--invalid"):{},...this.focused?So(this.appearance,".Input:focus"):{}}),this.floatingLabel.hidden="floating"!==t.label,this.floatingLabel.dataset.state=i.floatingLabelActive?"active":"resting",Lo(this.floatingLabel),Mo(this.floatingLabel,{display:"floating"===t.label?"block":"none",position:"absolute",zIndex:"2",top:i.floatingLabelActive?e.variables.spacingUnit:"50%",left:`calc(${e.variables.spacingUnit} * 3)`,pointerEvents:"none",color:i.floatingLabelActive?e.variables.colorTextSecondary:e.variables.colorTextPlaceholder,fontFamily:e.variables.fontFamily,fontSize:i.floatingLabelActive?"0.6875em":"1em",fontWeight:e.variables.fontWeightNormal,lineHeight:i.floatingLabelActive?"1rem":e.variables.lineHeight,transform:i.floatingLabelActive?"none":"translateY(-50%)",transformOrigin:"left center",transition:e.disableAnimations?"none":"top 150ms ease, transform 150ms ease, font-size 150ms ease, line-height 150ms ease, color 150ms ease",...So(this.appearance,".Label")}),Lo(this.providerMount),Mo(this.providerMount,{width:this.showIcon?"calc(100% - var(--ppc-card-brand-lane-width))":"100%",minWidth:"0",height:"100%",overflow:"hidden",boxSizing:"border-box",transition:e.disableAnimations?"none":"width 150ms ease"}),this.brandBadges&&this.brandLane&&(this.brandBadges.setState(r),this.brandBadges.setVisible(this.showIcon),Lo(this.brandLane),Mo(this.brandLane,{display:this.showIcon?"flex":"none",position:"absolute",zIndex:"3",top:"0",right:"0",width:"var(--ppc-card-brand-lane-width)",height:"100%",boxSizing:"border-box",alignItems:"center",justifyContent:"flex-end",paddingRight:s.endInset,pointerEvents:"none",transition:e.disableAnimations?"none":"width 150ms ease"}),Lo(this.brandBadges.root),Mo(this.brandBadges.root,{display:this.showIcon?"flex":"none",alignItems:"center",gap:s.badgeGap,pointerEvents:"none",color:e.variables.colorDanger})),this.loadingIndicator.hidden=!a,Lo(this.loadingIndicator),Mo(this.loadingIndicator,{display:a?"flex":"none",position:"absolute",zIndex:"4",inset:"0",boxSizing:"border-box",flexDirection:"column",justifyContent:"center",gap:`calc(${e.variables.spacingUnit} * 1.5)`,padding:`calc(${e.variables.spacingUnit} * 3)`,overflow:"hidden",background:e.variables.colorSurface,cursor:"progress"});const l=`color-mix(in srgb, ${e.variables.colorBorder} 72%, ${e.variables.colorSurface})`;Lo(this.loadingLabelLine),Mo(this.loadingLabelLine,{display:"floating"===t.label?"block":"none",width:"28%",height:"6px",borderRadius:e.variables.borderRadius,background:l}),Lo(this.loadingValueLine),Mo(this.loadingValueLine,{display:"block",width:"cardNumber"===this.type?"58%":"cardExpiry"===this.type?"48%":"42%",height:"10px",borderRadius:e.variables.borderRadius,background:l});const c=this.root.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!1,d="function"==typeof this.loadingValueLine.animate;a&&!e.disableAnimations&&!c&&d?this.loadingAnimation??(this.loadingAnimation=this.loadingValueLine.animate([{opacity:.55},{opacity:1},{opacity:.55}],{duration:1500,iterations:Number.POSITIVE_INFINITY,easing:"ease-in-out"})):(this.loadingAnimation?.cancel(),this.loadingAnimation=null),this.errorMessage.hidden=!n,this.errorMessage.textContent=o,Lo(this.errorMessage),Mo(this.errorMessage,{display:n?"block":"none",margin:"0",color:e.variables.colorDanger,fontFamily:e.variables.fontFamily,fontSize:"0.875em",fontWeight:e.variables.fontWeightNormal,lineHeight:e.variables.lineHeight,...So(this.appearance,".Error")})}assertAlive(){if(this.destroyed)throw new Error("[Paypercut Elements] Cannot update a destroyed card field surface.")}}class No{constructor(e,i,n){this.type=e,this.group=i,this.options=n,this.componentId=j(),this.componentGeneration=0,this.emitter=new t,this.surface=null,this.mounted=!1,this.ready=!1,this.destroyed=!1,this.mountGeneration=0,this.initializationTimeoutId=null,this.presentationSignature=null,this.copy=null,this.componentType=(e=>{switch(e){case"cardNumber":return"card_number";case"cardExpiry":return"card_expiry";case"cardCvc":return"card_cvc"}})(e)}mount(e){if(this.destroyed)throw new Error("[Paypercut Elements] Cannot mount a destroyed card field.");if(this.mounted)return;if("undefined"==typeof window||"undefined"==typeof document)throw new Error("[Paypercut Elements] Card fields 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=(e=>{const t="string"==typeof e?document.querySelector(e):e;if(!(t instanceof HTMLElement))throw new Error(`[Paypercut Elements] Card field mount target was not found: ${String(e)}`);return t})(e),i=this.mountGeneration+1;this.mountGeneration=i,this.mounted=!0,this.group.markComponentMounted(),this.armInitializationWatch(i),this.initialize(t,i)}async initialize(e,t){try{const i=await this.group.resolveCardFieldCopy(this.type);if(!this.isCurrentMount(t))return;const n=new Fo(e,{type:this.type,copy:i,appearance:this.group.getAppearance(),..."cardNumber"===this.type?{showIcon:this.options?.showIcon}:{}});n.providerMount.id=`paypercut-${this.type}-provider-${this.componentId}`,this.surface=n,this.copy=i;const o=n.getPresentation();this.presentationSignature=JSON.stringify(o),await this.group.mountCardField({id:this.componentId,type:this.type,target:n.providerMount,ariaLabel:i.ariaLabel,placeholder:o.placeholder,presentation:o,events:{onReady:()=>this.onProviderReady(t),onChange:e=>this.onProviderChange(t,e),onFocus:()=>this.onProviderFocus(t),onBlur:()=>this.onProviderBlur(t),onError:e=>{this.isCurrentMount(t)&&this.emitter.emit("error",e)}}}),this.isCurrentMount(t)&&this.group.onCardFieldAvailabilityChange()}catch(e){if(!this.isCurrentMount(t))return;const i=e.details;if(i)return void this.failInitialization(i.message,i);this.failInitialization("The secure card field could not be initialized.")}}on(e,t){return this.emitter.on(e,t)}clear(){this.command("clear")}focus(){this.command("focus")}blur(){this.command("blur")}getComponentOptions(){return{}}revealSubmissionError(e){if(!this.destroyed&&this.mounted&&this.ready){this.surface?.revealValidationError(e);try{this.group.commandCardField(this.componentId,this.componentType,"focus")}catch{}}}hasActiveSubmission(){return!1}handleControllerError(e){this.destroyed||(this.ready?(this.ready=!1,this.emitter.emit("error",e),this.group.onCardFieldAvailabilityChange()):this.failInitialization(e.message,e))}handleControllerEvent(e){"error"===e.event&&this.handleControllerError(e)}updateAppearance(e){!this.destroyed&&this.surface&&(this.surface.updateAppearance(e),this.syncPresentation())}announceAppearanceReady(){!this.destroyed&&this.mounted&&this.surface&&(this.ready=!0,this.clearInitializationWatch(),this.surface.handleReady(),this.emitter.emit("ready"),this.group.onCardFieldAvailabilityChange())}beginAppearanceTransition(){!this.destroyed&&this.mounted&&this.surface&&(this.ready=!1,this.clearInitializationWatch(),this.surface.beginAppearanceTransition(),this.armInitializationWatch(this.mountGeneration),this.group.onCardFieldAvailabilityChange())}isMounted(){return this.mounted&&!this.destroyed}isVisible(){return Si(this.surface?.root??null)}destroy(){this.destroyed||(this.destroyed=!0,this.mountGeneration+=1,this.ready=!1,this.clearInitializationWatch(),this.group.destroyCardField(this.componentId),this.group.onCardFieldAvailabilityChange(),this.surface?.destroy(),this.surface=null,this.copy=null,this.presentationSignature=null,this.mounted=!1,this.emitter.clear(),this.group.remove(this))}command(e){if(this.destroyed)throw new Error(`[Paypercut Elements] Cannot ${e} a destroyed card field.`);if(!this.mounted||!this.ready)throw new Error(`[Paypercut Elements] Cannot ${e} a card field before it is ready.`);this.group.commandCardField(this.componentId,this.componentType,e)}onProviderReady(e){this.isCurrentMount(e)&&!this.ready&&(this.ready=!0,this.clearInitializationWatch(),this.surface?.handleReady(),this.emitter.emit("ready"),this.group.onCardFieldAvailabilityChange())}onProviderChange(e,t){if(!this.isCurrentMount(e)||!this.copy)return;this.group.onCardFieldValueChange();const i=((e,t,i)=>({complete:t.complete,empty:t.empty,..."cardNumber"===e&&t.brand?{brand:t.brand}:{},...t.errorType?{error:{type:t.errorType,message:i.errors[t.errorType]}}:{}}))(this.type,t,this.copy);this.surface?.handleChange(i),this.syncPresentation(),this.emitter.emit("change",i)}onProviderFocus(e){this.isCurrentMount(e)&&(this.surface?.handleFocus(),this.syncPresentation(),this.emitter.emit("focus"))}onProviderBlur(e){this.isCurrentMount(e)&&(this.surface?.handleBlur(),this.syncPresentation(),this.emitter.emit("blur"))}failInitialization(e,t={code:"elements_provider_initialization_failed",message:e,recoverable:!0}){this.destroyed||this.ready||!this.mounted||(this.rollbackMount(),this.emitter.emit("error",t))}rollbackMount(){this.mountGeneration+=1,this.clearInitializationWatch(),this.group.destroyCardField(this.componentId),this.surface?.destroy(),this.surface=null,this.copy=null,this.presentationSignature=null,this.mounted=!1,this.ready=!1,this.group.onCardFieldAvailabilityChange()}isCurrentMount(e){return!this.destroyed&&this.mounted&&this.mountGeneration===e}syncPresentation(){if(!this.surface||!this.mounted||this.destroyed)return;const e=this.surface.getPresentation(),t=JSON.stringify(e);t!==this.presentationSignature&&(this.presentationSignature=t,this.group.updateCardFieldPresentation(this.componentId,e))}clearInitializationWatch(){null!==this.initializationTimeoutId&&"undefined"!=typeof window&&window.clearTimeout(this.initializationTimeoutId),this.initializationTimeoutId=null}armInitializationWatch(e){this.clearInitializationWatch(),this.initializationTimeoutId=window.setTimeout(()=>{this.isCurrentMount(e)&&!this.ready&&this.failInitialization("The secure card field did not become ready in time.")},4e4)}}function zo(e,t,i,n){Object.defineProperty(e,t,{get:i,set:n,enumerable:!0,configurable:!0})}function Uo(e,t){return Object.keys(t).forEach(function(i){"default"===i||"__esModule"===i||Object.prototype.hasOwnProperty.call(e,i)||Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[i]}})}),e}zo({},"basistheory",()=>Zo);const qo=(()=>{let e,t;const i=async(i,n,o={})=>{if(e)return;let r;r=!t||t?.includes("localhost")?"local":t.includes("dev")?"dev":"prod";const s={level:n,message:i,service:"web-elements-loader",env:r,referrer:document?.referrer,origin:window?.location.origin,url:window?.location.href,userAgent:navigator?.userAgent,...o};["local","dev"].includes(r)&&console.log(s);try{await fetch("https://http-intake.logs.datadoghq.com/v1/input/pubb96b84a13912504f4354f2d794ea4fab",{method:"POST",body:JSON.stringify(s),headers:{"Content-Type":"application/json"}})}catch{console.warn("There was an error sending telemetry.")}};return{disableTelemetry:t=>{e=t},setBaseUrl:e=>{t=e},log:{error:(e,t={})=>i(e,"error",t),info:(e,t={})=>i(e,"info",t),warn:(e,t={})=>i(e,"warn",t)}}})();class Bo extends Error{constructor(e,t,i){super(e),this.details=t,this.validation=i,this.name="BasisTheoryValidationError",Object.setPrototypeOf(this,Bo.prototype)}}const jo="Tried to load BasisTheoryElements in a non-DOM environment.",Go="Unable to load the Elements script. This may be due to network restrictions or browser extensions like ad blockers interfering with script loading. Check browser settings or network connection and try again.",Ho=["accel","bancontact","cartes-bancaires","culiance","dankort","ebt","eftpos-australia","nyce","private-label","prop","pulse","rupay","star","uatp","korean-local","visa","mastercard","american-express","discover","diners-club","jcb","unionpay","maestro","elo","hiper","hipercard","mir","unknown"],Wo=["left","right","none"],Vo=["additional-name","address-level1","address-level2","address-level3","address-level4","address-line1","address-line2","address-line3","bday-day","bday-month","bday-year","bday","billing","cc-additional-name","cc-csc","cc-exp-month","cc-exp-year","cc-exp","cc-family-name","cc-given-name","cc-name","cc-number","cc-type","country-name","country","current-password","email","family-name","fax","given-name","home","honorific-prefix","honorific-suffix","language","mobile","name","new-password","nickname","off","on","one-time-code","organization-title","organization","page","postal-code","sex","shipping","street-address","tel-area-code","tel-country-code","tel-extension","tel-local-prefix","tel-local-suffix","tel-local","tel-national","tel","transaction-amount","transaction-currency","url","username","work"];let $o;const Yo=(e,t)=>new Promise((i,n)=>{let o=(e=>{const t=document.querySelector(`script[src^="${e}"]`);if(t)return t;const i=document.head||document.body;if(!i)throw new Error("No <head> or <body> elements found in the document.");const n=Object.assign(document.createElement("script"),{src:e});return i.append(n),n})(e),r=!1;o.addEventListener("load",()=>{window.BasisTheoryElements?i(window.BasisTheoryElements):((async()=>{await qo.log.error("Elements not found on window on load",{logType:"elementsNotFoundOnWindow",logOrigin:"loadScript",retryCount:t})})(),n(new Error("Basis Theory Elements did not load properly. Check network tab for more details.")))}),o.addEventListener("error",async s=>{if(!r){r=!0,await qo.log.error("Elements script onError event",{logType:"elementsScriptOnError",logOrigin:"loadScript",retryCount:t,event:{message:s?.message,source:s?.filename,lineno:s?.lineno,colno:s?.colno,error:s?.error,target:s?.target}});try{o?.remove()}catch(e){await qo.log.error(`Error removing script from DOM on retry attempt ${t}`,{logType:"scriptRemovalError",logOrigin:"loadScript",retryCount:t,removalError:e})}if(0!==t){try{const i=await fetch(e);i.ok?(await qo.log.error("Second attempt to load elements script failed, fetch success",{logType:"elementsScriptFetchFailure",logOrigin:"loadScript",retryCount:t,fetchResult:"success",fetchResponse:i}),n(new Error(Go))):(await qo.log.error(`Second attempt to load elements script failed, fetch failed with status: ${i.status}.`,{logType:"elementsScriptFetchFailure",logOrigin:"loadScript",retryCount:t,fetchResult:"error",fetchResponse:i}),n(new Error(jo)))}catch(e){await qo.log.error("Second attempt failed to load elements script failed, fetch network error.",{logType:"elementsScriptFetchError",logOrigin:"loadScript",retryCount:t,fetchResult:"error",fetchError:e}),n(new Error(Go))}n(s?.error||s?.message||new Error(Go))}else Yo(e,t+1).then(i).catch(n)}})}),Ko=e=>{let t;e?._devMode&&e?.customDomain&&qo.log.warn("Dev mode and domain whitelabeling are both enabled - dev mode takes precedence."),t=e?._devMode?"https://js.flock-dev.com":e?.customDomain?(e=>{if("string"!=typeof e||!e.trim())throw new Error("Custom domain must be a non-empty string.");let t;try{t=new URL(e.toLowerCase().startsWith("http")?e:`https://${e}`)}catch{throw new Bo(`Invalid custom domain: "${e}"`,{})}if("https:"!==t.protocol)throw new Bo(`Custom domain must use HTTPS (got "${t.protocol}")`,{});if("/"!==t.pathname||t.search||t.hash)throw new Bo(`Custom domain must not include path, query, or hash (got "${t.href}")`,{});if(t.port)throw new Bo(`Custom domain must not include a port (got ":${t.port}")`,{});if(!/^(?=.{1,253}$)([a-zA-Z0-9-]{1,63}\.)+[a-zA-Z]{2,63}$/.test(t.hostname))throw new Bo(`Invalid hostname: "${t.hostname}"`,{});return t.origin})(e.customDomain):"https://js.basistheory.com";const i=`${t}/web-elements/2.12.1`,n=`${i}/client/index.js`,o=`${i}/hosted-elements/`;return e?.customDomain&&e._devMode,{origin:t,clientJsUrl:n,hostedElementsBaseUrl:o}},Zo=async(e,t)=>{if(!e||0===e.length)throw new Error("API key is required");const{origin:i,clientJsUrl:n,hostedElementsBaseUrl:o}=Ko(t);qo.setBaseUrl(i),qo.disableTelemetry(Boolean(t?.disableTelemetry));var r;return(await(r=n,$o||($o=new Promise((e,t)=>{if("object"!=typeof window)return void(async()=>{await qo.log.warn(jo,{logType:"elementsNonDomError",logOrigin:"loadElements"}),t(new Error(jo))})();if(window.BasisTheoryElements)return void e(window.BasisTheoryElements);const i=new URL(r).toString().replace(/\/$/u,"");Yo(i,0).then(e).catch(e=>{t(e)})})),$o)).init(e,o,!1,t?.useSameOriginApi??!0,t?.disableTelemetry??!1,t?.debug??!1,t?.environment??"production",t?.useNetworkCheck??!1,t?.customDomain?i:void 0)};var Jo={};zo(Jo,"AUTOCOMPLETE_VALUES",()=>Vo),zo(Jo,"CARD_BRANDS",()=>Ho),zo(Jo,"CARD_ICON_POSITIONS",()=>Wo);var Xo={},Qo={};zo(Qo,"VISA",()=>er),zo(Qo,"MASTERCARD",()=>tr),zo(Qo,"AMERICAN_EXPRESS",()=>ir),zo(Qo,"DINERS_CLUB",()=>nr),zo(Qo,"DISCOVER",()=>or),zo(Qo,"JCB",()=>rr),zo(Qo,"UNION_PAY",()=>sr),zo(Qo,"MAESTRO",()=>ar),zo(Qo,"ELO",()=>lr),zo(Qo,"MIR",()=>cr),zo(Qo,"HIPER",()=>dr),zo(Qo,"HIPERCARD",()=>pr),zo(Qo,"DEFAULT_CARD_TYPES",()=>hr);const er={niceType:"Visa",type:"visa",patterns:[4],gaps:[4,8,12],lengths:[16,18,19],code:{name:"CVV",size:3}},tr={niceType:"Mastercard",type:"mastercard",patterns:[[51,55],[2221,2229],[223,229],[23,26],[270,271],2720],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},ir={niceType:"American Express",type:"american-express",patterns:[34,37],gaps:[4,10],lengths:[15],code:{name:"CID",size:4}},nr={niceType:"Diners Club",type:"diners-club",patterns:[[300,305],36,38,39],gaps:[4,10],lengths:[14,16,19],code:{name:"CVV",size:3}},or={niceType:"Discover",type:"discover",patterns:[6011,[644,649],65],gaps:[4,8,12],lengths:[16,19],code:{name:"CID",size:3}},rr={niceType:"JCB",type:"jcb",patterns:[2131,1800,[3528,3589]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVV",size:3}},sr={niceType:"UnionPay",type:"unionpay",patterns:[620,[62100,62182],[62184,62187],[62185,62197],[62200,62205],[622010,622999],622018,[62207,62209],[623,626],6270,6272,6276,[627700,627779],[627781,627799],[6282,6289],6291,6292,810,[8110,8131],[8132,8151],[8152,8163],[8164,8171]],gaps:[4,8,12],lengths:[14,15,16,17,18,19],code:{name:"CVN",size:3}},ar={niceType:"Maestro",type:"maestro",patterns:[493698,[5e5,504174],[504176,506698],[506779,508999],[56,59],63,67,6],gaps:[4,8,12],lengths:[12,13,14,15,16,17,18,19],code:{name:"CVC",size:3}},lr={niceType:"Elo",type:"elo",patterns:[401178,401179,438935,457631,457632,431274,451416,457393,504175,[506699,506778],[509e3,509999],627780,636297,636368,[650031,650033],[650035,650051],[650405,650439],[650485,650538],[650541,650598],[650700,650718],[650720,650727],[650901,650978],[651652,651679],[655e3,655019],[655021,655058]],gaps:[4,8,12],lengths:[16],code:{name:"CVE",size:3}},cr={niceType:"Mir",type:"mir",patterns:[[2200,2204]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVP2",size:3}},dr={niceType:"Hiper",type:"hiper",patterns:[637095,63737423,63743358,637568,637599,637609,637612],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},pr={niceType:"Hipercard",type:"hipercard",patterns:[606282],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},hr=[er,tr,ir,nr,or,rr,sr,ar,lr,cr,dr,pr];var ur={};zo(ur,"CoBadgedSupport",()=>mr);var mr=function(e){return e.CartesBancaires="cartes-bancaires",e.Bancontact="bancontact",e.Dankort="dankort",e}({}),yr={};zo(yr,"ELEMENTS_TYPES",()=>gr);const gr=["card","cardExpirationDate","cardNumber","cardVerificationCode","copyButton","data","text"];var fr={};Uo(fr,{}),Uo(fr,{}),Uo(fr,{}),Uo(fr,{});var br={};zo(br,"SAFE_CSS_PROPERTIES",()=>vr),zo(br,"BUTTON_CSS_PROPERTIES",()=>wr),zo(br,"SAFE_CSS_PROPERTIES_ALTERNATES",()=>Pr),zo(br,"SAFE_CSS_PROPERTIES_WITH_ALTERNATES",()=>Er),zo(br,"CARD_ELEMENT_STYLE_VARIANT_SELECTORS",()=>Ar),zo(br,"BUTTON_ELEMENT_STYLE_VARIANT_SELECTORS",()=>Cr),zo(br,"CARD_ELEMENT_STYLE_VARIANTS",()=>Sr),zo(br,"CARD_ELEMENT_STYLE_FONTS_ATTR",()=>_r),zo(br,"BUTTON_ELEMENT_STYLE_VARIANTS",()=>Ir);const vr=["backgroundColor","color","fontFamily","fontSize","fontSmooth","fontStyle","fontVariant","fontWeight","letterSpacing","lineHeight","padding","textAlign","textDecoration","textShadow","textTransform"],wr=["alignItems","backgroundColor","border","borderBottom","borderColor","borderLeft","borderRadius","borderRight","borderStyle","borderTop","borderWidth","boxShadow","color","cursor","display","fontFamily","fontSize","fontWeight","gap","height","justifyContent","letterSpacing","lineHeight","margin","maxHeight","maxWidth","minHeight","minWidth","opacity","outline","padding","textAlign","textTransform","transform","transition","width"],Pr={fontSmooth:["-webkit-font-smoothing","-moz-osx-font-smoothing"]},Er=Object.keys(Pr),Ar=[":hover",":focus",":read-only","::placeholder","::selection",":disabled"],Cr=[":hover",":focus",":active"],Sr=["base","container","complete","invalid","empty"],_r="fonts",Ir=["base","container"];Uo(Xo,Qo),Uo(Xo,ur),Uo(Xo,{}),Uo(Xo,{}),Uo(Xo,yr),Uo(Xo,fr),Uo(Xo,{}),Uo(Xo,br);var Tr={},Rr={};zo(Rr,"DATA_CLASSIFICATIONS",()=>kr),zo(Rr,"DATA_IMPACT_LEVELS",()=>Or),zo(Rr,"DATA_RESTRICTION_POLICIES",()=>xr);const kr=["general","bank","pci","pii"],Or=["low","moderate","high"],xr=["mask","redact"];Uo(Tr,Rr),Uo(Tr,{}),Uo(Tr,{}),Uo(Tr,{}),Uo(Tr,{}),Uo(Tr,{}),Uo(Tr,{}),Uo(Tr,{});var Mr={},Lr={};Uo(Lr,{}),Uo(Mr,Lr),Uo(Jo,Xo),Uo(Jo,Tr),Uo(Jo,Mr);var Dr={};zo(Dr,"BasisTheoryApiError",()=>Fr),zo(Dr,"BasisTheoryValidationError",()=>Bo),zo(Dr,"BasisTheoryConfigurationError",()=>Nr),zo(Dr,"HttpClientError",()=>zr);class Fr extends Error{constructor(e,t,i,n){super(e),this.status=t,this.data=i,this._debug=n,this.name="BasisTheoryApiError",Object.setPrototypeOf(this,Fr.prototype)}}class Nr extends Error{constructor(e,t){super(e),this.details=t,this.name="BasisTheoryConfigurationError",Object.setPrototypeOf(this,Nr.prototype)}}class zr extends Error{constructor(e,t,i,n){super(e),this.name="HttpClientError",this.status=t,this.data=i,this.headers=n,Object.setPrototypeOf(this,zr.prototype)}}"undefined"!=typeof window&&document.currentScript&&!window.basistheory&&(window.basistheory=Zo);const Ur=new Set(["/hosted-elements/card-number-element.html","/hosted-elements/card-expiration-date-element.html","/hosted-elements/card-verification-code-element.html"]),qr=e=>{if(!(e=>{try{const t=new URL(e.src,window.location.href);return"https://js.basistheory.com"===t.origin&&t.pathname.includes("/web-elements/")&&Array.from(Ur).some(e=>t.pathname.endsWith(e))}catch{return!1}})(e))return!1;const t=new Set(e.allow.split(";").map(e=>e.trim()).filter(Boolean));return t.add("clipboard-write"),t.add("autofill *"),e.allow=Array.from(t).join("; "),!0},Br=(e,t,i)=>{e.getPropertyValue(t)===i&&"important"===e.getPropertyPriority(t)||e.setProperty(t,i,"important")},jr=new WeakMap;class Gr extends Error{constructor(){super("Basis Theory Elements initialization timed out."),this.name="InitializationAttemptTimeoutError"}}const Hr=()=>new Error("Basis Theory Elements initialization was cancelled."),Wr=e=>e.DataElement,Vr=(e,t)=>{if(!t||Wr(e)!==t)return!1;const i=t.iframe;try{return t.unmount(),!0}catch{return!!i&&(i.remove(),!0)}},$r=async e=>{let t;const i=new Promise((e,i)=>{t=globalThis.setTimeout(()=>i(new Gr),1e4)});e.catch(()=>{});try{return await Promise.race([e,i])}finally{void 0!==t&&globalThis.clearTimeout(t)}},Yr=(e,t)=>{if(t.aborted)return Promise.reject(Hr());const i=Symbol("basis-theory-initialization-waiter");return e.waiters.add(i),new Promise((n,o)=>{let r=!1;const s=n=>{r||(r=!0,e.waiters.delete(i),t.removeEventListener("abort",a),n())},a=()=>s(()=>o(Hr()));t.addEventListener("abort",a,{once:!0}),e.promise.then(e=>s(()=>n(e)),e=>s(()=>o(e instanceof Error?e:new Error(String(e)))))})},Kr=(e,t)=>{if("undefined"==typeof window)return Promise.reject(new Error("Basis Theory Elements requires a browser document."));if(t.aborted)return Promise.reject(Hr());const i=window,n=(e=>JSON.stringify({publicKey:e.publicKey,options:e.options}))(e),o=jr.get(i);if(o)return o.key!==n?Promise.reject(new Error("Basis Theory Elements is already initialized with another configuration.")):"ready"===o.kind?Promise.resolve(o.provider):"failed"===o.kind?o.restartable?(jr.delete(i),Kr(e,t)):Promise.reject(o.error):Yr(o,t);const r={kind:"pending",key:n,waiters:new Set,restartableAfterFailure:!1},s=Symbol("basis-theory-initialization-first-waiter");return r.waiters.add(s),r.promise=(async(e,t,i)=>{let n;for(let o=0;o<2;o+=1){if(0===i.waiters.size)throw Hr();const r=Wr(e),s=Promise.resolve().then(()=>Zo(t.publicKey,t.options)),a={discardLateResult:!1},l=t=>{if(a.cleanup?.candidate===t)return a.cleanup.succeeded;const i=Vr(e,t);return a.cleanup={candidate:t,succeeded:i},i},c=()=>{if(!a.discardLateResult)return;const t=a.candidate??Wr(e);t&&t!==r&&l(t)};s.then(c,c);try{const e=await $r(s);if(!e)throw new Error("Basis Theory Elements did not initialize.");if(0===i.waiters.size)throw Hr();return e}catch(t){n=t;const s=Wr(e),c=void 0!==s&&s!==r;c&&(a.candidate=s);const d=c&&l(s);if(a.discardLateResult=t instanceof Gr,!(o+1<2&&i.waiters.size>0&&d))throw i.restartableAfterFailure=d,t}}throw n})(i,e,r),r.waiters.delete(s),jr.set(i,r),r.promise.then(e=>{jr.get(i)===r&&jr.set(i,{kind:"ready",key:n,provider:e})},e=>{jr.get(i)===r&&jr.set(i,{kind:"failed",key:n,error:e instanceof Error?e:new Error(String(e)),restartable:r.restartableAfterFailure})}),Yr(r,t)},Zr=[250,750,1500],Jr=/[\u0000-\u001f\u007f]/;class Xr extends Error{constructor(){super("Basis Theory tokenization returned a successful response without a token identifier."),this.name="BasisTheoryTokenizationResponseInvalidError"}}const Qr=e=>{if(!e)return!1;if(e instanceof Xr)return!0;const t=e,i=[t.name,t.code,e instanceof Error?e.message:t.message,t.data].map(e=>String(e??"")).join(" ").toLowerCase();if(["timeout","timed out","api is unreachable","failed to fetch","load failed","networkerror","network request failed","connection reset","connection closed","valueresolutionfailure","value resolution failure"].some(e=>i.includes(e)))return!0;const n=(e=>{if(!e||"object"!=typeof e)return;const t=e,i=t.status??t.statusCode??t.response?.status;return Number.isSafeInteger(i)?Number(i):void 0})(e);return 0===n||408===n||409===n||425===n||429===n||void 0!==n&&n>=500};class es extends Error{constructor(e){super("Secure card tokenization may have completed, but its result could not be verified."),this.cause=e,this.code="elements_submit_indeterminate",this.name="BasisTheoryTokenizationIndeterminateError"}}const ts=[er,tr,ar],is=new Set(ts.map(({type:e})=>e)),ns=()=>new Error("The secure card field mount was cancelled."),os=(e,t)=>{const i=(e=>{if(!0===e.valid)return;const t=e.errors?.[0]?.type;return"incomplete"===t||"invalid"===t?t:void 0})(t),n="cardNumber"===e?"string"==typeof(o=t.cardBrand)&&is.has(o)?o:void 0:void 0;var o;return{complete:t.complete&&!0===t.valid,empty:t.empty,...n?{brand:n}:{},...i?{errorType:i}:{}}},rs=async(e,t,i)=>{const n=((e,t)=>{let i,n=!0,o=!1,r=!1;const s=()=>{if(!n||r||!o||!i)return;const s=((e,t)=>{const i=e.getBoundingClientRect(),n=t.getBoundingClientRect();return!(i.width<=0||i.height<=0)&&n.left<=i.left+1&&n.top<=i.top+1&&n.right+1>=i.right&&n.bottom+1>=i.bottom})(e,i);s&&(r=!0,t())},a="undefined"==typeof ResizeObserver?void 0:new ResizeObserver(()=>{s()});return a?.observe(e),{observeFrame:e=>{n&&(i!==e&&(i&&a?.unobserve(i),i=e,a?.observe(i)),Br(i.style,"width","100%"),Br(i.style,"height","100%"),Br(i.style,"display","block"),s())},providerReady:()=>{n&&!r&&(o=!0,s())},stop:()=>{n&&(n=!1,a?.disconnect())}}})(t.target,t.events.onReady),o=((e,t)=>{const i=e=>{e instanceof HTMLIFrameElement&&qr(e)&&t?.(e),(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("iframe").forEach(e=>{qr(e)&&t?.(e)})};i(e);const n=new MutationObserver(e=>{for(const t of e)"attributes"!==t.type?t.addedNodes.forEach(i):i(t.target)});n.observe(e,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["src"]});let o=!0;return()=>{o&&(o=!1,n.disconnect())}})(t.target,n.observeFrame),r={...t,events:{...t.events,onReady:n.providerReady}};let s=[];try{s=((e,t)=>{const i=[],n=(t,n)=>{i.push(e.on(t,n))};return n("ready",()=>t.events.onReady()),n("change",e=>{t.events.onChange(os(t.type,e))}),n("focus",()=>t.events.onFocus()),n("blur",()=>t.events.onBlur()),i})(e,r),await(async(e,t)=>{if(t.signal.aborted)throw ns();let i,n;const o=new Promise((e,t)=>{i=t}),r=()=>i?.(ns());t.signal.addEventListener("abort",r,{once:!0});const s=Promise.resolve().then(()=>e.mount(t.target)),a=new Promise((e,t)=>{n=globalThis.setTimeout(()=>t(new Error("Basis Theory secure card field mount timed out.")),8e3)});s.catch(()=>{});try{if(await Promise.race([s,o,a]),t.signal.aborted)throw ns()}finally{t.signal.removeEventListener("abort",r),void 0!==n&&globalThis.clearTimeout(n)}})(e,t)}catch(t){n.stop(),o(),s.forEach(e=>e.unsubscribe());try{e.unmount()}catch{}throw t}let a=!1;return{clear:()=>{a||e.clear()},focus:()=>{a||e.focus()},blur:()=>{a||e.blur()},update:async t=>{a||await e.update({...t,...t.style?{style:t.style}:{}})},destroy:()=>{if(!a){a=!0,i(),n.stop(),o(),s.forEach(e=>e.unsubscribe());try{e.unmount()}catch{}}}}},ss=e=>{if("string"!=typeof e)return;return e.trim()||void 0},as=(e,t,i)=>Number.isSafeInteger(e)&&Number(e)>=t&&Number(e)<=i?Number(e):void 0,ls=new Set(["bancontact","cartes_bancaires","dankort"]),cs={amex:"american_express",americanexpress:"american_express",cartesbancaires:"cartes_bancaires",dinersclub:"diners_club",master_card:"mastercard",unionpay:"union_pay"},ds=e=>{const t=ss(e)?.toLowerCase().replace(/[\s-]+/g,"_");return t?cs[t]??t:void 0},ps=e=>ss(e)?.toLowerCase(),hs=(e,t,i)=>{const n=ss(e.id);if(!n)throw new Error("Basis Theory returned no token identifier.");const o=e.card,r=(Array.isArray(o?.additional)?o.additional:[]).filter(e=>Boolean(e&&"object"==typeof e)),s=e=>r.map(e).find(e=>void 0!==e),a=ss(o?.last4),l=o?.issuerCountry?.alpha2,c=o?.issuer_country&&"object"==typeof o.issuer_country?o.issuer_country.alpha2:o?.issuer_country,d=ss(l??c??o?.issuer?.country??s(e=>{return(t=e.issuer_country??e.issuer?.country)&&"object"==typeof t?t.alpha2:t;var t})),p=ps(o?.funding)??s(e=>ps(e.funding)),h=ss(o?.issuer?.name)??s(e=>ss(e.issuer?.name)),u=as(o?.expirationMonth??o?.expiration_month,1,12),m=as(o?.expirationYear??o?.expiration_year,2e3,9999),{brand:y,displayBrand:g}=(e=>{const t=ds(e?.brand),i=Array.from(new Set((Array.isArray(e?.additional)?e.additional:[]).map(e=>ds(e?.brand)).filter(e=>Boolean(e)))),n=!!t&&ls.has(t),o=t&&!n?t:i.find(e=>!ls.has(e)),r=[t,...i].find(e=>e&&ls.has(e));return{brand:o,displayBrand:r??i.find(e=>e!==o)}})(o),f={...y?{brand:y}:{},...g?{display_brand:g}:{},...a&&/^\d{4}$/.test(a)?{last4:a}:{},...void 0===u?{}:{exp_month:u},...void 0===m?{}:{exp_year:m},...ss(e.fingerprint)?{fingerprint:ss(e.fingerprint)}:{},...ss(o?.bin)?{iin:ss(o?.bin)}:{},...p?{funding:p}:{},...h?{issuer:h}:{},...d?{country:d}:{},...ss(o?.segment)?.toLowerCase()?{segment:ss(o?.segment)?.toLowerCase()}:{},...i?{cardholder_name:i}:{}};return{instrumentToken:{type:t,id:n},..."sca_required"===o?.authentication||"sca_not_required"===o?.authentication?{authentication:o.authentication}:{},card:f}},us=async(e,t)=>{if("basis_theory_v2"!==e.driver)throw new Error("The configured card provider is not supported.");const i=await Kr({publicKey:e.publicKey,options:{...e.livemode?{}:{environment:"test"},useNetworkCheck:!0}},t.signal),n=new Map,o=async e=>{const t=((e,t)=>{if(!e)throw new Error("Basis Theory Elements did not initialize.");const i={targetId:t.target.id,inputMode:"numeric",placeholder:t.placeholder,style:t.style,validateOnChange:!0,"aria-label":t.ariaLabel};switch(t.type){case"cardNumber":return e.createElement("cardNumber",{...i,autoComplete:"cc-number",cardTypes:[...ts],iconPosition:"none"});case"cardExpiry":return e.createElement("cardExpirationDate",{...i,autoComplete:"cc-exp"});case"cardCvc":return e.createElement("cardVerificationCode",{...i,autoComplete:"cc-csc"})}})(i,e);n.set(e.type,t);try{return await rs(t,e,()=>{n.get(e.type)===t&&n.delete(e.type)})}catch(i){throw n.get(e.type)===t&&n.delete(e.type),i}};return{createField:async e=>{let t;for(let i=0;i<2;i+=1){if(e.signal.aborted)throw t??ns();try{return await o(e)}catch(n){if(t=n,e.signal.aborted||i+1===2)throw n}}throw t},createConfirmationData:async(e,t,o)=>{const r=n.get("cardNumber"),s=n.get("cardExpiry"),a=n.get("cardCvc");if(!r||!s||!a)throw new Error("The secure card fields are not ready.");const l={number:r,expiration_month:s.month(),expiration_year:s.year(),cvc:a,...t?{cardholderName:t}:{}},c=o?"token":"token_intent",d={type:"card",data:l},p={idempotencyKey:`paypercut-elements:${e}:card-tokenization`},h=await async function(e,t=e=>new Promise(t=>globalThis.setTimeout(t,e))){let i;for(let n=0;n<=Zr.length;n+=1)try{return await e()}catch(e){if(!Qr(e))throw e;i=e;const o=Zr[n];if(void 0===o)throw new es(i);await t(o)}throw new es(i)}(async()=>(e=>{if(!e||"object"!=typeof e||Array.isArray(e))throw new Xr;const t=e.id;if("string"!=typeof t||0===t.length||t.length>128||t!==t.trim()||Jr.test(t))throw new Xr;return e})(o?await i.tokens.create(d,p):await i.tokenIntents.create(d,p)));return hs(h,c,t)}}};const ms=["cardNumber","cardExpiry","cardCvc"];class ys extends Error{constructor(e,t){super(e.message),this.details=e,this.name="CardCollectionRuntimeError",void 0!==t&&(this.cause=t)}}const gs=()=>new ys({code:"elements_capability_unsupported",message:"Split card fields are not available for this payment configuration.",recoverable:!1}),fs=e=>e instanceof ys?e:new ys({code:"elements_provider_initialization_failed",message:"The secure card fields could not be initialized.",recoverable:!0},e),bs=e=>{if(!Number.isFinite(Date.parse(e.expiresAt))||Date.parse(e.expiresAt)<=Date.now())throw new ys({code:"elements_session_expired",message:"The secure card-field session has expired. Reload the payment form.",recoverable:!1});return e};class vs{constructor(e,t,i=(()=>us)()){this.compileAppearance=t,this.providerFactory=i,this.fields=new Map,this.bootstrapFailure=null,this.bootstrapWaiters=[],this.provider=null,this.providerPromise=null,this.providerAbortController=new AbortController,this.destroyed=!1,this.appearancePreviewGeneration=0,this.providerGenerationSequence=0,this.providerTargetIdSequence=0,this.providerTargetIds=new Set,this.pendingAppearancePreview=null,this.appearance=e}configure(e){if(this.destroyed||void 0!==this.bootstrap||this.bootstrapFailure)return;if(!(e=>(2===e?.protocolVersion||3===e?.protocolVersion)&&"messages"in e)(e))return void this.rejectBootstrap((e=>2!==e?.protocolVersion&&3!==e?.protocolVersion||!("error"in e)?gs():new ys(e.error))(e));this.bootstrap=e;const t=this.bootstrapWaiters;this.bootstrapWaiters=[],t.forEach(t=>t.resolve(e))}async resolveFieldCopy(e){if(this.destroyed)throw gs();const t=bs(await this.waitForBootstrap());return function(e,t,i){const n=t.card;switch(e){case"cardNumber":return{locale:i,ariaLabel:n.cardNumber,placeholder:n.cardNumberPlaceholder,errors:{...n.errors.number}};case"cardExpiry":return{locale:i,ariaLabel:n.expirationDate,placeholder:n.expirationDatePlaceholder,errors:{...n.errors.expirationDate}};case"cardCvc":return{locale:i,ariaLabel:n.securityCode,placeholder:n.cvvPlaceholder,errors:{...n.errors.cvv}}}}(e,t.messages,t.locale)}fail(e){this.destroyed||void 0!==this.bootstrap||this.bootstrapFailure||this.rejectBootstrap(new ys(e))}rejectBootstrap(e){this.bootstrapFailure=e;const t=this.bootstrapWaiters;this.bootstrapWaiters=[],t.forEach(t=>t.reject(e))}async mountField(e){if(this.destroyed)throw gs();if(this.fields.has(e.id))throw new Error("The secure card field is already mounted.");this.assignProviderTargetId(e.target,`paypercut-${e.type}-provider-${e.id}`);const t={id:e.id,type:e.type,target:e.target,providerHost:e.target,ariaLabel:e.ariaLabel,abortController:new AbortController,events:e.events,presentation:{...e.presentation},destroyed:!1,replacing:!1,providerField:null,providerGeneration:0,configurationRevision:0,updateRevision:0,updateChain:Promise.resolve(),pendingUpdate:null,providerReady:!1,lastChange:null};this.fields.set(e.id,t);try{const i=await this.getProvider();if(t.destroyed||this.fields.get(e.id)!==t)return;const n=t.configurationRevision,o=t.providerGeneration,r=await i.createField({type:e.type,target:e.target,signal:t.abortController.signal,style:this.compileAppearance(this.appearance,t.presentation),ariaLabel:e.ariaLabel,placeholder:t.presentation.placeholder,events:this.wrapEvents(t,o)});if(!this.isProviderGenerationCurrent(t,o))return void r.destroy();t.providerField=r,t.configurationRevision!==n&&(this.scheduleFieldUpdate(t,{placeholder:t.presentation.placeholder,style:this.compileAppearance(this.appearance,t.presentation)}),await t.updateChain),"cardCvc"===e.type&&this.numberBrand&&(this.scheduleFieldUpdate(t,{cardBrand:this.numberBrand}),await t.updateChain)}catch(i){if(this.destroyed)throw fs(i);if(!t.destroyed&&this.fields.get(e.id)===t)throw t.providerField?.destroy(),t.providerField=null,this.fields.delete(e.id),fs(i)}}command(e,t){const i=this.fields.get(e)?.providerField;if(!i)throw new Error("The secure card field is not ready.");i[t]()}updateFieldPresentation(e,t){if(this.destroyed)return;const i=this.fields.get(e);if(!i)return;i.presentation={...t},i.configurationRevision+=1;i.providerField&&this.scheduleFieldUpdate(i,{placeholder:t.placeholder,style:this.compileAppearance(this.appearance,t)})}destroyField(e){const t=this.fields.get(e);t&&(this.pendingAppearancePreview?.stages.some(e=>e.registration===t)&&this.cancelPendingAppearancePreview(new Error("A split card field was destroyed during Appearance Preview.")),t.destroyed=!0,t.providerGeneration+=1,t.replacing=!1,t.abortController.abort(),t.providerField?.destroy(),t.providerField=null,this.removeProviderHost(t),this.fields.delete(e))}updateAppearance(e){if(!this.destroyed){this.appearance=e;for(const t of this.fields.values()){t.configurationRevision+=1;t.providerField&&this.scheduleFieldUpdate(t,{style:this.compileAppearance(e,t.presentation)})}}}remountAppearance(e){return this.prepareAppearanceRemount(e).then(e=>e.commit())}prepareAppearanceRemount(e){if(this.destroyed)return Promise.reject(gs());this.cancelPendingAppearancePreview(new Error("A newer Appearance Preview superseded this replacement."));const t={generation:++this.appearancePreviewGeneration,appearance:be(e),stages:[]};this.pendingAppearancePreview=t;for(const e of this.fields.values())e.replacing=!0;return Promise.all(Array.from(this.fields.values()).map(e=>this.stageReplacementField(e,t))).then(e=>{if(this.pendingAppearancePreview!==t)throw new Error("A newer Appearance Preview superseded this replacement.");let i=!1;return{commit:()=>{if(!i&&this.pendingAppearancePreview===t){i=!0,this.appearance=t.appearance,this.numberBrand=void 0;for(const t of e)this.activateStagedField(t);this.pendingAppearancePreview=null}},rollback:()=>{if(!i){i=!0,this.pendingAppearancePreview===t&&(this.pendingAppearancePreview=null),this.discardStagedFields(t);for(const e of this.fields.values())e.replacing=!1}}}},e=>{this.pendingAppearancePreview===t&&(this.pendingAppearancePreview=null),this.discardStagedFields(t);for(const e of this.fields.values())e.replacing=!1;throw e})}getAppearanceRemountGeneration(){return this.appearancePreviewGeneration}cancelAppearanceRemount(e,t){this.pendingAppearancePreview?.generation===e&&this.cancelPendingAppearancePreview(t)}supportsDeveloperPresets(){return!1===this.bootstrap?.livemode}announceAppearanceCommit(){if(!this.destroyed)for(const e of this.fields.values())e.events.onChange(e.lastChange??{complete:!1,empty:!0})}canApplyDeveloperPreset(){return this.supportsDeveloperPresets()&&null!==this.resolveRequiredFields()}getSubmissionIssue(){const e=this.resolveRequiredFields();if(!e){return{type:ms.find(e=>!Array.from(this.fields.values()).some(t=>t.type===e&&null!==t.providerField&&t.providerReady))??"cardNumber",errorType:"incomplete"}}const t=e.find(e=>"invalid"===e.lastChange?.errorType);if(t)return{type:t.type,errorType:"invalid"};const i=e.find(e=>!0!==e.lastChange?.complete);return i?{type:i.type,errorType:"incomplete"}:null}assertCanSubmitPaymentMethod(){if(this.destroyed)throw gs();if(this.bootstrapFailure)throw this.bootstrapFailure;if(!this.bootstrap)throw new ys({code:"elements_not_ready",message:"The secure card fields are not ready yet.",recoverable:!0});const e=bs(this.bootstrap);if(3!==e.protocolVersion||!0!==e.capabilities.paymentMethodSubmission)throw new ys({code:"elements_capability_unsupported",message:"Split card-field submission is not supported by this Hosted Checkout version.",recoverable:!0});if(this.pendingAppearancePreview||Array.from(this.fields.values()).some(e=>e.replacing))throw new ys({code:"elements_not_ready",message:"The secure card fields are refreshing their Appearance.",recoverable:!0});const t=this.getSubmissionIssue();if(t)throw new ys({code:"invalid"===t.errorType?"elements_payment_details_invalid":"elements_card_fields_incomplete",message:"invalid"===t.errorType?"Some card details are invalid.":"Please complete your card details.",recoverable:!0})}async createConfirmationData(e,t,i){this.assertCanSubmitPaymentMethod();try{const n=await this.getProvider();return await n.createConfirmationData(e,t?.trim()||void 0,i)}catch(e){if(e instanceof ys)throw e;if(e instanceof es)throw new ys({code:"elements_submit_indeterminate",message:"Secure card tokenization may have completed, but its result could not be verified.",recoverable:!1},e);throw new ys({code:"elements_payment_method_creation_failed",message:"Payment details are temporarily unavailable. Please try again.",recoverable:!0},e)}}async applyDeveloperPreset(e){if(!this.supportsDeveloperPresets())throw new Error("Split-card test presets are unavailable for this payment configuration.");const t=this.resolveRequiredFields();if(!t)throw new Error("All three secure card fields must be ready before filling.");const i={cardNumber:e.number,cardExpiry:{month:e.expirationMonth,year:e.expirationYear},cardCvc:e.cvc},n=async()=>{await Promise.all(t.map(e=>this.enqueueDeveloperValueUpdate(e,i[e.type])))},o=()=>new Promise(e=>globalThis.setTimeout(e,150)),r=()=>t.every(e=>!0===e.lastChange?.complete);if(await n(),await o(),r()||(await n(),await o()),!r())throw new Error("The split-card test preset did not validate.")}resolveRequiredFields(){const e=ms.map(e=>Array.from(this.fields.values()).find(t=>t.type===e));return e.every(e=>null!==e?.providerField&&!0===e?.providerReady)?e:null}enqueueDeveloperValueUpdate(e,t){const i=e.providerField;if(!i||e.destroyed||this.destroyed||void 0===t)return Promise.reject(new Error("The secure card field is not ready."));const n=e.updateChain.catch(()=>{}).then(async()=>{if(this.destroyed||e.destroyed||e.providerField!==i)throw new Error("The secure card field is not ready.");await i.update({value:t})});return e.updateChain=n,n}scheduleFieldUpdate(e,t){const i=e.providerField;if(!i||e.destroyed||this.destroyed)return;e.pendingUpdate={...e.pendingUpdate,...t};const n=++e.updateRevision;e.updateChain=e.updateChain.catch(()=>{}).then(async()=>{if(this.destroyed||e.destroyed||e.providerField!==i||n!==e.updateRevision)return;const t=e.pendingUpdate;e.pendingUpdate=null,t&&await i.update(t)}).catch(()=>{this.destroyed||e.destroyed||e.providerField!==i||e.events.onError({code:"elements_provider_update_failed",message:"The secure card field could not be synchronized with the payment provider.",recoverable:!0})})}destroy(){if(this.destroyed)return;this.destroyed=!0,this.cancelPendingAppearancePreview(new Error("The secure card fields were destroyed during Appearance Preview.")),this.providerAbortController.abort();for(const e of this.fields.values())e.destroyed=!0,e.abortController.abort(),e.providerField?.destroy(),this.removeProviderHost(e);this.fields.clear(),this.provider=null,this.providerPromise=null;const e=new ys({code:"elements_destroyed",message:"The secure card fields were destroyed before initialization completed.",recoverable:!1});this.bootstrapWaiters.forEach(t=>t.reject(e)),this.bootstrapWaiters=[]}wrapEvents(e,t){const i=e.events;return{...i,onReady:()=>{this.isProviderGenerationCurrent(e,t)&&(e.providerReady=!0,e.replacing=!1,i.onReady())},onChange:n=>{this.isProviderGenerationCurrent(e,t)&&(e.lastChange=n,"cardNumber"===e.type&&this.updateCardBrand(n.brand),i.onChange(n))},onFocus:()=>{this.isProviderGenerationCurrent(e,t)&&i.onFocus()},onBlur:()=>{this.isProviderGenerationCurrent(e,t)&&i.onBlur()},onError:n=>{this.isProviderGenerationCurrent(e,t)&&i.onError(n)}}}stageReplacementField(e,t){const i=new AbortController,n=this.createStagingTarget(e);let o,r;const s=new Promise((e,t)=>{o=e,r=t});this.providerGenerationSequence=Math.max(this.providerGenerationSequence+1,e.providerGeneration+1);const a={registration:e,providerGeneration:this.providerGenerationSequence,abortController:i,target:n,providerField:null,ready:!1,activated:!1,lastChange:null,reject:()=>{}};let l=!1;const c=setTimeout(()=>{a.reject(new Error("A split card field did not become ready for Appearance Preview."))},15e3);a.reject=e=>{l||(l=!0,clearTimeout(c),r(e))},t.stages.push(a);const d=()=>{!l&&a.providerField&&a.ready&&(l=!0,clearTimeout(c),o(a))},p={onReady:()=>{this.pendingAppearancePreview===t&&(a.ready=!0,a.activated?e.events.onReady():d())},onChange:i=>{(this.pendingAppearancePreview===t||a.activated)&&(a.activated?this.isProviderGenerationCurrent(e,a.providerGeneration)&&(e.lastChange=i,"cardNumber"===e.type&&this.updateCardBrand(i.brand),e.events.onChange(i)):a.lastChange=i)},onFocus:()=>{a.activated&&this.isProviderGenerationCurrent(e,a.providerGeneration)&&e.events.onFocus()},onBlur:()=>{a.activated&&this.isProviderGenerationCurrent(e,a.providerGeneration)&&e.events.onBlur()},onError:i=>{a.activated?this.isProviderGenerationCurrent(e,a.providerGeneration)&&e.events.onError(i):this.pendingAppearancePreview===t&&a.reject(new Error(i.message))}};return this.getProvider().then(async o=>{if(this.pendingAppearancePreview===t)try{const r=await o.createField({type:e.type,target:n,signal:i.signal,style:this.compileAppearance(t.appearance,e.presentation),ariaLabel:e.ariaLabel,placeholder:e.presentation.placeholder,events:p});if(this.pendingAppearancePreview!==t)return void r.destroy();a.providerField=r,d()}catch(e){a.reject(e instanceof Error?e:new Error("Appearance replacement failed."))}},e=>a.reject(e instanceof Error?e:new Error("Appearance replacement failed."))),s}activateStagedField(e){const t=e.registration,i=t.providerField,n=t.providerHost;t.configurationRevision+=1,t.updateRevision+=1,t.pendingUpdate=null,t.updateChain=Promise.resolve(),t.abortController.abort(),t.abortController=e.abortController,t.providerGeneration=e.providerGeneration,t.providerField=e.providerField,t.providerReady=!0,t.replacing=!1,t.lastChange=e.lastChange??{complete:!1,empty:!0},e.activated=!0;try{i?.destroy()}catch{}n!==t.target&&n.remove(),this.activateStagingTarget(e.target,t.target),t.providerHost=e.target}createStagingTarget(e){const t=e.target;if("undefined"==typeof document||"function"!=typeof document.createElement||"function"!=typeof t.appendChild)return t;const i=document.createElement("div");return this.assignProviderTargetId(i,`${t.id}-appearance-preview-${this.appearancePreviewGeneration}`),i.dataset.paypercutAppearanceStage="",Object.assign(i.style,{position:"absolute",inset:"0",width:"100%",height:"100%",visibility:"hidden",pointerEvents:"none"}),t.appendChild(i),i}assignProviderTargetId(e,t){let i=e.id.trim()||t;for(;!i||this.providerTargetIds.has(i);)i=`${t}-${++this.providerTargetIdSequence}`;e.id=i,this.providerTargetIds.add(i)}activateStagingTarget(e,t){e!==t&&(e.removeAttribute?.("data-paypercut-appearance-stage"),Object.assign(e.style,{position:"relative",inset:"auto",width:"100%",height:"100%",visibility:"visible",pointerEvents:"auto"}))}removeProviderHost(e){e.providerHost!==e.target&&e.providerHost.remove(),e.providerHost=e.target}discardStagedFields(e){for(const t of e.stages)t.abortController.abort(),t.providerField?.destroy(),t.target!==t.registration.target&&t.target.remove()}cancelPendingAppearancePreview(e){const t=this.pendingAppearancePreview;if(t){this.pendingAppearancePreview=null,this.discardStagedFields(t);for(const i of t.stages)i.reject(e);for(const e of this.fields.values())e.replacing=!1}}isProviderGenerationCurrent(e,t){return!this.destroyed&&!e.destroyed&&this.fields.get(e.id)===e&&e.providerGeneration===t}updateCardBrand(e){if(e!==this.numberBrand){this.numberBrand=e;for(const t of this.fields.values())"cardCvc"===t.type&&t.providerField&&e&&this.scheduleFieldUpdate(t,{cardBrand:e})}}async getProvider(){if(this.destroyed)throw gs();return this.provider?this.provider:(this.providerPromise||(this.providerPromise=this.waitForBootstrap().then(bs).then(e=>this.providerFactory(e,{signal:this.providerAbortController.signal})).then(e=>{if(this.destroyed)throw gs();return this.provider=e,e}).catch(e=>{throw this.providerPromise=null,fs(e)})),this.providerPromise)}waitForBootstrap(){return this.bootstrapFailure?Promise.reject(this.bootstrapFailure):this.bootstrap?Promise.resolve(this.bootstrap):new Promise((e,t)=>{this.bootstrapWaiters.push({resolve:e,reject:t})})}}class ws{constructor(e,t){this.runtime=e,this.context=t,this.submissionSourceId=j(),this.tokenizations=new Map,this.destroyed=!1,this.activeRequestId=null,this.canceledRequests=new Set}validatePaymentMethod(){try{return this.assertCanSubmitPaymentMethod(),Promise.resolve()}catch(e){return Promise.reject(e)}}assertCanSubmitPaymentMethod(){if(this.destroyed||this.context.isDestroyed())throw new ys({code:"elements_destroyed",message:"The split card fields have been destroyed.",recoverable:!1});const e=this.runtime.getSubmissionIssue();e&&this.context.revealCardFieldSubmissionError(e.type,e.errorType);try{this.runtime.assertCanSubmitPaymentMethod()}catch(e){if(e instanceof ys)throw vn(e.details.code,e.details.message,e.details.recoverable??!0);throw e}}beginPaymentMethodSubmission(e,t,i,n){this.activeRequestId=e,this.activeFutureUsage=i,this.activeBillingDetails=n,this.canceledRequests.delete(e),this.context.onCardCollectionSubmissionStateChange(),n?this.context.submitCardCollection(this.submissionSourceId,e,t,n):this.context.submitCardCollection(this.submissionSourceId,e,t)}cancelPaymentMethodSubmission(e,t){this.tokenizations.has(e)?this.canceledRequests.add(e):this.canceledRequests.delete(e),this.activeRequestId===e&&(this.activeRequestId=null,this.activeFutureUsage=void 0,this.activeBillingDetails=void 0),this.tokenizations.delete(e),this.context.cancelCardCollectionSubmission(this.submissionSourceId,e,t)}attachPaymentMethodActionChannel(e,t,i){this.context.attachCardCollectionActionChannel(this.submissionSourceId,e,t,i)}onPaymentMethodSubmissionStateChange(){this.context.onCardCollectionSubmissionStateChange()}handleTokenizationRequest(e,t){if(this.destroyed||this.activeRequestId!==e||this.canceledRequests.has(e))return;if(this.activeFutureUsage!==t)return;if(this.tokenizations.has(e))return;const i=this.runtime.createConfirmationData(e,this.activeBillingDetails?.name,t).then(e=>({status:"succeeded",confirmationData:e}),e=>e instanceof ys?{status:"failed",code:e.details.code,message:e.details.message,recoverable:e.details.recoverable??!0}:{status:"failed",code:"elements_payment_method_creation_failed",message:"Payment details are temporarily unavailable. Please try again.",recoverable:!0});this.tokenizations.set(e,i),i.then(t=>{this.tokenizations.delete(e),this.destroyed||this.canceledRequests.delete(e)||this.activeRequestId===e&&(this.activeRequestId=null,this.activeFutureUsage=void 0,this.activeBillingDetails=void 0,this.context.sendCardCollectionTokenizationResult({channel:Ce,type:Me,controllerId:this.context.controllerId,componentId:this.submissionSourceId,componentType:"card_collection",requestId:e,result:t}))})}destroy(){this.destroyed||(this.destroyed=!0,this.activeRequestId=null,this.activeFutureUsage=void 0,this.activeBillingDetails=void 0,this.tokenizations.clear(),this.canceledRequests.clear())}}class Ps extends Error{constructor(e,t,i){super(t),this.code=e,this.name="AppearancePreviewError",void 0!==i&&(this.cause=i)}}const Es=(e,t,i)=>Object.assign(new Error(t),{code:e,recoverable:i});class As{constructor(e,t,i){if(this.clientOptions=e,this.elementsOptions=t,this.configurationIdentity=i,this.controllerId=j(),this.elements=new Map,this.cardFields=new Map,this.pendingComponents=new Map,this.controllerIframe=null,this.controlPort=null,this.controllerInitialized=!1,this.controllerBootstrapped=!1,this.destroyed=!1,this.appearancePreview=null,this.appearancePreviewGeneration=0,this.appearanceLocked=!1,this.warnedAboutSkippedAppearance=!1,this.updateRevision=0,this.validationRevision=0,this.validatedSource=null,this.pendingValidation=null,this.walletAttemptOverlay=new vo,this.splitCardDeveloperAssistant=null,this.windowMessageHandler=e=>this.onWindowMessage(e),this.hostedOrigin=function(){try{return new URL(r()).origin}catch{throw new Error("[Paypercut Elements] The configured hosted checkout URL is invalid.")}}(e.hostedCheckoutUrl),this.amount=t.amount,t.appearance&&fe(t.appearance),this.appearance=be(t.appearance),this.cardCollectionRuntime=new vs(this.appearance,_o),this.cardCollectionSubmissionSource=new ws(this.cardCollectionRuntime,this),this.paymentMethodSubmission=new fn(this.hostedOrigin),!o(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("card"===e){if(this.cardFields.size>0)throw Es("elements_component_conflict","A Card Element and split card fields cannot share one Elements group.",!1);if(Array.from(this.elements.values()).some(e=>"card"===e.componentType))throw Es("elements_component_conflict","Only one Card Element may be created in an Elements group.",!0);const e=new En(this);return this.elements.set(e.componentId,e),e}if("expressCheckout"===e){const e=new Vn(this,t);return this.elements.set(e.componentId,e),e}if("cardNumber"===e||"cardExpiry"===e||"cardCvc"===e){if("cardNumber"!==e&&void 0!==t)throw Es("elements_component_configuration_invalid",`${e} does not accept creation options.`,!0);if(Array.from(this.elements.values()).some(e=>"card"===e.componentType))throw Es("elements_component_conflict","Split card fields and a Card Element cannot share one Elements group.",!1);if(this.cardFields.has(e))throw Es("elements_card_field_duplicate",`Only one ${e} field may be created in an Elements group.`,!0);const i=new No(e,this,"cardNumber"===e?(e=>{if(void 0===e)return{};if(!e||"object"!=typeof e||Array.isArray(e))throw Es("elements_component_configuration_invalid","Card number Element options must be an object.",!0);const t=e;if(Object.keys(t).some(e=>"showIcon"!==e))throw Es("elements_component_configuration_invalid","Card number Element options contain an unsupported property.",!0);if(void 0!==t.showIcon&&"boolean"!=typeof t.showIcon)throw Es("elements_component_configuration_invalid","Card number Element showIcon must be a boolean.",!0);return void 0===t.showIcon?{}:{showIcon:t.showIcon}})(t):void 0);return this.cardFields.set(e,i),this.elements.set(i.componentId,i),this.ensureSplitCardDeveloperAssistant(),i}throw new Error(`[Paypercut Elements] Unsupported Element type: ${String(e)}`)}submit(){if(this.appearancePreview)return Promise.reject(this.appearancePreviewNotReadyError());let e;try{e=this.resolvePaymentMethodSource()}catch(e){return Promise.reject(e)}const t=this.paymentMethodSubmission.getIndeterminateAttemptError();if(t)return Promise.reject(t);const i=this.validationRevision;if(this.validatedSource?.sourceId===e.submissionSourceId&&this.validatedSource.revision===i)return Promise.resolve();if(this.pendingValidation?.sourceId===e.submissionSourceId&&this.pendingValidation.revision===i)return this.pendingValidation.promise;const n=e.validatePaymentMethod().then(()=>{if(this.destroyed)throw vn("elements_destroyed","The Elements group has been destroyed.",!1);if(i!==this.validationRevision)throw vn("elements_submit_required","Payment details changed while they were being validated. Submit the Elements group again.",!0);this.validatedSource={sourceId:e.submissionSourceId,revision:i}});return this.pendingValidation={sourceId:e.submissionSourceId,revision:i,promise:n},n.then(()=>{this.pendingValidation?.promise===n&&(this.pendingValidation=null)},()=>{this.pendingValidation?.promise===n&&(this.pendingValidation=null)}),n}createPaymentMethod(e){if(this.appearancePreview)return Promise.reject(this.appearancePreviewNotReadyError());let t;try{t=this.resolvePaymentMethodSource()}catch(e){return Promise.reject(e)}const i=this.paymentMethodSubmission.getIndeterminateAttemptError();if(i)return Promise.reject(i);if(this.validatedSource?.sourceId!==t.submissionSourceId||this.validatedSource.revision!==this.validationRevision){try{t.assertCanSubmitPaymentMethod()}catch(e){if(function(e,t){return le(e)&&e.code===t}(e,"elements_not_ready"))return Promise.reject(e)}return Promise.reject(vn("elements_submit_required","Call elements.submit() after the latest payment-details change before creating a Payment Method.",!0))}return this.paymentMethodSubmission.submit(t,this.elementsOptions.setupFutureUsage,e)}resolvePaymentMethodSource(){if(this.destroyed)throw vn("elements_destroyed","The Elements group has been destroyed.",!1);const e=Array.from(this.elements.values()).filter(e=>e instanceof En);if(e.length>1)throw vn("elements_component_conflict","More than one active payment-method source is mounted in this Elements group.",!0);if(1===e.length)return e[0];if(this.cardFields.size>0)return this.cardCollectionSubmissionSource;throw vn("elements_not_mounted","Create and mount a payment-method Element before submitting.",!0)}getClientOptions(){return{...this.clientOptions}}getElementsOptions(){return this.serializeElementsOptions(this.appearance)}getRenderableElementsOptions(){return this.serializeElementsOptions(this.appearancePreview?.appearance??this.appearance)}serializeElementsOptions(e){return{...this.elementsOptions,amount:this.amount,...e?{appearance:be(e)}:{}}}markComponentMounted(){this.appearanceLocked=!0}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=Ii(function(e){const t=new URLSearchParams;return Ti(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),t.set("cardCollectionProtocol",String(3)),ki("/elements/controller",e.hostedOrigin,t)}({hostedOrigin:this.hostedOrigin,controllerId:this.controllerId,clientOptions:this.clientOptions,elementsOptions:this.getElementsOptions(),sdkVersion:n.version,referrer:window.location.origin}),j()),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()}reattachComponent(e,t){!this.destroyed&&this.elements.has(e.componentId)?(this.invalidateSubmissionValidation(),this.paymentMethodSubmission.reinitializeSource(e instanceof En?e.submissionSourceId:e.componentId),this.detachComponent(e),this.pendingComponents.set(e.componentId,{element:e,port:t}),this.flushPendingComponents()):t.close()}submitComponent(e,t,i,n){const o={channel:Ce,type:xe,controllerId:this.controllerId,componentId:e,componentType:"card",requestId:t,deadlineAt:i,...n?{billingDetails:n}:{}};this.postControl(o)}validateComponent(e,t){const i={channel:Ce,type:Oe,controllerId:this.controllerId,componentId:e,componentType:"card",requestId:t};this.postControl(i)}invalidateSubmissionValidation(){this.validatedSource=null,this.validationRevision<Number.MAX_SAFE_INTEGER&&(this.validationRevision+=1)}submitCardCollection(e,t,i,n){const o={channel:Ce,type:xe,controllerId:this.controllerId,componentId:e,componentType:"card_collection",requestId:t,deadlineAt:i,...n?{billingDetails:n}:{}};this.postControl(o)}cancelCardCollectionSubmission(e,t,i="canceled"){const n={channel:Ce,type:Le,controllerId:this.controllerId,componentId:e,componentType:"card_collection",requestId:t,reason:i};this.postControl(n)}cancelComponentSubmission(e,t,i="canceled"){const n=this.elements.get(e);if(!n)return;const o={channel:Ce,type:Le,controllerId:this.controllerId,componentId:e,componentType:n.componentType,requestId:t,reason:i};this.postControl(o)}beginWalletAttempt(e,t,i,n){const o=this.elements.get(e);return!(!o||"express_checkout"!==o.componentType)&&this.walletAttemptOverlay.show(e,t,i,()=>this.cancelComponentSubmission(e,t),n)}hideWalletAttemptOverlay(e,t){this.walletAttemptOverlay.hide(e,t)}markWalletAttemptProcessing(e,t,i){this.walletAttemptOverlay.setPhase(e,t,i,"processing")}endWalletAttempt(e,t){this.walletAttemptOverlay.close(e,t)}attachActionChannel(e,t,i,n){const o=this.elements.get(e);if(!o)return void n.close();const r={channel:Ce,type:De,controllerId:this.controllerId,componentId:e,componentType:o.componentType,requestId:t,actionId:i};this.postControl(r,[n])}attachCardCollectionActionChannel(e,t,i,n){const o={channel:Ce,type:De,controllerId:this.controllerId,componentId:e,componentType:"card_collection",requestId:t,actionId:i};this.postControl(o,[n])}sendCardCollectionTokenizationResult(e){this.postControl(e)}revealCardFieldSubmissionError(e,t){this.cardFields.get(e)?.revealSubmissionError(t)}onCardCollectionSubmissionStateChange(){this.splitCardDeveloperAssistant?.collapse(),this.splitCardDeveloperAssistant?.refresh()}hasPaymentMethodSubmissionState(e){return this.paymentMethodSubmission.hasActiveSubmission(e)}hasCompletedPaymentMethodSubmission(e){return this.paymentMethodSubmission.hasCompletedSubmission(e)}sendApplePayCapabilities(e,t){const i={channel:Ce,type:Ue,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",available:t};this.postControl(i)}sendApplePayValidateMerchant(e,t,i){const n={channel:Ce,type:qe,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,validationUrl:i};this.postControl(n)}sendApplePayAuthorized(e,t,i){const n={channel:Ce,type:Be,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,payment:i};this.postControl(n)}sendApplePayCanceled(e,t){const i={channel:Ce,type:je,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t};this.postControl(i)}sendGooglePayCapabilities(e,t){const i={channel:Ce,type:He,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",available:t};this.postControl(i)}sendGooglePayClick(e,t){const i={channel:Ce,type:Ge,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t};this.postControl(i)}sendGooglePayDataChanged(e,t,i,n){const o={channel:Ce,type:We,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,updateId:i,dataJson:n};this.postControl(o)}sendGooglePayAuthorized(e,t,i){const n={channel:Ce,type:Ve,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,dataJson:i};this.postControl(n)}sendGooglePayPaymentData(e,t,i){const n={channel:Ce,type:$e,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,dataJson:i};this.postControl(n)}sendGooglePayCanceled(e,t){const i={channel:Ce,type:Ye,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t};this.postControl(i)}sendGooglePayError(e,t,i,n){const o={channel:Ce,type:Ke,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,code:i,message:n};this.postControl(o)}resolveWalletClick(e,t,i,n,o){i&&void 0!==o&&this.commitAmountUpdate(o);const r=this.getUpdateSnapshot().options,s={channel:Ce,type:Ze,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,accepted:i,...n?{options:n}:{},amount:r.amount,currency:r.currency};this.postControl(s)}resolveWalletUpdate(e,t,i,n,o){const r=this.getUpdateSnapshot().options,{amount:s=r.amount,...a}=o??{},l=Object.keys(a).length>0,c={channel:Ce,type:Je,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,updateId:i,accepted:n,...l?{update:a}:{},amount:s,currency:r.currency};this.postControl(c)}resolveWalletConfirmation(e,t,i,n){const o={channel:Ce,type:Xe,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,succeeded:i,...n?{error:n}:{}};this.postControl(o)}updateExpressCheckoutComponent(e,t,i){const n=this.elements.get(e);if(!n||"express_checkout"!==n.componentType)return;if(!this.controllerInitialized)return;const o={channel:Ce,type:Qe,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",componentRevision:t,componentOptions:i};this.postControl(o)}discoverDeveloperPresets(e){if(!0!==this.clientOptions.developerAssistant)return;const t={channel:Ce,type:Ne,controllerId:this.controllerId,componentId:e,componentType:"card"};this.postControl(t)}applyDeveloperPreset(e,t,i){const n={channel:Ce,type:ze,controllerId:this.controllerId,componentId:e,componentType:"card",requestId:t,presetId:i};this.postControl(n)}commandCardField(e,t,i){const n=this.elements.get(e);if(!n||n.componentType!==t)throw new Error("[Paypercut Elements] The secure card field is unavailable.");this.cardCollectionRuntime.command(e,i)}mountCardField(e){return this.ensureController(),this.cardCollectionRuntime.mountField(e)}resolveCardFieldCopy(e){return this.ensureController(),this.cardCollectionRuntime.resolveFieldCopy(e)}updateCardFieldPresentation(e,t){this.cardCollectionRuntime.updateFieldPresentation(e,t)}onCardFieldAvailabilityChange(){this.invalidateSubmissionValidation(),this.splitCardDeveloperAssistant?.refresh()}onCardFieldValueChange(){this.invalidateSubmissionValidation()}destroyCardField(e){this.cardCollectionRuntime.destroyField(e)}getUpdateSnapshot(){const e=this.appearancePreview?.appearance??this.appearance;return{updateRevision:this.updateRevision,options:Is(this.elementsOptions,this.amount,e)}}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){try{return this.applyUpdate({appearance:e}).catch(e=>{throw e instanceof Ps&&this.warnAppearancePreview(e),e})}catch(e){return e instanceof Ps&&this.warnAppearancePreview(e),Promise.reject(e)}}prepareAppearance(e){return this.prepareAppearanceCandidate(()=>Ss({appearance:e},this.appearance,this.amount).appearance)}prepareAppearanceReplacement(e){return this.prepareAppearanceCandidate(()=>(fe(e),be(e)))}prepareAppearanceCandidate(e){if(!this.isAppearancePreviewAvailable())return Promise.reject(new Ps("elements_appearance_preview_refused","Appearance Preview is unavailable while payment validation, Card authentication, or a wallet attempt is active."));const t=e();return this.clearAppearancePreviewFailures(),ve(t,this.appearance)?Promise.resolve({isCurrent:()=>!0,commit:()=>{},rollback:()=>Promise.resolve()}):this.startAppearancePreview(t,!0)}replaceAppearance(e){if(!this.isAppearancePreviewAvailable())return Promise.reject(new Ps("elements_appearance_preview_refused","Appearance Preview is unavailable while payment validation, Card authentication, or a wallet attempt is active."));fe(e);const t=be(e);return ve(t,this.appearance)?Promise.resolve():this.startAppearancePreview(t).then(()=>{})}isAppearancePreviewAvailable(){return!this.destroyed&&null===this.pendingValidation&&!this.paymentMethodSubmission.hasActiveSubmission()&&!Array.from(this.elements.values()).some(e=>e.hasActiveSubmission())}update(e){try{this.applyUpdate(e).catch(e=>{e instanceof Ps&&this.warnAppearancePreview(e)})}catch(e){if(e instanceof Ps)return void this.warnAppearancePreview(e);throw e}}applyUpdate(e){if(this.destroyed)throw new Error("[Paypercut Elements] Cannot update a destroyed group.");const t=Array.from(this.elements.values()).some(e=>e.hasActiveSubmission()),i=Array.from(this.elements.values()).some(e=>"express_checkout"===e.componentType?e.hasActiveProviderSubmission():e.hasActiveSubmission());if(null!==this.pendingValidation||this.paymentMethodSubmission.hasActiveSubmission()||(void 0!==e.appearance?t:i)){if(void 0!==e.appearance)throw new Ps("elements_appearance_preview_refused","Appearance Preview is unavailable while payment validation, Card authentication, or a wallet attempt is active.");throw Es("elements_submission_in_progress","[Paypercut Elements] Cannot update Elements while payment details are being submitted.",!0)}const n=Ss(e,this.appearance,this.amount),o=void 0!==e.appearance,r="remount"===this.elementsOptions.appearanceUpdates||!0===this.clientOptions.developerAssistant,s=this.hasMountedCardFields()||this.getMountedCardElements().length>0||this.getMountedExpressCheckoutElements().length>0,a=o&&this.appearanceLocked&&r&&s;o&&r&&this.clearAppearancePreviewFailures();o&&this.appearanceLocked&&!a&&(n.appearance=this.appearance,this.warnAboutSkippedAppearance());const l=!ve(n.appearance,this.appearance);if(n.amount===this.amount&&!l)return Promise.resolve();if(!l)return this.commitAmountUpdate(n.amount),Promise.resolve();if(this.updateRevision===Number.MAX_SAFE_INTEGER)throw new Error("[Paypercut Elements] The update revision limit has been reached.");if(this.amount=n.amount,l){if(a)return this.startAppearancePreview(n.appearance).then(()=>{});this.appearance=n.appearance,this.cardCollectionRuntime.updateAppearance(this.appearance);for(const e of this.cardFields.values())e.updateAppearance(this.appearance);this.splitCardDeveloperAssistant?.refresh()}if(this.invalidateSubmissionValidation(),this.updateRevision+=1,!this.controllerInitialized)return Promise.resolve();const c=this.getUpdateSnapshot(),d={channel:Ce,type:Fe,controllerId:this.controllerId,updateRevision:c.updateRevision,options:c.options};return this.postControl(d),Promise.resolve()}commitAmountUpdate(e){if(e===this.amount)return;if(this.updateRevision===Number.MAX_SAFE_INTEGER)throw new Error("[Paypercut Elements] The update revision limit has been reached.");if(this.amount=e,this.invalidateSubmissionValidation(),this.updateRevision+=1,!this.controllerInitialized)return;const t=this.getUpdateSnapshot();this.postControl({channel:Ce,type:Fe,controllerId:this.controllerId,updateRevision:t.updateRevision,options:t.options})}startAppearancePreview(e,t=!1){const i=++this.appearancePreviewGeneration,n=be(this.appearance),o=be(e);if(this.appearancePreview={generation:i,appearance:o},this.invalidateSubmissionValidation(),this.updateRevision+=1,this.controllerInitialized){const e=this.getUpdateSnapshot();this.postControl({channel:Ce,type:Fe,controllerId:this.controllerId,updateRevision:e.updateRevision,options:e.options})}return this.prepareMountedAppearanceTransitions(o).then(e=>{if(this.appearancePreview?.generation!==i)throw e.forEach(e=>e.rollback()),new Ps("elements_appearance_preview_superseded","A newer Appearance Preview replaced this request.");if(t)return{isCurrent:()=>this.appearancePreview?.generation===i,commit:()=>{e.forEach(e=>e.commit()),this.commitAppearancePreview(i,o)},rollback:async()=>{e.forEach(e=>e.rollback()),await this.restoreAppearancePreview(i,n)}};e.forEach(e=>e.commit()),this.commitAppearancePreview(i,o)},async e=>{if(this.appearancePreview?.generation!==i)throw new Ps("elements_appearance_preview_superseded","A newer Appearance Preview replaced this request.",e);throw await this.restoreAppearancePreview(i,n),new Ps("elements_appearance_preview_failed","Appearance Preview failed; the last successfully applied Appearance remains active.",e)})}async prepareMountedAppearanceTransitions(e){const t=[],i=[];if(this.hasMountedCardFields()){for(const e of this.cardFields.values())e.beginAppearanceTransition();t.push(this.cardCollectionRuntime.prepareAppearanceRemount(e));const n=this.cardCollectionRuntime.getAppearanceRemountGeneration();i.push(e=>this.cardCollectionRuntime.cancelAppearanceRemount(n,e))}for(const e of this.getMountedCardElements()){t.push(e.remountAppearance());const n=e.componentGeneration;i.push(t=>e.cancelAppearanceRemount(n,t))}for(const e of this.getMountedExpressCheckoutElements()){t.push(e.remountAppearance());const n=e.componentGeneration;i.push(t=>e.cancelAppearanceRemount(n,t))}try{return await Promise.all(t)}catch(e){const n=new Error("The coordinated Appearance Preview was cancelled.");i.forEach(e=>e(n));const o=await Promise.allSettled(t);for(const e of o)"fulfilled"===e.status&&e.value.rollback();throw e}}commitAppearancePreview(e,t){if(this.appearancePreview?.generation!==e)throw new Ps("elements_appearance_preview_superseded","A newer Appearance Preview replaced this request.");this.appearance=be(t),this.appearancePreview=null;for(const e of this.cardFields.values())e.updateAppearance(this.appearance);this.cardCollectionRuntime.announceAppearanceCommit();for(const e of this.cardFields.values())e.announceAppearanceReady();this.splitCardDeveloperAssistant?.refresh()}async restoreAppearancePreview(e,t){if(this.appearancePreview?.generation===e){this.appearancePreview={generation:e,appearance:be(t)},this.updateRevision+=1,this.postAppearancePreviewOptions();try{const i=await this.prepareMountedAppearanceTransitions(t);if(this.appearancePreview?.generation!==e)return void i.forEach(e=>e.rollback());i.forEach(e=>e.commit())}catch(t){if(this.appearancePreview?.generation===e){this.appearancePreview=null;for(const e of this.cardFields.values())e.updateAppearance(this.appearance);this.cardCollectionRuntime.announceAppearanceCommit();for(const e of this.cardFields.values())e.announceAppearanceReady();for(const e of this.getMountedCardElements())e.markAppearanceRecoveryFailed();for(const e of this.getMountedExpressCheckoutElements())e.markAppearanceRecoveryFailed();this.splitCardDeveloperAssistant?.refresh()}throw t}if(this.appearancePreview?.generation===e){this.appearancePreview=null;for(const e of this.cardFields.values())e.updateAppearance(this.appearance);this.cardCollectionRuntime.announceAppearanceCommit();for(const e of this.cardFields.values())e.announceAppearanceReady();this.splitCardDeveloperAssistant?.refresh()}}}postAppearancePreviewOptions(){if(!this.controllerInitialized)return;const e=this.getUpdateSnapshot();this.postControl({channel:Ce,type:Fe,controllerId:this.controllerId,updateRevision:e.updateRevision,options:e.options})}getMountedCardElements(){return Array.from(this.elements.values()).filter(e=>e instanceof En&&e.isMounted())}getMountedExpressCheckoutElements(){return Array.from(this.elements.values()).filter(e=>e instanceof Vn&&e.isMounted())}clearAppearancePreviewFailures(){if(null===this.appearancePreview)for(const e of this.getMountedCardElements())e.clearAppearancePreviewFailure()}hasMountedCardFields(){return Array.from(this.cardFields.values()).some(e=>e.isMounted())}hasVisibleCardFields(){return Array.from(this.cardFields.values()).some(e=>e.isVisible())}warnAppearancePreview(e){"elements_appearance_preview_superseded"!==e.code&&console.warn(`[Paypercut Elements] ${e.code}: ${e.message}`)}appearancePreviewNotReadyError(){return vn("elements_not_ready","Payment details are refreshing their Appearance.",!0)}warnAboutSkippedAppearance(){this.warnedAboutSkippedAppearance||(this.warnedAboutSkippedAppearance=!0,console.warn("[Paypercut Elements] elements_appearance_locked: Appearance is locked after the first Element mounts. Configure Appearance during initialization."))}isDestroyed(){return this.destroyed}remove(e){this.invalidateSubmissionValidation(),e instanceof En&&this.paymentMethodSubmission.releaseSource(e.submissionSourceId),this.detachComponent(e),this.elements.delete(e.componentId),e instanceof No&&this.cardFields.get(e.type)===e&&(this.cardFields.delete(e.type),this.paymentMethodSubmission.releaseSource(this.cardCollectionSubmissionSource.submissionSourceId),0===this.cardFields.size&&this.unregisterSplitCardDeveloperAssistant())}detachComponent(e){if(e instanceof No)return void this.cardCollectionRuntime.destroyField(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:Ce,type:ke,controllerId:this.controllerId,componentId:e.componentId,componentType:e.componentType};try{this.controlPort.postMessage(t)}catch{}}}destroy(){if(!this.destroyed){this.destroyed=!0,this.paymentMethodSubmission.destroy(),this.cardCollectionSubmissionSource.destroy(),this.unregisterSplitCardDeveloperAssistant();for(const e of Array.from(this.elements.values()))e.destroy();this.elements.clear(),this.cardFields.clear(),this.cardCollectionRuntime.destroy();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)}}ensureSplitCardDeveloperAssistant(){!this.splitCardDeveloperAssistant&&!0===this.clientOptions.developerAssistant&&0!==this.cardFields.size&&this.cardCollectionRuntime.supportsDeveloperPresets()&&"undefined"!=typeof window&&"undefined"!=typeof document&&(this.splitCardDeveloperAssistant=Ci({id:`${this.controllerId}:split-card-fields`,configurationIdentity:this.configurationIdentity,appearanceScopeId:this.controllerId,presetSource:"split-card",isVisible:()=>!this.destroyed&&this.hasVisibleCardFields(),isAvailable:()=>!this.destroyed&&this.cardCollectionRuntime.canApplyDeveloperPreset(),isAppearanceAvailable:()=>!this.destroyed&&this.hasMountedCardFields(),appearancePreviewClearsTestData:()=>!0,canPreview:()=>this.isAppearancePreviewAvailable(),applyCardValue:e=>this.cardCollectionRuntime.applyDeveloperPreset(e),getAppearance:()=>this.getAppearance(),updateAppearance:e=>this.updateAppearance(e),replaceAppearance:e=>this.replaceAppearance(e),prepareAppearance:e=>this.prepareAppearance(e),prepareAppearanceReplacement:e=>this.prepareAppearanceReplacement(e)}))}unregisterSplitCardDeveloperAssistant(){this.splitCardDeveloperAssistant?.unregister(),this.splitCardDeveloperAssistant=null}onWindowMessage(e){if(this.destroyed||this.controllerBootstrapped||!this.controllerIframe?.contentWindow||e.source!==this.controllerIframe.contentWindow||e.origin!==this.hostedOrigin||(t=e.data,!le(t)||!ce(t,St)||t.channel!==Ee||t.type!==Se))return;var t;this.controllerBootstrapped=!0;const i=new MessageChannel;this.controlPort=i.port1,this.controlPort.onmessage=e=>this.onControlMessage(e),this.controlPort.start();const o={channel:Ee,type:_e,controllerId:this.controllerId,payload:{publishableKey:this.clientOptions.publishableKey,apiUrl:s(this.clientOptions.apiUrl),sdkVersion:n.version,options:this.getUpdateSnapshot().options}};this.controllerIframe.contentWindow.postMessage(o,this.hostedOrigin,[i.port2])}onControlMessage(e){if(this.destroyed)return void e.ports.forEach(e=>e.close());if(t=e.data,le(t)&&ce(t,_t)&&t.channel===Ee&&t.type===Ie&&de(t.controllerId,oe)&&le(t.payload)&&(ce(t.payload,["sessionId"])||ce(t.payload,It))&&de(t.payload.sessionId,oe)&&(void 0===t.payload.cardCollection||Ht(t.payload.cardCollection))){if(e.data.controllerId!==this.controllerId)return;if(this.cardCollectionRuntime.configure(e.data.payload.cardCollection??null),this.ensureSplitCardDeveloperAssistant(),this.controllerInitialized=!0,this.flushPendingComponents(),this.updateRevision>0){const e=this.getUpdateSnapshot(),t={channel:Ce,type:Fe,controllerId:this.controllerId,updateRevision:e.updateRevision,options:e.options};this.postControl(t)}return}var t;if((e=>le(e)&&ce(e,Nt)&&e.channel===Ee&&e.type===Te&&de(e.controllerId,oe)&&le(e.payload)&&ce(e.payload,zt)&&de(e.payload.code,oe)&&de(e.payload.message,re)&&"boolean"==typeof e.payload.recoverable)(e.data)){if(e.data.controllerId!==this.controllerId)return;this.cardCollectionRuntime.fail(e.data.payload),this.paymentMethodSubmission.handleSourceError(this.cardCollectionSubmissionSource.submissionSourceId,e.data.payload);for(const t of this.elements.values())this.paymentMethodSubmission.handleSourceError(t instanceof En?t.submissionSourceId:t.componentId,e.data.payload),t.handleControllerError(e.data.payload);return}if(!(e=>{if(!(le(e)&&ce(e,void 0===e.componentGeneration?Ut:qt)&&e.channel===Ce&&e.type===et&&de(e.controllerId,oe)&&de(e.componentId,oe)&&$t(e.componentType))||void 0!==e.componentGeneration&&("number"!=typeof e.componentGeneration||!Number.isSafeInteger(e.componentGeneration)||e.componentGeneration<0)||!le(e.payload))return!1;const t=e.payload;if(Yt(e.componentType)&&!["ready","change","focus","blur","error"].includes(String(t.event)))return!1;switch(t.event){case"ready":return"card"===e.componentType||(Yt(e.componentType)?ce(t,["event"]):jt(t.availablePaymentMethods));case"secure_field_surface_invalid":return"card"===e.componentType&&ce(t,["event"]);case"change":return"card"===e.componentType?ce(t,["event"]):Yt(e.componentType)&&Kt(t,e.componentType);case"focus":case"blur":return Yt(e.componentType)&&ce(t,["event"]);case"resize":return Number.isFinite(t.height)&&t.height>=0&&t.height<=ot;case"phase":return("card"===e.componentType||"card_collection"===e.componentType)&&["submitting","ready"].includes(String(t.phase));case"tokenization_requested":return"card_collection"===e.componentType&&ce(t,void 0===t.setupFutureUsage?["event","requestId"]:["event","requestId","setupFutureUsage"])&&de(t.requestId,oe)&&(void 0===t.setupFutureUsage||"on_session"===t.setupFutureUsage||"off_session"===t.setupFutureUsage);case"validation_result":return"card"===e.componentType&&ce(t,["event","requestId","result"])&&de(t.requestId,oe)&&function(e){return le(e)&&("succeeded"===e.status&&ce(e,["status"])||"failed"===e.status&&ce(e,["status","code","message","recoverable"])&&de(e.code,oe)&&de(e.message,re)&&"boolean"==typeof e.recoverable)}(t.result);case"action_required":return de(t.requestId,oe)&&le(t.action)&&de(t.action.id,oe)&&"three_d_secure"===t.action.type;case"error":return(!Yt(e.componentType)||ce(t,["event","code","message","recoverable"]))&&de(t.code,oe)&&de(t.message,re)&&"boolean"==typeof t.recoverable;case"submit_result":return("card"===e.componentType||"card_collection"===e.componentType)&&de(t.requestId,oe)&&li(t.result);case"developer_catalog":return"card"===e.componentType&&Array.isArray(t.presets)&&t.presets.length>0&&t.presets.length<=rt&&t.presets.every(ci);case"developer_apply_result":return"card"===e.componentType&&de(t.requestId,oe)&&de(t.presetId,st)&&"boolean"==typeof t.ok&&(t.ok||de(t.errorCode,oe));case"available_payment_methods_change":return"express_checkout"===e.componentType&&jt(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&&de(t.requestId,oe)&&ni(t.request);case"apple_pay_merchant_session":return"express_checkout"===e.componentType&&de(t.requestId,oe)&&le(t.merchantSession);case"google_pay_capabilities_request":return"express_checkout"===e.componentType&&Xt(t.environment)&&ti(t.requestJson,ht);case"google_pay_button_target":return"express_checkout"===e.componentType&&"boolean"==typeof t.visible&&Xt(t.environment)&&ti(t.requestJson,ut)&&("black"===t.buttonColor||"white"===t.buttonColor)&&Qt(t.buttonType)&&Number.isFinite(t.buttonRadius)&&t.buttonRadius>=0&&t.buttonRadius<=yt&&ei(t.target);case"google_pay_start":return"express_checkout"===e.componentType&&de(t.requestId,oe)&&Xt(t.environment)&&ti(t.requestJson,ut);case"google_pay_data_changed_result":return"express_checkout"===e.componentType&&de(t.requestId,oe)&&de(t.updateId,oe)&&ti(t.resultJson,ut);case"google_pay_authorization_result":return"express_checkout"===e.componentType&&de(t.requestId,oe)&&ti(t.resultJson,mt);case"wallet_click":case"wallet_cancel":return"express_checkout"===e.componentType&&de(t.requestId,oe)&&Zt(t.wallet);case"wallet_shipping_address_change":return"express_checkout"===e.componentType&&de(t.requestId,oe)&&de(t.updateId,oe)&&Zt(t.wallet)&&ri(t.address);case"wallet_shipping_rate_change":return"express_checkout"===e.componentType&&de(t.requestId,oe)&&de(t.updateId,oe)&&Zt(t.wallet)&&si(t.shippingRate);case"wallet_confirm":return"express_checkout"===e.componentType&&de(t.requestId,oe)&&Zt(t.wallet)&&le(t.paymentMethod)&&de(t.paymentMethod.id,oe)&&"card"===t.paymentMethod.type&&(void 0===t.paymentMethodPreview||Jt(t.paymentMethodPreview))&&(void 0===t.billingDetails||ai(t.billingDetails))&&(void 0===t.shippingAddress||ii(t.shippingAddress))&&(void 0===t.shippingRate||si(t.shippingRate));default:return!1}})(e.data))return;const i=e.data;if(i.controllerId!==this.controllerId)return;if(0!==e.ports.length)return void e.ports.forEach(e=>e.close());if("card_collection"===i.componentType){if(i.componentId!==this.cardCollectionSubmissionSource.submissionSourceId)return;if("tokenization_requested"===i.payload.event){if(!this.paymentMethodSubmission.ownsAttempt(i.componentId,i.payload.requestId))return;this.cardCollectionSubmissionSource.handleTokenizationRequest(i.payload.requestId,i.payload.setupFutureUsage)}return void this.paymentMethodSubmission.handleSourceEvent(i.componentId,i.payload)}const n=this.elements.get(i.componentId);n&&i.componentType===n.componentType?(i.componentGeneration??0)===n.componentGeneration&&(this.paymentMethodSubmission.handleSourceEvent(n instanceof En?n.submissionSourceId:i.componentId,i.payload),n.handleControllerEvent(i.payload)):e.ports.forEach(e=>e.close())}flushPendingComponents(){if(this.controllerInitialized&&this.controlPort)for(const[e,t]of this.pendingComponents){const i={channel:Ce,type:Re,controllerId:this.controllerId,componentId:e,componentType:t.element.componentType,componentOptions:t.element.getComponentOptions(),...t.element.componentGeneration>0?{componentGeneration:t.element.componentGeneration}:{}};try{this.controlPort.postMessage(i,[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 Cs=new Set(["amount","appearance"]);function Ss(e,t,i=0){if(!le(e)||0===Object.keys(e).length||Object.keys(e).some(e=>!Cs.has(e)))throw new Error("[Paypercut Elements] Update options may contain only amount or appearance details.");const n=e.appearance,o=e.amount;if(void 0!==o&&(!Number.isSafeInteger(o)||o<0))throw new Error("[Paypercut Elements] Updated amount must be a non-negative safe integer.");return{amount:o??i,appearance:void 0===n?t:_s(n,t)}}function _s(e,t){fe(e);const i={...t?.rules};for(const[t,n]of Object.entries(e.rules??{}))i[t]={...i[t],...n};return be({...t,...e,...t?.variables||e.variables?{variables:{...t?.variables,...e.variables}}:{},...Object.keys(i).length>0?{rules:i}:{}})}function Is(e,t,i){const n=be(i);return{mode:e.mode,amount:t,currency:e.currency,...e.setupFutureUsage?{setupFutureUsage:e.setupFutureUsage}:{},...e.locale?{locale:Rs(e.locale)}:{},...n?{appearance:n}:{}}}const Ts=35;function Rs(e){const t=String(e);return t.length<=Ts&&!ae(t)?t:"auto"}const ks=6e5,Os="_secret_",xs=200,Ms=/^[A-Za-z0-9._:-]+$/,Ls=new Set([402]),Ds=new Set(["active","completed","expired","canceled"]),Fs=new Set(["failed","no_payment_required","paid","processing","unpaid"]),Ns=new Set(["canceled","expired","processing","requires_action","requires_capture","requires_confirmation","requires_payment_method","succeeded"]),zs=(e,t)=>{if(!le(e)||e.checkout_session!==t||!Number.isSafeInteger(e.amount_total)||Number(e.amount_total)<0||"string"!=typeof e.mode||!["payment","setup","subscription"].includes(e.mode)||"string"!=typeof e.state||!Ds.has(e.state)||"string"!=typeof e.payment_status||!Fs.has(e.payment_status)||null!==e.payment_object_status&&("string"!=typeof e.payment_object_status||!Ns.has(e.payment_object_status))||"boolean"!=typeof e.terminal||"boolean"!=typeof e.retryable||!le(e.polling)||"boolean"!=typeof e.polling.recommended||!Number.isSafeInteger(e.polling.recommended_after_ms)||Number(e.polling.recommended_after_ms)<0||Number(e.polling.recommended_after_ms)>ks)throw vn("elements_checkout_status_invalid","The payment status response was invalid.",!1);const i=(e=>{if(!le(e)||!ce(e,["iso","scale"])||"string"!=typeof e.iso||!/^[A-Za-z]{3}$/.test(e.iso)||!Number.isSafeInteger(e.scale)||Number(e.scale)<0)throw vn("elements_checkout_status_invalid","The payment status response was invalid.",!1);return{iso:e.iso.toUpperCase(),scale:Number(e.scale)}})(e.currency),n=(e=>{if(null==e)return null;if(!(le(e)&&"use_sdk"===e.type&&le(e.use_sdk)&&ce(e.use_sdk,["sdk","metadata"])&&"three_d_secure"===e.use_sdk.sdk&&le(e.use_sdk.metadata)))throw vn("elements_next_action_unsupported","The payment requires an action that this SDK version cannot handle.",!1);const t=e.use_sdk.metadata,i=t.vault_token_ref,n=t.vault_token_intent_ref,o=de(i,256);if(!(o!==de(n,256)&&ce(t,["payment_intent","payment_method","attempt","vault",o?"vault_token_ref":"vault_token_intent_ref","action_phase"])&&de(t.payment_intent,xs)&&de(t.payment_method,xs)&&de(t.attempt,xs)&&"bt"===t.vault&&"provider_recovery"===t.action_phase))throw vn("elements_next_action_invalid","The payment authentication action was invalid.",!1);return{paymentIntentId:t.payment_intent,paymentMethodId:t.payment_method,attemptId:t.attempt,vault:"bt",instrument:o?{type:"token",id:i}:{type:"token_intent",id:n},actionPhase:"provider_recovery"}})(e.next_action);if("requires_action"===e.payment_object_status&&null===n)throw vn("elements_next_action_invalid","The payment requires an action but no supported action was returned.",!1);return{checkoutSessionId:t,amount:Number(e.amount_total),currency:i.iso,mode:e.mode,state:e.state,paymentObjectStatus:e.payment_object_status,paymentStatus:e.payment_status,terminal:e.terminal,retryable:e.retryable,pollingRecommended:e.polling.recommended,recommendedAfterMs:Number(e.polling.recommended_after_ms),nextAction:n}},Us=e=>({checkoutSession:{id:e.checkoutSessionId,status:e.state,paymentStatus:e.paymentStatus,paymentObjectStatus:e.paymentObjectStatus}}),qs=e=>new Promise(t=>globalThis.setTimeout(t,Math.max(0,e))),Bs=e=>e instanceof Error&&"code"in e&&"string"==typeof e.code&&"recoverable"in e&&"boolean"==typeof e.recoverable,js=async(e,t,i,n)=>{const o=n.deadlineAt-Date.now();if(o<=0)throw vn(i,"The payment request timed out.",!0);const r=new AbortController,s=t.signal,a=()=>{return r.abort(s?(e=s).reason instanceof Error?e.reason:new DOMException("Aborted","AbortError"):void 0);var e};s?.addEventListener("abort",a,{once:!0});const l=globalThis.setTimeout(()=>r.abort(new DOMException("The payment request timed out.","TimeoutError")),Math.max(1,Math.min(3e4,o)));try{const o=await fetch(e,{...t,cache:"no-store",credentials:"omit",signal:r.signal});if(!o.ok)throw vn(i,`The payment service rejected the request (HTTP ${o.status}).`,o.status>=500||408===o.status||429===o.status||!0===n.recoverableStatuses?.has(o.status));try{return await o.json()}catch{throw vn(i,"The payment service returned an invalid response.",!0)}}catch(e){if(Bs(e))throw e;throw vn(i,"The payment service could not be reached.",!0)}finally{globalThis.clearTimeout(l),s?.removeEventListener("abort",a)}},Gs=(e,t)=>e.paymentIntentId===t.paymentIntentId&&e.paymentMethodId===t.paymentMethodId&&e.attemptId===t.attemptId&&e.vault===t.vault&&e.instrument.type===t.instrument.type&&e.instrument.id===t.instrument.id&&e.actionPhase===t.actionPhase;class Hs{constructor(e,t,i){this.publishableKey=e,this.billingDetailsFor=i,this.inFlight=new Map,this.activeAction=null,this.account=t.account,this.apiUrl=s(t.apiUrl),this.hostedOrigin=new URL(r(t.hostedCheckoutUrl)).origin,this.actionShell=new yn(this.hostedOrigin,e=>this.rejectActiveAction(e,"elements_action_canceled","Payment authentication was canceled.",!0),(e,t,i,n)=>this.rejectActiveAction(e,t,i,n))}confirm(e){let t;try{t=(e=>{if(!de(e,4096)||!e.startsWith("cs_"))throw vn("elements_client_secret_invalid","A valid Checkout Session client secret is required.",!1);const t=e.indexOf(Os,3),i=t<0?"":e.slice(3,t),n=t<0?"":e.slice(t+8);if(!de(i,xs)||!Ms.test(i)||!de(n,4e3))throw vn("elements_client_secret_invalid","A valid Checkout Session client secret is required.",!1);return{clientSecret:e,checkoutSessionId:i}})(e)}catch(e){return Promise.reject(e)}const i=this.inFlight.get(t.clientSecret);if(i)return i;const n=this.run(t).finally(()=>{this.inFlight.get(t.clientSecret)===n&&this.inFlight.delete(t.clientSecret)});return this.inFlight.set(t.clientSecret,n),n}async run(e){const t=Date.now()+ks;let i=0,n=null;for(;Date.now()<t;){let o;try{o=n??await this.getStatus(e,t)}catch(e){if(!Bs(e)||!e.recoverable)throw e;const i=t-Date.now();if(i<=0)break;await qs(Math.min(500,i));continue}if(n=null,o.terminal||"processing"===o.paymentObjectStatus)return Us(o);if(o.nextAction){if("payment"!==o.mode)throw vn("elements_next_action_unsupported","This confirmation action is only supported for payment-mode Checkout Sessions.",!1);if(i>=3)throw vn("elements_next_action_loop","The payment returned too many consecutive authentication actions.",!1);i+=1;const r=o.nextAction,s=await this.runAction(e,o,t);n=await this.confirmCheckout(e,s,r,t);continue}if(o.pollingRecommended){const e=t-Date.now();if(e<=0)break;await qs(Math.min(e,Math.max(250,o.recommendedAfterMs)));continue}return Us(o)}throw vn("elements_action_timeout","Payment confirmation timed out while waiting for an authoritative status.",!0)}async getStatus(e,t){const i=new URL(`/v1/checkouts/${encodeURIComponent(e.checkoutSessionId)}/status`,this.apiUrl);i.searchParams.set("key",this.publishableKey),i.searchParams.set("client_secret",e.clientSecret);const n=await js(i,{method:"GET",headers:{Accept:"application/json",...void 0!==this.account?{"Paypercut-Account":this.account}:{}}},"elements_checkout_status_failed",{deadlineAt:t});return zs(n,e.checkoutSessionId)}async confirmCheckout(e,t,i,n){const o=new URL(`/v1/checkouts/${encodeURIComponent(e.checkoutSessionId)}/confirm`,this.apiUrl),r=await(async(e,t)=>{const i=(new TextEncoder).encode(`paypercut-elements-confirm-v1:${e}:${t}`),n=await globalThis.crypto.subtle.digest("SHA-256",i);return`paypercut-elements-confirm-v1-${Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,"0")).join("")}`})(e.checkoutSessionId,t),s={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","Idempotency-Key":r,...void 0!==this.account?{"Paypercut-Account":this.account}:{}},body:JSON.stringify({key:this.publishableKey,client_secret:e.clientSecret,payment_method_options:{type:"card",card:{three_d_secure:{session_id:t}}}})};let a=null;for(let t=0;t<3;t+=1)try{return await js(o,s,"elements_checkout_confirmation_failed",{deadlineAt:n,recoverableStatuses:Ls}),null}catch(o){if(!Bs(o)||!o.recoverable)throw o;a=o;try{const t=await this.getStatus(e,n);if(t.terminal||"processing"===t.paymentObjectStatus||null===t.nextAction||!Gs(t.nextAction,i))return t}catch(e){if(Bs(e)&&!e.recoverable)throw e}if(t+1<3){const e=n-Date.now();if(e<=0)break;await qs(Math.min(e,250*2**t))}}throw a??vn("elements_checkout_confirmation_failed","The payment confirmation result is unknown.",!0)}runAction(e,t,i){if(!t.nextAction)return Promise.reject(vn("elements_next_action_invalid","No payment action is available.",!1));if(this.activeAction)return Promise.reject(vn("elements_action_in_progress","Another payment authentication is already in progress.",!0));const o=j(),r=new MessageChannel;return new Promise((s,a)=>{const l=globalThis.setTimeout(()=>{this.rejectActiveAction(o,"elements_action_timeout","Payment authentication timed out.",!0)},Math.max(1,i-Date.now()));this.activeAction={id:o,port:r.port1,resolve:s,reject:a,timeoutId:l},r.port1.onmessage=r=>{const s=this.activeAction;if(s&&s.id===o&&(a=r.data,le(a)&&de(a.actionId,128)&&("ready"===a.type?ce(a,["type","actionId"]):"complete"===a.type&&ce(a,["type","actionId","payload"])&&le(a.payload)&&ce(a.payload,["threeDSSessionId"])&&de(a.payload.threeDSSessionId,128)))&&r.data.actionId===o){var a;if("ready"===r.data.type){const r=this.billingDetailsFor(t.nextAction.paymentMethodId),a={type:"start",actionId:o,payload:{protocolVersion:1,publishableKey:this.publishableKey,...void 0!==this.account?{account:this.account}:{},apiUrl:this.apiUrl,sdkVersion:n.version,deadlineAt:i,checkoutSession:{id:e.checkoutSessionId,amount:t.amount,currency:t.currency,mode:t.mode},action:t.nextAction,...r?{billingDetails:r}:{}}};return void s.port.postMessage(a)}"complete"===r.data.type&&this.resolveActiveAction(o,r.data.payload.threeDSSessionId)}},r.port1.start();try{this.actionShell.show({id:o,type:"three_d_secure",source:"payment_confirmation"},r.port2)}catch{r.port2.close(),this.rejectActiveAction(o,"elements_action_channel_unavailable","The secure authentication window could not be opened.",!0)}})}resolveActiveAction(e,t){const i=this.activeAction;i&&i.id===e&&(this.activeAction=null,globalThis.clearTimeout(i.timeoutId),i.port.close(),this.actionShell.close(),i.resolve(t))}rejectActiveAction(e,t,i,n){const o=this.activeAction;o&&o.id===e&&(this.activeAction=null,globalThis.clearTimeout(o.timeoutId),o.port.close(),this.actionShell.close(),o.reject(vn(t,i,n)))}}wi();const Ws=/^[A-Za-z]{3}$/,Vs=new Set(["payment","setup","subscription"]),$s=new Set(["mode","amount","currency","setupFutureUsage","locale","appearanceUpdates","appearance"]);class Ys{constructor(e){this.options=e,this.groups=new WeakSet,this.paymentMethodBilling=new Map,this.paymentConfirmation=null,this.configurationIdentity=JSON.stringify([e.publishableKey,e.account??null,s(e.apiUrl),r(e.hostedCheckoutUrl)])}elements(e){const t=new As(this.options,function(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new Error("[Paypercut Elements] Elements options are required.");if(Object.keys(e).some(e=>!$s.has(e)))throw new Error("[Paypercut Elements] Elements options contain an unsupported property.");if(!Vs.has(e.mode))throw new Error("[Paypercut Elements] Mode must be payment, setup, or subscription.");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||!Ws.test(e.currency))throw new Error("[Paypercut Elements] Currency must be a three-letter ISO 4217 code.");if(t=e.setupFutureUsage,void 0!==t&&"on_session"!==t&&"off_session"!==t)throw new Error("[Paypercut Elements] setupFutureUsage must be on_session or off_session.");var t;if(void 0!==e.appearanceUpdates&&"locked"!==e.appearanceUpdates&&"remount"!==e.appearanceUpdates)throw new Error("[Paypercut Elements] appearanceUpdates must be locked or remount.");if("payment"!==e.mode&&void 0!==e.setupFutureUsage&&"off_session"!==e.setupFutureUsage)throw new Error(`[Paypercut Elements] ${e.mode} mode prepares cards for off-session use and cannot use setupFutureUsage on_session.`);e.appearance&&fe(e.appearance);return{...e,currency:e.currency.toUpperCase(),..."payment"===e.mode?e.setupFutureUsage?{setupFutureUsage:e.setupFutureUsage}:{}:{setupFutureUsage:"off_session"},appearanceUpdates:e.appearanceUpdates??"locked",...e.appearance?{appearance:be(e.appearance)}:{}}}(e),this.configurationIdentity);return this.groups.add(t),t}createPaymentMethod(e){const t=e&&"object"==typeof e&&!Array.isArray(e)?Object.keys(e):[];if(!e||"object"!=typeof e||Array.isArray(e)||t.length<1||t.length>2||t.some(e=>"elements"!==e&&"params"!==e)||!("elements"in e)||!(e.elements instanceof As)||!this.groups.has(e.elements))return Promise.reject(vn("elements_component_configuration_invalid","createPaymentMethod requires an Elements group created by this Paypercut client and optional params.billing_details.",!1));let i;try{const t=e.params;if(void 0!==t&&(!t||"object"!=typeof t||Array.isArray(t)||1!==Object.keys(t).length||!Object.prototype.hasOwnProperty.call(t,"billing_details")||void 0===t.billing_details))throw new Error("[Paypercut Elements] createPaymentMethod params must contain only billing_details.");i=function(e){if(void 0===e)return;if(!le(e)||0===Object.keys(e).length||Object.keys(e).some(e=>!Oi.has(e)))throw new Error("[Paypercut Elements] billing_details must contain only name, email, phone, or address.");let t;if(void 0!==e.address){if(!le(e.address)||0===Object.keys(e.address).length||Object.keys(e.address).some(e=>!xi.has(e)))throw new Error("[Paypercut Elements] Billing address must contain a supported address field.");const i=e.address,n=void 0===i.country?void 0:zi(i.country,"address country",2).toUpperCase();if(void 0!==n&&!/^[A-Z]{2}$/.test(n))throw new Error("[Paypercut Elements] Billing address country must be ISO 3166-1 alpha-2.");t=Object.freeze({...void 0===i.line1?{}:{line1:zi(i.line1,"address line1",Fi)},...void 0===i.line2?{}:{line2:zi(i.line2,"address line2",Fi)},...void 0===i.city?{}:{city:zi(i.city,"address city",Fi)},...void 0===i.state?{}:{state:zi(i.state,"address state",Fi)},...void 0===i.postal_code?{}:{postal_code:zi(i.postal_code,"address postal_code",Ni)},...void 0===n?{}:{country:n}})}return Object.freeze({...void 0===e.name?{}:{name:zi(e.name,"name",Mi)},...void 0===e.email?{}:{email:zi(e.email,"email",Li)},...void 0===e.phone?{}:{phone:zi(e.phone,"phone",Di)},...void 0===t?{}:{address:t}})}(t?.billing_details)}catch(e){return Promise.reject(vn("elements_component_configuration_invalid",e instanceof Error?e.message:"Billing details are invalid.",!1))}return e.elements.createPaymentMethod(i).then(e=>{const t=i?{...i.name?{name:i.name}:{},...i.email?{email:i.email}:{}}:void 0;if(t&&Object.keys(t).length>0&&(this.paymentMethodBilling.set(e.id,t),this.paymentMethodBilling.size>16)){const e=this.paymentMethodBilling.keys().next().value;"string"==typeof e&&this.paymentMethodBilling.delete(e)}return e})}confirmPayment(e){return this.confirmPaymentInput(e)}handleNextAction(e){return this.confirmPaymentInput(e)}confirmPaymentInput(e){return e&&"object"==typeof e&&!Array.isArray(e)&&1===Object.keys(e).length&&Object.prototype.hasOwnProperty.call(e,"clientSecret")?(this.paymentConfirmation??(this.paymentConfirmation=new Hs(this.options.publishableKey,{...void 0!==this.options.account?{account:this.options.account}:{},...this.options.apiUrl?{apiUrl:this.options.apiUrl}:{},...this.options.hostedCheckoutUrl?{hostedCheckoutUrl:this.options.hostedCheckoutUrl}:{}},e=>this.paymentMethodBilling.get(e))),this.paymentConfirmation.confirm(e.clientSecret)):Promise.reject(vn("elements_client_secret_invalid","confirmPayment requires only a Checkout Session clientSecret.",!1))}}const Ks=function(e,t){if("string"==typeof e){if(void 0!==t&&(!t||"object"!=typeof t||Array.isArray(t)))throw new Error("[Paypercut Elements] Client options must be an object.");return new Ys(Zs({...t,publishableKey:e}))}if(void 0!==t)throw new Error("[Paypercut Elements] Pass client options in one initializer object.");return new Ys(Zs(e))};function Zs(e){if(!e||"object"!=typeof e||Array.isArray(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()||ae(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}}Ks.version=n.version;let Js=!1;const Xs=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Qs=/^(0|(\d+(\.\d+)?(px|rem|em)))$/;function ea(e){e&&(void 0===e.brandColor||Xs.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||Qs.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 ta{constructor(e){this.options=e,this.emitter=new t,this.mounted=!1,this.destroyed=!1,this.iframe=null,this.applePaySession=null,this.applePayBridgeTimeout=null,this.messageHandler=this.onMessage.bind(this),this.threeDSModal=new d({modalId:"paypercut-3ds-modal",buildUrl:e=>this.buildThreeDSUrl(e),onCancel:()=>this.handle3DSShellCancel(),onReady:e=>this.postThreeDSInit(e)}),window.addEventListener("message",this.messageHandler),v(e.ui_mode??u.EMBEDDED)===u.EMBEDDED&&function(){if("undefined"==typeof window)return;if(window.ApplePaySession)return;if(Js)return;Js=!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=r(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=v(this.options.ui_mode??u.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)f(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(m.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)b(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&&(ea(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(!o(e.origin))return;const t=e.data;if(!t||"object"!=typeof t||!("type"in t))return;const i=Boolean(this.iframe?.contentWindow&&e.source===this.iframe.contentWindow),n=this.threeDSModal.ownsMessageSource(e.source),r=new Set(["PAYPERCUT_THREEDS_FRAME_RESIZE","THREEDS_READY","THREEDS_COMPLETE","THREEDS_CANCELED","THREEDS_ERROR"]);if((!r.has(t.type)||n)&&(r.has(t.type)||i)&&(!t.checkoutId||t.checkoutId===this.options.id))switch(t.type){case"CHECKOUT_LOADED":this.emitter.emit(g.Loaded),this.postToIframe({type:w,checkoutId:this.options.id,applePayBridge:!0});break;case"CHECKOUT_PROCESSING":this.emitter.emit(g.Processing,{checkoutId:t.checkoutId});break;case"CHECKOUT_SUCCESS":const{payment_method:i={},payment:n=null}=t;this.emitter.emit(g.Success,{payment_method:i,payment:n});break;case"CHECKOUT_ERROR":this.emitter.emit(g.Error,(t&&t.error)??t);break;case"CHECKOUT_CANCEL":this.emitter.emit(g.Cancel,{checkoutId:t.checkoutId,wallet:t.wallet});break;case"CHECKOUT_EXPIRED":this.emitter.emit(g.Expired);break;case"CHECKOUT_RESIZE":this.emitter.emit(g.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(g.ThreeDSStarted);break;case"THREEDS_READY":this.handle3DSReady();break;case"THREEDS_COMPLETE":this.postToIframe(t),this.threeDSModal.close(),this.emitter.emit(g.ThreeDSComplete);break;case"THREEDS_CANCELED":this.postToIframe(t),this.threeDSModal.close(),this.emitter.emit(g.ThreeDSCanceled);break;case"THREEDS_ERROR":this.postToIframe(t),this.threeDSModal.close(),this.emitter.emit(g.ThreeDSError,t.error);break;case"FORM_VALIDATION":this.emitter.emit(g.FormValidation,{checkoutId:t.checkoutId,wallet:t.wallet});break;case P:this.handleApplePayStart(t);break;case A:this.handleApplePayMerchantSession(t.merchantSession);break;case C:this.abortApplePaySession();break;case _: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=r(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=r(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(g.ThreeDSCanceled)}handle3DSReady(){this.threeDSModal.handleReady()||console.error("[PaypercutCheckout] No pending 3DS data or iframe not ready")}postThreeDSInit(e){const t=r(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:T,checkoutId:this.options.id});const i=N(t);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:T,checkoutId:this.options.id})}this.applePaySession=n,n.onvalidatemerchant=e=>{this.applePayBridgeTimeout=setTimeout(()=>this.abortApplePaySession(),D),this.postToIframe({type:E,checkoutId:this.options.id,validationURL:e.validationURL})},n.onpaymentauthorized=e=>{this.postToIframe({type:S,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:T,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?(ea(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 ia=function(e){return new ta(e)};return ia.version=n.version,"undefined"!=typeof window&&(window.Paypercut=Ks,window.PaypercutExpressCheckout=ne),ia}();
1
+ var PaypercutCheckout=function(){"use strict";var e="undefined"!=typeof document?document.currentScript:null;class t{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)}})}emitAndThrow(e,...t){let i;if(this.handlers.get(e)?.forEach(e=>{try{e(...t)}catch(e){void 0===i&&(i=e)}}),void 0!==i){if(i instanceof Error)throw i;throw new Error(String(i))}}hasListeners(e){const t=this.handlers.get(e);return!!t&&t.size>0}clear(){this.handlers.clear()}}const i="1.4.5",n={version:i,defaultCheckoutOrigin:"https://buy.paypercut.io",defaultApiOrigin:"https://api.paypercut.io",defaultVaultApiUrl:"https://api.basistheory.com",allowedOrigins:["https://buy.paypercut.io"]};function o(e){return!!n.allowedOrigins.includes(e)}function r(e){return n.defaultCheckoutOrigin}function s(e){return n.defaultApiOrigin}function a(){return n.defaultVaultApiUrl}function l(){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 c(e,t,i){const n=Math.min(t,i);return Math.min(Math.max(e,n),i)}class d{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=l();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 o=()=>{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)"},r=()=>{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",r),n.addEventListener("focus",r),n.addEventListener("mouseleave",o),n.addEventListener("blur",o),n.addEventListener("mouseup",r),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.ownsMessageSource(e.source))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())}ownsMessageSource(e){return Boolean(this.iframe?.contentWindow&&e===this.iframe.contentWindow)}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 o=l(),r=Math.min(860,Math.max(0,o.width-32)),s=Math.min(860,Math.max(0,o.height-112)),a=i.width??460,d=i.height??680,p=c(a,320,r),h=c(d,300,s);e.style.width=`${o.width}px`,e.style.height=`${o.height}px`,e.style.minHeight=`${o.height}px`,t.style.width=`${Math.round(p)}px`,t.style.height=`${Math.round(h)}px`,n&&(n.style.width=`${Math.round(p)}px`,n.style.height=`${Math.round(h)}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 u,m,y,g;function f(e){return Object.values(m).includes(e)}function b(e){return Object.values(y).includes(e)}function v(e){var t;if(e)return t=e,Object.values(u).includes(t)?e:void console.warn(`[PaypercutCheckout] Invalid ui_mode: "${e}". Valid options: ${Object.values(u).join(", ")}`)}!function(e){e.EMBEDDED="embedded"}(u||(u={})),function(e){e.CARD="card"}(m||(m={})),function(e){e.APPLE_PAY="apple_pay",e.GOOGLE_PAY="google_pay"}(y||(y={})),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"}(g||(g={}));const w="SDK_CAPABILITIES",P="APPLE_PAY_START",E="APPLE_PAY_VALIDATE_MERCHANT",A="APPLE_PAY_MERCHANT_SESSION",C="APPLE_PAY_MERCHANT_ERROR",S="APPLE_PAY_PAYMENT_DATA",_="APPLE_PAY_PAYMENT_RESULT",I="APPLE_PAY_CANCELLED",T="APPLE_PAY_SESSION_ERROR",R=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 k(e){return e||"en"}function O(e){const t=e.split("-")[0].toLowerCase();return R.has(t)?t:"en"}var x;!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"}(x||(x={}));const M=14,L=3,D=15e3,F=10;function N(e){return e.supportsVersion?.(M)?M:L}const z=16,U=16,q=3,B=8;function j(){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()*U);return("x"===e?t:t&q|B).toString(z)})}const G=100,H=2;function W(e){return(e/G).toFixed(H)}function V(e){return e.startsWith("pk_live_")}let $=null;function Y(){return $||($=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)}),$)}let K=null;function Z(){return K||(K=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)}),K)}function J(e,t,i="DE"){const n={};return void 0!==e.amount&&(n.newTransactionInfo={totalPriceStatus:"FINAL",totalPriceLabel:"Total",totalPrice:W(e.amount),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??`${W(e.amount)} ${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}const X=540,Q=3e3,ee=3e4;function te(e){return"checkout"===e?"check-out":e}class ie{constructor(e){this.options=e,this.emitter=new t,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=j(),this.idempotencyKey=j(),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=e.shippingOptions??[],this.messageHandler=this.onMessage.bind(this),this.threeDSModal=new d({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=r(this.options.hostedCheckoutUrl),t=new URL("/express/tokenize",e);return t.searchParams.set("instanceId",this.instanceId),t.searchParams.set("liveMode",String(V(this.options.publishableKey))),t.toString()}async fetchExpressConfig(){const e=s(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=V(this.options.publishableKey),o="BCR2DN5T735375Y7",r=i.payment_domain?.wallets?.google_pay?.merchant_ref??"",s=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:a(),googlePayMerchantId:n?"active"===s?r:o:r||o,googlePayStatus:s,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??"",threeDSecure:i.three_d_secure??null}}catch(e){console.error("[PaypercutExpressCheckout] Failed to fetch express config:",e)}}onMessage(e){if(!o(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))return;const i=Boolean(this.tokenizeIframe?.contentWindow&&e.source===this.tokenizeIframe.contentWindow),n=this.threeDSModal.ownsMessageSource(e.source),r=new Set(["PAYPERCUT_THREEDS_FRAME_RESIZE","THREEDS_READY","THREEDS_COMPLETE","THREEDS_CANCELED","THREEDS_ERROR"]);if((!r.has(t.type)||n)&&(r.has(t.type)||i)&&(!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(x.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(x.Error,new Error(e?.message??"Payment method creation failed")),this.emitter.emit(x.PaymentMethodFailed,{error:e?.message??"Payment method creation failed"}),this.applePayPendingBillingDetails=null,this.applePayPendingShippingDetails=null,this.applePayPendingShippingOption=null}):(this.completeApplePaySession(!1),this.emitter.emit(x.Error,new Error(t.error??"Apple Pay payment failed")),this.emitter.emit(x.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(x.PaymentMethodCreated,{paymentMethodId:e,wallet:"google_pay",billingDetails:this.pendingGpayBillingDetails??void 0,shippingDetails:this.pendingGpayShippingDetails??void 0,selectedShippingOption:this.pendingGpayShippingOption})}).catch(e=>{this.emitter.emit(x.Error,new Error(e?.message??"Payment method creation failed")),this.emitter.emit(x.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(x.Cancel):(this.emitter.emit(x.Error,new Error(e)),this.emitter.emit(x.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:[y.APPLE_PAY,y.GOOGLE_PAY],n=i.includes(y.APPLE_PAY),o=i.includes(y.GOOGLE_PAY),r=this.options.layout??"auto";this.preferredLayout="auto"===r?"row":r;const s=document.createElement("div");this.wrapper=s,Object.assign(s.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),s.appendChild(this.gpayContainer),Z().catch(e=>{console.error("[PaypercutExpressCheckout] Failed to load Google Pay script:",e)})),n&&(this.applePayContainer=document.createElement("div"),this.applyLayoutToContainers(this.preferredLayout,this.applePayContainer),s.appendChild(this.applePayContainer),Y()),t.appendChild(s),"auto"===r&&"undefined"!=typeof ResizeObserver&&(this.layoutResizeObserver=new ResizeObserver(e=>{const i=e[0]?.contentRect.width??t.offsetWidth;this.pendingObservedLayout=i<=X?"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 a=this.buildTokenizeSrc();this.tokenizeIframe=document.createElement("iframe"),this.tokenizeIframe.id="paypercut-express-tokenize-iframe",this.tokenizeIframe.src=a,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(),o&&e&&this.mountGooglePayFromConfig(),this.emitter.emit(x.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",k(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",te(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)}}),i=t?.borderRadius??"0.5rem";e.style.width="100%",this.injectGpayInnerStyles(e,i),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 i=this.options.locale?k(this.options.locale):"en",n=this.options.buttonOptions,o=document.createElement("apple-pay-button");o.setAttribute("buttonstyle",n?.applePayStyle??"black"),o.setAttribute("type",te(n?.type??"plain")),o.setAttribute("locale",i),o.style.setProperty("--apple-pay-button-width","100%"),o.style.setProperty("--apple-pay-button-height","48px"),o.style.setProperty("--apple-pay-button-border-radius",n?.borderRadius??"0.5rem"),o.style.display="block",o.style.cursor="pointer",o.addEventListener("click",()=>this.startApplePay());const r=()=>{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")?r():customElements?.whenDefined("apple-pay-button").then(r).catch(()=>r())}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=j(),this.setSessionActive(!0),this.emitter.emit(x.Click);const t=await new Promise(e=>{if(!this.emitter.hasListeners(x.SessionStart))return void e(null);const t=setTimeout(()=>e(null),Q);this.emitter.emit(x.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(x.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=W(this.applePayCurrentAmount),o=this.currentLineItems.map(e=>({label:e.label,amount:W(e.amount),type:e.type??"final"})),r={countryCode:this.options.countryCode??"DE",currencyCode:this.options.currency,merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],supportedNetworks:["visa","masterCard"],lineItems:o,total:{label:i,amount:n,type:"final"},requiredBillingContactFields:["postalAddress","name","email"],requiredShippingContactFields:["postalAddress","name","email"]};this.applePayCurrentShippingOptions.length&&(r.shippingMethods=this.applePayCurrentShippingOptions.map(e=>({label:e.label,detail:e.detail??"",amount:W(e.amount),identifier:e.id}))),r.shippingType="shipping",this.abortApplePaySession();const s=N(e);try{const t=new e(s,r);this.applePaySession=t,t.onvalidatemerchant=async e=>{const n=this.expressConfig?.vaultApiUrl??a(),o=this.expressConfig?.publicKey??"";try{const r={"Content-Type":"application/json","BT-API-KEY":o};this.idempotencyKey&&(r["Idempotency-Key"]=this.idempotencyKey);const s=await fetch(`${n}/apple-pay/session`,{method:"POST",headers:r,body:JSON.stringify({display_name:i,domain:window.location.host,validation_url:e.validationURL})});if(!s.ok){const e=await s.json().catch(()=>({}));throw new Error(e?.message??`Merchant validation failed: HTTP ${s.status}`)}const a=await s.json();t.completeMerchantValidation(a)}catch(e){console.error("[PaypercutExpressCheckout] Apple Pay merchant validation failed"),this.abortApplePaySession(),this.emitter.emit(x.Error,new Error(e?.message??"Apple Pay merchant validation failed")),this.emitter.emit(x.Cancel)}},t.onshippingcontactselected=async n=>{const o=n.shippingContact,r=await new Promise(e=>{this.applePayPendingCallback={type:"contact",resolve:e},this.emitter.emit(x.ShippingAddressChange,{address:{country:o.countryCode??"",state:o.administrativeArea,city:o.locality,postalCode:o.postalCode},updateWith:e=>this.update(e)}),setTimeout(()=>e({}),ee)});this.applePayPendingCallback=null,"number"==typeof r.amount&&(this.applePayCurrentAmount=r.amount),Array.isArray(r.lineItems)&&(this.currentLineItems=r.lineItems),Array.isArray(r.shippingOptions)&&(this.applePayCurrentShippingOptions=r.shippingOptions);const s="invalid_shipping_address"===r.status?e.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS:e.STATUS_SUCCESS;try{t.completeShippingContactSelection(s,this.applePayCurrentShippingOptions.map(e=>({label:e.label,detail:e.detail??"",amount:W(e.amount),identifier:e.id})),{label:i,amount:W(this.applePayCurrentAmount),type:"final"},this.currentLineItems.map(e=>({label:e.label,amount:W(e.amount),type:e.type??"final"})))}catch(e){console.error("[PaypercutExpressCheckout] completeShippingContactSelection failed",e)}},t.onshippingmethodselected=async n=>{const o=n.shippingMethod,r={id:o.identifier,label:o.label,detail:o.detail,amount:(s=o.amount,Math.round(Number.parseFloat(s)*G))};var s;this.applePayPendingShippingOption=r;const a=await new Promise(e=>{this.applePayPendingCallback={type:"method",resolve:e},this.emitter.emit(x.ShippingOptionChange,{shippingOption:r,updateWith:e=>this.update(e)}),setTimeout(()=>e({}),ee)});this.applePayPendingCallback=null,"number"==typeof a.amount&&(this.applePayCurrentAmount=a.amount),Array.isArray(a.lineItems)&&(this.currentLineItems=a.lineItems);try{t.completeShippingMethodSelection(e.STATUS_SUCCESS,{label:i,amount:W(this.applePayCurrentAmount),type:"final"},this.currentLineItems.map(e=>({label:e.label,amount:W(e.amount),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??""},threeDSecure:this.expressConfig?.threeDSecure??null})},t.oncancel=()=>{this.applePaySession=null,this.applePayPendingCallback=null,this.applePayPendingShippingOption=null,this.emitter.emit(x.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=V(this.options.publishableKey),i=e.tenantId,n=e.googlePayMerchantId,o=e.displayName||"Checkout";return i?n?(console.log({liveMode:t}),!t||e.merchantMcc&&e.merchantUrl?void Z().then(()=>{this.mountGooglePayButton(i,n,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,i,n){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 r=n?"PRODUCTION":"TEST",s=this.options.countryCode;s||console.warn('[PaypercutExpressCheckout] countryCode is not set. This is required for Google Pay in production. Pass it via options.countryCode (e.g. "DE").');const a={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:W(this.options.amount),currencyCode:this.options.currency,countryCode:s},callbackIntents:["PAYMENT_AUTHORIZATION","SHIPPING_ADDRESS","SHIPPING_OPTION"],shippingAddressRequired:!0,shippingOptionRequired:!0};this.options.allowedCountries?.length&&(a.shippingAddressParameters={allowedCountryCodes:this.options.allowedCountries,phoneNumberRequired:!1}),this.options.shippingOptions?.length&&(a.shippingOptionParameters={defaultSelectedOptionId:this.options.shippingOptions[0].id,shippingOptions:this.options.shippingOptions.map(e=>({id:e.id,label:e.label,description:e.detail??`${W(e.amount)} ${this.options.currency}`}))}),this.gpayPaymentRequest=a,this.gpayClient=new o.payments.api.PaymentsClient({environment:r,paymentDataCallbacks:{onPaymentAuthorized:e=>this.handleGooglePayAuthorized(e),onPaymentDataChanged:e=>this.handleGooglePayDataChanged(e)}});const l=this.options.buttonOptions,c=this.gpayClient.createButton({onClick:()=>this.startGooglePay(a),buttonSizeMode:"fill",buttonType:l?.type??"plain",buttonColor:l?.googlePayColor??"default",...this.options.locale&&{buttonLocale:O(this.options.locale)}}),d=l?.borderRadius??"0.5rem";c.style.width="100%",this.injectGpayInnerStyles(c,d),this.gpayContainer.appendChild(c)}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=j(),this.setSessionActive(!0),this.emitter.emit(x.Click),this.emitter.hasListeners(x.SessionStart)){const t=await new Promise(e=>{const t=setTimeout(()=>e(null),Q);this.emitter.emit(x.SessionStart,{wallet:"google_pay",updateWith:i=>{clearTimeout(t),e(i)}})});if(!t)return this.setSessionActive(!1),void this.emitter.emit(x.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??`${W(e.amount)} ${this.options.currency}`}))}),null!=t.amount&&(this.gpayCurrentAmount=t.amount,e.transactionInfo={...e.transactionInfo,totalPrice:W(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(x.Cancel):this.emitter.emit(x.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,o=e.shippingAddress,r=e.shippingOptionData,s=n?{name:n.name,address:{line1:n.address1,city:n.locality,state:n.administrativeArea,postalCode:n.postalCode,country:n.countryCode}}:null,a=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=r?this.currentShippingOptions.find(e=>e.id===r.id)??{id:r.id,label:r.label??r.id,amount:0}:void 0;this.pendingGpayBillingDetails=s,this.pendingGpayShippingDetails=a,this.pendingGpayShippingOption=l;const c=await new Promise((e,n)=>{const o=setTimeout(()=>{this.pendingGpayResolve=null,this.pendingGpayReject=null,n(new Error("Tokenization timed out"))},ee);this.pendingGpayResolve=t=>{clearTimeout(o),e(t)},this.pendingGpayReject=e=>{clearTimeout(o),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:s,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??""},threeDSecure:this.expressConfig?.threeDSecure??null})});if(c.__closeSheet)return{transactionState:"SUCCESS"};if(!c.success){const e=c.error??"Tokenization failed";return this.emitter.emit(x.Error,new Error(e)),this.emitter.emit(x.PaymentMethodFailed,{error:e}),{transactionState:"ERROR"}}const d=await this.createPaymentMethod({btTokenId:c.btTokenId,cardPayload:c.cardPayload,billingDetails:c.billingDetails,csessId:c.csessId,walletType:"google_pay"});return this.emitter.emit(x.PaymentMethodCreated,{paymentMethodId:d,wallet:"google_pay",billingDetails:s??void 0,shippingDetails:a,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(x.Error,new Error(e?.message??"Google Pay authorization failed")),this.emitter.emit(x.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 J({amount:this.gpayCurrentAmount||this.options.amount,shippingOptions:this.currentShippingOptions},this.options.currency,this.options.countryCode);if("SHIPPING_ADDRESS"===t){return J(await new Promise(e=>{this.emitter.emit(x.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 J(await new Promise(i=>{this.emitter.emit(x.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),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":"",i=e?"none":"";this.applePayContainer&&(this.applePayContainer.style.opacity=t,this.applePayContainer.style.pointerEvents=i,this.applePayContainer.inert=e,this.applePayContainer.setAttribute("aria-busy",String(e))),this.gpayContainer&&(this.gpayContainer.style.opacity=t,this.gpayContainer.style.pointerEvents=i,this.gpayContainer.inert=e,this.gpayContainer.setAttribute("aria-busy",String(e)))}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:o,walletType:r}=e;if(!i||!t)throw new Error("[createPaymentMethod] Missing required tokenization data.");const a=new URL("/v1/payment_methods",s(this.options.apiUrl)),l={type:"card",key:this.options.publishableKey,card:{token:o??"",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:r,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}},c=await fetch(a.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l),cache:"no-store"});if(!c.ok){const e=await c.text().catch(()=>`HTTP ${c.status}`);throw new Error(`Payment method creation failed (${c.status}): ${e}`)}return(await c.json()).id}postToTokenizeIframe(e){if(!this.tokenizeIframe?.contentWindow)return;const t=r(this.options.hostedCheckoutUrl);this.tokenizeIframe.contentWindow.postMessage(e,t)}buildThreeDSUrl(e){const t=r(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(x.Cancel)}handle3DSReady(){this.threeDSModal.handleReady()||console.error("[PaypercutExpressCheckout] No pending 3DS data or iframe not ready")}postThreeDSInit(e){const t=r(this.options.hostedCheckoutUrl);e.contentWindow?.postMessage({type:"THREEDS_INIT",instanceId:this.instanceId},t)}}const ne=function(e){return new ie(e)},oe=128,re=1024,se=/[\u0000-\u001f\u007f]/u,ae=e=>se.test(e),le=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ce=(e,t)=>Object.keys(e).every(e=>t.includes(e))&&t.every(t=>Object.prototype.hasOwnProperty.call(e,t)),de=(e,t)=>"string"==typeof e&&e.length>0&&e.length<=t&&e===e.trim()&&!ae(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"]),he=new Set([".Input",".Input--invalid",".Input:focus",".Label",".Error",".Text",".WalletButton",".WalletButton--applePay",".WalletButton--googlePay",".ActionShell"]),ue=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"]),me=/[{};]|<\/style|@import|expression\s*\(|javascript\s*:|url\s*\(/i,ye=/var\(\s*--([A-Za-z][A-Za-z0-9]*)\s*\)/gi;function ge(e){return"string"==typeof e&&e.length>0&&e.length<=512&&e===e.trim()&&!ae(e)&&!me.test(e)&&function(e){const t=e.replace(ye,(e,t)=>pe.has(t)?"":"var(invalid)");return!/var\s*\(/i.test(t)}(e)}function fe(e){if(!Pe(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(!Pe(e.variables))throw new Error("[Paypercut Elements] Appearance variables are invalid.");for(const[t,i]of Object.entries(e.variables))if(!pe.has(t)||!ge(i))throw new Error(`[Paypercut Elements] Appearance variable ${t} is invalid.`)}if(void 0!==e.rules){if(!Pe(e.rules))throw new Error("[Paypercut Elements] Appearance rules are invalid.");for(const[t,i]of Object.entries(e.rules)){if(!he.has(t)||!Pe(i))throw new Error(`[Paypercut Elements] Appearance rule ${t} is invalid.`);for(const[e,n]of Object.entries(i))if(!ue.has(e)||!ge(n))throw new Error(`[Paypercut Elements] Appearance rule ${t}.${e} is invalid.`)}}}function be(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 ve(e,t){return we(e??{})===we(t??{})}function we(e){return Array.isArray(e)?`[${e.map(we).join(",")}]`:Pe(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${we(e[t])}`).join(",")}}`:JSON.stringify(e)}function Pe(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const Ee="paypercut.elements.controller",Ae="paypercut.elements.component.bootstrap",Ce="paypercut.elements.component",Se="PAYPERCUT_ELEMENTS_CONTROLLER_FRAME_READY",_e="PAYPERCUT_ELEMENTS_CONTROLLER_INIT",Ie="PAYPERCUT_ELEMENTS_CONTROLLER_INITIALIZED",Te="PAYPERCUT_ELEMENTS_CONTROLLER_ERROR",Re="PAYPERCUT_ELEMENTS_CONTROLLER_ATTACH_COMPONENT",ke="PAYPERCUT_ELEMENTS_CONTROLLER_DETACH_COMPONENT",Oe="PAYPERCUT_ELEMENTS_CONTROLLER_VALIDATE_COMPONENT",xe="PAYPERCUT_ELEMENTS_CONTROLLER_SUBMIT_COMPONENT",Me="PAYPERCUT_ELEMENTS_CONTROLLER_CARD_COLLECTION_TOKENIZATION_RESULT",Le="PAYPERCUT_ELEMENTS_CONTROLLER_CANCEL_COMPONENT_SUBMISSION",De="PAYPERCUT_ELEMENTS_CONTROLLER_ATTACH_ACTION_CHANNEL",Fe="PAYPERCUT_ELEMENTS_CONTROLLER_UPDATE_OPTIONS",Ne="PAYPERCUT_ELEMENTS_CONTROLLER_DISCOVER_DEVELOPER_PRESETS",ze="PAYPERCUT_ELEMENTS_CONTROLLER_APPLY_DEVELOPER_PRESET",Ue="PAYPERCUT_ELEMENTS_CONTROLLER_APPLE_PAY_CAPABILITIES",qe="PAYPERCUT_ELEMENTS_CONTROLLER_APPLE_PAY_VALIDATE_MERCHANT",Be="PAYPERCUT_ELEMENTS_CONTROLLER_APPLE_PAY_AUTHORIZED",je="PAYPERCUT_ELEMENTS_CONTROLLER_APPLE_PAY_CANCELED",Ge="PAYPERCUT_ELEMENTS_CONTROLLER_GOOGLE_PAY_CLICK",He="PAYPERCUT_ELEMENTS_CONTROLLER_GOOGLE_PAY_CAPABILITIES",We="PAYPERCUT_ELEMENTS_CONTROLLER_GOOGLE_PAY_DATA_CHANGED",Ve="PAYPERCUT_ELEMENTS_CONTROLLER_GOOGLE_PAY_AUTHORIZED",$e="PAYPERCUT_ELEMENTS_CONTROLLER_GOOGLE_PAY_PAYMENT_DATA",Ye="PAYPERCUT_ELEMENTS_CONTROLLER_GOOGLE_PAY_CANCELED",Ke="PAYPERCUT_ELEMENTS_CONTROLLER_GOOGLE_PAY_ERROR",Ze="PAYPERCUT_ELEMENTS_CONTROLLER_RESOLVE_WALLET_CLICK",Je="PAYPERCUT_ELEMENTS_CONTROLLER_RESOLVE_WALLET_UPDATE",Xe="PAYPERCUT_ELEMENTS_CONTROLLER_RESOLVE_WALLET_CONFIRMATION",Qe="PAYPERCUT_ELEMENTS_CONTROLLER_UPDATE_COMPONENT_OPTIONS",et="PAYPERCUT_ELEMENTS_CONTROLLER_COMPONENT_EVENT",tt="PAYPERCUT_ELEMENTS_COMPONENT_FRAME_READY",it="PAYPERCUT_ELEMENTS_COMPONENT_CONNECT";function nt(e){return"ready"===e.event||"resize"===e.event||"secure_field_surface_invalid"===e.event}const ot=8192,rt=16,st=64,at=80,lt=160,ct=64,dt=256,pt=320,ht=32768,ut=65536,mt=16384,yt=1024,gt=8192,ft=4,bt=2,vt=3,wt=1,Pt=12,Et=2e3,At=512,Ct=["applePay","googlePay"],St=["channel","type"],_t=["channel","type","controllerId","payload"],It=["sessionId","cardCollection"],Tt=["protocolVersion","driver","publicKey","livemode","expiresAt"],Rt=[...Tt,"locale","messages"],kt=[...Rt,"capabilities"],Ot=["paymentMethodSubmission"],xt=[...Tt,"error"],Mt=["card"],Lt=["cardNumber","cardNumberPlaceholder","expirationDate","expirationDatePlaceholder","securityCode","cvvPlaceholder","errors"],Dt=["number","expirationDate","cvv"],Ft=["incomplete","invalid"],Nt=["channel","type","controllerId","payload"],zt=["code","message","recoverable"],Ut=["channel","type","controllerId","componentId","componentType","payload"],qt=[...Ut,"componentGeneration"],Bt=["x","y","width","height"],jt=e=>le(e)&&ce(e,Ct)&&"boolean"==typeof e.applePay&&"boolean"==typeof e.googlePay,Gt=e=>le(e)&&ce(e,St)&&e.channel===Ae&&e.type===tt,Ht=e=>!!(le(e)&&"basis_theory_v2"===e.driver&&de(e.publicKey,At)&&"boolean"==typeof e.livemode&&"string"==typeof e.expiresAt&&Number.isFinite(Date.parse(e.expiresAt)))&&(1===e.protocolVersion?ce(e,Tt):(2===e.protocolVersion||3===e.protocolVersion)&&(2===e.protocolVersion&&ce(e,Rt)?de(e.locale,dt)&&Vt(e.messages):3===e.protocolVersion&&ce(e,kt)&&le(e.capabilities)&&ce(e.capabilities,Ot)?!0===e.capabilities.paymentMethodSubmission&&de(e.locale,dt)&&Vt(e.messages):ce(e,xt)&&Wt(e.error))),Wt=e=>le(e)&&ce(e,zt)&&de(e.code,oe)&&de(e.message,re)&&"boolean"==typeof e.recoverable,Vt=e=>{if(!le(e)||!ce(e,Mt)||!le(e.card))return!1;const t=e.card;if(!ce(t,Lt)||!le(t.errors))return!1;const i=t.errors;if(!ce(i,Dt))return!1;return!!Lt.filter(e=>"errors"!==e).every(e=>de(t[e],re))&&Dt.every(e=>{const t=i[e];return le(t)&&ce(t,Ft)&&Ft.every(e=>de(t[e],re))})},$t=e=>"card"===e||"express_checkout"===e||"card_collection"===e||Yt(e),Yt=e=>"card_number"===e||"card_expiry"===e||"card_cvc"===e,Kt=(e,t)=>{const i=new Set(["event","complete","empty","brand","error"]);return!(!Object.keys(e).every(e=>i.has(e))||"boolean"!=typeof e.complete||"boolean"!=typeof e.empty||"card_number"!==t&&void 0!==e.brand||void 0!==e.brand&&!de(e.brand,ct))&&(void 0===e.error||le(e.error)&&ce(e.error,["type","message"])&&("incomplete"===e.error.type||"invalid"===e.error.type)&&de(e.error.message,re))},Zt=e=>"apple_pay"===e||"google_pay"===e,Jt=e=>le(e)&&Object.keys(e).every(e=>["type","brand","displayBrand","last4","expMonth","expYear","wallet"].includes(e))&&"card"===e.type&&de(e.brand,ct)&&de(e.displayBrand,ct)&&"string"==typeof e.last4&&/^\d{4}$/.test(e.last4)&&(void 0===e.expMonth||Number.isSafeInteger(e.expMonth)&&e.expMonth>=wt&&e.expMonth<=Pt)&&(void 0===e.expYear||Number.isSafeInteger(e.expYear)&&e.expYear>=Et)&&Zt(e.wallet),Xt=e=>"TEST"===e||"PRODUCTION"===e,Qt=e=>"string"==typeof e&&["book","buy","checkout","donate","order","pay","plain","short","subscribe"].includes(e),ei=e=>le(e)&&ce(e,Bt)&&Bt.every(t=>Number.isFinite(e[t]))&&e.x>=-8192&&e.x<=gt&&e.y>=-8192&&e.y<=gt&&e.width>0&&e.width<=ot&&e.height>0&&e.height<=ot,ti=(e,t)=>{if(!de(e,t))return!1;try{const t=JSON.parse(e);return le(t)}catch{return!1}},ii=e=>le(e)&&Object.keys(e).every(e=>"name"===e||"address"===e)&&(void 0===e.name||de(e.name,dt))&&(void 0===e.address||oi(e.address)),ni=e=>!(!le(e)||!le(e.total))&&(de(e.countryCode,bt)&&de(e.currencyCode,vt)&&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)))&&de(e.total.label,oe)&&/^\d+(?:\.\d{1,3})?$/.test(String(e.total.amount))&&["final","pending"].includes(String(e.total.type))),oi=e=>{if(!le(e))return!1;const t=new Set(["name","line1","line2","city","state","postalCode","country"]);return Object.entries(e).every(([e,i])=>t.has(e)&&de(i,"country"===e?bt:dt))},ri=e=>{if(!le(e))return!1;const t=new Set(["recipient","addressLine","city","state","postalCode","country"]);return Object.entries(e).every(([e,i])=>!!t.has(e)&&("addressLine"===e?Array.isArray(i)&&i.length<=ft&&i.every(e=>de(e,dt)):de(i,"country"===e?bt:dt)))},si=e=>le(e)&&Object.keys(e).every(e=>["id","displayName","amount","detail"].includes(e))&&de(e.id,oe)&&de(e.displayName,dt)&&Number.isSafeInteger(e.amount)&&e.amount>=0,ai=e=>{if(!le(e))return!1;const t=new Set(["name","email","phone","address"]);return Object.entries(e).every(([e,i])=>!!t.has(e)&&("address"===e?oi(i):de(i,"email"===e?pt:dt)))},li=e=>!!le(e)&&("succeeded"===e.status?ce(e,["status","paymentMethod"])&&le(e.paymentMethod)&&ce(e.paymentMethod,["id","type"])&&de(e.paymentMethod.id,oe)&&de(e.paymentMethod.type,ct):"failed"===e.status&&ce(e,["status","code","message","recoverable"])&&de(e.code,oe)&&de(e.message,re)&&"boolean"==typeof e.recoverable),ci=e=>le(e)&&de(e.id,st)&&de(e.label,at)&&de(e.description,lt)&&"string"==typeof e.last4&&/^\d{4}$/.test(e.last4)&&["success","challenge","warning","danger"].includes(String(e.tone)),di="paypercut-developer-assistance.iife.min.js",pi=/\/paypercut-checkout(?:-dev)?\.iife\.min\.js$/,hi="string"==typeof __filename?function(e){const t=e.replace(/\\/g,"/");return new URL(`file://${t.startsWith("/")?"":"/"}${t}`).href}(__filename):e&&"SCRIPT"===e.tagName.toUpperCase()&&e.src||new URL("paypercut-checkout.iife.min.js",document.baseURI).href,ui="undefined"==typeof document?null:document.currentScript?.getAttribute("src")??null;let mi=!1;function yi(e){mi||e()||(mi=!0,"undefined"!=typeof document&&"function"==typeof document.createElement&&Boolean(document.head||document.documentElement)?Promise.resolve().then(fi).then(()=>{if(!e())throw new Error}).catch(gi):gi())}function gi(){console.warn("[Paypercut Elements] developer_assistance_load_failed: Developer Assistant is unavailable. The SDK and Elements continue to work.")}function fi(){if(ui||function(e){try{return pi.test(new URL(e).pathname)}catch{return!1}}(hi))return e=function(e){const t=new URL(e);if(pi.test(t.pathname)){const e=new URL(di,t);return e.search=t.search,e.hash="",e.href}return/\.js$/.test(t.pathname)?t.pathname=t.pathname.replace(/[^/]+$/,di):/\/cdn\/?$/.test(t.pathname)?t.pathname=t.pathname.replace(/\/cdn\/?$/,`/dist/${di}`):t.pathname=`${t.pathname.replace(/\/$/,"")}/dist/${di}`,t.hash="",t.href}(hi),new Promise((t,i)=>{const n=document.createElement("script");n.async=!0,n.src=e,n.addEventListener("load",()=>t(),{once:!0}),n.addEventListener("error",()=>i(new Error),{once:!0}),(document.head||document.documentElement).appendChild(n)});var e;const t=new URL("developer-assistance.mjs",hi).href;return import(t)}const bi=Symbol.for("paypercut.checkout-js.developer-assistance");function vi(){const e=globalThis;return e[bi]??(e[bi]={coreVersions:new Set,provider:null,registrations:new Set}),e[bi]}function wi(){const e=vi();if(e.provider&&e.provider.version!==i){for(const t of e.registrations)Pi(t);e.provider=null}e.coreVersions.add(i)}function Pi(e){try{e.delegate?.unregister()}catch{}e.delegate=null}function Ei(e,t){e.registered&&(function(e){try{return e.target.isVisible?.()??!0}catch{return!1}}(e)?t.provider?.version!==i?yi(()=>function(e){return e.provider?.version===i&&Array.from(e.registrations).some(e=>e.registered&&null!==e.delegate)}(t)):function(e,t){if(e.registered&&!e.delegate)try{e.delegate=t.register(e.target)}catch{}}(e,t.provider):Pi(e))}let Ai=null;function Ci(e){const t=vi();wi();const i={target:e,delegate:null,registered:!0};return t.registrations.add(i),function(e){!Ai&&"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&document.documentElement&&(Ai=new MutationObserver(()=>{for(const t of e.registrations)Ei(t,e)}),Ai.observe(document.documentElement,{attributes:!0,attributeFilter:["aria-hidden","class","hidden","style"],childList:!0,subtree:!0}))}(t),Ei(i,t),{unregister(){i.registered&&(i.registered=!1,t.registrations.delete(i),Pi(i),function(e){e.registrations.size>0||(Ai?.disconnect(),Ai=null)}(t))},refresh(){i.registered&&(Ei(i,t),i.delegate?.refresh())},collapse(){i.registered&&i.delegate?.collapse()}}}function Si(e){if(!e?.isConnected)return!1;for(let t=e;t;t=t.parentElement){if(t.hidden||t.inert||"true"===t.getAttribute("aria-hidden"))return!1;const e=t.ownerDocument.defaultView?.getComputedStyle(t);if("none"===e?.display||"hidden"===e?.visibility||"collapse"===e?.visibility||"hidden"===e?.contentVisibility)return!1}return!0}let _i=!1;function Ii(e,t){const i=new URL(e);return i.searchParams.set("__paypercut_navigation",t),i.toString()}function Ti(e,t,i=!0){var n;e.set("controllerId",t.controllerId),e.set("apiKey",t.clientOptions.publishableKey),Ri(e,"account",t.clientOptions.account),i&&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){Ri(e,"publicOptions[appearance][theme]",t?.theme),Ri(e,"publicOptions[appearance][inputs]",t?.inputs),Ri(e,"publicOptions[appearance][labels]",t?.labels),Ri(e,"publicOptions[appearance][disableAnimations]",t?.disableAnimations);for(const[i,n]of Object.entries(t?.variables??{}).sort(([e],[t])=>e.localeCompare(t)))Ri(e,`publicOptions[appearance][variables][${i}]`,n);for(const[i,n]of Object.entries(t?.rules??{}).sort(([e],[t])=>e.localeCompare(t)))for(const[t,o]of Object.entries(n??{}).sort(([e],[t])=>e.localeCompare(t)))Ri(e,`publicOptions[appearance][rules][${i}][${t}]`,o)}(e,t.elementsOptions.appearance)}function Ri(e,t,i){void 0!==i&&e.set(t,String(i))}function ki(e,t,i){const n=new URL(e,t);n.hash=i.toString();const o=n.toString();return!_i&&o.length>4096&&(_i=!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}const Oi=new Set(["name","email","phone","address"]),xi=new Set(["line1","line2","city","state","postal_code","country"]),Mi=200,Li=320,Di=64,Fi=256,Ni=64,zi=(e,t,i)=>{if("string"!=typeof e)throw new Error(`[Paypercut Elements] Billing ${t} must be a string.`);const n=e.trim();if(0===n.length||n.length>i||ae(n))throw new Error(`[Paypercut Elements] Billing ${t} is invalid.`);return n};function Ui(e,t){return e===t||!(!e||!t)&&(e.name===t.name&&e.email===t.email&&e.phone===t.phone&&e.address?.line1===t.address?.line1&&e.address?.line2===t.address?.line2&&e.address?.city===t.address?.city&&e.address?.state===t.address?.state&&e.address?.postal_code===t.address?.postal_code&&e.address?.country===t.address?.country)}const qi="paypercut.elements.action",Bi="PAYPERCUT_ELEMENTS_ACTION_FRAME_READY",ji="PAYPERCUT_ELEMENTS_ACTION_INIT",Gi="PAYPERCUT_ELEMENTS_ACTION_WAKE",Hi="PAYPERCUT_ELEMENTS_ACTION_PHASE",Wi="PAYPERCUT_ELEMENTS_ACTION_RESULT",Vi="PAYPERCUT_ELEMENTS_ACTION_ERROR",$i=["channel","type","requestId","payload"],Yi=["channel","type"],Ki=["phase"],Zi=["status"],Ji=["code","message","recoverable"],Xi=(e,t)=>le(e)&&ce(e,$i)&&e.channel===qi&&e.type===t&&de(e.requestId,oe)&&void 0!==e.payload,Qi=e=>Xi(e,Hi)&&le(e.payload)&&ce(e.payload,Ki)&&"string"==typeof e.payload.phase&&["loading","content_ready","completing"].includes(e.payload.phase),en=e=>Xi(e,Wi)&&le(e.payload)&&ce(e.payload,Zi)&&"canceled"===e.payload.status,tn=e=>Xi(e,Vi)&&le(e.payload)&&ce(e.payload,Ji)&&de(e.payload.code,oe)&&de(e.payload.message,re)&&"boolean"==typeof e.payload.recoverable,nn=15e3,on=220,rn=400,sn=2147483647,an="rgb(40 40 40 / 0%)",ln="rgb(40 40 40 / 75%)",cn="transparent";let dn=0,pn="",hn="";const un=(e,t,i)=>{null===i?e.removeAttribute(t):e.setAttribute(t,i)};class mn{constructor(){this.host=null,this.active=!1,this.isolatedSiblings=new Map,this.isolationObserver=null}mount(){const e=this.ensureHost();return e.parentElement!==document.body&&document.body.prepend(e),e.removeAttribute("popover"),e.hidden=!1,e.style.display="block",e.style.visibility="visible",e.style.opacity="0",e.style.pointerEvents="none",e}open(){const e=this.mount();if(e.style.opacity="1",e.style.pointerEvents="auto",this.active||(this.active=!0,0===dn&&(pn=document.body.style.overflow,hn=document.documentElement.style.overflow,document.body.style.overflow="hidden",document.documentElement.style.overflow="hidden"),dn+=1,this.isolateMerchantPage(e)),e.setAttribute("popover","manual"),"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=an,this.host.style.opacity="0",this.host.style.pointerEvents="none")}finishClose(){const e=this.host;if(e){try{e.hidePopover?.()}catch{}e.hidden=!0,e.style.display="none",e.style.visibility="visible",e.style.opacity="0",e.style.pointerEvents="none",e.style.background=an,this.active&&(this.active=!1,this.restoreMerchantPage(),0!==dn&&(dn-=1,0===dn&&(document.body.style.overflow=pn,document.documentElement.style.overflow=hn)))}}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.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",visibility:"visible",opacity:"0",pointerEvents:"none",overflow:"hidden",background:an,colorScheme:"light only",transition:`background ${rn}ms ease-in-out, opacity ${rn}ms ease-in-out`,willChange:"background, opacity",zIndex:String(sn)}),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 i of e)for(const e of Array.from(i.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,i,n=nn){this.hostedOrigin=e,this.onCancel=t,this.onError=i,this.bootstrapTimeoutMs=n,this.host=new mn,this.frame=null,this.action=null,this.bootstrapTimeout=null,this.removalTimeout=null,this.previouslyFocused=null,this.componentPort=null,this.actionFrameInitialized=!1,this.actionPresented=!1,this.lifecycleInterrupted=!1,this.returnWakeListenersAttached=!1,this.onWindowMessage=e=>{const t=this.frame,i=this.action;if(t?.contentWindow&&i&&e.source===t.contentWindow&&e.origin===this.hostedOrigin){if(n=e.data,le(n)&&ce(n,Yi)&&n.channel===qi&&n.type===Bi){if(this.actionFrameInitialized)return;this.clearBootstrapTimeout();const e={channel:qi,type:ji,requestId:i.id,payload:{source:i.source??"component",actionId:i.id,actionType:i.type}},n=this.componentPort;return n?(t.contentWindow.postMessage(e,this.hostedOrigin,[n]),this.componentPort=null,this.actionFrameInitialized=!0,this.attachReturnWakeListeners(),void window.requestAnimationFrame(()=>{this.frame===t&&(t.style.opacity="1")})):void this.onError(i.id,"elements_action_channel_unavailable","The secure authentication channel is unavailable.",!0)}var n;if(!(Qi(e.data)||en(e.data)||tn(e.data))||e.data.requestId===i.id)return Qi(e.data)?(t.dataset.paypercutActionPhase=e.data.payload.phase,void("content_ready"!==e.data.payload.phase||this.actionPresented||(this.actionPresented=!0,t.removeAttribute("aria-hidden"),t.tabIndex=0,this.host.open(),window.requestAnimationFrame(()=>{this.frame===t&&this.actionPresented&&t.focus({preventScroll:!0})})))):void(en(e.data)?"canceled"===e.data.payload.status&&this.onCancel(i.id):tn(e.data)&&this.onError(i.id,e.data.payload.code,e.data.payload.message,e.data.payload.recoverable))}},this.onVisibilityChange=()=>{"visible"===document.visibilityState?this.sendReturnWake("visibility"):this.lifecycleInterrupted=!0},this.onPageHide=()=>{this.lifecycleInterrupted=!0},this.onPageShow=()=>{this.sendReturnWake("pageshow")},this.onOffline=()=>{this.lifecycleInterrupted=!0},this.onOnline=()=>{this.sendReturnWake("online")},this.onWindowFocus=()=>{this.lifecycleInterrupted&&this.sendReturnWake("focus")}}isOpen(){return null!==this.frame}show(e,t){if(this.action?.id===e.id&&this.frame)return void t.close();this.removeFrame(!1,!1),this.action=e,this.componentPort=t,this.actionFrameInitialized=!1,this.actionPresented=!1,this.lifecycleInterrupted=!1,this.previouslyFocused=document.activeElement instanceof HTMLElement?document.activeElement:null;const i=document.createElement("iframe");i.id=`paypercut-elements-action-frame-${e.id}`,i.title="3D Secure authentication",i.referrerPolicy="origin",i.src=new URL("/elements/actions/three-d-secure",this.hostedOrigin).toString(),i.allow="payment *; publickey-credentials-get *",i.setAttribute("allowtransparency","true"),i.setAttribute("frameborder","0"),i.setAttribute("aria-hidden","true"),i.tabIndex=-1,i.setAttribute("scrolling","no"),Object.assign(i.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:cn,colorScheme:"light only",opacity:"0",transition:`opacity ${on}ms ease-in-out`,willChange:"opacity"}),this.frame=i,window.addEventListener("message",this.onWindowMessage);this.host.mount().replaceChildren(i),this.bootstrapTimeout=window.setTimeout(()=>{this.frame===i&&this.onError(e.id,"elements_action_shell_timeout","The secure authentication window could not be loaded.",!0)},this.bootstrapTimeoutMs);let n=0;i.addEventListener("load",()=>{this.frame===i&&(n+=1,1!==n&&this.onError(e.id,"elements_submit_indeterminate","The secure authentication window reloaded while its result was unknown.",!1))})}close(){const e=this.frame;e&&(e.setAttribute("aria-hidden","true"),e.tabIndex=-1,e.style.opacity="0",this.host.beginClose(),this.clearRemovalTimeout(),this.removalTimeout=window.setTimeout(()=>{this.frame===e&&this.removeFrame()},rn))}destroy(){this.removeFrame(!0)}sendReturnWake(e){const t=this.frame,i=this.action;if(!this.actionFrameInitialized||!t?.contentWindow||!i||"visible"!==document.visibilityState)return;const n=((e,t)=>({channel:qi,type:Gi,requestId:e,payload:{source:t}}))(i.id,e);t.contentWindow.postMessage(n,this.hostedOrigin),this.lifecycleInterrupted=!1}attachReturnWakeListeners(){this.returnWakeListenersAttached||(this.returnWakeListenersAttached=!0,document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("pagehide",this.onPageHide),window.addEventListener("pageshow",this.onPageShow),window.addEventListener("offline",this.onOffline),window.addEventListener("online",this.onOnline),window.addEventListener("focus",this.onWindowFocus))}detachReturnWakeListeners(){this.returnWakeListenersAttached&&(this.returnWakeListenersAttached=!1,document.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("pagehide",this.onPageHide),window.removeEventListener("pageshow",this.onPageShow),window.removeEventListener("offline",this.onOffline),window.removeEventListener("online",this.onOnline),window.removeEventListener("focus",this.onWindowFocus))}removeFrame(e=!1,t=!0){const i=this.frame;this.frame=null,this.action=null,this.componentPort?.close(),this.componentPort=null,this.actionFrameInitialized=!1,this.lifecycleInterrupted=!1,this.detachReturnWakeListeners(),this.clearBootstrapTimeout(),this.clearRemovalTimeout(),window.removeEventListener("message",this.onWindowMessage),i?.remove(),e?this.host.destroy():this.host.finishClose();const n=this.previouslyFocused;if(this.previouslyFocused=null,t&&n?.isConnected)try{n.focus({preventScroll:!0})}catch{n.focus()}}clearBootstrapTimeout(){null!==this.bootstrapTimeout&&(window.clearTimeout(this.bootstrapTimeout),this.bootstrapTimeout=null)}clearRemovalTimeout(){null!==this.removalTimeout&&(window.clearTimeout(this.removalTimeout),this.removalTimeout=null)}}const gn=6e5;class fn{constructor(e){this.hostedOrigin=e,this.pending=null,this.indeterminateAttempt=null,this.completed=null,this.destroyed=!1,this.actionShell=null,this.futureUsageSelected=!1,this.billingDetailsSelected=!1}submit(e,t,i){if(this.destroyed)return Promise.reject(vn("elements_destroyed","The Elements group has been destroyed.",!1));if(this.futureUsageSelected&&this.selectedFutureUsage!==t||this.billingDetailsSelected&&!Ui(this.selectedBillingDetails,i))return Promise.reject(bn());if(this.completed)return this.completed.futureUsage===t&&Ui(this.completed.billingDetails,i)?Promise.resolve({...this.completed.reference}):Promise.reject(bn());if(this.indeterminateAttempt)return Promise.reject(vn("elements_submit_indeterminate","A previous submission has an unknown result. Create a new Elements group before making a deliberate new attempt.",!1));if(this.pending)return this.pending.source.submissionSourceId===e.submissionSourceId?this.pending.futureUsage===t&&Ui(this.pending.billingDetails,i)?this.pending.promise:Promise.reject(bn()):Promise.reject(vn("elements_submit_in_progress","Another payment method is already being prepared.",!0));try{e.assertCanSubmitPaymentMethod()}catch(e){return Promise.reject(wn(e))}this.futureUsageSelected=!0,this.selectedFutureUsage=t,this.billingDetailsSelected=!0,this.selectedBillingDetails=i;const n=j(),o=Date.now()+gn;let r,s;const a=new Promise((e,t)=>{r=e,s=t}),l={source:e,requestId:n,...t?{futureUsage:t}:{},...i?{billingDetails:i}:{},actionId:null,promise:a,resolve:r,reject:s,timeoutId:window.setTimeout(()=>{this.pending===l&&(this.markIndeterminate(l),this.cancelPendingSource(l,"timed_out"),this.rejectPending("elements_submit_timeout","Preparing the payment details timed out and the result is unknown.",!1))},gn)};this.pending=l,e.onPaymentMethodSubmissionStateChange();try{i?e.beginPaymentMethodSubmission(n,o,t,i):t?e.beginPaymentMethodSubmission(n,o,t):e.beginPaymentMethodSubmission(n,o)}catch{this.rejectPending("elements_submit_failed","Unable to submit the payment details.",!0)}return a}handleSourceEvent(e,t){"error"!==t.event?"action_required"!==t.event&&"submit_result"!==t.event||this.handleSubmissionEvent(e,t):this.handleSourceError(e,t)}handleSourceError(e,t){const i=this.pending;i?.source.submissionSourceId===e&&(this.markIndeterminate(i),this.cancelPendingSource(i,"failed"),this.rejectPending("elements_submit_indeterminate","elements_submit_indeterminate"===t.code?t.message:"The payment form became unavailable while its submission result was unknown.",!1))}hasActiveSubmission(e){return void 0===e?null!==this.pending||null!==this.indeterminateAttempt:this.pending?.source.submissionSourceId===e||null!==this.indeterminateAttempt}getIndeterminateAttemptError(){return this.indeterminateAttempt?vn("elements_submit_indeterminate","A previous submission has an unknown result. Create a new Elements group before making a deliberate new attempt.",!1):null}hasCompletedSubmission(e){return null!==this.completed}ownsAttempt(e,t){return this.pending?.source.submissionSourceId===e&&this.pending.requestId===t}releaseSource(e){const t=this.pending;if(t?.source.submissionSourceId===e){this.markIndeterminate(t);try{t.source.cancelPaymentMethodSubmission(t.requestId,"destroyed")}catch{}this.rejectPending("elements_submit_indeterminate","The payment form was removed while its submission result was unknown.",!1)}}reinitializeSource(e){const t=this.pending;if(t&&t.source.submissionSourceId===e){this.markIndeterminate(t);try{t.source.cancelPaymentMethodSubmission(t.requestId,"destroyed")}catch{}this.rejectPending("elements_submit_indeterminate","The secure payment form reloaded while its submission result was unknown.",!1)}}destroy(){this.destroyed||(this.destroyed=!0,this.pending&&(this.markIndeterminate(this.pending),this.cancelPendingSource(this.pending,"destroyed"),this.rejectPending("elements_submit_indeterminate","The Elements group was destroyed while its submission result was unknown.",!1)),this.actionShell?.destroy(),this.actionShell=null)}handleSubmissionEvent(e,t){const i=this.pending;if(i&&i.source.submissionSourceId===e&&t.requestId===i.requestId){if("action_required"===t.event){i.actionId=t.action.id;const e=new MessageChannel;try{i.source.attachPaymentMethodActionChannel(t.requestId,t.action.id,e.port1),this.getActionShell().show(t.action,e.port2),i.source.onPaymentMethodSubmissionStateChange()}catch{e.port1.close(),e.port2.close(),this.cancelPendingSource(i,"failed"),this.rejectPending("elements_action_channel_unavailable","The required payment authentication could not be opened.",!0)}return}if(this.pending=null,window.clearTimeout(i.timeoutId),this.actionShell?.close(),"succeeded"===t.result.status){const n={type:"payment_method",id:t.result.paymentMethod.id};this.completed={sourceId:e,...i.futureUsage?{futureUsage:i.futureUsage}:{},...i.billingDetails?{billingDetails:i.billingDetails}:{},reference:n},i.resolve({...n})}else"elements_submit_indeterminate"===t.result.code&&(this.indeterminateAttempt={sourceId:e,requestId:i.requestId}),i.reject(vn(t.result.code,t.result.message,t.result.recoverable));i.source.onPaymentMethodSubmissionStateChange()}}cancelAction(e){const t=this.pending;if(t&&t.actionId===e){try{t.source.cancelPaymentMethodSubmission(t.requestId,"canceled")}catch{}this.rejectPending("elements_action_canceled","Payment authentication was canceled.",!0)}}failAction(e,t,i,n){const o=this.pending;if(o&&o.actionId===e){"elements_submit_indeterminate"===t&&this.markIndeterminate(o);try{o.source.cancelPaymentMethodSubmission(o.requestId,"failed")}catch{}this.rejectPending(t,i,n)}}rejectPending(e,t,i){const n=this.pending;n&&(this.pending=null,window.clearTimeout(n.timeoutId),this.actionShell?.close(),n.reject(vn(e,t,i)),n.source.onPaymentMethodSubmissionStateChange())}cancelPendingSource(e,t){try{e.source.cancelPaymentMethodSubmission(e.requestId,t)}catch{}}markIndeterminate(e){this.indeterminateAttempt={sourceId:e.source.submissionSourceId,requestId:e.requestId}}getActionShell(){return this.actionShell??(this.actionShell=new yn(this.hostedOrigin,e=>this.cancelAction(e),(e,t,i,n)=>this.failAction(e,t,i,n))),this.actionShell}}const bn=()=>vn("elements_component_configuration_invalid","This Elements group has already started Payment Method creation with different futureUsage or billing details. Create a new Elements group to change either value.",!1);function vn(e,t,i){const n=new Error(t);return n.name="ElementsSubmitError",n.code=e,n.recoverable=i,n}const wn=e=>e instanceof Error&&"code"in e&&"string"==typeof e.code&&"recoverable"in e&&"boolean"==typeof e.recoverable?e:vn("elements_submit_failed",e instanceof Error?e.message:"Unable to submit the payment details.",!0);function Pn(e,t){const i=e.parentNode;if(!i)throw new Error("The payment component is not mounted.");const n={pointerEvents:e.style.pointerEvents,inert:e.inert,ariaBusy:e.getAttribute("aria-busy")},o={position:i instanceof HTMLElement?i.style.position:"",establishesContainingBlock:i instanceof HTMLElement&&"function"==typeof window.getComputedStyle&&"static"!==window.getComputedStyle(i).position},r=t.style.transition,s=t.style.opacity,a=t.id;t.id=`${a}-appearance-preview`,t.dataset.paypercutAppearanceTransition="replacement",t.setAttribute("aria-hidden","true"),t.inert=!0,t.style.position="absolute",t.style.inset="0",t.style.opacity="0",t.style.pointerEvents="none",t.style.transition="none";try{i instanceof HTMLElement&&!o.establishesContainingBlock&&(i.style.position="relative"),i.appendChild(t),e.dataset.paypercutAppearanceTransition="previous",e.setAttribute("aria-busy","true"),e.inert=!0,e.style.pointerEvents="none"}catch(e){throw t.remove(),t.id=a,i instanceof HTMLElement&&!o.establishesContainingBlock&&(i.style.position=o.position),e}let l=!1;const c=()=>{i instanceof HTMLElement&&!o.establishesContainingBlock&&(i.style.position=o.position)};return{previous:e,replacement:t,commit(){l||(l=!0,e.remove(),t.id=a,delete t.dataset.paypercutAppearanceTransition,t.removeAttribute("aria-hidden"),t.inert=!1,t.style.position="",t.style.inset="",t.style.opacity=s,t.style.pointerEvents="",t.getBoundingClientRect(),t.style.transition=r,c())},rollback(){l||(l=!0,t.remove(),delete e.dataset.paypercutAppearanceTransition,null===n.ariaBusy?e.removeAttribute("aria-busy"):e.setAttribute("aria-busy",n.ariaBusy),e.inert=n.inert,e.style.pointerEvents=n.pointerEvents,c())}}}class En{constructor(e){this.group=e,this.componentId=j(),this.componentType="card",this.componentGeneration=0,this.submissionSourceId=this.componentId,this.emitter=new t,this.iframe=null,this.mounted=!1,this.connected=!1,this.destroyed=!1,this.ready=!1,this.developerAssistant=null,this.pendingDeveloperPreset=null,this.pendingValidation=null,this.initializationTimeoutId=null,this.initializationReloads=0,this.pendingAppearanceRemount=null,this.appearancePreviewError=null,this.messageHandler=e=>this.onWindowMessage(e)}mount(e){if(this.destroyed)throw new Error("[Paypercut Elements] Cannot mount a destroyed Card Element.");if(this.mounted)return;if("undefined"==typeof window||"undefined"==typeof document)throw new Error("[Paypercut Elements] Card 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),i=this.createFrame();this.iframe=i,this.mounted=!0,this.group.markComponentMounted(),window.addEventListener("message",this.messageHandler),this.group.ensureController(),t.appendChild(i),this.armInitializationWatch(i)}on(e,t){return this.emitter.on(e,t)}assertCanSubmitPaymentMethod(){if(this.destroyed||this.group.isDestroyed())throw vn("elements_destroyed","The Card Element has been destroyed.",!1);if(!this.mounted)throw vn("elements_not_mounted","The Card Element has not been mounted.",!0);if(!this.ready)throw vn("elements_not_ready","The Card Element is not ready yet.",!0);if(this.pendingDeveloperPreset)throw vn("elements_test_preset_in_progress","Wait for the test card preset to finish filling before submitting.",!0)}validatePaymentMethod(){try{this.assertCanSubmitPaymentMethod()}catch(e){return Promise.reject(e)}if(this.pendingValidation)return this.pendingValidation.promise;const e=j();let t,i;const n=new Promise((e,n)=>{t=e,i=n}),o={requestId:e,promise:n,resolve:t,reject:i,timeoutId:window.setTimeout(()=>{this.pendingValidation===o&&(this.pendingValidation=null,i(vn("elements_submit_timeout","Validating the payment details timed out. Please try again.",!0)))},15e3)};this.pendingValidation=o;try{this.group.validateComponent(this.componentId,e)}catch{this.settleValidation(vn("elements_submit_failed","The secure card form could not be validated.",!0))}return n}beginPaymentMethodSubmission(e,t,i,n){this.clearInitializationWatch(),this.developerAssistant?.collapse(),this.developerAssistant?.refresh(),this.group.submitComponent(this.componentId,e,t,n)}cancelPaymentMethodSubmission(e,t){try{this.group.cancelComponentSubmission(this.componentId,e,t)}catch{}}attachPaymentMethodActionChannel(e,t,i){this.group.attachActionChannel(this.componentId,e,t,i)}onPaymentMethodSubmissionStateChange(){this.developerAssistant?.collapse(),this.developerAssistant?.refresh()}hasActiveSubmission(){return this.group.hasPaymentMethodSubmissionState(this.componentId)||null!==this.pendingValidation||null!==this.pendingDeveloperPreset}getComponentOptions(){return{}}handleControllerError(e){this.destroyed||(this.clearInitializationWatch(),this.ready=!1,this.settleValidation(vn(e.code,e.message,e.recoverable??!0)),this.emitter.emit("error",e))}handleControllerEvent(e){if(this.destroyed)return;const t=this.pendingAppearanceRemount;if(!t||nt(e))switch(e.event){case"ready":if(!this.ready){if(this.ready=!0,this.clearInitializationWatch(),t&&t===this.pendingAppearanceRemount){t.resolve(this.prepareSettledAppearanceTransition(t));break}this.emitter.emit("ready"),this.group.discoverDeveloperPresets(this.componentId)}break;case"secure_field_surface_invalid":if(!t||t!==this.pendingAppearanceRemount)break;if(!t.automaticRecoveryAttempted){this.retryInvalidAppearanceGeometry(t);break}this.showAppearancePreviewFailure(),this.rejectAppearanceRemount(new Error("The replacement Card Element reported invalid secure-field geometry twice."));break;case"resize":this.resize(e.height);break;case"error":this.handleControllerError(e);break;case"phase":this.developerAssistant?.refresh();break;case"action_required":case"submit_result":break;case"validation_result":if(e.requestId!==this.pendingValidation?.requestId)break;"succeeded"===e.result.status?this.settleValidation():this.settleValidation(vn(e.result.code,e.result.message,e.result.recoverable));break;case"developer_catalog":this.registerDeveloperPresets(e.presets);break;case"developer_apply_result":this.handleDeveloperApplyResult(e);break;case"change":this.group.invalidateSubmissionValidation()}else"error"===e.event&&this.rejectAppearanceRemount(new Error("The replacement Card Element could not render its Appearance."))}destroy(){this.destroyed||(this.destroyed=!0,this.rejectAppearanceRemount(new Error("The Card Element was destroyed during Appearance Preview.")),this.ready=!1,this.clearInitializationWatch(),this.settleValidation(vn("elements_destroyed","The Card Element has been destroyed.",!1)),this.clearDeveloperAssistant("The card form was destroyed."),"undefined"!=typeof window&&window.removeEventListener("message",this.messageHandler),this.iframe?.remove(),this.appearancePreviewError?.remove(),this.appearancePreviewError=null,this.iframe=null,this.mounted=!1,this.emitter.clear(),this.group.remove(this))}remountAppearance(){this.rejectAppearanceRemount(new Error("A newer Appearance Preview superseded this one."));const e=this.iframe,t=e?.parentNode;if(this.destroyed||!this.mounted||!e||!t)return Promise.resolve({commit:()=>{},rollback:()=>{}});let i,n;const o=new Promise((e,t)=>{i=e,n=t}),r=this.ready,s=this.componentGeneration;this.ready=!1,this.componentGeneration+=1,this.initializationReloads=0,this.clearInitializationWatch(),this.group.invalidateSubmissionValidation(),this.settleValidation(vn("elements_not_ready","The Card Element is refreshing its Appearance.",!0));try{const t=this.createFrame(),o=Pn(e,t);this.pendingAppearanceRemount={resolve:i,reject:n,transition:o,wasReady:r,settled:!1,automaticRecoveryAttempted:!1},this.iframe=t,this.group.detachComponent(this),this.armInitializationWatch(t)}catch(t){this.iframe=e,this.ready=r,this.componentGeneration=s;const i=t instanceof Error?t:new Error("Unable to replace the Card Element frame.");return this.pendingAppearanceRemount?this.rejectAppearanceRemount(i):n(i),o}return o}cancelAppearanceRemount(e,t){this.componentGeneration===e&&this.rejectAppearanceRemount(t)}markAppearanceRecoveryFailed(){this.ready=!1,this.iframe&&(this.iframe.inert=!0,this.iframe.style.pointerEvents="none"),this.emitter.emit("error",{code:"elements_appearance_preview_recovery_failed",message:"The Card Element could not restore its last Appearance.",recoverable:!0})}clearAppearancePreviewFailure(){this.appearancePreviewError?.remove(),this.appearancePreviewError=null}isMounted(){return this.mounted&&!this.destroyed}onWindowMessage(e){if(this.destroyed||!this.iframe?.contentWindow||e.source!==this.iframe.contentWindow||e.origin!==this.group.hostedOrigin||!Gt(e.data))return;const t=this.connected;this.connected=!0,t&&(this.ready=!1,this.group.invalidateSubmissionValidation(),this.settleValidation(vn("elements_reinitialized","The secure card form reloaded while it was being validated.",!0)),this.hasActiveSubmission()||this.armInitializationWatch(this.iframe));const i=new MessageChannel,n={channel:Ae,type:it,controllerId:this.group.controllerId,componentId:this.componentId,componentType:this.componentType};try{this.iframe.contentWindow.postMessage(n,this.group.hostedOrigin,[i.port2]),t?this.group.reattachComponent(this,i.port1):this.group.attachComponent(this,i.port1)}catch{if(i.port1.close(),i.port2.close(),this.pendingAppearanceRemount)return void this.rejectAppearanceRemount(new Error("The replacement Card Element could not connect to its controller."));this.handleControllerError({code:"elements_component_connect_failed",message:"The secure card 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})}armInitializationWatch(e){this.clearInitializationWatch(),this.initializationTimeoutId=window.setTimeout(()=>{if(this.initializationTimeoutId=null,!this.destroyed&&this.mounted&&!this.ready&&this.iframe===e&&!this.hasActiveSubmission())if(this.pendingAppearanceRemount)this.handleInitializationTimeout();else{if(this.initializationReloads<1){this.initializationReloads+=1;const t=e.parentNode;if(!t)return void this.handleInitializationTimeout();this.group.retryStalledControllerInitialization();const i=this.createFrame(),n=this.componentGeneration;this.componentGeneration+=1;try{this.iframe=i,t.replaceChild(i,e),this.armInitializationWatch(i)}catch{this.iframe=e,this.componentGeneration=n,this.handleInitializationTimeout()}return}this.handleInitializationTimeout()}},4e4)}createFrame(){const e=document.createElement("iframe");return e.id=`paypercut-card-element-${this.componentId}`,e.title="Secure card form",e.referrerPolicy="origin",e.src=Ii(function(e){const t=new URLSearchParams;return Ti(t,e),t.set("componentName","card"),t.set("elementId",e.componentId),t.set("mode",e.elementsOptions.mode),t.set("amount",String(e.elementsOptions.amount)),t.set("currency",e.elementsOptions.currency),ki("/elements/components/card",e.hostedOrigin,t)}({hostedOrigin:this.group.hostedOrigin,controllerId:this.group.controllerId,componentId:this.componentId,clientOptions:this.group.getClientOptions(),elementsOptions:this.group.getRenderableElementsOptions(),referrer:window.location.origin}),j()),e.allow="payment *; publickey-credentials-get *; autofill *",e.setAttribute("allowtransparency","true"),e.setAttribute("frameborder","0"),e.setAttribute("role","presentation"),e.setAttribute("scrolling","no"),Object.assign(e.style,{width:"100%",maxWidth:"100%",minWidth:"0",height:"0",margin:"0",padding:"0",border:"0",display:"block",overflow:"hidden",colorScheme:"normal",transition:"height 350ms ease-in-out, opacity 400ms ease-in-out 100ms",willChange:"height, opacity"}),e}clearInitializationWatch(){null!==this.initializationTimeoutId&&"undefined"!=typeof window&&window.clearTimeout(this.initializationTimeoutId),this.initializationTimeoutId=null}handleInitializationTimeout(){this.pendingAppearanceRemount?this.rejectAppearanceRemount(new Error("The replacement Card Element did not become ready in time.")):this.handleControllerError({code:"elements_component_initialization_timeout",message:"The secure card form did not become ready in time.",recoverable:!0})}retryInvalidAppearanceGeometry(e){if(e!==this.pendingAppearanceRemount||e.settled)return;const t=e.transition.previous;this.clearInitializationWatch(),e.transition.rollback(),this.iframe=t,this.componentGeneration+=1,this.initializationReloads=0,e.automaticRecoveryAttempted=!0;try{const i=this.createFrame();e.transition=Pn(t,i),this.iframe=i,this.group.detachComponent(this),this.armInitializationWatch(i)}catch(e){this.rejectAppearanceRemount(e instanceof Error?e:new Error("Unable to retry the Card Element Appearance Preview."))}}showAppearancePreviewFailure(){if(this.appearancePreviewError?.isConnected)return;const e=this.pendingAppearanceRemount?.transition.previous.parentNode;if(!(e instanceof HTMLElement))return;const t=document.createElement("div");t.dataset.paypercutAppearancePreviewError="true",t.setAttribute("role","alert"),t.setAttribute("aria-live","assertive"),t.textContent="Appearance Preview could not produce usable secure fields. Retry the Appearance update or restore a known-good Appearance.",Object.assign(t.style,{marginTop:"8px",padding:"10px 12px",border:"1px solid #f04438",borderRadius:"8px",color:"#b42318",background:"#fff1f0",font:"13px/1.4 system-ui, sans-serif"}),e.appendChild(t),this.appearancePreviewError=t}rejectAppearanceRemount(e){const t=this.pendingAppearanceRemount;t&&(this.pendingAppearanceRemount=null,t.settled||(t.settled=!0,t.transition.rollback(),this.iframe=t.transition.previous,this.ready=t.wasReady,t.reject(e)))}prepareSettledAppearanceTransition(e){return{commit:()=>{e.settled||(e.settled=!0,this.pendingAppearanceRemount===e&&(this.pendingAppearanceRemount=null),e.transition.commit(),queueMicrotask(()=>{this.destroyed||(this.emitter.emit("ready"),this.group.discoverDeveloperPresets(this.componentId))}))},rollback:()=>{e.settled||(e.settled=!0,this.pendingAppearanceRemount===e&&(this.pendingAppearanceRemount=null),e.transition.rollback(),this.iframe=e.transition.previous,this.ready=e.wasReady)}}}settleValidation(e){const t=this.pendingValidation;t&&(this.pendingValidation=null,window.clearTimeout(t.timeoutId),e?t.reject(e):t.resolve())}registerDeveloperPresets(e){!0===this.group.getClientOptions().developerAssistant&&(this.developerAssistant?this.developerAssistant.refresh():this.developerAssistant=Ci({id:`${this.group.controllerId}:${this.componentId}`,configurationIdentity:this.group.configurationIdentity,appearanceScopeId:this.group.controllerId,presets:e,isVisible:()=>Si(this.iframe?.parentElement??null),isAvailable:()=>this.canApplyDeveloperPreset(),isAppearanceAvailable:()=>this.isMounted(),appearancePreviewClearsTestData:()=>!0,canPreview:()=>this.group.isAppearancePreviewAvailable(),applyPreset:e=>this.applyDeveloperPreset(e),getAppearance:()=>this.group.getAppearance(),updateAppearance:e=>this.group.updateAppearance(e),replaceAppearance:e=>this.group.replaceAppearance(e),prepareAppearance:e=>this.group.prepareAppearance(e),prepareAppearanceReplacement:e=>this.group.prepareAppearanceReplacement(e)}))}canApplyDeveloperPreset(){return!0===this.group.getClientOptions().developerAssistant&&this.ready&&!this.destroyed&&!this.group.hasPaymentMethodSubmissionState(this.componentId)&&!this.group.hasCompletedPaymentMethodSubmission(this.componentId)&&!this.pendingDeveloperPreset}applyDeveloperPreset(e){if(!this.canApplyDeveloperPreset())return Promise.reject(new Error("Test card presets are unavailable right now."));const t=j();return new Promise((i,n)=>{const o={requestId:t,presetId:e,resolve:i,reject:n,timeoutId:window.setTimeout(()=>{this.pendingDeveloperPreset===o&&(this.pendingDeveloperPreset=null,n(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),n(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)))}}const An="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",Cn="apple-pay-modal",Sn="paypercut-apple-pay-modal-focus-style";let _n=null,In=null,Tn=0;function Rn(){"undefined"!=typeof window&&"undefined"!=typeof document&&(!function(){if(document.querySelectorAll(Cn).forEach(e=>{kn(e)}),In||!document.documentElement)return;In=new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e instanceof Element&&(e.matches(Cn)&&kn(e),e.querySelectorAll(Cn).forEach(e=>{kn(e)}))})})}),In.observe(document.documentElement,{childList:!0,subtree:!0})}(),Tn+=1)}function kn(e,t=0){const i=e.shadowRoot;if(!i)return void(t<F&&requestAnimationFrame(()=>kn(e,t+1)));if(i.getElementById(Sn))return;const n=document.createElement("style");n.id=Sn,n.textContent="[data-modal-element-overlay]:focus, [data-modal-element-overlay]:focus-visible, .modal-overlay:focus, .modal-overlay:focus-visible { outline: none !important; }",i.appendChild(n)}const On=250,xn=3500,Mn=["paymentMethods","layout","buttonType","buttonTheme","buttonHeight","buttonRadius"],Ln=6e4,Dn=3e4,Fn=.5,Nn=40,zn=64,Un=24,qn=4,Bn=64,jn=256,Gn=2,Hn=10,Wn={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 Vn{constructor(e,i={}){this.group=e,this.componentId=j(),this.componentType="express_checkout",this.componentGeneration=0,this.emitter=new t,this.componentRevision=0,this.iframe=null,this.mounted=!1,this.connectedFrame=null,this.destroyed=!1,this.ready=!1,this.developerAssistant=null,this.pendingPreview=null,this.previewTransitionActive=!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.googlePayPopupRecovery=null,this.googlePayUpdates=new Map,this.googlePayAuthorization=null,this.googlePayButtonTarget=null,this.googlePayButtonContainer=null,this.mountSurface=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,e=>this.cancelAction(e),(e,t,i,n)=>this.failAction(e,t,i,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=Zn(i)}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.");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);this.applePayModalObserverAcquired||(Rn(),this.applePayModalObserverAcquired=!0);const i=this.createFrame();this.iframe=i,this.mounted=!0,this.group.markComponentMounted(),window.addEventListener("message",this.messageHandler),this.group.ensureController(),this.mountSurface=function(e){const t=document.createElement("div");return t.dataset.paypercutElementsExpressMount="",Object.assign(t.style,{position:"relative",display:"block",width:"100%",minWidth:"0",margin:"0",padding:"0",border:"0"}),t.appendChild(e),t}(i),t.appendChild(this.mountSurface),this.registerDeveloperAssistant()}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(!oo(e)||0===Object.keys(e).length||"amount"in e)throw new Error("[Paypercut Elements] Express Checkout update options must contain checkout details or wallet order.");const{paymentMethodOrder:t,...i}=e;Qn(t);const n=Xn(i);return{...n,..."paymentMethodOrder"in e?{paymentMethodOrder:t?.slice()}:{}}}(e);if("paymentMethodOrder"in t&&this.previewTransitionActive)throw new Error("[Paypercut Elements] Cannot update wallet order while an Appearance preview is active.");if(this.options=Zn({...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 mo(this.pendingPreview?.nextOptions??this.options)}isMounted(){return this.mounted&&!this.destroyed}remountAppearance(){return this.preparePreviewFrame(this.options)}cancelAppearanceRemount(e,t){this.componentGeneration===e&&this.rejectPendingPreview(t)}markAppearanceRecoveryFailed(){this.ready=!1,this.previewTransitionActive=!1,this.iframe&&(this.iframe.inert=!0,this.iframe.style.pointerEvents="none"),this.googlePayButtonContainer&&(this.googlePayButtonContainer.style.visibility="hidden",this.googlePayButtonContainer.style.pointerEvents="none"),this.emitter.emit("error",{code:"elements_appearance_preview_recovery_failed",message:"Express Checkout could not restore its last Appearance.",recoverable:!0})}updateDeveloperDisplayOptions(e){const t=Zn(function(e,t){return{...e,...t,...t.paymentMethods?{paymentMethods:{...e.paymentMethods,...t.paymentMethods}}:{},...t.layout?{layout:{...e.layout,...t.layout}}:{},...t.buttonType?{buttonType:{...e.buttonType,...t.buttonType}}:{},...t.buttonTheme?{buttonTheme:{...e.buttonTheme,...t.buttonTheme}}:{}}}(this.options,e));return this.replacePreviewFrame(t,!0)}replaceDeveloperDisplayOptions(e){const t=mo(this.options);for(const e of Mn)delete t[e];return this.replacePreviewFrame(Zn({...t,...mo(e)}),!0)}hasActiveSubmission(){return null!==this.activeAttempt||null!==this.applePaySession||null!==this.googlePayRequestId}hasActiveProviderSubmission(){const e=null!==this.googlePayRequestId&&this.activeAttempt?.requestId===this.googlePayRequestId&&!1===this.activeAttempt.approved;return!0===this.activeAttempt?.approved||null!==this.applePaySession||null!==this.googlePayRequestId&&!e}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)return;const t=this.pendingPreview;if(!t||nt(e))switch(e.event){case"ready":if(!this.ready){if(this.ready=!0,t&&t===this.pendingPreview){window.clearTimeout(t.timeoutId),t.availablePaymentMethods={...e.availablePaymentMethods},t.resolve(this.prepareSettledPreviewTransition(t));break}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():_n||(_n=new Promise(e=>{const t=Array.from(document.scripts).find(e=>e.src===An),i=t??document.createElement("script"),n=()=>e();i.addEventListener("load",n,{once:!0}),i.addEventListener("error",n,{once:!0}),t||(i.src=An,i.crossOrigin="anonymous",i.async=!0,i.dataset.paypercutApplePaySdk="true",document.head.appendChild(i))}),_n)).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.activeAttempt.actionId=e.action.id,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})}else"error"===e.event&&this.failPendingPreview(new Error("The replacement Express Checkout frame could not render."))}emitWalletConfirm(e){const t=e.requestId;let i=!1;const n=(n,r)=>{if(!i&&!this.destroyed&&this.activeAttempt?.requestId===t){if(i=!0,window.clearTimeout(o),this.group.resolveWalletConfirmation(this.componentId,t,n,r),"apple_pay"===e.wallet)return this.completeApplePay(n),void this.finalizeWalletAttempt({requestId:t,skipApplePayCompletion:!0});this.finalizeWalletAttempt({requestId:t})}},o=window.setTimeout(()=>n(!1,{code:"merchant_confirmation_timeout",message:"The merchant did not finish the checkout in time."}),Ln),r={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:()=>n(!0),paymentFailed:e=>n(!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 r.paymentFailed(e)}try{this.emitter.emitAndThrow("confirm",r)}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}),r.paymentFailed(e)}}destroy(){this.destroyed||(this.destroyed=!0,this.rejectPendingPreview(new Error("Express Checkout was destroyed during Appearance Preview.")),this.developerAssistant?.unregister(),this.developerAssistant=null,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&&(Tn<=0?Tn=0:(Tn-=1,0===Tn&&(In?.disconnect(),In=null))),this.applePayModalObserverAcquired=!1),this.iframe?.remove(),this.iframe=null,this.mountSurface?.remove(),this.mountSurface=null,this.connectedFrame=null,this.mounted=!1,this.emitter.clear(),this.group.remove(this))}createFrame(e=this.options){const t=document.createElement("iframe"),i=!0===this.group.getRenderableElementsOptions().appearance?.disableAnimations;return t.id=`paypercut-express-checkout-element-${this.componentId}`,t.title="Express checkout",t.referrerPolicy="origin",t.src=Ii(function(e){const t=new URLSearchParams;return Ti(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),void 0!==e.options.paymentMethodOrder&&t.set("publicOptions[paymentMethodOrder]",e.options.paymentMethodOrder.join(",")),Ri(t,"publicOptions[paymentMethods][applePay]",e.options.paymentMethods?.applePay),Ri(t,"publicOptions[paymentMethods][googlePay]",e.options.paymentMethods?.googlePay),Ri(t,"publicOptions[layout][maxColumns]",e.options.layout?.maxColumns),Ri(t,"publicOptions[layout][maxRows]",e.options.layout?.maxRows),Ri(t,"publicOptions[layout][overflow]",e.options.layout?.overflow),Ri(t,"publicOptions[buttonType][applePay]",e.options.buttonType?.applePay),Ri(t,"publicOptions[buttonType][googlePay]",e.options.buttonType?.googlePay),Ri(t,"publicOptions[buttonTheme][applePay]",e.options.buttonTheme?.applePay),Ri(t,"publicOptions[buttonTheme][googlePay]",e.options.buttonTheme?.googlePay),Ri(t,"publicOptions[buttonHeight]",e.options.buttonHeight),Ri(t,"publicOptions[buttonRadius]",e.options.buttonRadius),Ri(t,"publicOptions[emailRequired]",e.options.emailRequired),Ri(t,"publicOptions[phoneNumberRequired]",e.options.phoneNumberRequired),Ri(t,"publicOptions[billingAddressRequired]",e.options.billingAddressRequired),Ri(t,"publicOptions[shippingAddressRequired]",e.options.shippingAddressRequired),e.options.allowedShippingCountries?.length&&t.set("publicOptions[allowedShippingCountries]",e.options.allowedShippingCountries.join(",")),ki("/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.getRenderableElementsOptions(),options:e,referrer:window.location.origin}),j()),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:i?"none":"height 250ms ease-in-out, opacity 250ms ease-in-out",willChange:i?"auto":"height, opacity"}),t}replacePreviewFrame(e,t=!1){const i=mo(this.options);return this.preparePreviewFrame(e,t).then(e=>e.commit(),async e=>{if(function(e){return oo(e)&&!0===e.skipAppearanceRecovery||oo(e)&&"elements_appearance_preview_refused"===e.code}(e))throw e;if(t&&!this.destroyed&&this.mounted)try{(await this.preparePreviewFrame(i)).commit()}catch{this.markAppearanceRecoveryFailed()}throw e})}preparePreviewFrame(e,t=!1){if(this.hasActiveSubmission()||!this.group.isAppearancePreviewAvailable())return Promise.reject(Object.assign(new Error("Express Checkout preview is unavailable while payment validation or a wallet attempt is active."),{code:"elements_appearance_preview_refused"}));this.rejectPendingPreview(Yn(new Error("A newer Express Checkout preview superseded this one.")));const i=this.iframe,n=i?.parentNode;if(this.destroyed||!this.mounted||!i||!n)return Promise.resolve({commit:()=>{},rollback:()=>{}});const o=this.ready;let r,s;this.ready=!1,this.componentGeneration+=1;const a=new Promise((e,t)=>{r=e,s=t});try{const n=this.createFrame(e),a=Pn(i,n),l={resolve:r,reject:s,timeoutId:0,nextOptions:mo(e),commitOptions:t,transition:a,wasReady:o,settled:!1};l.timeoutId=window.setTimeout(()=>{this.pendingPreview===l&&this.failPendingPreview(new Error("The replacement Express Checkout frame did not become ready."))},1e4),this.pendingPreview=l,this.previewTransitionActive=!0,this.iframe=n,this.googlePayButtonContainer&&(this.googlePayButtonContainer.style.pointerEvents="none"),this.group.detachComponent(this)}catch(e){this.iframe=i,this.ready=o,this.componentGeneration-=1,s(Yn(e instanceof Error?e:new Error("Unable to replace the Express Checkout frame.")))}return a}rejectPendingPreview(e){const t=this.pendingPreview;t&&(this.pendingPreview=null,window.clearTimeout(t.timeoutId),t.settled||(t.settled=!0,t.transition.rollback(),this.iframe=t.transition.previous,this.ready=t.wasReady,this.previewTransitionActive=!1,this.positionGooglePayButton(),t.reject(e)))}failPendingPreview(e){this.pendingPreview&&this.rejectPendingPreview(e)}prepareSettledPreviewTransition(e){return{commit:()=>{if(e.settled)return;e.settled=!0,this.pendingPreview===e&&(this.pendingPreview=null),e.transition.commit(),e.commitOptions&&(this.options=mo(e.nextOptions)),this.previewTransitionActive=!1,this.positionGooglePayButton();const t=e.availablePaymentMethods;queueMicrotask(()=>{!this.destroyed&&t&&this.emitter.emit("ready",{availablePaymentMethods:t})})},rollback:()=>{e.settled||(e.settled=!0,this.pendingPreview===e&&(this.pendingPreview=null),e.transition.rollback(),this.iframe=e.transition.previous,this.ready=e.wasReady,this.previewTransitionActive=!1,this.positionGooglePayButton())}}}registerDeveloperAssistant(){!0===this.group.getClientOptions().developerAssistant&&(this.developerAssistant=Ci({id:`${this.group.controllerId}:${this.componentId}:express-checkout`,configurationIdentity:this.group.configurationIdentity,appearanceScopeId:this.group.controllerId,componentDisplayScopeId:this.componentId,isVisible:()=>Si(this.iframe?.parentElement??null),isAvailable:()=>!0,isAppearanceAvailable:()=>this.isMounted(),canPreview:()=>this.group.isAppearancePreviewAvailable(),getAppearance:()=>this.group.getAppearance(),updateAppearance:e=>this.group.updateAppearance(e),replaceAppearance:e=>this.group.replaceAppearance(e),prepareAppearance:e=>this.group.prepareAppearance(e),prepareAppearanceReplacement:e=>this.group.prepareAppearanceReplacement(e),getComponentDisplayOptions:()=>{return mo({...(e=this.options).paymentMethods?{paymentMethods:e.paymentMethods}:{},...e.layout?{layout:e.layout}:{},...e.buttonType?{buttonType:e.buttonType}:{},...e.buttonTheme?{buttonTheme:e.buttonTheme}:{},...void 0!==e.buttonHeight?{buttonHeight:e.buttonHeight}:{},...void 0!==e.buttonRadius?{buttonRadius:e.buttonRadius}:{}});var e},updateComponentDisplayOptions:e=>this.updateDeveloperDisplayOptions(e),replaceComponentDisplayOptions:e=>this.replaceDeveloperDisplayOptions(e)}))}onWindowMessage(e){if(this.destroyed||!this.iframe?.contentWindow||e.source!==this.iframe.contentWindow||e.source===this.connectedFrame||e.origin!==this.group.hostedOrigin||!Gt(e.data))return;const t=this.connectedFrame,i=null!==t;this.connectedFrame=e.source;const n=new MessageChannel,o={channel:Ae,type:it,controllerId:this.group.controllerId,componentId:this.componentId,componentType:this.componentType};try{this.iframe.contentWindow.postMessage(o,this.group.hostedOrigin,[n.port2]),i?this.group.reattachComponent(this,n.port1):this.group.attachComponent(this,n.port1)}catch{this.connectedFrame=t,n.port1.close(),n.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(Wn).map(([t,i])=>{const n={name:t,value:e.style.getPropertyValue(t),priority:e.style.getPropertyPriority(t)};return e.style.setProperty(t,i,"important"),n});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[i,n]of Object.entries(e))t.style.setProperty(i,n,"important");const i=t.getBoundingClientRect();return void((Math.abs(i.left)>Fn||Math.abs(i.top)>Fn)&&t.style.setProperty("transform",`translate3d(${-i.left}px, ${-i.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:i,value:n,priority:o}of t)n?e.style.setProperty(i,n,o):e.style.removeProperty(i);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=mo(this.options),void this.group.resolveWalletClick(this.componentId,e,!0,this.options);let i=!1;const n=(n,r)=>{if(i||this.destroyed||this.activeAttempt?.requestId!==e)return;const s=n?Xn(r):void 0,{amount:a,...l}=s??{},c=Object.keys(l).length>0?l:void 0;i=!0,window.clearTimeout(o),n&&this.activeAttempt?.requestId===e&&(this.activeAttempt.approved=!0,this.activeOptions=mo({...this.options,...c??{}})),void 0===a?this.group.resolveWalletClick(this.componentId,e,n,c):this.group.resolveWalletClick(this.componentId,e,n,c,a),n||(this.group.endWalletAttempt(this.componentId,e),"google_pay"===t&&this.googlePayRequestId===e||(this.activeAttempt=null,this.activeOptions=null))},o=window.setTimeout(()=>n(!1),Dn),r=()=>{const e="merchant_click_handler_failed",t="The merchant click handler returned invalid data.";this.emitter.emit("error",{code:e,message:t,recoverable:!1}),n(!1)};try{this.emitter.emitAndThrow("click",{wallet:t,resolve:e=>{try{n(!0,e)}catch{r()}},reject:()=>n(!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}),n(!1)}}emitShippingAddressChange(e,t,i,n,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:i,address:n},o)}emitShippingRateChange(e,t,i,n,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:i,shippingRate:n},o)}emitShippingUpdate(e,t,i,n,o){let r=!1;const s=(e,n)=>{if(r||this.destroyed||this.activeAttempt?.requestId!==t)return;const s=e?function(e){if(void 0===e)return;if(!oo(e)||Object.keys(e).some(e=>!["amount","lineItems","shippingRates"].includes(e)))throw uo();const t=e.amount;if(void 0!==t&&("number"!=typeof t||!Number.isSafeInteger(t)||t<0))throw uo();return Jn(e.lineItems,"name"),Jn(e.shippingRates,"displayName",!0),mo(e)}(n):void 0;if(r=!0,window.clearTimeout(a),e&&s){const e=Object.prototype.hasOwnProperty.call(s,"lineItems"),t=Object.prototype.hasOwnProperty.call(s,"shippingRates");this.activeOptions=mo({...this.activeOptions??this.options,...e?{lineItems:s.lineItems}:{},...t?{shippingRates:s.shippingRates}:{}})}this.group.resolveWalletUpdate(this.componentId,t,i,e,s),o?.(this.walletUpdateSettlement(e,s))},a=window.setTimeout(()=>s(!1),Dn),l=e=>{this.emitter.emit("error",{code:"merchant_shipping_update_handler_failed",message:e,recoverable:!1}),s(!1)};try{this.emitter.emitAndThrow(e,{...n,resolve:e=>{try{s(!0,e)}catch{l("The merchant shipping update handler returned invalid data.")}},reject:()=>s(!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}),s(!1)}}cancelAction(e){const t=this.activeAttempt;t&&t.actionId===e&&this.group.cancelComponentSubmission(this.componentId,t.requestId)}failAction(e,t,i,n){const o=this.activeAttempt;o&&o.actionId===e&&(o&&this.finalizeWalletAttempt({cancelSubmission:!0}),this.emitter.emit("error",{code:t,message:i,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 Z(),this.destroyed)return;const i=ro(t),n=this.createGooglePayClient(e),o=await n.isReadyToPay(i);if(this.destroyed)return;this.googlePayClient=n,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 Z(),this.destroyed||t!==this.googlePayButtonGeneration)return;const i=ro(e.requestJson),n=i.allowedPaymentMethods;if(!Array.isArray(n))throw new Error("Invalid Google Pay request.");const o=this.createGooglePayClient(e.environment),r=await o.isReadyToPay({apiVersion:i.apiVersion,apiVersionMinor:i.apiVersionMinor,allowedPaymentMethods:n});if(this.destroyed||t!==this.googlePayButtonGeneration)return;const s=!0===r?.result;if(this.googlePayClient=o,this.googlePayEnvironment=e.environment,this.group.sendGooglePayCapabilities(this.componentId,s),!s)return void this.removeGooglePayButton();this.mountGooglePayButton(o,e,i,n)}catch{if(this.destroyed||t!==this.googlePayButtonGeneration)return;this.removeGooglePayButton(),this.group.sendGooglePayCapabilities(this.componentId,!1)}}mountGooglePayButton(e,t,i,n){if(this.removeGooglePayButton(),!this.mountSurface)return;const o=function(e){const t=document.createElement("div");return t.dataset.paypercutElementsGooglePayButton=e,Object.assign(t.style,{position:"absolute",margin:"0",padding:"0",border:"0",overflow:"hidden",zIndex:"2147483000",pointerEvents:"auto",visibility:"hidden"}),t}(this.componentId),r=e.createButton({buttonColor:t.buttonColor,buttonType:t.buttonType,buttonRadius:t.buttonRadius,buttonSizeMode:"fill",allowedPaymentMethods:n,onClick:()=>{if(this.destroyed||this.previewTransitionActive||this.googlePayRequestId||this.activeAttempt)return;const e=j();o.style.visibility="hidden",o.style.pointerEvents="none",this.group.sendGooglePayClick(this.componentId,e),this.startGooglePay(e,t.environment,so(i))}});Object.assign(r.style,{width:"100%",height:"100%",margin:"0"}),o.appendChild(r),this.mountSurface.appendChild(o),this.googlePayButtonContainer=o,window.addEventListener("resize",this.googlePayButtonPositionHandler),"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,i=this.iframe;if(!e||!t?.visible||!i||this.previewTransitionActive||this.googlePayRequestId)return;const n=i.getBoundingClientRect(),o=t.target.x,r=t.target.y;Object.assign(e.style,{left:`${o}px`,top:`${r}px`,width:`${t.target.width}px`,height:`${t.target.height}px`,borderRadius:`${t.buttonRadius}px`,visibility:n.width>0&&n.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),this.googlePayButtonResizeObserver?.disconnect(),this.googlePayButtonResizeObserver=null,this.googlePayButtonContainer?.remove(),this.googlePayButtonContainer=null}destroyGooglePayButton(){this.googlePayButtonGeneration+=1,this.googlePayButtonTarget=null,this.removeGooglePayButton()}startGooglePay(e,t,i){let n;this.clearGooglePayAttempt(),this.googlePayButtonContainer&&(this.googlePayButtonContainer.style.visibility="hidden",this.googlePayButtonContainer.style.pointerEvents="none");try{n=ro(i)}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 i=new Set(Array.isArray(n.callbackIntents)?n.callbackIntents.filter(e=>"string"==typeof e):[]),o={};(i.has("OFFER")||i.has("SHIPPING_ADDRESS")||i.has("SHIPPING_OPTION"))&&(o.onPaymentDataChanged=t=>this.requestGooglePayDataChanged(e,t)),i.has("PAYMENT_AUTHORIZATION")&&(o.onPaymentAuthorized=t=>this.requestGooglePayAuthorization(e,t)),this.googlePayClient=this.createGooglePayClient(t,Object.keys(o).length>0?o:void 0);const r=((e,t,i=window)=>{const n=i.open;let o=null,r=!1,s=!1,a=null,l=null;const c=(e,t,r)=>{const s=n.call(i,e,t,r);return!o&&s&&(o=s),s};try{i.open=c,r=i.open===c}catch{r=!1}let d;try{d=e()}finally{r&&i.open===c&&(i.open=n)}const p=()=>{s||(s=!0,null!==a&&i.clearTimeout(a),null!==l&&i.clearTimeout(l),a=null,l=null,o=null)},h=()=>{try{return i.document?.hasFocus()??!0}catch{return!1}},u=()=>{if(s||!o)return;let e=!1;try{e=o.closed}catch{return void p()}e&&h()?(a=null,l=i.setTimeout(()=>{s||(l=null,h()?(p(),t()):a=i.setTimeout(u,On))},xn)):a=i.setTimeout(u,On)};return o&&(a=i.setTimeout(u,On)),{result:d,stop:p}})(()=>this.googlePayClient.loadPaymentData(n),()=>{if(this.googlePayRequestId===e&&!this.destroyed)try{this.group.sendGooglePayCanceled(this.componentId,e)}finally{this.clearGooglePayAttempt(e)}});this.googlePayPopupRecovery=r;const s=r.result;Promise.resolve(s).then(t=>{this.googlePayRequestId!==e||this.destroyed||(this.clearGooglePayPopupRecovery(),this.googlePayProcessingRequestId=e,this.group.markWalletAttemptProcessing(this.componentId,e,"google_pay"),this.group.sendGooglePayPaymentData(this.componentId,e,so(t)))},t=>{if(this.googlePayRequestId===e&&!this.destroyed)try{!function(e){return oo(e)&&("CANCELED"===e.statusCode||"CANCELED"===e.code)}(t)?this.group.sendGooglePayError(this.componentId,e,co(t),po(t)):this.group.sendGooglePayCanceled(this.componentId,e)}finally{this.clearGooglePayAttempt(e)}})}catch(t){this.group.sendGooglePayError(this.componentId,e,co(t),po(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 i=globalThis.google?.payments?.api?.PaymentsClient;if(!i)throw new Error("Google Pay is unavailable.");return new i({environment:e,...t?{paymentDataCallbacks:t}:{}})}requestGooglePayDataChanged(e,t){if(this.googlePayRequestId!==e)return Promise.resolve(ao("OTHER_ERROR","The payment attempt is stale."));const i=j();return new Promise(n=>{const o=setTimeout(()=>{this.googlePayUpdates.delete(i),n(ao("OTHER_ERROR","The merchant update timed out."))},Dn);this.googlePayUpdates.set(i,{requestId:e,resolve:n,timeout:o});try{this.group.sendGooglePayDataChanged(this.componentId,e,i,so(t))}catch{clearTimeout(o),this.googlePayUpdates.delete(i),n(ao("OTHER_ERROR","The merchant update was invalid."))}})}requestGooglePayAuthorization(e,t){return this.googlePayRequestId!==e||this.googlePayAuthorization?Promise.resolve(lo("The payment attempt is stale.")):new Promise(i=>{const n=setTimeout(()=>{this.googlePayAuthorization=null,i(lo("The merchant authorization timed out."))},Dn);this.googlePayAuthorization={requestId:e,resolve:i,timeout:n};try{this.group.sendGooglePayAuthorized(this.componentId,e,so(t))}catch{clearTimeout(n),this.googlePayAuthorization=null,i(lo("The merchant authorization was invalid."))}})}resolveGooglePayDataChanged(e,t,i){const n=this.googlePayUpdates.get(t);if(n&&n.requestId===e&&this.googlePayRequestId===e){this.googlePayUpdates.delete(t),clearTimeout(n.timeout);try{n.resolve(ro(i))}catch{n.resolve(ao("OTHER_ERROR","The merchant update was invalid."))}}}resolveGooglePayAuthorization(e,t){const i=this.googlePayAuthorization;if(i&&i.requestId===e&&this.googlePayRequestId===e){this.googlePayAuthorization=null,clearTimeout(i.timeout);try{i.resolve(ro(t))}catch{i.resolve(lo("The merchant authorization was invalid."))}}}clearGooglePayAttempt(e){if(!e||this.googlePayRequestId===e){this.clearGooglePayPopupRecovery(),this.googlePayRequestId=null,this.googlePayProcessingRequestId=null;for(const e of this.googlePayUpdates.values())clearTimeout(e.timeout),e.resolve(ao("OTHER_ERROR","The payment attempt was canceled."));this.googlePayUpdates.clear(),this.googlePayAuthorization&&(clearTimeout(this.googlePayAuthorization.timeout),this.googlePayAuthorization.resolve(lo("The payment attempt was canceled.")),this.googlePayAuthorization=null),this.positionGooglePayButton()}}clearGooglePayPopupRecovery(){this.googlePayPopupRecovery?.stop(),this.googlePayPopupRecovery=null}startApplePay(e,t){this.abortApplePay();const i=window.ApplePaySession;if(!i||!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 n;try{const e=N(i);n=new i(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=n,n.onvalidatemerchant=t=>{this.applePayTimeout=setTimeout(()=>{this.abortApplePay(),this.group.sendApplePayCanceled(this.componentId,e)},D),this.group.sendApplePayValidateMerchant(this.componentId,e,t.validationURL)},n.onpaymentauthorized=t=>{this.group.sendApplePayAuthorized(this.componentId,e,t.payment)},n.onshippingcontactselected=i=>{const o=function(e){if(!oo(e))return;const t=Array.isArray(e.addressLines)?e.addressLines.filter(e=>"string"==typeof e&&""!==e):[],i=[e.givenName,e.familyName].filter(e=>"string"==typeof e&&""!==e).join(" "),n={...i?{recipient:i}:{},...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(n).length?n:void 0}(i.shippingContact);o?this.emitShippingAddressChange(e,j(),"apple_pay",o,e=>this.completeApplePayShippingContactSelection(n,t,e)):this.completeApplePayShippingContactSelection(n,t,{accepted:!1,amount:this.group.getUpdateSnapshot().options.amount,currency:this.group.getUpdateSnapshot().options.currency})},n.onshippingmethodselected=i=>{const o=(this.activeOptions?.shippingRates??this.options.shippingRates??[]).find(e=>e.id===i.shippingMethod?.identifier);o?this.emitShippingRateChange(e,j(),"apple_pay",o,e=>this.completeApplePayShippingMethodSelection(n,t,e)):this.completeApplePayShippingMethodSelection(n,t,{accepted:!1,amount:this.group.getUpdateSnapshot().options.amount,currency:this.group.getUpdateSnapshot().options.currency})},n.oncancel=()=>{this.clearApplePayTimeout(),this.applePaySession=null,this.activeOptions=null,this.group.sendApplePayCanceled(this.componentId,e)};try{n.begin()}catch{this.abortApplePay(),this.group.sendApplePayCanceled(this.componentId,e)}}completeApplePay(e){if(!this.applePaySession)return;const t=this.applePaySession,i=window.ApplePaySession;this.clearApplePayTimeout(),this.applePaySession=null;try{t.completePayment(e?i.STATUS_SUCCESS:i.STATUS_FAILURE)}catch{try{t.abort()}catch{}}}abortApplePay(){this.clearApplePayTimeout();try{this.applePaySession?.abort()}catch{}this.applePaySession=null}walletUpdateSettlement(e,t){const i=this.group.getUpdateSnapshot().options;return{accepted:e,...t?{update:t}:{},amount:t?.amount??i.amount,currency:i.currency}}prepareApplePayRequest(e){const t=this.group.getUpdateSnapshot().options,i=this.activeOptions??this.options,n=t.currency;return{...e,currencyCode:n.toUpperCase(),total:to(e.total.label,t.amount,n),...i.lineItems?.length?{lineItems:io(i.lineItems,n)}:{lineItems:void 0},...i.shippingAddressRequired?{requiredShippingContactFields:["name","postalAddress",...i.emailRequired?["email"]:[],...i.phoneNumberRequired?["phone"]:[]]}:{requiredShippingContactFields:void 0},...i.shippingAddressRequired&&i.shippingRates?.length?{shippingMethods:no(i.shippingRates,n)}:{shippingMethods:void 0}}}completeApplePayShippingContactSelection(e,t,i){if(e!==this.applePaySession)return;const n=i.update?.shippingRates??this.activeOptions?.shippingRates??[],o=window.ApplePayError;try{e.completeShippingContactSelection({newShippingMethods:i.accepted?no(n,i.currency):[],newTotal:to(t.total.label,i.amount,i.currency),newLineItems:io(i.update?.lineItems??this.activeOptions?.lineItems,i.currency),...!i.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,i){if(e===this.applePaySession)try{e.completeShippingMethodSelection({newTotal:to(t.total.label,i.amount,i.currency),newLineItems:io(i.update?.lineItems??this.activeOptions?.lineItems,i.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 $n=new Set(["paymentMethodOrder","paymentMethods","layout","buttonType","buttonTheme","buttonHeight","buttonRadius","emailRequired","phoneNumberRequired","billingAddressRequired","shippingAddressRequired","allowedShippingCountries","lineItems","shippingRates"]);function Yn(e){return Object.assign(e,{skipAppearanceRecovery:!0})}const Kn=256;function Zn(e){const t=e;if(!oo(t)||Object.keys(t).some(e=>!$n.has(e)))throw new Error("[Paypercut Elements] Express Checkout options are invalid.");if(Qn(e.paymentMethodOrder),void 0!==e.buttonHeight&&("number"!=typeof e.buttonHeight||!Number.isSafeInteger(e.buttonHeight)||e.buttonHeight<Nn||e.buttonHeight>zn))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>Un))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 uo();for(const t of["maxColumns","maxRows"]){const i=e.layout[t];if(void 0!==i&&("number"!=typeof i||!Number.isSafeInteger(i)||i<1||i>qn))throw uo()}if(void 0!==e.layout.overflow&&!["auto","never"].includes(e.layout.overflow))throw uo()}if(e.paymentMethods)for(const t of Object.values(e.paymentMethods))if(void 0!==t&&!["auto","always","never"].includes(t))throw uo();if(e.buttonType){if(void 0!==e.buttonType.applePay&&!["plain","buy","check-out","donate","book","subscribe"].includes(e.buttonType.applePay))throw uo();if(void 0!==e.buttonType.googlePay&&!["plain","pay","buy","checkout","donate","book","subscribe"].includes(e.buttonType.googlePay))throw uo()}if(e.buttonTheme){if(void 0!==e.buttonTheme.applePay&&!["black","white","white-outline"].includes(e.buttonTheme.applePay))throw uo();if(void 0!==e.buttonTheme.googlePay&&!["black","white"].includes(e.buttonTheme.googlePay))throw uo()}if(e.allowedShippingCountries&&(!Array.isArray(e.allowedShippingCountries)||e.allowedShippingCountries.length>Kn||e.allowedShippingCountries.some(e=>!/^[A-Za-z]{2}$/.test(e))))throw uo();for(const t of[e.emailRequired,e.phoneNumberRequired,e.billingAddressRequired,e.shippingAddressRequired])if(void 0!==t&&"boolean"!=typeof t)throw uo();return Jn(e.lineItems,"name"),Jn(e.shippingRates,"displayName",!0),mo({...e,...e.allowedShippingCountries?{allowedShippingCountries:e.allowedShippingCountries.map(e=>e.toUpperCase())}:{}})}function Jn(e,t,i=!1){if(void 0!==e){if(!Array.isArray(e)||e.length>Bn)throw uo();for(const n of e)if(!oo(n)||"number"!=typeof n.amount||!Number.isSafeInteger(n.amount)||n.amount<0||!ho(n[t],jn)||i&&!ho(n.id,oe))throw uo()}}function Xn(e){if(void 0===e)return;const t=new Set(["amount","lineItems","emailRequired","phoneNumberRequired","billingAddressRequired","shippingAddressRequired","allowedShippingCountries","shippingRates"]);if(!oo(e)||Object.keys(e).some(e=>!t.has(e)))throw uo();if(void 0!==e.amount&&("number"!=typeof e.amount||!Number.isSafeInteger(e.amount)||e.amount<0))throw uo();Jn(e.lineItems,"name"),Jn(e.shippingRates,"displayName",!0);for(const t of[e.emailRequired,e.phoneNumberRequired,e.billingAddressRequired,e.shippingAddressRequired])if(void 0!==t&&"boolean"!=typeof t)throw uo();if(void 0!==e.allowedShippingCountries&&(!Array.isArray(e.allowedShippingCountries)||e.allowedShippingCountries.length>Kn||e.allowedShippingCountries.some(e=>!/^[A-Za-z]{2}$/.test(e))))throw uo();return mo({...e,...e.allowedShippingCountries?{allowedShippingCountries:e.allowedShippingCountries.map(e=>e.toUpperCase())}:{}})}function Qn(e){if(void 0!==e&&(!Array.isArray(e)||[...e].some(e=>"apple_pay"!==e&&"google_pay"!==e)||new Set(e).size!==e.length))throw uo()}function eo(e,t){const i=function(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e.toUpperCase()}).resolvedOptions().maximumFractionDigits??Gn}catch{return Gn}}(t);return(e/Hn**i).toFixed(i)}function to(e,t,i){return{label:e,amount:eo(t,i),type:"final"}}function io(e,t){return(e??[]).map(e=>({label:e.name,amount:eo(e.amount,t),type:"final"}))}function no(e,t){return e.map(e=>({identifier:e.id,label:e.displayName,detail:"",amount:eo(e.amount,t)}))}function oo(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ro(e){const t=JSON.parse(e);if(!oo(t))throw new Error("Expected a JSON object.");return t}function so(e){if(!oo(e))throw new Error("Expected an object.");return JSON.stringify(e)}function ao(e,t){return{error:{reason:e,message:t,intent:"PAYMENT_AUTHORIZATION"}}}function lo(e){return{transactionState:"ERROR",error:{intent:"PAYMENT_AUTHORIZATION",reason:"PAYMENT_DATA_INVALID",message:e}}}function co(e){if(oo(e)){const t=e.statusCode??e.code;if(de(t,oe))return t}return"elements_google_pay_failed"}function po(e){if(oo(e)){const t=e.statusMessage??e.message;if(de(t,re))return t}return e instanceof Error&&e.message?e.message.slice(0,re):"Google Pay could not be completed."}const ho=de;function uo(){return new Error("[Paypercut Elements] Express Checkout options are invalid.")}function mo(e){return JSON.parse(JSON.stringify(e))}const yo="16px",go="1094 / 742",fo="http://www.w3.org/2000/svg";let bo=null;const vo=(e,t,i)=>{null===i?e.removeAttribute(t):e.setAttribute(t,i)};class wo{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,i,n,o){const r=bo;if(r)return r.owner===this&&r.componentId===e&&r.requestId===t;const s=this.ensureHost();return bo={owner:this,componentId:e,requestId:t},this.cancelAttempt=n,this.providerElement=o??null,this.previouslyFocused=document.activeElement instanceof HTMLElement?document.activeElement:null,this.updateCopy(i,"provider_open"),document.body.prepend(s),s.hidden=!1,s.style.display="flex",this.lockMerchantPage(s),document.addEventListener("keydown",this.keyHandler,!0),this.cancelButton?.focus({preventScroll:!0}),!0}setPhase(e,t,i,n){this.matches(e,t)&&this.updateCopy(i,n)}hide(e,t){this.matches(e,t)&&this.hideHost()}close(e,t){this.matches(e,t)&&(bo=null,this.cancelAttempt=null,this.providerElement=null,this.hideHost())}destroy(){bo?.owner===this&&(bo=null),this.cancelAttempt=null,this.providerElement=null,this.hideHost(),this.host?.remove(),this.host=null,this.cancelButton=null}isActive(){return bo?.owner===this}matches(e,t){return bo?.owner===this&&bo.componentId===e&&bo.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 i=document.createElement("div");i.dataset.paypercutWalletBadge="",i.dataset.paypercutWalletOverlayTile="",Object.assign(i.style,{width:"min(165.52107px, 46vw)",aspectRatio:go,padding:"0",border:"0",boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"center",overflow:"visible",background:"transparent",boxShadow:"none"});const n=document.createElement("h2");n.id="paypercut-wallet-overlay-title",Object.assign(n.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:`${yo} 0 0`,color:"rgba(255, 255, 255, 0.9)",fontSize:"clamp(16px, 3.6vw, 18px)",lineHeight:"1.45",fontWeight:"400"});const r=(()=>{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(fo,"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 i=document.createElementNS(fo,"circle");i.setAttribute("cx","12"),i.setAttribute("cy","12"),i.setAttribute("r","9"),i.setAttribute("fill","none"),i.setAttribute("stroke","rgba(255, 255, 255, 0.28)"),i.setAttribute("stroke-width","2.5");const n=document.createElementNS(fo,"circle");if(n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9"),n.setAttribute("fill","none"),n.setAttribute("stroke","#fff"),n.setAttribute("stroke-width","2.5"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-dasharray","18 39"),!("function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches)){const e=document.createElementNS(fo,"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"),n.append(e)}return t.append(i,n),e.append(t),e})(),s=document.createElement("button");return s.type="button",s.textContent="Cancel payment",s.addEventListener("click",()=>this.cancel()),s.addEventListener("focus",()=>{s.style.boxShadow=s.matches(":focus-visible")?"0 0 0 3px rgba(138, 188, 255, 0.9)":"none"}),s.addEventListener("blur",()=>{s.style.boxShadow="none"}),s.addEventListener("pointerenter",()=>{s.style.background="rgba(132, 132, 132, 0.42)"}),s.addEventListener("pointerleave",()=>{s.style.background="rgba(111, 111, 111, 0.32)"}),Object.assign(s.style,{width:"min(260px, 100%)",minHeight:"44px",marginTop:yo,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(i,n,o,r,s),e.append(t),this.host=e,this.cancelButton=s,e}updateCopy(e,t){const i=(e=>"apple_pay"===e?"Apple Pay":"Google Pay")(e),n=this.host?.querySelector("[data-paypercut-wallet-badge]"),o=this.host?.querySelector("[data-paypercut-wallet-progress]"),r=this.host?.querySelector("#paypercut-wallet-overlay-title"),s=this.host?.querySelector("#paypercut-wallet-overlay-description");if(this.host&&(this.host.dataset.paypercutWalletOverlayPhase=t,this.host.setAttribute("aria-busy","processing"===t?"true":"false")),n&&(n.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 i=t.content.firstElementChild;if(!(i instanceof SVGElement))throw new Error("Unable to create the wallet provider mark.");return i.removeAttribute("style"),i.setAttribute("aria-hidden","true"),i.setAttribute("focusable","false"),i.dataset.paypercutWalletMark=e,Object.assign(i.style,{display:"block",flex:"none",width:"apple_pay"===e?"68.74%":"100%",maxWidth:"100%",height:"apple_pay"===e?"auto":"100%"}),i})(e)),n.style.aspectRatio=go,n.style.background="transparent",n.style.boxShadow="none",n.style.display="provider_open"===t?"flex":"none"),r&&(r.style.marginTop="processing"===t?"0":"apple_pay"===e?"8px":"2px"),o&&(o.style.display="processing"===t?"grid":"none"),"processing"===t)return r&&(r.textContent="Processing your payment"),void(s&&(s.textContent=`${i} returned your payment details. Please wait while we securely prepare the next step.`));r&&(r.textContent=`${i} is open`),s&&(s.textContent=`Complete your payment in the open ${i} window, or close ${i} 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),i=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&&i(e);this.isolationObserver=new MutationObserver(e=>{for(const t of e)for(const e of Array.from(t.addedNodes))e instanceof HTMLElement&&i(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,vo(e.element,"aria-hidden",e.ariaHidden),vo(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}}}const Po={colorPrimary:"#0570de",colorPrimaryText:"#ffffff",colorBackground:"#ffffff",colorSurface:"#ffffff",colorText:"#2b2d2f",colorTextSecondary:"#6a6c6f",colorTextPlaceholder:"#737474",colorDanger:"#cc1818",colorSuccess:"#30b130",colorWarning:"#e69e2c",colorBorder:"#d7dde0",colorFocus:"#0570de",colorMuted:"#f2f4f5",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',fontSizeBase:"16px",fontWeightNormal:"400",fontWeightMedium:"500",lineHeight:"1.5",spacingUnit:"4px",gridColumnSpacing:"12px",gridRowSpacing:"12px",labelSpacing:"6px",borderRadius:"4px",buttonBorderRadius:"4px",buttonExpressCheckoutBorderRadius:"4px",buttonPadding:"12px"},Eo={...Po,colorBackground:"#15171c",colorSurface:"#1d2027",colorText:"#f3f4f6",colorTextSecondary:"#aeb7c7",colorTextPlaceholder:"#8f99aa",colorBorder:"#3a404b",colorFocus:"#7db7ff",colorMuted:"#252932"},Ao=new Set(Object.keys(Po)),Co=/var\(\s*--([A-Za-z][A-Za-z0-9]*)\s*\)/g;function So(e){const t=e?.theme??"light",i="dark"===t?Eo:Po,n=Object.fromEntries(Object.entries(e?.variables??{}).filter(([e,t])=>Ao.has(e)&&"string"==typeof t));return{theme:t,disableAnimations:e?.disableAnimations??!1,variables:{...i,...n}}}function _o(e,t){const i=e?.rules?.[t];if(!i)return{};const n=So(e).variables;return Object.fromEntries(Object.entries(i).flatMap(([e,t])=>"string"==typeof t&&ge(t)?[[e,t.replace(Co,(e,t)=>t in n?n[t]:e)]]:[]))}function Io(e,t){const i=So(e).variables,n=_o(e,".Input"),o=_o(e,".Input--invalid"),r=n.backgroundColor??i.colorSurface,s=n.color??i.colorText,a=o.backgroundColor??r,l=o.color??s,c="undefined"!=typeof navigator&&/\bCriOS\//.test(navigator.userAgent),d=e=>c?`${e} !important`:e;return{base:{backgroundColor:r,color:s,fontFamily:i.fontFamily,fontSize:i.fontSizeBase,fontWeight:i.fontWeightNormal,lineHeight:i.lineHeight,padding:t&&t.floatingLabels?t.floatingLabelActive?"23px 12px 9px 12px":"16px 12px 16px 12px":"12px","::placeholder":{color:i.colorTextPlaceholder},":disabled":{backgroundColor:r},...n},empty:{backgroundColor:d(r),color:d(s)},invalid:{...o,backgroundColor:d(a),color:d(l)},complete:{backgroundColor:d(r),color:d(s)}}}const To=(e,t)=>Array.from({length:t},()=>e).join(" + "),Ro="http://www.w3.org/2000/svg",ko=(e,t,i)=>{const n=document.createElementNS(Ro,"svg");return n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false"),n.setAttribute("width",String(e)),n.setAttribute("height",String(t)),n.setAttribute("viewBox",i),n.style.display="block",n.style.flex="none",n},Oo=(e,t)=>{const i=document.createElementNS(Ro,"rect");for(const[e,n]of Object.entries(t))i.setAttribute(e,n);return e.appendChild(i),i},xo=(e,t)=>{const i=document.createElementNS(Ro,"path");for(const[e,n]of Object.entries(t))i.setAttribute(e,n);return e.appendChild(i),i};class Mo{constructor(e){this.labels=e,this.visa=(()=>{const e=ko(48,28,"0 0 48 28");return Oo(e,{x:"0.5",y:"0.5",width:"47",height:"27",rx:"3.5",fill:"#ffffff",stroke:"#d7dde0"}),xo(e,{d:"M15.875 19.02h-2.726l-2.044-7.835c-.097-.36-.303-.679-.606-.829-.757-.378-1.59-.678-2.499-.829v-.302h4.392c.606 0 1.06.453 1.136.979l1.061 5.652 2.725-6.631h2.65l-4.089 9.795Zm5.604 0h-2.575l2.121-9.795h2.574l-2.12 9.795Zm5.451-7.08c.076-.528.53-.83 1.061-.83.833-.075 1.741.076 2.499.452l.454-2.109C30.187 9.152 29.353 9 28.597 9c-2.499 0-4.317 1.357-4.317 3.24 0 1.432 1.288 2.184 2.197 2.638.983.451 1.362.753 1.286 1.205 0 .678-.757.979-1.514.979-.909 0-1.818-.225-2.65-.603l-.454 2.11c.909.376 1.892.528 2.801.528 2.802.074 4.544-1.282 4.544-3.316 0-2.562-3.56-2.712-3.56-3.841ZM39.5 19.02l-2.044-9.795H35.26c-.455 0-.909.302-1.061.753L30.414 19.02h2.65l.529-1.431h3.257l.303 1.431H39.5Zm-3.861-7.157.756 3.692h-2.12l1.364-3.692Z",fill:"#172B85"}),e})(),this.mastercard=(()=>{const e=ko(48,28,"0 0 48 28");return Oo(e,{x:"0.5",y:"0.5",width:"47",height:"27",rx:"3.5",fill:"#ffffff",stroke:"#d7dde0"}),xo(e,{d:"M23.1 7.7a8.1 8.1 0 1 0 0 12.6 8.1 8.1 0 0 1 0-12.6Z",fill:"#EB001B"}),xo(e,{d:"M24 8.5a8.1 8.1 0 0 0 0 11 8.1 8.1 0 0 0 0-11Z",fill:"#FF5F00"}),xo(e,{d:"M24.9 7.7a8.1 8.1 0 1 1 0 12.6 8.1 8.1 0 0 0 0-12.6Z",fill:"#F79E1B"}),e})(),this.invalid=(()=>{const e=ko(36,28,"0 0 36 28");return e.style.color="currentColor",Oo(e,{x:"1",y:"2",width:"27",height:"20",rx:"3",fill:"none",stroke:"currentColor","stroke-width":"2"}),xo(e,{d:"M2 8h25",stroke:"currentColor","stroke-width":"2"}),xo(e,{d:"M27.7 11.1a2 2 0 0 1 3.6 0l4.4 9a2 2 0 0 1-1.8 2.9h-8.8a2 2 0 0 1-1.8-2.9l4.4-9Z",fill:"currentColor"}),xo(e,{d:"M29.5 14.4v3.4m0 2.3v.1",stroke:"#ffffff","stroke-linecap":"round","stroke-width":"1.8"}),e})(),this.root=document.createElement("div"),this.root.dataset.paypercutCardBrandBadges="",this.root.setAttribute("role","img"),this.root.append(this.visa,this.mastercard,this.invalid),this.setState("accepted")}setState(e){this.root.dataset.cardBrandState=e,this.root.setAttribute("aria-label",((e,t)=>t[e])(e,this.labels)),this.visa.style.display="accepted"===e||"visa"===e?"block":"none",this.mastercard.style.display="accepted"===e||"mastercard"===e?"block":"none",this.invalid.style.display="invalid"===e?"block":"none"}setVisible(e){this.root.hidden=!e,this.root.setAttribute("aria-hidden",e?"false":"true")}}const Lo=(e,t)=>{for(const[i,n]of Object.entries(t))e.style.setProperty(i.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`),n)},Do=e=>{e.removeAttribute("style")},Fo=e=>{const t=e?.inputs??"condensed",i=e?.labels??"auto";return{input:t,label:"auto"===i?"condensed"===t?"floating":"above":i}};class No{constructor(e,t){this.focused=!1,this.ready=!1,this.validation={empty:!0},this.visibleError=!1,this.submissionErrorVisible=!1,this.loadingAnimation=null,this.appearanceTransition=!1,this.destroyed=!1,this.type=t.type,this.copy=t.copy,this.appearance=t.appearance,this.showIcon="cardNumber"===this.type&&(t.showIcon??!0),this.root=document.createElement("div"),this.root.dataset.paypercutCardField="",this.root.dataset.field=this.type,this.root.lang=this.copy.locale,this.labelAbove=document.createElement("span"),this.labelAbove.dataset.paypercutCardFieldLabel="above",this.labelAbove.textContent=this.copy.ariaLabel,this.inputFrame=document.createElement("div"),this.inputFrame.dataset.paypercutCardFieldInput="",this.inputFrame.dataset.field=this.type,this.floatingLabel=document.createElement("span"),this.floatingLabel.dataset.paypercutCardFieldLabel="floating",this.floatingLabel.setAttribute("aria-hidden","true"),this.floatingLabel.textContent=this.copy.ariaLabel,this.providerMount=document.createElement("div"),this.providerMount.dataset.paypercutCardFieldProvider="",this.loadingIndicator=document.createElement("div"),this.loadingIndicator.dataset.paypercutCardFieldLoading="",this.loadingIndicator.setAttribute("aria-hidden","true"),this.loadingLabelLine=document.createElement("span"),this.loadingLabelLine.dataset.paypercutCardFieldLoadingLine="label",this.loadingValueLine=document.createElement("span"),this.loadingValueLine.dataset.paypercutCardFieldLoadingLine="value",this.loadingIndicator.append(this.loadingLabelLine,this.loadingValueLine),this.brandBadges="cardNumber"===this.type?new Mo({accepted:`${this.copy.ariaLabel}: Visa, Mastercard`,invalid:this.copy.errors.invalid,visa:"Visa",mastercard:"Mastercard"}):null,this.brandLane="cardNumber"===this.type?document.createElement("div"):null,this.brandLane&&(this.brandLane.dataset.paypercutCardBrandLane=""),this.errorMessage=document.createElement("p"),this.errorMessage.dataset.paypercutCardFieldError="",this.errorMessage.setAttribute("role","alert"),this.errorMessage.setAttribute("aria-live","polite"),this.inputFrame.appendChild(this.floatingLabel),this.inputFrame.appendChild(this.providerMount),this.brandBadges&&this.brandLane&&(this.brandLane.appendChild(this.brandBadges.root),this.inputFrame.appendChild(this.brandLane)),this.inputFrame.appendChild(this.loadingIndicator),this.root.appendChild(this.labelAbove),this.root.appendChild(this.inputFrame),this.root.appendChild(this.errorMessage),e.appendChild(this.root),this.render()}getPresentation(){const e=Fo(this.appearance),t=this.focused||!this.validation.empty;return{floatingLabels:"floating"===e.label,floatingLabelActive:t,placeholder:"floating"!==e.label||t?this.copy.placeholder:""}}updateAppearance(e){this.assertAlive(),this.appearance=e,this.render()}beginAppearanceTransition(){this.assertAlive(),this.appearanceTransition=!0,this.render()}handleReady(){this.assertAlive(),this.ready&&!this.appearanceTransition||(this.ready=!0,this.appearanceTransition=!1,this.render())}handleChange(e){this.assertAlive(),this.validation={empty:e.empty,...e.brand?{brand:e.brand}:{},...e.error?{error:{...e.error}}:{}},e.error||(this.submissionErrorVisible=!1),this.visibleError=Boolean(e.error)&&(this.submissionErrorVisible||!this.focused&&!e.empty),this.render()}handleFocus(){this.assertAlive(),this.focused=!0,this.visibleError=this.submissionErrorVisible&&Boolean(this.validation.error),this.render()}handleBlur(){this.assertAlive(),this.focused=!1,this.visibleError=Boolean(this.validation.error)&&(this.submissionErrorVisible||!this.validation.empty),this.render()}revealValidationError(e){this.assertAlive(),this.validation.error||(this.validation={...this.validation,error:{type:e,message:this.copy.errors[e]}}),this.submissionErrorVisible=Boolean(this.validation.error),this.visibleError=Boolean(this.validation.error),this.render()}destroy(){this.destroyed||(this.destroyed=!0,this.loadingAnimation?.cancel(),this.loadingAnimation=null,this.root.remove())}render(){const e=So(this.appearance),t=Fo(this.appearance),i=this.getPresentation(),n=this.visibleError,o=n?this.validation.error?.message??"":"",r=n?"invalid":(e=>{const t=e?.trim().toLowerCase().replace(/[ _-]+/g,"");return"visa"===t?"visa":"mastercard"===t?"mastercard":void 0})(this.validation.brand)??"accepted",s=((e,t="accepted")=>{const i="accepted"===t?96:"invalid"===t?36:48,n="accepted"===t?2:0;return{badgeGap:`calc(${To(e,2)})`,endInset:`calc(${To(e,3)})`,laneWidth:`calc(${i}px + ${To(e,n+3)})`}})(e.variables.spacingUnit,r),a=!this.ready;this.root.dataset.focused=this.focused?"true":"false",this.root.dataset.invalid=n?"true":"false",this.root.dataset.loading=a?"true":"false",this.root.dataset.appearanceTransition=this.appearanceTransition?"updating":"idle",this.root.setAttribute("aria-busy",a||this.appearanceTransition?"true":"false"),this.root.dataset.theme=e.theme,this.root.dataset.inputLayout=t.input,this.root.dataset.labelLayout=t.label,this.inputFrame.dataset.focused=this.focused?"true":"false",this.inputFrame.dataset.invalid=n?"true":"false",this.inputFrame.inert=this.appearanceTransition,Do(this.root),Lo(this.root,{display:"grid",width:"100%",minWidth:"0",gap:e.variables.labelSpacing,boxSizing:"border-box",color:e.variables.colorText,colorScheme:e.theme,fontFamily:e.variables.fontFamily,fontSize:e.variables.fontSizeBase,fontWeight:e.variables.fontWeightNormal,lineHeight:e.variables.lineHeight}),this.labelAbove.hidden="above"!==t.label,Do(this.labelAbove),Lo(this.labelAbove,{display:"above"===t.label?"block":"none",color:e.variables.colorText,fontFamily:e.variables.fontFamily,fontSize:"0.875em",fontWeight:e.variables.fontWeightMedium,lineHeight:e.variables.lineHeight,..._o(this.appearance,".Label")}),Do(this.inputFrame),Lo(this.inputFrame,{position:"relative",width:"100%",minWidth:"0",height:"floating"===t.label?"56px":"48px",overflow:"hidden",boxSizing:"border-box",borderStyle:"solid",borderWidth:"1px",borderColor:this.focused?e.variables.colorFocus:n?e.variables.colorDanger:e.variables.colorBorder,borderRadius:e.variables.borderRadius,background:e.variables.colorSurface,color:e.variables.colorText,transition:e.disableAnimations?"none":"border-color 150ms ease, box-shadow 150ms ease",boxShadow:this.focused?`inset 0 0 0 1px ${e.variables.colorFocus}, 0 0 0 3px color-mix(in srgb, ${e.variables.colorFocus} 25%, transparent)`:n?`inset 0 0 0 1px ${e.variables.colorDanger}`:"none","--ppc-card-brand-lane-width":this.showIcon?s.laneWidth:"0px",pointerEvents:this.appearanceTransition?"none":"auto",..._o(this.appearance,".Input"),...n?_o(this.appearance,".Input--invalid"):{},...this.focused?_o(this.appearance,".Input:focus"):{}}),this.floatingLabel.hidden="floating"!==t.label,this.floatingLabel.dataset.state=i.floatingLabelActive?"active":"resting",Do(this.floatingLabel),Lo(this.floatingLabel,{display:"floating"===t.label?"block":"none",position:"absolute",zIndex:"2",top:i.floatingLabelActive?e.variables.spacingUnit:"50%",left:`calc(${e.variables.spacingUnit} * 3)`,pointerEvents:"none",color:i.floatingLabelActive?e.variables.colorTextSecondary:e.variables.colorTextPlaceholder,fontFamily:e.variables.fontFamily,fontSize:i.floatingLabelActive?"0.6875em":"1em",fontWeight:e.variables.fontWeightNormal,lineHeight:i.floatingLabelActive?"1rem":e.variables.lineHeight,transform:i.floatingLabelActive?"none":"translateY(-50%)",transformOrigin:"left center",transition:e.disableAnimations?"none":"top 150ms ease, transform 150ms ease, font-size 150ms ease, line-height 150ms ease, color 150ms ease",..._o(this.appearance,".Label")}),Do(this.providerMount),Lo(this.providerMount,{width:this.showIcon?"calc(100% - var(--ppc-card-brand-lane-width))":"100%",minWidth:"0",height:"100%",overflow:"hidden",boxSizing:"border-box",transition:e.disableAnimations?"none":"width 150ms ease"}),this.brandBadges&&this.brandLane&&(this.brandBadges.setState(r),this.brandBadges.setVisible(this.showIcon),Do(this.brandLane),Lo(this.brandLane,{display:this.showIcon?"flex":"none",position:"absolute",zIndex:"3",top:"0",right:"0",width:"var(--ppc-card-brand-lane-width)",height:"100%",boxSizing:"border-box",alignItems:"center",justifyContent:"flex-end",paddingRight:s.endInset,pointerEvents:"none",transition:e.disableAnimations?"none":"width 150ms ease"}),Do(this.brandBadges.root),Lo(this.brandBadges.root,{display:this.showIcon?"flex":"none",alignItems:"center",gap:s.badgeGap,pointerEvents:"none",color:e.variables.colorDanger})),this.loadingIndicator.hidden=!a,Do(this.loadingIndicator),Lo(this.loadingIndicator,{display:a?"flex":"none",position:"absolute",zIndex:"4",inset:"0",boxSizing:"border-box",flexDirection:"column",justifyContent:"center",gap:`calc(${e.variables.spacingUnit} * 1.5)`,padding:`calc(${e.variables.spacingUnit} * 3)`,overflow:"hidden",background:e.variables.colorSurface,cursor:"progress"});const l=`color-mix(in srgb, ${e.variables.colorBorder} 72%, ${e.variables.colorSurface})`;Do(this.loadingLabelLine),Lo(this.loadingLabelLine,{display:"floating"===t.label?"block":"none",width:"28%",height:"6px",borderRadius:e.variables.borderRadius,background:l}),Do(this.loadingValueLine),Lo(this.loadingValueLine,{display:"block",width:"cardNumber"===this.type?"58%":"cardExpiry"===this.type?"48%":"42%",height:"10px",borderRadius:e.variables.borderRadius,background:l});const c=this.root.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!1,d="function"==typeof this.loadingValueLine.animate;a&&!e.disableAnimations&&!c&&d?this.loadingAnimation??(this.loadingAnimation=this.loadingValueLine.animate([{opacity:.55},{opacity:1},{opacity:.55}],{duration:1500,iterations:Number.POSITIVE_INFINITY,easing:"ease-in-out"})):(this.loadingAnimation?.cancel(),this.loadingAnimation=null),this.errorMessage.hidden=!n,this.errorMessage.textContent=o,Do(this.errorMessage),Lo(this.errorMessage,{display:n?"block":"none",margin:"0",color:e.variables.colorDanger,fontFamily:e.variables.fontFamily,fontSize:"0.875em",fontWeight:e.variables.fontWeightNormal,lineHeight:e.variables.lineHeight,..._o(this.appearance,".Error")})}assertAlive(){if(this.destroyed)throw new Error("[Paypercut Elements] Cannot update a destroyed card field surface.")}}class zo{constructor(e,i,n){this.type=e,this.group=i,this.options=n,this.componentId=j(),this.componentGeneration=0,this.emitter=new t,this.surface=null,this.mounted=!1,this.ready=!1,this.destroyed=!1,this.mountGeneration=0,this.initializationTimeoutId=null,this.presentationSignature=null,this.copy=null,this.componentType=(e=>{switch(e){case"cardNumber":return"card_number";case"cardExpiry":return"card_expiry";case"cardCvc":return"card_cvc"}})(e)}mount(e){if(this.destroyed)throw new Error("[Paypercut Elements] Cannot mount a destroyed card field.");if(this.mounted)return;if("undefined"==typeof window||"undefined"==typeof document)throw new Error("[Paypercut Elements] Card fields 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=(e=>{const t="string"==typeof e?document.querySelector(e):e;if(!(t instanceof HTMLElement))throw new Error(`[Paypercut Elements] Card field mount target was not found: ${String(e)}`);return t})(e),i=this.mountGeneration+1;this.mountGeneration=i,this.mounted=!0,this.group.markComponentMounted(),this.armInitializationWatch(i),this.initialize(t,i)}async initialize(e,t){try{const i=await this.group.resolveCardFieldCopy(this.type);if(!this.isCurrentMount(t))return;const n=new No(e,{type:this.type,copy:i,appearance:this.group.getAppearance(),..."cardNumber"===this.type?{showIcon:this.options?.showIcon}:{}});n.providerMount.id=`paypercut-${this.type}-provider-${this.componentId}`,this.surface=n,this.copy=i;const o=n.getPresentation();this.presentationSignature=JSON.stringify(o),await this.group.mountCardField({id:this.componentId,type:this.type,target:n.providerMount,ariaLabel:i.ariaLabel,placeholder:o.placeholder,presentation:o,events:{onReady:()=>this.onProviderReady(t),onChange:e=>this.onProviderChange(t,e),onFocus:()=>this.onProviderFocus(t),onBlur:()=>this.onProviderBlur(t),onError:e=>{this.isCurrentMount(t)&&this.emitter.emit("error",e)}}}),this.isCurrentMount(t)&&this.group.onCardFieldAvailabilityChange()}catch(e){if(!this.isCurrentMount(t))return;const i=e.details;if(i)return void this.failInitialization(i.message,i);this.failInitialization("The secure card field could not be initialized.")}}on(e,t){return this.emitter.on(e,t)}clear(){this.command("clear")}focus(){this.command("focus")}blur(){this.command("blur")}getComponentOptions(){return{}}revealSubmissionError(e){if(!this.destroyed&&this.mounted&&this.ready){this.surface?.revealValidationError(e);try{this.group.commandCardField(this.componentId,this.componentType,"focus")}catch{}}}hasActiveSubmission(){return!1}handleControllerError(e){this.destroyed||(this.ready?(this.ready=!1,this.emitter.emit("error",e),this.group.onCardFieldAvailabilityChange()):this.failInitialization(e.message,e))}handleControllerEvent(e){"error"===e.event&&this.handleControllerError(e)}updateAppearance(e){!this.destroyed&&this.surface&&(this.surface.updateAppearance(e),this.syncPresentation())}announceAppearanceReady(){!this.destroyed&&this.mounted&&this.surface&&(this.ready=!0,this.clearInitializationWatch(),this.surface.handleReady(),this.emitter.emit("ready"),this.group.onCardFieldAvailabilityChange())}beginAppearanceTransition(){!this.destroyed&&this.mounted&&this.surface&&(this.ready=!1,this.clearInitializationWatch(),this.surface.beginAppearanceTransition(),this.armInitializationWatch(this.mountGeneration),this.group.onCardFieldAvailabilityChange())}isMounted(){return this.mounted&&!this.destroyed}isVisible(){return Si(this.surface?.root??null)}destroy(){this.destroyed||(this.destroyed=!0,this.mountGeneration+=1,this.ready=!1,this.clearInitializationWatch(),this.group.destroyCardField(this.componentId),this.group.onCardFieldAvailabilityChange(),this.surface?.destroy(),this.surface=null,this.copy=null,this.presentationSignature=null,this.mounted=!1,this.emitter.clear(),this.group.remove(this))}command(e){if(this.destroyed)throw new Error(`[Paypercut Elements] Cannot ${e} a destroyed card field.`);if(!this.mounted||!this.ready)throw new Error(`[Paypercut Elements] Cannot ${e} a card field before it is ready.`);this.group.commandCardField(this.componentId,this.componentType,e)}onProviderReady(e){this.isCurrentMount(e)&&!this.ready&&(this.ready=!0,this.clearInitializationWatch(),this.surface?.handleReady(),this.emitter.emit("ready"),this.group.onCardFieldAvailabilityChange())}onProviderChange(e,t){if(!this.isCurrentMount(e)||!this.copy)return;this.group.onCardFieldValueChange();const i=((e,t,i)=>({complete:t.complete,empty:t.empty,..."cardNumber"===e&&t.brand?{brand:t.brand}:{},...t.errorType?{error:{type:t.errorType,message:i.errors[t.errorType]}}:{}}))(this.type,t,this.copy);this.surface?.handleChange(i),this.syncPresentation(),this.emitter.emit("change",i)}onProviderFocus(e){this.isCurrentMount(e)&&(this.surface?.handleFocus(),this.syncPresentation(),this.emitter.emit("focus"))}onProviderBlur(e){this.isCurrentMount(e)&&(this.surface?.handleBlur(),this.syncPresentation(),this.emitter.emit("blur"))}failInitialization(e,t={code:"elements_provider_initialization_failed",message:e,recoverable:!0}){this.destroyed||this.ready||!this.mounted||(this.rollbackMount(),this.emitter.emit("error",t))}rollbackMount(){this.mountGeneration+=1,this.clearInitializationWatch(),this.group.destroyCardField(this.componentId),this.surface?.destroy(),this.surface=null,this.copy=null,this.presentationSignature=null,this.mounted=!1,this.ready=!1,this.group.onCardFieldAvailabilityChange()}isCurrentMount(e){return!this.destroyed&&this.mounted&&this.mountGeneration===e}syncPresentation(){if(!this.surface||!this.mounted||this.destroyed)return;const e=this.surface.getPresentation(),t=JSON.stringify(e);t!==this.presentationSignature&&(this.presentationSignature=t,this.group.updateCardFieldPresentation(this.componentId,e))}clearInitializationWatch(){null!==this.initializationTimeoutId&&"undefined"!=typeof window&&window.clearTimeout(this.initializationTimeoutId),this.initializationTimeoutId=null}armInitializationWatch(e){this.clearInitializationWatch(),this.initializationTimeoutId=window.setTimeout(()=>{this.isCurrentMount(e)&&!this.ready&&this.failInitialization("The secure card field did not become ready in time.")},4e4)}}function Uo(e,t,i,n){Object.defineProperty(e,t,{get:i,set:n,enumerable:!0,configurable:!0})}function qo(e,t){return Object.keys(t).forEach(function(i){"default"===i||"__esModule"===i||Object.prototype.hasOwnProperty.call(e,i)||Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[i]}})}),e}Uo({},"basistheory",()=>Jo);const Bo=(()=>{let e,t;const i=async(i,n,o={})=>{if(e)return;let r;r=!t||t?.includes("localhost")?"local":t.includes("dev")?"dev":"prod";const s={level:n,message:i,service:"web-elements-loader",env:r,referrer:document?.referrer,origin:window?.location.origin,url:window?.location.href,userAgent:navigator?.userAgent,...o};["local","dev"].includes(r)&&console.log(s);try{await fetch("https://http-intake.logs.datadoghq.com/v1/input/pubb96b84a13912504f4354f2d794ea4fab",{method:"POST",body:JSON.stringify(s),headers:{"Content-Type":"application/json"}})}catch{console.warn("There was an error sending telemetry.")}};return{disableTelemetry:t=>{e=t},setBaseUrl:e=>{t=e},log:{error:(e,t={})=>i(e,"error",t),info:(e,t={})=>i(e,"info",t),warn:(e,t={})=>i(e,"warn",t)}}})();class jo extends Error{constructor(e,t,i){super(e),this.details=t,this.validation=i,this.name="BasisTheoryValidationError",Object.setPrototypeOf(this,jo.prototype)}}const Go="Tried to load BasisTheoryElements in a non-DOM environment.",Ho="Unable to load the Elements script. This may be due to network restrictions or browser extensions like ad blockers interfering with script loading. Check browser settings or network connection and try again.",Wo=["accel","bancontact","cartes-bancaires","culiance","dankort","ebt","eftpos-australia","nyce","private-label","prop","pulse","rupay","star","uatp","korean-local","visa","mastercard","american-express","discover","diners-club","jcb","unionpay","maestro","elo","hiper","hipercard","mir","unknown"],Vo=["left","right","none"],$o=["additional-name","address-level1","address-level2","address-level3","address-level4","address-line1","address-line2","address-line3","bday-day","bday-month","bday-year","bday","billing","cc-additional-name","cc-csc","cc-exp-month","cc-exp-year","cc-exp","cc-family-name","cc-given-name","cc-name","cc-number","cc-type","country-name","country","current-password","email","family-name","fax","given-name","home","honorific-prefix","honorific-suffix","language","mobile","name","new-password","nickname","off","on","one-time-code","organization-title","organization","page","postal-code","sex","shipping","street-address","tel-area-code","tel-country-code","tel-extension","tel-local-prefix","tel-local-suffix","tel-local","tel-national","tel","transaction-amount","transaction-currency","url","username","work"];let Yo;const Ko=(e,t)=>new Promise((i,n)=>{let o=(e=>{const t=document.querySelector(`script[src^="${e}"]`);if(t)return t;const i=document.head||document.body;if(!i)throw new Error("No <head> or <body> elements found in the document.");const n=Object.assign(document.createElement("script"),{src:e});return i.append(n),n})(e),r=!1;o.addEventListener("load",()=>{window.BasisTheoryElements?i(window.BasisTheoryElements):((async()=>{await Bo.log.error("Elements not found on window on load",{logType:"elementsNotFoundOnWindow",logOrigin:"loadScript",retryCount:t})})(),n(new Error("Basis Theory Elements did not load properly. Check network tab for more details.")))}),o.addEventListener("error",async s=>{if(!r){r=!0,await Bo.log.error("Elements script onError event",{logType:"elementsScriptOnError",logOrigin:"loadScript",retryCount:t,event:{message:s?.message,source:s?.filename,lineno:s?.lineno,colno:s?.colno,error:s?.error,target:s?.target}});try{o?.remove()}catch(e){await Bo.log.error(`Error removing script from DOM on retry attempt ${t}`,{logType:"scriptRemovalError",logOrigin:"loadScript",retryCount:t,removalError:e})}if(0!==t){try{const i=await fetch(e);i.ok?(await Bo.log.error("Second attempt to load elements script failed, fetch success",{logType:"elementsScriptFetchFailure",logOrigin:"loadScript",retryCount:t,fetchResult:"success",fetchResponse:i}),n(new Error(Ho))):(await Bo.log.error(`Second attempt to load elements script failed, fetch failed with status: ${i.status}.`,{logType:"elementsScriptFetchFailure",logOrigin:"loadScript",retryCount:t,fetchResult:"error",fetchResponse:i}),n(new Error(Go)))}catch(e){await Bo.log.error("Second attempt failed to load elements script failed, fetch network error.",{logType:"elementsScriptFetchError",logOrigin:"loadScript",retryCount:t,fetchResult:"error",fetchError:e}),n(new Error(Ho))}n(s?.error||s?.message||new Error(Ho))}else Ko(e,t+1).then(i).catch(n)}})}),Zo=e=>{let t;e?._devMode&&e?.customDomain&&Bo.log.warn("Dev mode and domain whitelabeling are both enabled - dev mode takes precedence."),t=e?._devMode?"https://js.flock-dev.com":e?.customDomain?(e=>{if("string"!=typeof e||!e.trim())throw new Error("Custom domain must be a non-empty string.");let t;try{t=new URL(e.toLowerCase().startsWith("http")?e:`https://${e}`)}catch{throw new jo(`Invalid custom domain: "${e}"`,{})}if("https:"!==t.protocol)throw new jo(`Custom domain must use HTTPS (got "${t.protocol}")`,{});if("/"!==t.pathname||t.search||t.hash)throw new jo(`Custom domain must not include path, query, or hash (got "${t.href}")`,{});if(t.port)throw new jo(`Custom domain must not include a port (got ":${t.port}")`,{});if(!/^(?=.{1,253}$)([a-zA-Z0-9-]{1,63}\.)+[a-zA-Z]{2,63}$/.test(t.hostname))throw new jo(`Invalid hostname: "${t.hostname}"`,{});return t.origin})(e.customDomain):"https://js.basistheory.com";const i=`${t}/web-elements/2.12.1`,n=`${i}/client/index.js`,o=`${i}/hosted-elements/`;return e?.customDomain&&e._devMode,{origin:t,clientJsUrl:n,hostedElementsBaseUrl:o}},Jo=async(e,t)=>{if(!e||0===e.length)throw new Error("API key is required");const{origin:i,clientJsUrl:n,hostedElementsBaseUrl:o}=Zo(t);Bo.setBaseUrl(i),Bo.disableTelemetry(Boolean(t?.disableTelemetry));var r;return(await(r=n,Yo||(Yo=new Promise((e,t)=>{if("object"!=typeof window)return void(async()=>{await Bo.log.warn(Go,{logType:"elementsNonDomError",logOrigin:"loadElements"}),t(new Error(Go))})();if(window.BasisTheoryElements)return void e(window.BasisTheoryElements);const i=new URL(r).toString().replace(/\/$/u,"");Ko(i,0).then(e).catch(e=>{t(e)})})),Yo)).init(e,o,!1,t?.useSameOriginApi??!0,t?.disableTelemetry??!1,t?.debug??!1,t?.environment??"production",t?.useNetworkCheck??!1,t?.customDomain?i:void 0)};var Xo={};Uo(Xo,"AUTOCOMPLETE_VALUES",()=>$o),Uo(Xo,"CARD_BRANDS",()=>Wo),Uo(Xo,"CARD_ICON_POSITIONS",()=>Vo);var Qo={},er={};Uo(er,"VISA",()=>tr),Uo(er,"MASTERCARD",()=>ir),Uo(er,"AMERICAN_EXPRESS",()=>nr),Uo(er,"DINERS_CLUB",()=>or),Uo(er,"DISCOVER",()=>rr),Uo(er,"JCB",()=>sr),Uo(er,"UNION_PAY",()=>ar),Uo(er,"MAESTRO",()=>lr),Uo(er,"ELO",()=>cr),Uo(er,"MIR",()=>dr),Uo(er,"HIPER",()=>pr),Uo(er,"HIPERCARD",()=>hr),Uo(er,"DEFAULT_CARD_TYPES",()=>ur);const tr={niceType:"Visa",type:"visa",patterns:[4],gaps:[4,8,12],lengths:[16,18,19],code:{name:"CVV",size:3}},ir={niceType:"Mastercard",type:"mastercard",patterns:[[51,55],[2221,2229],[223,229],[23,26],[270,271],2720],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},nr={niceType:"American Express",type:"american-express",patterns:[34,37],gaps:[4,10],lengths:[15],code:{name:"CID",size:4}},or={niceType:"Diners Club",type:"diners-club",patterns:[[300,305],36,38,39],gaps:[4,10],lengths:[14,16,19],code:{name:"CVV",size:3}},rr={niceType:"Discover",type:"discover",patterns:[6011,[644,649],65],gaps:[4,8,12],lengths:[16,19],code:{name:"CID",size:3}},sr={niceType:"JCB",type:"jcb",patterns:[2131,1800,[3528,3589]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVV",size:3}},ar={niceType:"UnionPay",type:"unionpay",patterns:[620,[62100,62182],[62184,62187],[62185,62197],[62200,62205],[622010,622999],622018,[62207,62209],[623,626],6270,6272,6276,[627700,627779],[627781,627799],[6282,6289],6291,6292,810,[8110,8131],[8132,8151],[8152,8163],[8164,8171]],gaps:[4,8,12],lengths:[14,15,16,17,18,19],code:{name:"CVN",size:3}},lr={niceType:"Maestro",type:"maestro",patterns:[493698,[5e5,504174],[504176,506698],[506779,508999],[56,59],63,67,6],gaps:[4,8,12],lengths:[12,13,14,15,16,17,18,19],code:{name:"CVC",size:3}},cr={niceType:"Elo",type:"elo",patterns:[401178,401179,438935,457631,457632,431274,451416,457393,504175,[506699,506778],[509e3,509999],627780,636297,636368,[650031,650033],[650035,650051],[650405,650439],[650485,650538],[650541,650598],[650700,650718],[650720,650727],[650901,650978],[651652,651679],[655e3,655019],[655021,655058]],gaps:[4,8,12],lengths:[16],code:{name:"CVE",size:3}},dr={niceType:"Mir",type:"mir",patterns:[[2200,2204]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVP2",size:3}},pr={niceType:"Hiper",type:"hiper",patterns:[637095,63737423,63743358,637568,637599,637609,637612],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},hr={niceType:"Hipercard",type:"hipercard",patterns:[606282],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},ur=[tr,ir,nr,or,rr,sr,ar,lr,cr,dr,pr,hr];var mr={};Uo(mr,"CoBadgedSupport",()=>yr);var yr=function(e){return e.CartesBancaires="cartes-bancaires",e.Bancontact="bancontact",e.Dankort="dankort",e}({}),gr={};Uo(gr,"ELEMENTS_TYPES",()=>fr);const fr=["card","cardExpirationDate","cardNumber","cardVerificationCode","copyButton","data","text"];var br={};qo(br,{}),qo(br,{}),qo(br,{}),qo(br,{});var vr={};Uo(vr,"SAFE_CSS_PROPERTIES",()=>wr),Uo(vr,"BUTTON_CSS_PROPERTIES",()=>Pr),Uo(vr,"SAFE_CSS_PROPERTIES_ALTERNATES",()=>Er),Uo(vr,"SAFE_CSS_PROPERTIES_WITH_ALTERNATES",()=>Ar),Uo(vr,"CARD_ELEMENT_STYLE_VARIANT_SELECTORS",()=>Cr),Uo(vr,"BUTTON_ELEMENT_STYLE_VARIANT_SELECTORS",()=>Sr),Uo(vr,"CARD_ELEMENT_STYLE_VARIANTS",()=>_r),Uo(vr,"CARD_ELEMENT_STYLE_FONTS_ATTR",()=>Ir),Uo(vr,"BUTTON_ELEMENT_STYLE_VARIANTS",()=>Tr);const wr=["backgroundColor","color","fontFamily","fontSize","fontSmooth","fontStyle","fontVariant","fontWeight","letterSpacing","lineHeight","padding","textAlign","textDecoration","textShadow","textTransform"],Pr=["alignItems","backgroundColor","border","borderBottom","borderColor","borderLeft","borderRadius","borderRight","borderStyle","borderTop","borderWidth","boxShadow","color","cursor","display","fontFamily","fontSize","fontWeight","gap","height","justifyContent","letterSpacing","lineHeight","margin","maxHeight","maxWidth","minHeight","minWidth","opacity","outline","padding","textAlign","textTransform","transform","transition","width"],Er={fontSmooth:["-webkit-font-smoothing","-moz-osx-font-smoothing"]},Ar=Object.keys(Er),Cr=[":hover",":focus",":read-only","::placeholder","::selection",":disabled"],Sr=[":hover",":focus",":active"],_r=["base","container","complete","invalid","empty"],Ir="fonts",Tr=["base","container"];qo(Qo,er),qo(Qo,mr),qo(Qo,{}),qo(Qo,{}),qo(Qo,gr),qo(Qo,br),qo(Qo,{}),qo(Qo,vr);var Rr={},kr={};Uo(kr,"DATA_CLASSIFICATIONS",()=>Or),Uo(kr,"DATA_IMPACT_LEVELS",()=>xr),Uo(kr,"DATA_RESTRICTION_POLICIES",()=>Mr);const Or=["general","bank","pci","pii"],xr=["low","moderate","high"],Mr=["mask","redact"];qo(Rr,kr),qo(Rr,{}),qo(Rr,{}),qo(Rr,{}),qo(Rr,{}),qo(Rr,{}),qo(Rr,{}),qo(Rr,{});var Lr={},Dr={};qo(Dr,{}),qo(Lr,Dr),qo(Xo,Qo),qo(Xo,Rr),qo(Xo,Lr);var Fr={};Uo(Fr,"BasisTheoryApiError",()=>Nr),Uo(Fr,"BasisTheoryValidationError",()=>jo),Uo(Fr,"BasisTheoryConfigurationError",()=>zr),Uo(Fr,"HttpClientError",()=>Ur);class Nr extends Error{constructor(e,t,i,n){super(e),this.status=t,this.data=i,this._debug=n,this.name="BasisTheoryApiError",Object.setPrototypeOf(this,Nr.prototype)}}class zr extends Error{constructor(e,t){super(e),this.details=t,this.name="BasisTheoryConfigurationError",Object.setPrototypeOf(this,zr.prototype)}}class Ur extends Error{constructor(e,t,i,n){super(e),this.name="HttpClientError",this.status=t,this.data=i,this.headers=n,Object.setPrototypeOf(this,Ur.prototype)}}"undefined"!=typeof window&&document.currentScript&&!window.basistheory&&(window.basistheory=Jo);const qr=new Set(["/hosted-elements/card-number-element.html","/hosted-elements/card-expiration-date-element.html","/hosted-elements/card-verification-code-element.html"]),Br=e=>{if(!(e=>{try{const t=new URL(e.src,window.location.href);return"https://js.basistheory.com"===t.origin&&t.pathname.includes("/web-elements/")&&Array.from(qr).some(e=>t.pathname.endsWith(e))}catch{return!1}})(e))return!1;const t=new Set(e.allow.split(";").map(e=>e.trim()).filter(Boolean));return t.add("clipboard-write"),t.add("autofill *"),e.allow=Array.from(t).join("; "),!0},jr=(e,t,i)=>{e.getPropertyValue(t)===i&&"important"===e.getPropertyPriority(t)||e.setProperty(t,i,"important")},Gr=new WeakMap;class Hr extends Error{constructor(){super("Basis Theory Elements initialization timed out."),this.name="InitializationAttemptTimeoutError"}}const Wr=()=>new Error("Basis Theory Elements initialization was cancelled."),Vr=e=>e.DataElement,$r=(e,t)=>{if(!t||Vr(e)!==t)return!1;const i=t.iframe;try{return t.unmount(),!0}catch{return!!i&&(i.remove(),!0)}},Yr=async e=>{let t;const i=new Promise((e,i)=>{t=globalThis.setTimeout(()=>i(new Hr),1e4)});e.catch(()=>{});try{return await Promise.race([e,i])}finally{void 0!==t&&globalThis.clearTimeout(t)}},Kr=(e,t)=>{if(t.aborted)return Promise.reject(Wr());const i=Symbol("basis-theory-initialization-waiter");return e.waiters.add(i),new Promise((n,o)=>{let r=!1;const s=n=>{r||(r=!0,e.waiters.delete(i),t.removeEventListener("abort",a),n())},a=()=>s(()=>o(Wr()));t.addEventListener("abort",a,{once:!0}),e.promise.then(e=>s(()=>n(e)),e=>s(()=>o(e instanceof Error?e:new Error(String(e)))))})},Zr=(e,t)=>{if("undefined"==typeof window)return Promise.reject(new Error("Basis Theory Elements requires a browser document."));if(t.aborted)return Promise.reject(Wr());const i=window,n=(e=>JSON.stringify({publicKey:e.publicKey,options:e.options}))(e),o=Gr.get(i);if(o)return o.key!==n?Promise.reject(new Error("Basis Theory Elements is already initialized with another configuration.")):"ready"===o.kind?Promise.resolve(o.provider):"failed"===o.kind?o.restartable?(Gr.delete(i),Zr(e,t)):Promise.reject(o.error):Kr(o,t);const r={kind:"pending",key:n,waiters:new Set,restartableAfterFailure:!1},s=Symbol("basis-theory-initialization-first-waiter");return r.waiters.add(s),r.promise=(async(e,t,i)=>{let n;for(let o=0;o<2;o+=1){if(0===i.waiters.size)throw Wr();const r=Vr(e),s=Promise.resolve().then(()=>Jo(t.publicKey,t.options)),a={discardLateResult:!1},l=t=>{if(a.cleanup?.candidate===t)return a.cleanup.succeeded;const i=$r(e,t);return a.cleanup={candidate:t,succeeded:i},i},c=()=>{if(!a.discardLateResult)return;const t=a.candidate??Vr(e);t&&t!==r&&l(t)};s.then(c,c);try{const e=await Yr(s);if(!e)throw new Error("Basis Theory Elements did not initialize.");if(0===i.waiters.size)throw Wr();return e}catch(t){n=t;const s=Vr(e),c=void 0!==s&&s!==r;c&&(a.candidate=s);const d=c&&l(s);if(a.discardLateResult=t instanceof Hr,!(o+1<2&&i.waiters.size>0&&d))throw i.restartableAfterFailure=d,t}}throw n})(i,e,r),r.waiters.delete(s),Gr.set(i,r),r.promise.then(e=>{Gr.get(i)===r&&Gr.set(i,{kind:"ready",key:n,provider:e})},e=>{Gr.get(i)===r&&Gr.set(i,{kind:"failed",key:n,error:e instanceof Error?e:new Error(String(e)),restartable:r.restartableAfterFailure})}),Kr(r,t)},Jr=[250,750,1500],Xr=/[\u0000-\u001f\u007f]/;class Qr extends Error{constructor(){super("Basis Theory tokenization returned a successful response without a token identifier."),this.name="BasisTheoryTokenizationResponseInvalidError"}}const es=e=>{if(!e)return!1;if(e instanceof Qr)return!0;const t=e,i=[t.name,t.code,e instanceof Error?e.message:t.message,t.data].map(e=>String(e??"")).join(" ").toLowerCase();if(["timeout","timed out","api is unreachable","failed to fetch","load failed","networkerror","network request failed","connection reset","connection closed","valueresolutionfailure","value resolution failure"].some(e=>i.includes(e)))return!0;const n=(e=>{if(!e||"object"!=typeof e)return;const t=e,i=t.status??t.statusCode??t.response?.status;return Number.isSafeInteger(i)?Number(i):void 0})(e);return 0===n||408===n||409===n||425===n||429===n||void 0!==n&&n>=500};class ts extends Error{constructor(e){super("Secure card tokenization may have completed, but its result could not be verified."),this.cause=e,this.code="elements_submit_indeterminate",this.name="BasisTheoryTokenizationIndeterminateError"}}const is=[tr,ir,lr],ns=new Set(is.map(({type:e})=>e)),os=()=>new Error("The secure card field mount was cancelled."),rs=(e,t)=>{const i=(e=>{if(!0===e.valid)return;const t=e.errors?.[0]?.type;return"incomplete"===t||"invalid"===t?t:void 0})(t),n="cardNumber"===e?"string"==typeof(o=t.cardBrand)&&ns.has(o)?o:void 0:void 0;var o;return{complete:t.complete&&!0===t.valid,empty:t.empty,...n?{brand:n}:{},...i?{errorType:i}:{}}},ss=async(e,t,i)=>{const n=((e,t)=>{let i,n=!0,o=!1,r=!1;const s=()=>{if(!n||r||!o||!i)return;const s=((e,t)=>{const i=e.getBoundingClientRect(),n=t.getBoundingClientRect();return!(i.width<=0||i.height<=0)&&n.left<=i.left+1&&n.top<=i.top+1&&n.right+1>=i.right&&n.bottom+1>=i.bottom})(e,i);s&&(r=!0,t())},a="undefined"==typeof ResizeObserver?void 0:new ResizeObserver(()=>{s()});return a?.observe(e),{observeFrame:e=>{n&&(i!==e&&(i&&a?.unobserve(i),i=e,a?.observe(i)),jr(i.style,"width","100%"),jr(i.style,"height","100%"),jr(i.style,"display","block"),s())},providerReady:()=>{n&&!r&&(o=!0,s())},stop:()=>{n&&(n=!1,a?.disconnect())}}})(t.target,t.events.onReady),o=((e,t)=>{const i=e=>{e instanceof HTMLIFrameElement&&Br(e)&&t?.(e),(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("iframe").forEach(e=>{Br(e)&&t?.(e)})};i(e);const n=new MutationObserver(e=>{for(const t of e)"attributes"!==t.type?t.addedNodes.forEach(i):i(t.target)});n.observe(e,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["src"]});let o=!0;return()=>{o&&(o=!1,n.disconnect())}})(t.target,n.observeFrame),r={...t,events:{...t.events,onReady:n.providerReady}};let s=[];try{s=((e,t)=>{const i=[],n=(t,n)=>{i.push(e.on(t,n))};return n("ready",()=>t.events.onReady()),n("change",e=>{t.events.onChange(rs(t.type,e))}),n("focus",()=>t.events.onFocus()),n("blur",()=>t.events.onBlur()),i})(e,r),await(async(e,t)=>{if(t.signal.aborted)throw os();let i,n;const o=new Promise((e,t)=>{i=t}),r=()=>i?.(os());t.signal.addEventListener("abort",r,{once:!0});const s=Promise.resolve().then(()=>e.mount(t.target)),a=new Promise((e,t)=>{n=globalThis.setTimeout(()=>t(new Error("Basis Theory secure card field mount timed out.")),8e3)});s.catch(()=>{});try{if(await Promise.race([s,o,a]),t.signal.aborted)throw os()}finally{t.signal.removeEventListener("abort",r),void 0!==n&&globalThis.clearTimeout(n)}})(e,t)}catch(t){n.stop(),o(),s.forEach(e=>e.unsubscribe());try{e.unmount()}catch{}throw t}let a=!1;return{clear:()=>{a||e.clear()},focus:()=>{a||e.focus()},blur:()=>{a||e.blur()},update:async t=>{a||await e.update({...t,...t.style?{style:t.style}:{}})},destroy:()=>{if(!a){a=!0,i(),n.stop(),o(),s.forEach(e=>e.unsubscribe());try{e.unmount()}catch{}}}}},as=e=>{if("string"!=typeof e)return;return e.trim()||void 0},ls=(e,t,i)=>Number.isSafeInteger(e)&&Number(e)>=t&&Number(e)<=i?Number(e):void 0,cs=new Set(["bancontact","cartes_bancaires","dankort"]),ds={amex:"american_express",americanexpress:"american_express",cartesbancaires:"cartes_bancaires",dinersclub:"diners_club",master_card:"mastercard",unionpay:"union_pay"},ps=e=>{const t=as(e)?.toLowerCase().replace(/[\s-]+/g,"_");return t?ds[t]??t:void 0},hs=e=>as(e)?.toLowerCase(),us=(e,t,i)=>{const n=as(e.id);if(!n)throw new Error("Basis Theory returned no token identifier.");const o=e.card,r=(Array.isArray(o?.additional)?o.additional:[]).filter(e=>Boolean(e&&"object"==typeof e)),s=e=>r.map(e).find(e=>void 0!==e),a=as(o?.last4),l=o?.issuerCountry?.alpha2,c=o?.issuer_country&&"object"==typeof o.issuer_country?o.issuer_country.alpha2:o?.issuer_country,d=as(l??c??o?.issuer?.country??s(e=>{return(t=e.issuer_country??e.issuer?.country)&&"object"==typeof t?t.alpha2:t;var t})),p=hs(o?.funding)??s(e=>hs(e.funding)),h=as(o?.issuer?.name)??s(e=>as(e.issuer?.name)),u=ls(o?.expirationMonth??o?.expiration_month,1,12),m=ls(o?.expirationYear??o?.expiration_year,2e3,9999),{brand:y,displayBrand:g}=(e=>{const t=ps(e?.brand),i=Array.from(new Set((Array.isArray(e?.additional)?e.additional:[]).map(e=>ps(e?.brand)).filter(e=>Boolean(e)))),n=!!t&&cs.has(t),o=t&&!n?t:i.find(e=>!cs.has(e)),r=[t,...i].find(e=>e&&cs.has(e));return{brand:o,displayBrand:r??i.find(e=>e!==o)}})(o),f={...y?{brand:y}:{},...g?{display_brand:g}:{},...a&&/^\d{4}$/.test(a)?{last4:a}:{},...void 0===u?{}:{exp_month:u},...void 0===m?{}:{exp_year:m},...as(e.fingerprint)?{fingerprint:as(e.fingerprint)}:{},...as(o?.bin)?{iin:as(o?.bin)}:{},...p?{funding:p}:{},...h?{issuer:h}:{},...d?{country:d}:{},...as(o?.segment)?.toLowerCase()?{segment:as(o?.segment)?.toLowerCase()}:{},...i?{cardholder_name:i}:{}};return{instrumentToken:{type:t,id:n},..."sca_required"===o?.authentication||"sca_not_required"===o?.authentication?{authentication:o.authentication}:{},card:f}},ms=async(e,t)=>{if("basis_theory_v2"!==e.driver)throw new Error("The configured card provider is not supported.");const i=await Zr({publicKey:e.publicKey,options:{...e.livemode?{}:{environment:"test"},useNetworkCheck:!0}},t.signal),n=new Map,o=async e=>{const t=((e,t)=>{if(!e)throw new Error("Basis Theory Elements did not initialize.");const i={targetId:t.target.id,inputMode:"numeric",placeholder:t.placeholder,style:t.style,validateOnChange:!0,"aria-label":t.ariaLabel};switch(t.type){case"cardNumber":return e.createElement("cardNumber",{...i,autoComplete:"cc-number",cardTypes:[...is],iconPosition:"none"});case"cardExpiry":return e.createElement("cardExpirationDate",{...i,autoComplete:"cc-exp"});case"cardCvc":return e.createElement("cardVerificationCode",{...i,autoComplete:"cc-csc"})}})(i,e);n.set(e.type,t);try{return await ss(t,e,()=>{n.get(e.type)===t&&n.delete(e.type)})}catch(i){throw n.get(e.type)===t&&n.delete(e.type),i}};return{createField:async e=>{let t;for(let i=0;i<2;i+=1){if(e.signal.aborted)throw t??os();try{return await o(e)}catch(n){if(t=n,e.signal.aborted||i+1===2)throw n}}throw t},createConfirmationData:async(e,t,o)=>{const r=n.get("cardNumber"),s=n.get("cardExpiry"),a=n.get("cardCvc");if(!r||!s||!a)throw new Error("The secure card fields are not ready.");const l={number:r,expiration_month:s.month(),expiration_year:s.year(),cvc:a,...t?{cardholderName:t}:{}},c=o?"token":"token_intent",d={type:"card",data:l},p={idempotencyKey:`paypercut-elements:${e}:card-tokenization`},h=await async function(e,t=e=>new Promise(t=>globalThis.setTimeout(t,e))){let i;for(let n=0;n<=Jr.length;n+=1)try{return await e()}catch(e){if(!es(e))throw e;i=e;const o=Jr[n];if(void 0===o)throw new ts(i);await t(o)}throw new ts(i)}(async()=>(e=>{if(!e||"object"!=typeof e||Array.isArray(e))throw new Qr;const t=e.id;if("string"!=typeof t||0===t.length||t.length>128||t!==t.trim()||Xr.test(t))throw new Qr;return e})(o?await i.tokens.create(d,p):await i.tokenIntents.create(d,p)));return us(h,c,t)}}};const ys=["cardNumber","cardExpiry","cardCvc"];class gs extends Error{constructor(e,t){super(e.message),this.details=e,this.name="CardCollectionRuntimeError",void 0!==t&&(this.cause=t)}}const fs=()=>new gs({code:"elements_capability_unsupported",message:"Split card fields are not available for this payment configuration.",recoverable:!1}),bs=e=>e instanceof gs?e:new gs({code:"elements_provider_initialization_failed",message:"The secure card fields could not be initialized.",recoverable:!0},e),vs=e=>{if(!Number.isFinite(Date.parse(e.expiresAt))||Date.parse(e.expiresAt)<=Date.now())throw new gs({code:"elements_session_expired",message:"The secure card-field session has expired. Reload the payment form.",recoverable:!1});return e};class ws{constructor(e,t,i=(()=>ms)()){this.compileAppearance=t,this.providerFactory=i,this.fields=new Map,this.bootstrapFailure=null,this.bootstrapWaiters=[],this.provider=null,this.providerPromise=null,this.providerAbortController=new AbortController,this.destroyed=!1,this.appearancePreviewGeneration=0,this.providerGenerationSequence=0,this.providerTargetIdSequence=0,this.providerTargetIds=new Set,this.pendingAppearancePreview=null,this.appearance=e}configure(e){if(this.destroyed||void 0!==this.bootstrap||this.bootstrapFailure)return;if(!(e=>(2===e?.protocolVersion||3===e?.protocolVersion)&&"messages"in e)(e))return void this.rejectBootstrap((e=>2!==e?.protocolVersion&&3!==e?.protocolVersion||!("error"in e)?fs():new gs(e.error))(e));this.bootstrap=e;const t=this.bootstrapWaiters;this.bootstrapWaiters=[],t.forEach(t=>t.resolve(e))}async resolveFieldCopy(e){if(this.destroyed)throw fs();const t=vs(await this.waitForBootstrap());return function(e,t,i){const n=t.card;switch(e){case"cardNumber":return{locale:i,ariaLabel:n.cardNumber,placeholder:n.cardNumberPlaceholder,errors:{...n.errors.number}};case"cardExpiry":return{locale:i,ariaLabel:n.expirationDate,placeholder:n.expirationDatePlaceholder,errors:{...n.errors.expirationDate}};case"cardCvc":return{locale:i,ariaLabel:n.securityCode,placeholder:n.cvvPlaceholder,errors:{...n.errors.cvv}}}}(e,t.messages,t.locale)}fail(e){this.destroyed||void 0!==this.bootstrap||this.bootstrapFailure||this.rejectBootstrap(new gs(e))}rejectBootstrap(e){this.bootstrapFailure=e;const t=this.bootstrapWaiters;this.bootstrapWaiters=[],t.forEach(t=>t.reject(e))}async mountField(e){if(this.destroyed)throw fs();if(this.fields.has(e.id))throw new Error("The secure card field is already mounted.");this.assignProviderTargetId(e.target,`paypercut-${e.type}-provider-${e.id}`);const t={id:e.id,type:e.type,target:e.target,providerHost:e.target,ariaLabel:e.ariaLabel,abortController:new AbortController,events:e.events,presentation:{...e.presentation},destroyed:!1,replacing:!1,providerField:null,providerGeneration:0,configurationRevision:0,updateRevision:0,updateChain:Promise.resolve(),pendingUpdate:null,providerReady:!1,lastChange:null};this.fields.set(e.id,t);try{const i=await this.getProvider();if(t.destroyed||this.fields.get(e.id)!==t)return;const n=t.configurationRevision,o=t.providerGeneration,r=await i.createField({type:e.type,target:e.target,signal:t.abortController.signal,style:this.compileAppearance(this.appearance,t.presentation),ariaLabel:e.ariaLabel,placeholder:t.presentation.placeholder,events:this.wrapEvents(t,o)});if(!this.isProviderGenerationCurrent(t,o))return void r.destroy();t.providerField=r,t.configurationRevision!==n&&(this.scheduleFieldUpdate(t,{placeholder:t.presentation.placeholder,style:this.compileAppearance(this.appearance,t.presentation)}),await t.updateChain),"cardCvc"===e.type&&this.numberBrand&&(this.scheduleFieldUpdate(t,{cardBrand:this.numberBrand}),await t.updateChain)}catch(i){if(this.destroyed)throw bs(i);if(!t.destroyed&&this.fields.get(e.id)===t)throw t.providerField?.destroy(),t.providerField=null,this.fields.delete(e.id),bs(i)}}command(e,t){const i=this.fields.get(e)?.providerField;if(!i)throw new Error("The secure card field is not ready.");i[t]()}updateFieldPresentation(e,t){if(this.destroyed)return;const i=this.fields.get(e);if(!i)return;i.presentation={...t},i.configurationRevision+=1;i.providerField&&this.scheduleFieldUpdate(i,{placeholder:t.placeholder,style:this.compileAppearance(this.appearance,t)})}destroyField(e){const t=this.fields.get(e);t&&(this.pendingAppearancePreview?.stages.some(e=>e.registration===t)&&this.cancelPendingAppearancePreview(new Error("A split card field was destroyed during Appearance Preview.")),t.destroyed=!0,t.providerGeneration+=1,t.replacing=!1,t.abortController.abort(),t.providerField?.destroy(),t.providerField=null,this.removeProviderHost(t),this.fields.delete(e))}updateAppearance(e){if(!this.destroyed){this.appearance=e;for(const t of this.fields.values()){t.configurationRevision+=1;t.providerField&&this.scheduleFieldUpdate(t,{style:this.compileAppearance(e,t.presentation)})}}}remountAppearance(e){return this.prepareAppearanceRemount(e).then(e=>e.commit())}prepareAppearanceRemount(e){if(this.destroyed)return Promise.reject(fs());this.cancelPendingAppearancePreview(new Error("A newer Appearance Preview superseded this replacement."));const t={generation:++this.appearancePreviewGeneration,appearance:be(e),stages:[]};this.pendingAppearancePreview=t;for(const e of this.fields.values())e.replacing=!0;return Promise.all(Array.from(this.fields.values()).map(e=>this.stageReplacementField(e,t))).then(e=>{if(this.pendingAppearancePreview!==t)throw new Error("A newer Appearance Preview superseded this replacement.");let i=!1;return{commit:()=>{if(!i&&this.pendingAppearancePreview===t){i=!0,this.appearance=t.appearance,this.numberBrand=void 0;for(const t of e)this.activateStagedField(t);this.pendingAppearancePreview=null}},rollback:()=>{if(!i){i=!0,this.pendingAppearancePreview===t&&(this.pendingAppearancePreview=null),this.discardStagedFields(t);for(const e of this.fields.values())e.replacing=!1}}}},e=>{this.pendingAppearancePreview===t&&(this.pendingAppearancePreview=null),this.discardStagedFields(t);for(const e of this.fields.values())e.replacing=!1;throw e})}getAppearanceRemountGeneration(){return this.appearancePreviewGeneration}cancelAppearanceRemount(e,t){this.pendingAppearancePreview?.generation===e&&this.cancelPendingAppearancePreview(t)}supportsDeveloperPresets(){return!1===this.bootstrap?.livemode}announceAppearanceCommit(){if(!this.destroyed)for(const e of this.fields.values())e.events.onChange(e.lastChange??{complete:!1,empty:!0})}canApplyDeveloperPreset(){return this.supportsDeveloperPresets()&&null!==this.resolveRequiredFields()}getSubmissionIssue(){const e=this.resolveRequiredFields();if(!e){return{type:ys.find(e=>!Array.from(this.fields.values()).some(t=>t.type===e&&null!==t.providerField&&t.providerReady))??"cardNumber",errorType:"incomplete"}}const t=e.find(e=>"invalid"===e.lastChange?.errorType);if(t)return{type:t.type,errorType:"invalid"};const i=e.find(e=>!0!==e.lastChange?.complete);return i?{type:i.type,errorType:"incomplete"}:null}assertCanSubmitPaymentMethod(){if(this.destroyed)throw fs();if(this.bootstrapFailure)throw this.bootstrapFailure;if(!this.bootstrap)throw new gs({code:"elements_not_ready",message:"The secure card fields are not ready yet.",recoverable:!0});const e=vs(this.bootstrap);if(3!==e.protocolVersion||!0!==e.capabilities.paymentMethodSubmission)throw new gs({code:"elements_capability_unsupported",message:"Split card-field submission is not supported by this Hosted Checkout version.",recoverable:!0});if(this.pendingAppearancePreview||Array.from(this.fields.values()).some(e=>e.replacing))throw new gs({code:"elements_not_ready",message:"The secure card fields are refreshing their Appearance.",recoverable:!0});const t=this.getSubmissionIssue();if(t)throw new gs({code:"invalid"===t.errorType?"elements_payment_details_invalid":"elements_card_fields_incomplete",message:"invalid"===t.errorType?"Some card details are invalid.":"Please complete your card details.",recoverable:!0})}async createConfirmationData(e,t,i){this.assertCanSubmitPaymentMethod();try{const n=await this.getProvider();return await n.createConfirmationData(e,t?.trim()||void 0,i)}catch(e){if(e instanceof gs)throw e;if(e instanceof ts)throw new gs({code:"elements_submit_indeterminate",message:"Secure card tokenization may have completed, but its result could not be verified.",recoverable:!1},e);throw new gs({code:"elements_payment_method_creation_failed",message:"Payment details are temporarily unavailable. Please try again.",recoverable:!0},e)}}async applyDeveloperPreset(e){if(!this.supportsDeveloperPresets())throw new Error("Split-card test presets are unavailable for this payment configuration.");const t=this.resolveRequiredFields();if(!t)throw new Error("All three secure card fields must be ready before filling.");const i={cardNumber:e.number,cardExpiry:{month:e.expirationMonth,year:e.expirationYear},cardCvc:e.cvc},n=async()=>{await Promise.all(t.map(e=>this.enqueueDeveloperValueUpdate(e,i[e.type])))},o=()=>new Promise(e=>globalThis.setTimeout(e,150)),r=()=>t.every(e=>!0===e.lastChange?.complete);if(await n(),await o(),r()||(await n(),await o()),!r())throw new Error("The split-card test preset did not validate.")}resolveRequiredFields(){const e=ys.map(e=>Array.from(this.fields.values()).find(t=>t.type===e));return e.every(e=>null!==e?.providerField&&!0===e?.providerReady)?e:null}enqueueDeveloperValueUpdate(e,t){const i=e.providerField;if(!i||e.destroyed||this.destroyed||void 0===t)return Promise.reject(new Error("The secure card field is not ready."));const n=e.updateChain.catch(()=>{}).then(async()=>{if(this.destroyed||e.destroyed||e.providerField!==i)throw new Error("The secure card field is not ready.");await i.update({value:t})});return e.updateChain=n,n}scheduleFieldUpdate(e,t){const i=e.providerField;if(!i||e.destroyed||this.destroyed)return;e.pendingUpdate={...e.pendingUpdate,...t};const n=++e.updateRevision;e.updateChain=e.updateChain.catch(()=>{}).then(async()=>{if(this.destroyed||e.destroyed||e.providerField!==i||n!==e.updateRevision)return;const t=e.pendingUpdate;e.pendingUpdate=null,t&&await i.update(t)}).catch(()=>{this.destroyed||e.destroyed||e.providerField!==i||e.events.onError({code:"elements_provider_update_failed",message:"The secure card field could not be synchronized with the payment provider.",recoverable:!0})})}destroy(){if(this.destroyed)return;this.destroyed=!0,this.cancelPendingAppearancePreview(new Error("The secure card fields were destroyed during Appearance Preview.")),this.providerAbortController.abort();for(const e of this.fields.values())e.destroyed=!0,e.abortController.abort(),e.providerField?.destroy(),this.removeProviderHost(e);this.fields.clear(),this.provider=null,this.providerPromise=null;const e=new gs({code:"elements_destroyed",message:"The secure card fields were destroyed before initialization completed.",recoverable:!1});this.bootstrapWaiters.forEach(t=>t.reject(e)),this.bootstrapWaiters=[]}wrapEvents(e,t){const i=e.events;return{...i,onReady:()=>{this.isProviderGenerationCurrent(e,t)&&(e.providerReady=!0,e.replacing=!1,i.onReady())},onChange:n=>{this.isProviderGenerationCurrent(e,t)&&(e.lastChange=n,"cardNumber"===e.type&&this.updateCardBrand(n.brand),i.onChange(n))},onFocus:()=>{this.isProviderGenerationCurrent(e,t)&&i.onFocus()},onBlur:()=>{this.isProviderGenerationCurrent(e,t)&&i.onBlur()},onError:n=>{this.isProviderGenerationCurrent(e,t)&&i.onError(n)}}}stageReplacementField(e,t){const i=new AbortController,n=this.createStagingTarget(e);let o,r;const s=new Promise((e,t)=>{o=e,r=t});this.providerGenerationSequence=Math.max(this.providerGenerationSequence+1,e.providerGeneration+1);const a={registration:e,providerGeneration:this.providerGenerationSequence,abortController:i,target:n,providerField:null,ready:!1,activated:!1,lastChange:null,reject:()=>{}};let l=!1;const c=setTimeout(()=>{a.reject(new Error("A split card field did not become ready for Appearance Preview."))},15e3);a.reject=e=>{l||(l=!0,clearTimeout(c),r(e))},t.stages.push(a);const d=()=>{!l&&a.providerField&&a.ready&&(l=!0,clearTimeout(c),o(a))},p={onReady:()=>{this.pendingAppearancePreview===t&&(a.ready=!0,a.activated?e.events.onReady():d())},onChange:i=>{(this.pendingAppearancePreview===t||a.activated)&&(a.activated?this.isProviderGenerationCurrent(e,a.providerGeneration)&&(e.lastChange=i,"cardNumber"===e.type&&this.updateCardBrand(i.brand),e.events.onChange(i)):a.lastChange=i)},onFocus:()=>{a.activated&&this.isProviderGenerationCurrent(e,a.providerGeneration)&&e.events.onFocus()},onBlur:()=>{a.activated&&this.isProviderGenerationCurrent(e,a.providerGeneration)&&e.events.onBlur()},onError:i=>{a.activated?this.isProviderGenerationCurrent(e,a.providerGeneration)&&e.events.onError(i):this.pendingAppearancePreview===t&&a.reject(new Error(i.message))}};return this.getProvider().then(async o=>{if(this.pendingAppearancePreview===t)try{const r=await o.createField({type:e.type,target:n,signal:i.signal,style:this.compileAppearance(t.appearance,e.presentation),ariaLabel:e.ariaLabel,placeholder:e.presentation.placeholder,events:p});if(this.pendingAppearancePreview!==t)return void r.destroy();a.providerField=r,d()}catch(e){a.reject(e instanceof Error?e:new Error("Appearance replacement failed."))}},e=>a.reject(e instanceof Error?e:new Error("Appearance replacement failed."))),s}activateStagedField(e){const t=e.registration,i=t.providerField,n=t.providerHost;t.configurationRevision+=1,t.updateRevision+=1,t.pendingUpdate=null,t.updateChain=Promise.resolve(),t.abortController.abort(),t.abortController=e.abortController,t.providerGeneration=e.providerGeneration,t.providerField=e.providerField,t.providerReady=!0,t.replacing=!1,t.lastChange=e.lastChange??{complete:!1,empty:!0},e.activated=!0;try{i?.destroy()}catch{}n!==t.target&&n.remove(),this.activateStagingTarget(e.target,t.target),t.providerHost=e.target}createStagingTarget(e){const t=e.target;if("undefined"==typeof document||"function"!=typeof document.createElement||"function"!=typeof t.appendChild)return t;const i=document.createElement("div");return this.assignProviderTargetId(i,`${t.id}-appearance-preview-${this.appearancePreviewGeneration}`),i.dataset.paypercutAppearanceStage="",Object.assign(i.style,{position:"absolute",inset:"0",width:"100%",height:"100%",visibility:"hidden",pointerEvents:"none"}),t.appendChild(i),i}assignProviderTargetId(e,t){let i=e.id.trim()||t;for(;!i||this.providerTargetIds.has(i);)i=`${t}-${++this.providerTargetIdSequence}`;e.id=i,this.providerTargetIds.add(i)}activateStagingTarget(e,t){e!==t&&(e.removeAttribute?.("data-paypercut-appearance-stage"),Object.assign(e.style,{position:"relative",inset:"auto",width:"100%",height:"100%",visibility:"visible",pointerEvents:"auto"}))}removeProviderHost(e){e.providerHost!==e.target&&e.providerHost.remove(),e.providerHost=e.target}discardStagedFields(e){for(const t of e.stages)t.abortController.abort(),t.providerField?.destroy(),t.target!==t.registration.target&&t.target.remove()}cancelPendingAppearancePreview(e){const t=this.pendingAppearancePreview;if(t){this.pendingAppearancePreview=null,this.discardStagedFields(t);for(const i of t.stages)i.reject(e);for(const e of this.fields.values())e.replacing=!1}}isProviderGenerationCurrent(e,t){return!this.destroyed&&!e.destroyed&&this.fields.get(e.id)===e&&e.providerGeneration===t}updateCardBrand(e){if(e!==this.numberBrand){this.numberBrand=e;for(const t of this.fields.values())"cardCvc"===t.type&&t.providerField&&e&&this.scheduleFieldUpdate(t,{cardBrand:e})}}async getProvider(){if(this.destroyed)throw fs();return this.provider?this.provider:(this.providerPromise||(this.providerPromise=this.waitForBootstrap().then(vs).then(e=>this.providerFactory(e,{signal:this.providerAbortController.signal})).then(e=>{if(this.destroyed)throw fs();return this.provider=e,e}).catch(e=>{throw this.providerPromise=null,bs(e)})),this.providerPromise)}waitForBootstrap(){return this.bootstrapFailure?Promise.reject(this.bootstrapFailure):this.bootstrap?Promise.resolve(this.bootstrap):new Promise((e,t)=>{this.bootstrapWaiters.push({resolve:e,reject:t})})}}class Ps{constructor(e,t){this.runtime=e,this.context=t,this.submissionSourceId=j(),this.tokenizations=new Map,this.destroyed=!1,this.activeRequestId=null,this.canceledRequests=new Set}validatePaymentMethod(){try{return this.assertCanSubmitPaymentMethod(),Promise.resolve()}catch(e){return Promise.reject(e)}}assertCanSubmitPaymentMethod(){if(this.destroyed||this.context.isDestroyed())throw new gs({code:"elements_destroyed",message:"The split card fields have been destroyed.",recoverable:!1});const e=this.runtime.getSubmissionIssue();e&&this.context.revealCardFieldSubmissionError(e.type,e.errorType);try{this.runtime.assertCanSubmitPaymentMethod()}catch(e){if(e instanceof gs)throw vn(e.details.code,e.details.message,e.details.recoverable??!0);throw e}}beginPaymentMethodSubmission(e,t,i,n){this.activeRequestId=e,this.activeFutureUsage=i,this.activeBillingDetails=n,this.canceledRequests.delete(e),this.context.onCardCollectionSubmissionStateChange(),n?this.context.submitCardCollection(this.submissionSourceId,e,t,n):this.context.submitCardCollection(this.submissionSourceId,e,t)}cancelPaymentMethodSubmission(e,t){this.tokenizations.has(e)?this.canceledRequests.add(e):this.canceledRequests.delete(e),this.activeRequestId===e&&(this.activeRequestId=null,this.activeFutureUsage=void 0,this.activeBillingDetails=void 0),this.tokenizations.delete(e),this.context.cancelCardCollectionSubmission(this.submissionSourceId,e,t)}attachPaymentMethodActionChannel(e,t,i){this.context.attachCardCollectionActionChannel(this.submissionSourceId,e,t,i)}onPaymentMethodSubmissionStateChange(){this.context.onCardCollectionSubmissionStateChange()}handleTokenizationRequest(e,t){if(this.destroyed||this.activeRequestId!==e||this.canceledRequests.has(e))return;if(this.activeFutureUsage!==t)return;if(this.tokenizations.has(e))return;const i=this.runtime.createConfirmationData(e,this.activeBillingDetails?.name,t).then(e=>({status:"succeeded",confirmationData:e}),e=>e instanceof gs?{status:"failed",code:e.details.code,message:e.details.message,recoverable:e.details.recoverable??!0}:{status:"failed",code:"elements_payment_method_creation_failed",message:"Payment details are temporarily unavailable. Please try again.",recoverable:!0});this.tokenizations.set(e,i),i.then(t=>{this.tokenizations.delete(e),this.destroyed||this.canceledRequests.delete(e)||this.activeRequestId===e&&(this.activeRequestId=null,this.activeFutureUsage=void 0,this.activeBillingDetails=void 0,this.context.sendCardCollectionTokenizationResult({channel:Ce,type:Me,controllerId:this.context.controllerId,componentId:this.submissionSourceId,componentType:"card_collection",requestId:e,result:t}))})}destroy(){this.destroyed||(this.destroyed=!0,this.activeRequestId=null,this.activeFutureUsage=void 0,this.activeBillingDetails=void 0,this.tokenizations.clear(),this.canceledRequests.clear())}}class Es extends Error{constructor(e,t,i){super(t),this.code=e,this.name="AppearancePreviewError",void 0!==i&&(this.cause=i)}}const As=(e,t,i)=>Object.assign(new Error(t),{code:e,recoverable:i});class Cs{constructor(e,t,i){if(this.clientOptions=e,this.elementsOptions=t,this.configurationIdentity=i,this.controllerId=j(),this.elements=new Map,this.cardFields=new Map,this.pendingComponents=new Map,this.controllerIframe=null,this.controlPort=null,this.controllerInitialized=!1,this.controllerBootstrapped=!1,this.destroyed=!1,this.appearancePreview=null,this.appearancePreviewGeneration=0,this.appearanceLocked=!1,this.warnedAboutSkippedAppearance=!1,this.updateRevision=0,this.validationRevision=0,this.validatedSource=null,this.pendingValidation=null,this.walletAttemptOverlay=new wo,this.splitCardDeveloperAssistant=null,this.windowMessageHandler=e=>this.onWindowMessage(e),this.hostedOrigin=function(){try{return new URL(r()).origin}catch{throw new Error("[Paypercut Elements] The configured hosted checkout URL is invalid.")}}(e.hostedCheckoutUrl),this.amount=t.amount,t.appearance&&fe(t.appearance),this.appearance=be(t.appearance),this.cardCollectionRuntime=new ws(this.appearance,Io),this.cardCollectionSubmissionSource=new Ps(this.cardCollectionRuntime,this),this.paymentMethodSubmission=new fn(this.hostedOrigin),!o(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("card"===e){if(this.cardFields.size>0)throw As("elements_component_conflict","A Card Element and split card fields cannot share one Elements group.",!1);if(Array.from(this.elements.values()).some(e=>"card"===e.componentType))throw As("elements_component_conflict","Only one Card Element may be created in an Elements group.",!0);const e=new En(this);return this.elements.set(e.componentId,e),e}if("expressCheckout"===e){const e=new Vn(this,t);return this.elements.set(e.componentId,e),e}if("cardNumber"===e||"cardExpiry"===e||"cardCvc"===e){if("cardNumber"!==e&&void 0!==t)throw As("elements_component_configuration_invalid",`${e} does not accept creation options.`,!0);if(Array.from(this.elements.values()).some(e=>"card"===e.componentType))throw As("elements_component_conflict","Split card fields and a Card Element cannot share one Elements group.",!1);if(this.cardFields.has(e))throw As("elements_card_field_duplicate",`Only one ${e} field may be created in an Elements group.`,!0);const i=new zo(e,this,"cardNumber"===e?(e=>{if(void 0===e)return{};if(!e||"object"!=typeof e||Array.isArray(e))throw As("elements_component_configuration_invalid","Card number Element options must be an object.",!0);const t=e;if(Object.keys(t).some(e=>"showIcon"!==e))throw As("elements_component_configuration_invalid","Card number Element options contain an unsupported property.",!0);if(void 0!==t.showIcon&&"boolean"!=typeof t.showIcon)throw As("elements_component_configuration_invalid","Card number Element showIcon must be a boolean.",!0);return void 0===t.showIcon?{}:{showIcon:t.showIcon}})(t):void 0);return this.cardFields.set(e,i),this.elements.set(i.componentId,i),this.ensureSplitCardDeveloperAssistant(),i}throw new Error(`[Paypercut Elements] Unsupported Element type: ${String(e)}`)}submit(){if(this.appearancePreview)return Promise.reject(this.appearancePreviewNotReadyError());let e;try{e=this.resolvePaymentMethodSource()}catch(e){return Promise.reject(e)}const t=this.paymentMethodSubmission.getIndeterminateAttemptError();if(t)return Promise.reject(t);const i=this.validationRevision;if(this.validatedSource?.sourceId===e.submissionSourceId&&this.validatedSource.revision===i)return Promise.resolve();if(this.pendingValidation?.sourceId===e.submissionSourceId&&this.pendingValidation.revision===i)return this.pendingValidation.promise;const n=e.validatePaymentMethod().then(()=>{if(this.destroyed)throw vn("elements_destroyed","The Elements group has been destroyed.",!1);if(i!==this.validationRevision)throw vn("elements_submit_required","Payment details changed while they were being validated. Submit the Elements group again.",!0);this.validatedSource={sourceId:e.submissionSourceId,revision:i}});return this.pendingValidation={sourceId:e.submissionSourceId,revision:i,promise:n},n.then(()=>{this.pendingValidation?.promise===n&&(this.pendingValidation=null)},()=>{this.pendingValidation?.promise===n&&(this.pendingValidation=null)}),n}createPaymentMethod(e){if(this.appearancePreview)return Promise.reject(this.appearancePreviewNotReadyError());let t;try{t=this.resolvePaymentMethodSource()}catch(e){return Promise.reject(e)}const i=this.paymentMethodSubmission.getIndeterminateAttemptError();if(i)return Promise.reject(i);if(this.validatedSource?.sourceId!==t.submissionSourceId||this.validatedSource.revision!==this.validationRevision){try{t.assertCanSubmitPaymentMethod()}catch(e){if(function(e,t){return le(e)&&e.code===t}(e,"elements_not_ready"))return Promise.reject(e)}return Promise.reject(vn("elements_submit_required","Call elements.submit() after the latest payment-details change before creating a Payment Method.",!0))}return this.paymentMethodSubmission.submit(t,this.elementsOptions.setupFutureUsage,e)}resolvePaymentMethodSource(){if(this.destroyed)throw vn("elements_destroyed","The Elements group has been destroyed.",!1);const e=Array.from(this.elements.values()).filter(e=>e instanceof En);if(e.length>1)throw vn("elements_component_conflict","More than one active payment-method source is mounted in this Elements group.",!0);if(1===e.length)return e[0];if(this.cardFields.size>0)return this.cardCollectionSubmissionSource;throw vn("elements_not_mounted","Create and mount a payment-method Element before submitting.",!0)}getClientOptions(){return{...this.clientOptions}}getElementsOptions(){return this.serializeElementsOptions(this.appearance)}getRenderableElementsOptions(){return this.serializeElementsOptions(this.appearancePreview?.appearance??this.appearance)}serializeElementsOptions(e){return{...this.elementsOptions,amount:this.amount,...e?{appearance:be(e)}:{}}}markComponentMounted(){this.appearanceLocked=!0}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=Ii(function(e){const t=new URLSearchParams;return Ti(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),t.set("cardCollectionProtocol",String(3)),ki("/elements/controller",e.hostedOrigin,t)}({hostedOrigin:this.hostedOrigin,controllerId:this.controllerId,clientOptions:this.clientOptions,elementsOptions:this.getElementsOptions(),sdkVersion:n.version,referrer:window.location.origin}),j()),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)}retryStalledControllerInitialization(){const e=this.controllerIframe,t=e?.parentNode;if(this.destroyed||this.controllerInitialized||!e||!t)return!1;let i;try{i=e.cloneNode(!1),i.src=Ii(e.src,j()),t.replaceChild(i,e)}catch{return!1}return this.controlPort?.close(),this.controlPort=null,this.controllerBootstrapped=!1,this.controllerIframe=i,!0}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()}reattachComponent(e,t){!this.destroyed&&this.elements.has(e.componentId)?(this.invalidateSubmissionValidation(),this.paymentMethodSubmission.reinitializeSource(e instanceof En?e.submissionSourceId:e.componentId),this.detachComponent(e),this.pendingComponents.set(e.componentId,{element:e,port:t}),this.flushPendingComponents()):t.close()}submitComponent(e,t,i,n){const o={channel:Ce,type:xe,controllerId:this.controllerId,componentId:e,componentType:"card",requestId:t,deadlineAt:i,...n?{billingDetails:n}:{}};this.postControl(o)}validateComponent(e,t){const i={channel:Ce,type:Oe,controllerId:this.controllerId,componentId:e,componentType:"card",requestId:t};this.postControl(i)}invalidateSubmissionValidation(){this.validatedSource=null,this.validationRevision<Number.MAX_SAFE_INTEGER&&(this.validationRevision+=1)}submitCardCollection(e,t,i,n){const o={channel:Ce,type:xe,controllerId:this.controllerId,componentId:e,componentType:"card_collection",requestId:t,deadlineAt:i,...n?{billingDetails:n}:{}};this.postControl(o)}cancelCardCollectionSubmission(e,t,i="canceled"){const n={channel:Ce,type:Le,controllerId:this.controllerId,componentId:e,componentType:"card_collection",requestId:t,reason:i};this.postControl(n)}cancelComponentSubmission(e,t,i="canceled"){const n=this.elements.get(e);if(!n)return;const o={channel:Ce,type:Le,controllerId:this.controllerId,componentId:e,componentType:n.componentType,requestId:t,reason:i};this.postControl(o)}beginWalletAttempt(e,t,i,n){const o=this.elements.get(e);return!(!o||"express_checkout"!==o.componentType)&&this.walletAttemptOverlay.show(e,t,i,()=>this.cancelComponentSubmission(e,t),n)}hideWalletAttemptOverlay(e,t){this.walletAttemptOverlay.hide(e,t)}markWalletAttemptProcessing(e,t,i){this.walletAttemptOverlay.setPhase(e,t,i,"processing")}endWalletAttempt(e,t){this.walletAttemptOverlay.close(e,t)}attachActionChannel(e,t,i,n){const o=this.elements.get(e);if(!o)return void n.close();const r={channel:Ce,type:De,controllerId:this.controllerId,componentId:e,componentType:o.componentType,requestId:t,actionId:i};this.postControl(r,[n])}attachCardCollectionActionChannel(e,t,i,n){const o={channel:Ce,type:De,controllerId:this.controllerId,componentId:e,componentType:"card_collection",requestId:t,actionId:i};this.postControl(o,[n])}sendCardCollectionTokenizationResult(e){this.postControl(e)}revealCardFieldSubmissionError(e,t){this.cardFields.get(e)?.revealSubmissionError(t)}onCardCollectionSubmissionStateChange(){this.splitCardDeveloperAssistant?.collapse(),this.splitCardDeveloperAssistant?.refresh()}hasPaymentMethodSubmissionState(e){return this.paymentMethodSubmission.hasActiveSubmission(e)}hasCompletedPaymentMethodSubmission(e){return this.paymentMethodSubmission.hasCompletedSubmission(e)}sendApplePayCapabilities(e,t){const i={channel:Ce,type:Ue,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",available:t};this.postControl(i)}sendApplePayValidateMerchant(e,t,i){const n={channel:Ce,type:qe,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,validationUrl:i};this.postControl(n)}sendApplePayAuthorized(e,t,i){const n={channel:Ce,type:Be,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,payment:i};this.postControl(n)}sendApplePayCanceled(e,t){const i={channel:Ce,type:je,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t};this.postControl(i)}sendGooglePayCapabilities(e,t){const i={channel:Ce,type:He,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",available:t};this.postControl(i)}sendGooglePayClick(e,t){const i={channel:Ce,type:Ge,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t};this.postControl(i)}sendGooglePayDataChanged(e,t,i,n){const o={channel:Ce,type:We,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,updateId:i,dataJson:n};this.postControl(o)}sendGooglePayAuthorized(e,t,i){const n={channel:Ce,type:Ve,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,dataJson:i};this.postControl(n)}sendGooglePayPaymentData(e,t,i){const n={channel:Ce,type:$e,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,dataJson:i};this.postControl(n)}sendGooglePayCanceled(e,t){const i={channel:Ce,type:Ye,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t};this.postControl(i)}sendGooglePayError(e,t,i,n){const o={channel:Ce,type:Ke,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,code:i,message:n};this.postControl(o)}resolveWalletClick(e,t,i,n,o){i&&void 0!==o&&this.commitAmountUpdate(o);const r=this.getUpdateSnapshot().options,s={channel:Ce,type:Ze,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,accepted:i,...n?{options:n}:{},amount:r.amount,currency:r.currency};this.postControl(s)}resolveWalletUpdate(e,t,i,n,o){const r=this.getUpdateSnapshot().options,{amount:s=r.amount,...a}=o??{},l=Object.keys(a).length>0,c={channel:Ce,type:Je,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,updateId:i,accepted:n,...l?{update:a}:{},amount:s,currency:r.currency};this.postControl(c)}resolveWalletConfirmation(e,t,i,n){const o={channel:Ce,type:Xe,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",requestId:t,succeeded:i,...n?{error:n}:{}};this.postControl(o)}updateExpressCheckoutComponent(e,t,i){const n=this.elements.get(e);if(!n||"express_checkout"!==n.componentType)return;if(!this.controllerInitialized)return;const o={channel:Ce,type:Qe,controllerId:this.controllerId,componentId:e,componentType:"express_checkout",componentRevision:t,componentOptions:i};this.postControl(o)}discoverDeveloperPresets(e){if(!0!==this.clientOptions.developerAssistant)return;const t={channel:Ce,type:Ne,controllerId:this.controllerId,componentId:e,componentType:"card"};this.postControl(t)}applyDeveloperPreset(e,t,i){const n={channel:Ce,type:ze,controllerId:this.controllerId,componentId:e,componentType:"card",requestId:t,presetId:i};this.postControl(n)}commandCardField(e,t,i){const n=this.elements.get(e);if(!n||n.componentType!==t)throw new Error("[Paypercut Elements] The secure card field is unavailable.");this.cardCollectionRuntime.command(e,i)}mountCardField(e){return this.ensureController(),this.cardCollectionRuntime.mountField(e)}resolveCardFieldCopy(e){return this.ensureController(),this.cardCollectionRuntime.resolveFieldCopy(e)}updateCardFieldPresentation(e,t){this.cardCollectionRuntime.updateFieldPresentation(e,t)}onCardFieldAvailabilityChange(){this.invalidateSubmissionValidation(),this.splitCardDeveloperAssistant?.refresh()}onCardFieldValueChange(){this.invalidateSubmissionValidation()}destroyCardField(e){this.cardCollectionRuntime.destroyField(e)}getUpdateSnapshot(){const e=this.appearancePreview?.appearance??this.appearance;return{updateRevision:this.updateRevision,options:Ts(this.elementsOptions,this.amount,e)}}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){try{return this.applyUpdate({appearance:e}).catch(e=>{throw e instanceof Es&&this.warnAppearancePreview(e),e})}catch(e){return e instanceof Es&&this.warnAppearancePreview(e),Promise.reject(e)}}prepareAppearance(e){return this.prepareAppearanceCandidate(()=>_s({appearance:e},this.appearance,this.amount).appearance)}prepareAppearanceReplacement(e){return this.prepareAppearanceCandidate(()=>(fe(e),be(e)))}prepareAppearanceCandidate(e){if(!this.isAppearancePreviewAvailable())return Promise.reject(new Es("elements_appearance_preview_refused","Appearance Preview is unavailable while payment validation, Card authentication, or a wallet attempt is active."));const t=e();return this.clearAppearancePreviewFailures(),ve(t,this.appearance)?Promise.resolve({isCurrent:()=>!0,commit:()=>{},rollback:()=>Promise.resolve()}):this.startAppearancePreview(t,!0)}replaceAppearance(e){if(!this.isAppearancePreviewAvailable())return Promise.reject(new Es("elements_appearance_preview_refused","Appearance Preview is unavailable while payment validation, Card authentication, or a wallet attempt is active."));fe(e);const t=be(e);return ve(t,this.appearance)?Promise.resolve():this.startAppearancePreview(t).then(()=>{})}isAppearancePreviewAvailable(){return!this.destroyed&&null===this.pendingValidation&&!this.paymentMethodSubmission.hasActiveSubmission()&&!Array.from(this.elements.values()).some(e=>e.hasActiveSubmission())}update(e){try{this.applyUpdate(e).catch(e=>{e instanceof Es&&this.warnAppearancePreview(e)})}catch(e){if(e instanceof Es)return void this.warnAppearancePreview(e);throw e}}applyUpdate(e){if(this.destroyed)throw new Error("[Paypercut Elements] Cannot update a destroyed group.");const t=Array.from(this.elements.values()).some(e=>e.hasActiveSubmission()),i=Array.from(this.elements.values()).some(e=>"express_checkout"===e.componentType?e.hasActiveProviderSubmission():e.hasActiveSubmission());if(null!==this.pendingValidation||this.paymentMethodSubmission.hasActiveSubmission()||(void 0!==e.appearance?t:i)){if(void 0!==e.appearance)throw new Es("elements_appearance_preview_refused","Appearance Preview is unavailable while payment validation, Card authentication, or a wallet attempt is active.");throw As("elements_submission_in_progress","[Paypercut Elements] Cannot update Elements while payment details are being submitted.",!0)}const n=_s(e,this.appearance,this.amount),o=void 0!==e.appearance,r="remount"===this.elementsOptions.appearanceUpdates||!0===this.clientOptions.developerAssistant,s=this.hasMountedCardFields()||this.getMountedCardElements().length>0||this.getMountedExpressCheckoutElements().length>0,a=o&&this.appearanceLocked&&r&&s;o&&r&&this.clearAppearancePreviewFailures();o&&this.appearanceLocked&&!a&&(n.appearance=this.appearance,this.warnAboutSkippedAppearance());const l=!ve(n.appearance,this.appearance);if(n.amount===this.amount&&!l)return Promise.resolve();if(!l)return this.commitAmountUpdate(n.amount),Promise.resolve();if(this.updateRevision===Number.MAX_SAFE_INTEGER)throw new Error("[Paypercut Elements] The update revision limit has been reached.");if(this.amount=n.amount,l){if(a)return this.startAppearancePreview(n.appearance).then(()=>{});this.appearance=n.appearance,this.cardCollectionRuntime.updateAppearance(this.appearance);for(const e of this.cardFields.values())e.updateAppearance(this.appearance);this.splitCardDeveloperAssistant?.refresh()}if(this.invalidateSubmissionValidation(),this.updateRevision+=1,!this.controllerInitialized)return Promise.resolve();const c=this.getUpdateSnapshot(),d={channel:Ce,type:Fe,controllerId:this.controllerId,updateRevision:c.updateRevision,options:c.options};return this.postControl(d),Promise.resolve()}commitAmountUpdate(e){if(e===this.amount)return;if(this.updateRevision===Number.MAX_SAFE_INTEGER)throw new Error("[Paypercut Elements] The update revision limit has been reached.");if(this.amount=e,this.invalidateSubmissionValidation(),this.updateRevision+=1,!this.controllerInitialized)return;const t=this.getUpdateSnapshot();this.postControl({channel:Ce,type:Fe,controllerId:this.controllerId,updateRevision:t.updateRevision,options:t.options})}startAppearancePreview(e,t=!1){const i=++this.appearancePreviewGeneration,n=be(this.appearance),o=be(e);if(this.appearancePreview={generation:i,appearance:o},this.invalidateSubmissionValidation(),this.updateRevision+=1,this.controllerInitialized){const e=this.getUpdateSnapshot();this.postControl({channel:Ce,type:Fe,controllerId:this.controllerId,updateRevision:e.updateRevision,options:e.options})}return this.prepareMountedAppearanceTransitions(o).then(e=>{if(this.appearancePreview?.generation!==i)throw e.forEach(e=>e.rollback()),new Es("elements_appearance_preview_superseded","A newer Appearance Preview replaced this request.");if(t)return{isCurrent:()=>this.appearancePreview?.generation===i,commit:()=>{e.forEach(e=>e.commit()),this.commitAppearancePreview(i,o)},rollback:async()=>{e.forEach(e=>e.rollback()),await this.restoreAppearancePreview(i,n)}};e.forEach(e=>e.commit()),this.commitAppearancePreview(i,o)},async e=>{if(this.appearancePreview?.generation!==i)throw new Es("elements_appearance_preview_superseded","A newer Appearance Preview replaced this request.",e);throw await this.restoreAppearancePreview(i,n),new Es("elements_appearance_preview_failed","Appearance Preview failed; the last successfully applied Appearance remains active.",e)})}async prepareMountedAppearanceTransitions(e){const t=[],i=[];if(this.hasMountedCardFields()){for(const e of this.cardFields.values())e.beginAppearanceTransition();t.push(this.cardCollectionRuntime.prepareAppearanceRemount(e));const n=this.cardCollectionRuntime.getAppearanceRemountGeneration();i.push(e=>this.cardCollectionRuntime.cancelAppearanceRemount(n,e))}for(const e of this.getMountedCardElements()){t.push(e.remountAppearance());const n=e.componentGeneration;i.push(t=>e.cancelAppearanceRemount(n,t))}for(const e of this.getMountedExpressCheckoutElements()){t.push(e.remountAppearance());const n=e.componentGeneration;i.push(t=>e.cancelAppearanceRemount(n,t))}try{return await Promise.all(t)}catch(e){const n=new Error("The coordinated Appearance Preview was cancelled.");i.forEach(e=>e(n));const o=await Promise.allSettled(t);for(const e of o)"fulfilled"===e.status&&e.value.rollback();throw e}}commitAppearancePreview(e,t){if(this.appearancePreview?.generation!==e)throw new Es("elements_appearance_preview_superseded","A newer Appearance Preview replaced this request.");this.appearance=be(t),this.appearancePreview=null;for(const e of this.cardFields.values())e.updateAppearance(this.appearance);this.cardCollectionRuntime.announceAppearanceCommit();for(const e of this.cardFields.values())e.announceAppearanceReady();this.splitCardDeveloperAssistant?.refresh()}async restoreAppearancePreview(e,t){if(this.appearancePreview?.generation===e){this.appearancePreview={generation:e,appearance:be(t)},this.updateRevision+=1,this.postAppearancePreviewOptions();try{const i=await this.prepareMountedAppearanceTransitions(t);if(this.appearancePreview?.generation!==e)return void i.forEach(e=>e.rollback());i.forEach(e=>e.commit())}catch(t){if(this.appearancePreview?.generation===e){this.appearancePreview=null;for(const e of this.cardFields.values())e.updateAppearance(this.appearance);this.cardCollectionRuntime.announceAppearanceCommit();for(const e of this.cardFields.values())e.announceAppearanceReady();for(const e of this.getMountedCardElements())e.markAppearanceRecoveryFailed();for(const e of this.getMountedExpressCheckoutElements())e.markAppearanceRecoveryFailed();this.splitCardDeveloperAssistant?.refresh()}throw t}if(this.appearancePreview?.generation===e){this.appearancePreview=null;for(const e of this.cardFields.values())e.updateAppearance(this.appearance);this.cardCollectionRuntime.announceAppearanceCommit();for(const e of this.cardFields.values())e.announceAppearanceReady();this.splitCardDeveloperAssistant?.refresh()}}}postAppearancePreviewOptions(){if(!this.controllerInitialized)return;const e=this.getUpdateSnapshot();this.postControl({channel:Ce,type:Fe,controllerId:this.controllerId,updateRevision:e.updateRevision,options:e.options})}getMountedCardElements(){return Array.from(this.elements.values()).filter(e=>e instanceof En&&e.isMounted())}getMountedExpressCheckoutElements(){return Array.from(this.elements.values()).filter(e=>e instanceof Vn&&e.isMounted())}clearAppearancePreviewFailures(){if(null===this.appearancePreview)for(const e of this.getMountedCardElements())e.clearAppearancePreviewFailure()}hasMountedCardFields(){return Array.from(this.cardFields.values()).some(e=>e.isMounted())}hasVisibleCardFields(){return Array.from(this.cardFields.values()).some(e=>e.isVisible())}warnAppearancePreview(e){"elements_appearance_preview_superseded"!==e.code&&console.warn(`[Paypercut Elements] ${e.code}: ${e.message}`)}appearancePreviewNotReadyError(){return vn("elements_not_ready","Payment details are refreshing their Appearance.",!0)}warnAboutSkippedAppearance(){this.warnedAboutSkippedAppearance||(this.warnedAboutSkippedAppearance=!0,console.warn("[Paypercut Elements] elements_appearance_locked: Appearance is locked after the first Element mounts. Configure Appearance during initialization."))}isDestroyed(){return this.destroyed}remove(e){this.invalidateSubmissionValidation(),e instanceof En&&this.paymentMethodSubmission.releaseSource(e.submissionSourceId),this.detachComponent(e),this.elements.delete(e.componentId),e instanceof zo&&this.cardFields.get(e.type)===e&&(this.cardFields.delete(e.type),this.paymentMethodSubmission.releaseSource(this.cardCollectionSubmissionSource.submissionSourceId),0===this.cardFields.size&&this.unregisterSplitCardDeveloperAssistant())}detachComponent(e){if(e instanceof zo)return void this.cardCollectionRuntime.destroyField(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:Ce,type:ke,controllerId:this.controllerId,componentId:e.componentId,componentType:e.componentType};try{this.controlPort.postMessage(t)}catch{}}}destroy(){if(!this.destroyed){this.destroyed=!0,this.paymentMethodSubmission.destroy(),this.cardCollectionSubmissionSource.destroy(),this.unregisterSplitCardDeveloperAssistant();for(const e of Array.from(this.elements.values()))e.destroy();this.elements.clear(),this.cardFields.clear(),this.cardCollectionRuntime.destroy();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)}}ensureSplitCardDeveloperAssistant(){!this.splitCardDeveloperAssistant&&!0===this.clientOptions.developerAssistant&&0!==this.cardFields.size&&this.cardCollectionRuntime.supportsDeveloperPresets()&&"undefined"!=typeof window&&"undefined"!=typeof document&&(this.splitCardDeveloperAssistant=Ci({id:`${this.controllerId}:split-card-fields`,configurationIdentity:this.configurationIdentity,appearanceScopeId:this.controllerId,presetSource:"split-card",isVisible:()=>!this.destroyed&&this.hasVisibleCardFields(),isAvailable:()=>!this.destroyed&&this.cardCollectionRuntime.canApplyDeveloperPreset(),isAppearanceAvailable:()=>!this.destroyed&&this.hasMountedCardFields(),appearancePreviewClearsTestData:()=>!0,canPreview:()=>this.isAppearancePreviewAvailable(),applyCardValue:e=>this.cardCollectionRuntime.applyDeveloperPreset(e),getAppearance:()=>this.getAppearance(),updateAppearance:e=>this.updateAppearance(e),replaceAppearance:e=>this.replaceAppearance(e),prepareAppearance:e=>this.prepareAppearance(e),prepareAppearanceReplacement:e=>this.prepareAppearanceReplacement(e)}))}unregisterSplitCardDeveloperAssistant(){this.splitCardDeveloperAssistant?.unregister(),this.splitCardDeveloperAssistant=null}onWindowMessage(e){if(this.destroyed||this.controllerBootstrapped||!this.controllerIframe?.contentWindow||e.source!==this.controllerIframe.contentWindow||e.origin!==this.hostedOrigin||(t=e.data,!le(t)||!ce(t,St)||t.channel!==Ee||t.type!==Se))return;var t;this.controllerBootstrapped=!0;const i=new MessageChannel;this.controlPort=i.port1,this.controlPort.onmessage=e=>this.onControlMessage(e),this.controlPort.start();const o={channel:Ee,type:_e,controllerId:this.controllerId,payload:{publishableKey:this.clientOptions.publishableKey,apiUrl:s(this.clientOptions.apiUrl),sdkVersion:n.version,options:this.getUpdateSnapshot().options}};this.controllerIframe.contentWindow.postMessage(o,this.hostedOrigin,[i.port2])}onControlMessage(e){if(this.destroyed)return void e.ports.forEach(e=>e.close());if(t=e.data,le(t)&&ce(t,_t)&&t.channel===Ee&&t.type===Ie&&de(t.controllerId,oe)&&le(t.payload)&&(ce(t.payload,["sessionId"])||ce(t.payload,It))&&de(t.payload.sessionId,oe)&&(void 0===t.payload.cardCollection||Ht(t.payload.cardCollection))){if(e.data.controllerId!==this.controllerId)return;if(this.cardCollectionRuntime.configure(e.data.payload.cardCollection??null),this.ensureSplitCardDeveloperAssistant(),this.controllerInitialized=!0,this.flushPendingComponents(),this.updateRevision>0){const e=this.getUpdateSnapshot(),t={channel:Ce,type:Fe,controllerId:this.controllerId,updateRevision:e.updateRevision,options:e.options};this.postControl(t)}return}var t;if((e=>le(e)&&ce(e,Nt)&&e.channel===Ee&&e.type===Te&&de(e.controllerId,oe)&&le(e.payload)&&ce(e.payload,zt)&&de(e.payload.code,oe)&&de(e.payload.message,re)&&"boolean"==typeof e.payload.recoverable)(e.data)){if(e.data.controllerId!==this.controllerId)return;this.cardCollectionRuntime.fail(e.data.payload),this.paymentMethodSubmission.handleSourceError(this.cardCollectionSubmissionSource.submissionSourceId,e.data.payload);for(const t of this.elements.values())this.paymentMethodSubmission.handleSourceError(t instanceof En?t.submissionSourceId:t.componentId,e.data.payload),t.handleControllerError(e.data.payload);return}if(!(e=>{if(!(le(e)&&ce(e,void 0===e.componentGeneration?Ut:qt)&&e.channel===Ce&&e.type===et&&de(e.controllerId,oe)&&de(e.componentId,oe)&&$t(e.componentType))||void 0!==e.componentGeneration&&("number"!=typeof e.componentGeneration||!Number.isSafeInteger(e.componentGeneration)||e.componentGeneration<0)||!le(e.payload))return!1;const t=e.payload;if(Yt(e.componentType)&&!["ready","change","focus","blur","error"].includes(String(t.event)))return!1;switch(t.event){case"ready":return"card"===e.componentType||(Yt(e.componentType)?ce(t,["event"]):jt(t.availablePaymentMethods));case"secure_field_surface_invalid":return"card"===e.componentType&&ce(t,["event"]);case"change":return"card"===e.componentType?ce(t,["event"]):Yt(e.componentType)&&Kt(t,e.componentType);case"focus":case"blur":return Yt(e.componentType)&&ce(t,["event"]);case"resize":return Number.isFinite(t.height)&&t.height>=0&&t.height<=ot;case"phase":return("card"===e.componentType||"card_collection"===e.componentType)&&["submitting","ready"].includes(String(t.phase));case"tokenization_requested":return"card_collection"===e.componentType&&ce(t,void 0===t.setupFutureUsage?["event","requestId"]:["event","requestId","setupFutureUsage"])&&de(t.requestId,oe)&&(void 0===t.setupFutureUsage||"on_session"===t.setupFutureUsage||"off_session"===t.setupFutureUsage);case"validation_result":return"card"===e.componentType&&ce(t,["event","requestId","result"])&&de(t.requestId,oe)&&function(e){return le(e)&&("succeeded"===e.status&&ce(e,["status"])||"failed"===e.status&&ce(e,["status","code","message","recoverable"])&&de(e.code,oe)&&de(e.message,re)&&"boolean"==typeof e.recoverable)}(t.result);case"action_required":return de(t.requestId,oe)&&le(t.action)&&de(t.action.id,oe)&&"three_d_secure"===t.action.type;case"error":return(!Yt(e.componentType)||ce(t,["event","code","message","recoverable"]))&&de(t.code,oe)&&de(t.message,re)&&"boolean"==typeof t.recoverable;case"submit_result":return("card"===e.componentType||"card_collection"===e.componentType)&&de(t.requestId,oe)&&li(t.result);case"developer_catalog":return"card"===e.componentType&&Array.isArray(t.presets)&&t.presets.length>0&&t.presets.length<=rt&&t.presets.every(ci);case"developer_apply_result":return"card"===e.componentType&&de(t.requestId,oe)&&de(t.presetId,st)&&"boolean"==typeof t.ok&&(t.ok||de(t.errorCode,oe));case"available_payment_methods_change":return"express_checkout"===e.componentType&&jt(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&&de(t.requestId,oe)&&ni(t.request);case"apple_pay_merchant_session":return"express_checkout"===e.componentType&&de(t.requestId,oe)&&le(t.merchantSession);case"google_pay_capabilities_request":return"express_checkout"===e.componentType&&Xt(t.environment)&&ti(t.requestJson,ht);case"google_pay_button_target":return"express_checkout"===e.componentType&&"boolean"==typeof t.visible&&Xt(t.environment)&&ti(t.requestJson,ut)&&("black"===t.buttonColor||"white"===t.buttonColor)&&Qt(t.buttonType)&&Number.isFinite(t.buttonRadius)&&t.buttonRadius>=0&&t.buttonRadius<=yt&&ei(t.target);case"google_pay_start":return"express_checkout"===e.componentType&&de(t.requestId,oe)&&Xt(t.environment)&&ti(t.requestJson,ut);case"google_pay_data_changed_result":return"express_checkout"===e.componentType&&de(t.requestId,oe)&&de(t.updateId,oe)&&ti(t.resultJson,ut);case"google_pay_authorization_result":return"express_checkout"===e.componentType&&de(t.requestId,oe)&&ti(t.resultJson,mt);case"wallet_click":case"wallet_cancel":return"express_checkout"===e.componentType&&de(t.requestId,oe)&&Zt(t.wallet);case"wallet_shipping_address_change":return"express_checkout"===e.componentType&&de(t.requestId,oe)&&de(t.updateId,oe)&&Zt(t.wallet)&&ri(t.address);case"wallet_shipping_rate_change":return"express_checkout"===e.componentType&&de(t.requestId,oe)&&de(t.updateId,oe)&&Zt(t.wallet)&&si(t.shippingRate);case"wallet_confirm":return"express_checkout"===e.componentType&&de(t.requestId,oe)&&Zt(t.wallet)&&le(t.paymentMethod)&&de(t.paymentMethod.id,oe)&&"card"===t.paymentMethod.type&&(void 0===t.paymentMethodPreview||Jt(t.paymentMethodPreview))&&(void 0===t.billingDetails||ai(t.billingDetails))&&(void 0===t.shippingAddress||ii(t.shippingAddress))&&(void 0===t.shippingRate||si(t.shippingRate));default:return!1}})(e.data))return;const i=e.data;if(i.controllerId!==this.controllerId)return;if(0!==e.ports.length)return void e.ports.forEach(e=>e.close());if("card_collection"===i.componentType){if(i.componentId!==this.cardCollectionSubmissionSource.submissionSourceId)return;if("tokenization_requested"===i.payload.event){if(!this.paymentMethodSubmission.ownsAttempt(i.componentId,i.payload.requestId))return;this.cardCollectionSubmissionSource.handleTokenizationRequest(i.payload.requestId,i.payload.setupFutureUsage)}return void this.paymentMethodSubmission.handleSourceEvent(i.componentId,i.payload)}const n=this.elements.get(i.componentId);n&&i.componentType===n.componentType?(i.componentGeneration??0)===n.componentGeneration&&(this.paymentMethodSubmission.handleSourceEvent(n instanceof En?n.submissionSourceId:i.componentId,i.payload),n.handleControllerEvent(i.payload)):e.ports.forEach(e=>e.close())}flushPendingComponents(){if(this.controllerInitialized&&this.controlPort)for(const[e,t]of this.pendingComponents){const i={channel:Ce,type:Re,controllerId:this.controllerId,componentId:e,componentType:t.element.componentType,componentOptions:t.element.getComponentOptions(),...t.element.componentGeneration>0?{componentGeneration:t.element.componentGeneration}:{}};try{this.controlPort.postMessage(i,[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 Ss=new Set(["amount","appearance"]);function _s(e,t,i=0){if(!le(e)||0===Object.keys(e).length||Object.keys(e).some(e=>!Ss.has(e)))throw new Error("[Paypercut Elements] Update options may contain only amount or appearance details.");const n=e.appearance,o=e.amount;if(void 0!==o&&(!Number.isSafeInteger(o)||o<0))throw new Error("[Paypercut Elements] Updated amount must be a non-negative safe integer.");return{amount:o??i,appearance:void 0===n?t:Is(n,t)}}function Is(e,t){fe(e);const i={...t?.rules};for(const[t,n]of Object.entries(e.rules??{}))i[t]={...i[t],...n};return be({...t,...e,...t?.variables||e.variables?{variables:{...t?.variables,...e.variables}}:{},...Object.keys(i).length>0?{rules:i}:{}})}function Ts(e,t,i){const n=be(i);return{mode:e.mode,amount:t,currency:e.currency,...e.setupFutureUsage?{setupFutureUsage:e.setupFutureUsage}:{},...e.locale?{locale:ks(e.locale)}:{},...n?{appearance:n}:{}}}const Rs=35;function ks(e){const t=String(e);return t.length<=Rs&&!ae(t)?t:"auto"}const Os=6e5,xs="_secret_",Ms=200,Ls=/^[A-Za-z0-9._:-]+$/,Ds=new Set([402]),Fs=new Set(["active","completed","expired","canceled"]),Ns=new Set(["failed","no_payment_required","paid","processing","unpaid"]),zs=new Set(["canceled","expired","processing","requires_action","requires_capture","requires_confirmation","requires_payment_method","succeeded"]),Us=(e,t)=>{if(!le(e)||e.checkout_session!==t||!Number.isSafeInteger(e.amount_total)||Number(e.amount_total)<0||"string"!=typeof e.mode||!["payment","setup","subscription"].includes(e.mode)||"string"!=typeof e.state||!Fs.has(e.state)||"string"!=typeof e.payment_status||!Ns.has(e.payment_status)||null!==e.payment_object_status&&("string"!=typeof e.payment_object_status||!zs.has(e.payment_object_status))||"boolean"!=typeof e.terminal||"boolean"!=typeof e.retryable||!le(e.polling)||"boolean"!=typeof e.polling.recommended||!Number.isSafeInteger(e.polling.recommended_after_ms)||Number(e.polling.recommended_after_ms)<0||Number(e.polling.recommended_after_ms)>Os)throw vn("elements_checkout_status_invalid","The payment status response was invalid.",!1);const i=(e=>{if(!le(e)||!ce(e,["iso","scale"])||"string"!=typeof e.iso||!/^[A-Za-z]{3}$/.test(e.iso)||!Number.isSafeInteger(e.scale)||Number(e.scale)<0)throw vn("elements_checkout_status_invalid","The payment status response was invalid.",!1);return{iso:e.iso.toUpperCase(),scale:Number(e.scale)}})(e.currency),n=(e=>{if(null==e)return null;if(!(le(e)&&"use_sdk"===e.type&&le(e.use_sdk)&&ce(e.use_sdk,["sdk","metadata"])&&"three_d_secure"===e.use_sdk.sdk&&le(e.use_sdk.metadata)))throw vn("elements_next_action_unsupported","The payment requires an action that this SDK version cannot handle.",!1);const t=e.use_sdk.metadata,i=t.vault_token_ref,n=t.vault_token_intent_ref,o=de(i,256);if(!(o!==de(n,256)&&ce(t,["payment_intent","payment_method","attempt","vault",o?"vault_token_ref":"vault_token_intent_ref","action_phase"])&&de(t.payment_intent,Ms)&&de(t.payment_method,Ms)&&de(t.attempt,Ms)&&"bt"===t.vault&&"provider_recovery"===t.action_phase))throw vn("elements_next_action_invalid","The payment authentication action was invalid.",!1);return{paymentIntentId:t.payment_intent,paymentMethodId:t.payment_method,attemptId:t.attempt,vault:"bt",instrument:o?{type:"token",id:i}:{type:"token_intent",id:n},actionPhase:"provider_recovery"}})(e.next_action);if("requires_action"===e.payment_object_status&&null===n)throw vn("elements_next_action_invalid","The payment requires an action but no supported action was returned.",!1);return{checkoutSessionId:t,amount:Number(e.amount_total),currency:i.iso,mode:e.mode,state:e.state,paymentObjectStatus:e.payment_object_status,paymentStatus:e.payment_status,terminal:e.terminal,retryable:e.retryable,pollingRecommended:e.polling.recommended,recommendedAfterMs:Number(e.polling.recommended_after_ms),nextAction:n}},qs=e=>({checkoutSession:{id:e.checkoutSessionId,status:e.state,paymentStatus:e.paymentStatus,paymentObjectStatus:e.paymentObjectStatus}}),Bs=e=>new Promise(t=>globalThis.setTimeout(t,Math.max(0,e))),js=e=>e instanceof Error&&"code"in e&&"string"==typeof e.code&&"recoverable"in e&&"boolean"==typeof e.recoverable,Gs=async(e,t,i,n)=>{const o=n.deadlineAt-Date.now();if(o<=0)throw vn(i,"The payment request timed out.",!0);const r=new AbortController,s=t.signal,a=()=>{return r.abort(s?(e=s).reason instanceof Error?e.reason:new DOMException("Aborted","AbortError"):void 0);var e};s?.addEventListener("abort",a,{once:!0});const l=globalThis.setTimeout(()=>r.abort(new DOMException("The payment request timed out.","TimeoutError")),Math.max(1,Math.min(3e4,o)));try{const o=await fetch(e,{...t,cache:"no-store",credentials:"omit",signal:r.signal});if(!o.ok)throw vn(i,`The payment service rejected the request (HTTP ${o.status}).`,o.status>=500||408===o.status||429===o.status||!0===n.recoverableStatuses?.has(o.status));try{return await o.json()}catch{throw vn(i,"The payment service returned an invalid response.",!0)}}catch(e){if(js(e))throw e;throw vn(i,"The payment service could not be reached.",!0)}finally{globalThis.clearTimeout(l),s?.removeEventListener("abort",a)}},Hs=(e,t)=>e.paymentIntentId===t.paymentIntentId&&e.paymentMethodId===t.paymentMethodId&&e.attemptId===t.attemptId&&e.vault===t.vault&&e.instrument.type===t.instrument.type&&e.instrument.id===t.instrument.id&&e.actionPhase===t.actionPhase;class Ws{constructor(e,t,i){this.publishableKey=e,this.billingDetailsFor=i,this.inFlight=new Map,this.activeAction=null,this.account=t.account,this.apiUrl=s(t.apiUrl),this.hostedOrigin=new URL(r(t.hostedCheckoutUrl)).origin,this.actionShell=new yn(this.hostedOrigin,e=>this.rejectActiveAction(e,"elements_action_canceled","Payment authentication was canceled.",!0),(e,t,i,n)=>this.rejectActiveAction(e,t,i,n))}confirm(e){let t;try{t=(e=>{if(!de(e,4096)||!e.startsWith("cs_"))throw vn("elements_client_secret_invalid","A valid Checkout Session client secret is required.",!1);const t=e.indexOf(xs,3),i=t<0?"":e.slice(3,t),n=t<0?"":e.slice(t+8);if(!de(i,Ms)||!Ls.test(i)||!de(n,4e3))throw vn("elements_client_secret_invalid","A valid Checkout Session client secret is required.",!1);return{clientSecret:e,checkoutSessionId:i}})(e)}catch(e){return Promise.reject(e)}const i=this.inFlight.get(t.clientSecret);if(i)return i;const n=this.run(t).finally(()=>{this.inFlight.get(t.clientSecret)===n&&this.inFlight.delete(t.clientSecret)});return this.inFlight.set(t.clientSecret,n),n}async run(e){const t=Date.now()+Os;let i=0,n=null;for(;Date.now()<t;){let o;try{o=n??await this.getStatus(e,t)}catch(e){if(!js(e)||!e.recoverable)throw e;const i=t-Date.now();if(i<=0)break;await Bs(Math.min(500,i));continue}if(n=null,o.terminal||"processing"===o.paymentObjectStatus)return qs(o);if(o.nextAction){if("payment"!==o.mode)throw vn("elements_next_action_unsupported","This confirmation action is only supported for payment-mode Checkout Sessions.",!1);if(i>=3)throw vn("elements_next_action_loop","The payment returned too many consecutive authentication actions.",!1);i+=1;const r=o.nextAction,s=await this.runAction(e,o,t);n=await this.confirmCheckout(e,s,r,t);continue}if(o.pollingRecommended){const e=t-Date.now();if(e<=0)break;await Bs(Math.min(e,Math.max(250,o.recommendedAfterMs)));continue}return qs(o)}throw vn("elements_action_timeout","Payment confirmation timed out while waiting for an authoritative status.",!0)}async getStatus(e,t){const i=new URL(`/v1/checkouts/${encodeURIComponent(e.checkoutSessionId)}/status`,this.apiUrl);i.searchParams.set("key",this.publishableKey),i.searchParams.set("client_secret",e.clientSecret);const n=await Gs(i,{method:"GET",headers:{Accept:"application/json",...void 0!==this.account?{"Paypercut-Account":this.account}:{}}},"elements_checkout_status_failed",{deadlineAt:t});return Us(n,e.checkoutSessionId)}async confirmCheckout(e,t,i,n){const o=new URL(`/v1/checkouts/${encodeURIComponent(e.checkoutSessionId)}/confirm`,this.apiUrl),r=await(async(e,t)=>{const i=(new TextEncoder).encode(`paypercut-elements-confirm-v1:${e}:${t}`),n=await globalThis.crypto.subtle.digest("SHA-256",i);return`paypercut-elements-confirm-v1-${Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,"0")).join("")}`})(e.checkoutSessionId,t),s={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","Idempotency-Key":r,...void 0!==this.account?{"Paypercut-Account":this.account}:{}},body:JSON.stringify({key:this.publishableKey,client_secret:e.clientSecret,payment_method_options:{type:"card",card:{three_d_secure:{session_id:t}}}})};let a=null;for(let t=0;t<3;t+=1)try{return await Gs(o,s,"elements_checkout_confirmation_failed",{deadlineAt:n,recoverableStatuses:Ds}),null}catch(o){if(!js(o)||!o.recoverable)throw o;a=o;try{const t=await this.getStatus(e,n);if(t.terminal||"processing"===t.paymentObjectStatus||null===t.nextAction||!Hs(t.nextAction,i))return t}catch(e){if(js(e)&&!e.recoverable)throw e}if(t+1<3){const e=n-Date.now();if(e<=0)break;await Bs(Math.min(e,250*2**t))}}throw a??vn("elements_checkout_confirmation_failed","The payment confirmation result is unknown.",!0)}runAction(e,t,i){if(!t.nextAction)return Promise.reject(vn("elements_next_action_invalid","No payment action is available.",!1));if(this.activeAction)return Promise.reject(vn("elements_action_in_progress","Another payment authentication is already in progress.",!0));const o=j(),r=new MessageChannel;return new Promise((s,a)=>{const l=globalThis.setTimeout(()=>{this.rejectActiveAction(o,"elements_action_timeout","Payment authentication timed out.",!0)},Math.max(1,i-Date.now()));this.activeAction={id:o,port:r.port1,resolve:s,reject:a,timeoutId:l},r.port1.onmessage=r=>{const s=this.activeAction;if(s&&s.id===o&&(a=r.data,le(a)&&de(a.actionId,128)&&("ready"===a.type?ce(a,["type","actionId"]):"complete"===a.type&&ce(a,["type","actionId","payload"])&&le(a.payload)&&ce(a.payload,["threeDSSessionId"])&&de(a.payload.threeDSSessionId,128)))&&r.data.actionId===o){var a;if("ready"===r.data.type){const r=this.billingDetailsFor(t.nextAction.paymentMethodId),a={type:"start",actionId:o,payload:{protocolVersion:1,publishableKey:this.publishableKey,...void 0!==this.account?{account:this.account}:{},apiUrl:this.apiUrl,sdkVersion:n.version,deadlineAt:i,checkoutSession:{id:e.checkoutSessionId,amount:t.amount,currency:t.currency,mode:t.mode},action:t.nextAction,...r?{billingDetails:r}:{}}};return void s.port.postMessage(a)}"complete"===r.data.type&&this.resolveActiveAction(o,r.data.payload.threeDSSessionId)}},r.port1.start();try{this.actionShell.show({id:o,type:"three_d_secure",source:"payment_confirmation"},r.port2)}catch{r.port2.close(),this.rejectActiveAction(o,"elements_action_channel_unavailable","The secure authentication window could not be opened.",!0)}})}resolveActiveAction(e,t){const i=this.activeAction;i&&i.id===e&&(this.activeAction=null,globalThis.clearTimeout(i.timeoutId),i.port.close(),this.actionShell.close(),i.resolve(t))}rejectActiveAction(e,t,i,n){const o=this.activeAction;o&&o.id===e&&(this.activeAction=null,globalThis.clearTimeout(o.timeoutId),o.port.close(),this.actionShell.close(),o.reject(vn(t,i,n)))}}wi();const Vs=/^[A-Za-z]{3}$/,$s=new Set(["payment","setup","subscription"]),Ys=new Set(["mode","amount","currency","setupFutureUsage","locale","appearanceUpdates","appearance"]);class Ks{constructor(e){this.options=e,this.groups=new WeakSet,this.paymentMethodBilling=new Map,this.paymentConfirmation=null,this.configurationIdentity=JSON.stringify([e.publishableKey,e.account??null,s(e.apiUrl),r(e.hostedCheckoutUrl)])}elements(e){const t=new Cs(this.options,function(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new Error("[Paypercut Elements] Elements options are required.");if(Object.keys(e).some(e=>!Ys.has(e)))throw new Error("[Paypercut Elements] Elements options contain an unsupported property.");if(!$s.has(e.mode))throw new Error("[Paypercut Elements] Mode must be payment, setup, or subscription.");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||!Vs.test(e.currency))throw new Error("[Paypercut Elements] Currency must be a three-letter ISO 4217 code.");if(t=e.setupFutureUsage,void 0!==t&&"on_session"!==t&&"off_session"!==t)throw new Error("[Paypercut Elements] setupFutureUsage must be on_session or off_session.");var t;if(void 0!==e.appearanceUpdates&&"locked"!==e.appearanceUpdates&&"remount"!==e.appearanceUpdates)throw new Error("[Paypercut Elements] appearanceUpdates must be locked or remount.");if("payment"!==e.mode&&void 0!==e.setupFutureUsage&&"off_session"!==e.setupFutureUsage)throw new Error(`[Paypercut Elements] ${e.mode} mode prepares cards for off-session use and cannot use setupFutureUsage on_session.`);e.appearance&&fe(e.appearance);return{...e,currency:e.currency.toUpperCase(),..."payment"===e.mode?e.setupFutureUsage?{setupFutureUsage:e.setupFutureUsage}:{}:{setupFutureUsage:"off_session"},appearanceUpdates:e.appearanceUpdates??"locked",...e.appearance?{appearance:be(e.appearance)}:{}}}(e),this.configurationIdentity);return this.groups.add(t),t}createPaymentMethod(e){const t=e&&"object"==typeof e&&!Array.isArray(e)?Object.keys(e):[];if(!e||"object"!=typeof e||Array.isArray(e)||t.length<1||t.length>2||t.some(e=>"elements"!==e&&"params"!==e)||!("elements"in e)||!(e.elements instanceof Cs)||!this.groups.has(e.elements))return Promise.reject(vn("elements_component_configuration_invalid","createPaymentMethod requires an Elements group created by this Paypercut client and optional params.billing_details.",!1));let i;try{const t=e.params;if(void 0!==t&&(!t||"object"!=typeof t||Array.isArray(t)||1!==Object.keys(t).length||!Object.prototype.hasOwnProperty.call(t,"billing_details")||void 0===t.billing_details))throw new Error("[Paypercut Elements] createPaymentMethod params must contain only billing_details.");i=function(e){if(void 0===e)return;if(!le(e)||0===Object.keys(e).length||Object.keys(e).some(e=>!Oi.has(e)))throw new Error("[Paypercut Elements] billing_details must contain only name, email, phone, or address.");let t;if(void 0!==e.address){if(!le(e.address)||0===Object.keys(e.address).length||Object.keys(e.address).some(e=>!xi.has(e)))throw new Error("[Paypercut Elements] Billing address must contain a supported address field.");const i=e.address,n=void 0===i.country?void 0:zi(i.country,"address country",2).toUpperCase();if(void 0!==n&&!/^[A-Z]{2}$/.test(n))throw new Error("[Paypercut Elements] Billing address country must be ISO 3166-1 alpha-2.");t=Object.freeze({...void 0===i.line1?{}:{line1:zi(i.line1,"address line1",Fi)},...void 0===i.line2?{}:{line2:zi(i.line2,"address line2",Fi)},...void 0===i.city?{}:{city:zi(i.city,"address city",Fi)},...void 0===i.state?{}:{state:zi(i.state,"address state",Fi)},...void 0===i.postal_code?{}:{postal_code:zi(i.postal_code,"address postal_code",Ni)},...void 0===n?{}:{country:n}})}return Object.freeze({...void 0===e.name?{}:{name:zi(e.name,"name",Mi)},...void 0===e.email?{}:{email:zi(e.email,"email",Li)},...void 0===e.phone?{}:{phone:zi(e.phone,"phone",Di)},...void 0===t?{}:{address:t}})}(t?.billing_details)}catch(e){return Promise.reject(vn("elements_component_configuration_invalid",e instanceof Error?e.message:"Billing details are invalid.",!1))}return e.elements.createPaymentMethod(i).then(e=>{const t=i?{...i.name?{name:i.name}:{},...i.email?{email:i.email}:{}}:void 0;if(t&&Object.keys(t).length>0&&(this.paymentMethodBilling.set(e.id,t),this.paymentMethodBilling.size>16)){const e=this.paymentMethodBilling.keys().next().value;"string"==typeof e&&this.paymentMethodBilling.delete(e)}return e})}confirmPayment(e){return this.confirmPaymentInput(e)}handleNextAction(e){return this.confirmPaymentInput(e)}confirmPaymentInput(e){return e&&"object"==typeof e&&!Array.isArray(e)&&1===Object.keys(e).length&&Object.prototype.hasOwnProperty.call(e,"clientSecret")?(this.paymentConfirmation??(this.paymentConfirmation=new Ws(this.options.publishableKey,{...void 0!==this.options.account?{account:this.options.account}:{},...this.options.apiUrl?{apiUrl:this.options.apiUrl}:{},...this.options.hostedCheckoutUrl?{hostedCheckoutUrl:this.options.hostedCheckoutUrl}:{}},e=>this.paymentMethodBilling.get(e))),this.paymentConfirmation.confirm(e.clientSecret)):Promise.reject(vn("elements_client_secret_invalid","confirmPayment requires only a Checkout Session clientSecret.",!1))}}const Zs=function(e,t){if("string"==typeof e){if(void 0!==t&&(!t||"object"!=typeof t||Array.isArray(t)))throw new Error("[Paypercut Elements] Client options must be an object.");return new Ks(Js({...t,publishableKey:e}))}if(void 0!==t)throw new Error("[Paypercut Elements] Pass client options in one initializer object.");return new Ks(Js(e))};function Js(e){if(!e||"object"!=typeof e||Array.isArray(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()||ae(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}}Zs.version=n.version;let Xs=!1;const Qs=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,ea=/^(0|(\d+(\.\d+)?(px|rem|em)))$/;function ta(e){e&&(void 0===e.brandColor||Qs.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||ea.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 ia{constructor(e){this.options=e,this.emitter=new t,this.mounted=!1,this.destroyed=!1,this.iframe=null,this.applePaySession=null,this.applePayBridgeTimeout=null,this.messageHandler=this.onMessage.bind(this),this.threeDSModal=new d({modalId:"paypercut-3ds-modal",buildUrl:e=>this.buildThreeDSUrl(e),onCancel:()=>this.handle3DSShellCancel(),onReady:e=>this.postThreeDSInit(e)}),window.addEventListener("message",this.messageHandler),v(e.ui_mode??u.EMBEDDED)===u.EMBEDDED&&function(){if("undefined"==typeof window)return;if(window.ApplePaySession)return;if(Xs)return;Xs=!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=r(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=v(this.options.ui_mode??u.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)f(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(m.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)b(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&&(ta(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(!o(e.origin))return;const t=e.data;if(!t||"object"!=typeof t||!("type"in t))return;const i=Boolean(this.iframe?.contentWindow&&e.source===this.iframe.contentWindow),n=this.threeDSModal.ownsMessageSource(e.source),r=new Set(["PAYPERCUT_THREEDS_FRAME_RESIZE","THREEDS_READY","THREEDS_COMPLETE","THREEDS_CANCELED","THREEDS_ERROR"]);if((!r.has(t.type)||n)&&(r.has(t.type)||i)&&(!t.checkoutId||t.checkoutId===this.options.id))switch(t.type){case"CHECKOUT_LOADED":this.emitter.emit(g.Loaded),this.postToIframe({type:w,checkoutId:this.options.id,applePayBridge:!0});break;case"CHECKOUT_PROCESSING":this.emitter.emit(g.Processing,{checkoutId:t.checkoutId});break;case"CHECKOUT_SUCCESS":const{payment_method:i={},payment:n=null}=t;this.emitter.emit(g.Success,{payment_method:i,payment:n});break;case"CHECKOUT_ERROR":this.emitter.emit(g.Error,(t&&t.error)??t);break;case"CHECKOUT_CANCEL":this.emitter.emit(g.Cancel,{checkoutId:t.checkoutId,wallet:t.wallet});break;case"CHECKOUT_EXPIRED":this.emitter.emit(g.Expired);break;case"CHECKOUT_RESIZE":this.emitter.emit(g.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(g.ThreeDSStarted);break;case"THREEDS_READY":this.handle3DSReady();break;case"THREEDS_COMPLETE":this.postToIframe(t),this.threeDSModal.close(),this.emitter.emit(g.ThreeDSComplete);break;case"THREEDS_CANCELED":this.postToIframe(t),this.threeDSModal.close(),this.emitter.emit(g.ThreeDSCanceled);break;case"THREEDS_ERROR":this.postToIframe(t),this.threeDSModal.close(),this.emitter.emit(g.ThreeDSError,t.error);break;case"FORM_VALIDATION":this.emitter.emit(g.FormValidation,{checkoutId:t.checkoutId,wallet:t.wallet});break;case P:this.handleApplePayStart(t);break;case A:this.handleApplePayMerchantSession(t.merchantSession);break;case C:this.abortApplePaySession();break;case _: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=r(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=r(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(g.ThreeDSCanceled)}handle3DSReady(){this.threeDSModal.handleReady()||console.error("[PaypercutCheckout] No pending 3DS data or iframe not ready")}postThreeDSInit(e){const t=r(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:T,checkoutId:this.options.id});const i=N(t);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:T,checkoutId:this.options.id})}this.applePaySession=n,n.onvalidatemerchant=e=>{this.applePayBridgeTimeout=setTimeout(()=>this.abortApplePaySession(),D),this.postToIframe({type:E,checkoutId:this.options.id,validationURL:e.validationURL})},n.onpaymentauthorized=e=>{this.postToIframe({type:S,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:T,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?(ta(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 na=function(e){return new ia(e)};return na.version=n.version,"undefined"!=typeof window&&(window.Paypercut=Zs,window.PaypercutExpressCheckout=ne),na}();
2
2
  //# sourceMappingURL=paypercut-checkout.iife.min.js.map