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