!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Hexea=e():t.Hexea=e()}(self,()=>(()=>{"use strict";var t={d:(e,i)=>{for(var n in i)t.o(i,n)&&!t.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:i[n]})}};t.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),t.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var e={};t.d(e,{default:()=>ct});const i="validation_error";const n=class{constructor(t,e=null,n=null,o=null){this.type=i,this.message=t,this.modelState=o,this.errors=n,this.responseCode=e}},o="configuration_error";const a=class{constructor(t){this.type=o,this.message=t}},s="internal_server_error";const r=class{constructor(t,e=null,i=null,n=null){this.type=s,this.message=t,this.responseCode=e,this.errors=i,this.detailed_error_message=n}};const l=class{constructor(t,e="*"){var i,n,o;this.startSession=this.startSession.bind(this),this.invoke=this.invoke.bind(this),this.message=this.message.bind(this),this.ready=this.ready.bind(this),this.frameCallback=this.frameCallback.bind(this),this.frameCallbackError=this.frameCallbackError.bind(this),this.frameReady=this.frameReady.bind(this),this.isAlive=this.isAlive.bind(this),this.sendMessage=this.sendMessage.bind(this),this.processMessage=this.processMessage.bind(this),this.rpcID=0,this.target=t,this.host=e,this.promises={},this.readyQueue=[],this.readyStatus=!1,this.methods={},i=window,n="message",o=this.message,i.addEventListener?i.addEventListener(n,o,!1):i.attachEvent(`on${n}`,o)}startSession(){return this.sendMessage("frameReady"),this.frameReady()}unbind(){var t,e,i;t=window,e="message",i=this.message,t.removeEventListener?t.removeEventListener(e,i,!1):t.detachEvent(`on${e}`,i)}invoke(t,...e){return this.ready(()=>this.sendMessage(t,e))}message(t){let e=!1;try{e=t.source===this.target&&("*"===this.host||t.origin===this.host)}catch(t){}e&&this.processMessage(t.data)}ready(t){return this.readyStatus?t():new Promise(e=>{this.readyQueue.push(()=>{e(t())})})}frameCallback(t,e){this.promises[t]&&this.promises[t].resolve(e),delete this.promises[t]}frameCallbackError(t,e){this.promises[t]&&this.promises[t].reject(e),delete this.promises[t]}frameReady(){return this.readyStatus=!0,this.readyQueue.forEach(t=>{t()}),!1}isAlive(){return!0}sendMessage(t,e=[]){const i=++this.rpcID;return new Promise((n,o)=>{this.promises[i]={resolve:n,reject:o};const a=JSON.stringify({method:t,args:e,id:i});if(null==(null!=this.target?this.target.postMessage:null)){const t=new Error("Unable to communicate. Please contact support if the problem persists.");if(null==this.methods.rpcError)throw t;return void this.methods.rpcError(t)}this.target.postMessage(a,this.host)})}processMessage(t){let e,l;try{l=JSON.parse(t)}catch(t){return}if(-1!==["frameReady","frameCallback","frameCallbackError","isAlive"].indexOf(l.method)){e=null;const t=this[l.method];null!=t&&(e=t.apply(this,l.args))}else e="function"==typeof this.methods[l.method]?this.methods[l.method](...l.args):void 0;"frameCallback"!==l.method&&"frameCallbackError"!==l.method&&(Promise.resolve(e)===e?e.then(t=>this.invoke("frameCallback",l.id,t)).catch(t=>{return this.invoke("frameCallbackError",l.id,(e=t).type===i?new n(e.message):e.type===o?new a(e.message):e.type===s?new r(e.message):e);var e}):this.invoke("frameCallback",l.id,e))}},c="cardExpiration",d="cardNumber",h="cardSwipe",p="cardVerificationValue";const m=class{constructor(t,e,i,n={}){this.paymentMethod=t,this.type=e,this.element=i,this.options=n,this.rpc=null,this.isDestroyed=!1,this.onChange=this.onChange.bind(this),this.onFocus=this.onFocus.bind(this),this.onBlur=this.onBlur.bind(this),this.callbacks={},this.initialize()}initialize(){this.createElement(),this.createRPC(),this.findLabel()}blur(){this.rpc&&this.rpc.invoke("blur")}clear(){this.rpc&&this.rpc.invoke("clear")}focus(){this.rpc&&this.rpc.invoke("focus")}destroy(){if(!this.isDestroyed){this.isDestroyed=!0;try{this.paymentMethod&&"function"==typeof this.paymentMethod.unregisterFrame&&this.paymentMethod.unregisterFrame(this)}catch(t){this.paymentMethod&&"function"==typeof this.paymentMethod.logTrace&&this.paymentMethod.logTrace("[Field] Failed to unregister field frame",{fieldType:this.type,error:t})}this.rpc&&this.rpc.unbind&&this.rpc.unbind(),this.component&&this.component.parentNode?this.component.parentNode.removeChild(this.component):this.frame&&this.frame.parentNode&&this.frame.parentNode.removeChild(this.frame),this.component=null,this.frame=null,this.rpc=null,this.callbacks={}}}on(t,e){if("function"!=typeof e)throw new Error("callback must be a function");this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(e)}emit(t,...e){(this.callbacks[t]||[]).forEach(t=>{t(...e)})}onChange(t){this.emit("change",t)}onFocus(){this.emit("focus")}onBlur(){this.emit("blur")}createElement(){const t=document.createElement("div");t.style.cssText="border: none !important;\nmargin: 0px !important;\npadding: 0px !important;\ndisplay: block !important;\nbackground: transparent !important;\nposition: relative !important;\nopacity: 1 !important;\n";const e=document.createElement("iframe");e.setAttribute("frameBorder","0"),e.setAttribute("allowtransparency","true"),e.setAttribute("scrolling","no"),e.name=this.getFrameID(),e.title="Secure payment method input frame",e.style.cssText="border: none !important;\nmargin: 0px !important;\npadding: 0px !important;\nwidth: 1px !important;\nmin-width: 100% !important;\noverflow: hidden !important;\ndisplay: block !important;\nheight: 20px;\nvisibility: hidden\n",e.addEventListener("load",()=>{e.style.visibility="visible"}),t.appendChild(e),e.src=this.getFieldHtmlUrl(),this.element.appendChild(t),this.component=t,this.frame=e}getFieldHtmlUrl(){const{pcct:t,hexeaOrigin:e,hexeaInstanceId:i}=this.paymentMethod.client,{origin:n}=window.location,o=`?origin=${encodeURIComponent(n)}&uid=${i}&pcct=${t}&ts=${Date.now()}`;switch(this.type){case d:return`${e}/hexea/cardnumber${o}`;case c:return`${e}/hexea/cardexpiration${o}`;case h:return`${e}/hexea/cardswipe${o}`;case p:return`${e}/hexea/cardverificationvalue${o}`;default:throw new Error(`${this.type} is not a valid field type. Try ${d}, ${c}, ${h}, or ${p} instead`)}}createRPC(){const{frame:t,paymentMethod:e,options:i}=this,n=new l(t.contentWindow,this.paymentMethod.client.hexeaOrigin);n.methods.change=this.onChange,n.methods.focus=this.onFocus,n.methods.blur=this.onBlur,this.rpc=n,n.invoke("setOptions",i).then(({height:i})=>{e.registerFrame(this),t.style.height=`${i}px`,t.style.minHeight=`${i}px !important`,this.emit("ready")})}findLabel(){const t=t=>{t.addEventListener("click",t=>{t.preventDefault(),this.focus()})};const{id:e}=this.element;if(e){const i=document.querySelector(`label[for="${e}"]`);i&&t(i)}!function e(i){i&&("LABEL"===i.tagName?t(i):e(i.parentNode))}(this.element.parentNode)}getFrameID(){return this.options.frameID}createPublicApi(){return{on:this.on.bind(this),blur:this.blur.bind(this),clear:this.clear.bind(this),focus:this.focus.bind(this)}}};class u{static configCache=new Map;static getConfigValue(t,e=null){return 0===u.configCache.size&&u.initializeCache(),u.configCache.has(t)?u.configCache.get(t):e}static setConfig(t){t&&"object"==typeof t&&0!==Object.keys(t).length&&(u.configCache.clear(),Object.entries(t).forEach(([t,e])=>{u.configCache.set(t,e)}))}static initializeCache(){let t={};if(u.isRunningLocally()){const e=process.env.ENV_CONFIG;"string"==typeof e?t=JSON.parse(e||"{}"):"object"==typeof e&&null!==e&&(t=e)}Object.entries(t).forEach(([t,e])=>{u.configCache.set(t,e)})}static isRunningLocally(){return!1}}const y=u,g=["amex","discover","masterCard","visa"];class f{static sdkReadyPromise=null;static ensureApplePaySDKLoaded(t){f.sdkReadyPromise||(f.sdkReadyPromise=new Promise((e,i)=>{if(document.querySelector(`script[src="${t}"]`))f.pollForSDKReady(e,i);else{const n=document.createElement("script");n.async=!0,n.src=t,n.crossOrigin="anonymous",n.onload=()=>{f.pollForSDKReady(e,i)},n.onerror=t=>{i(t)},document.body.appendChild(n)}}))}static pollForSDKReady(t,e){let i=0;const n=()=>{window.ApplePaySession&&window.ApplePaySession.applePayCapabilities?t():(i+=100,i>=5e3?e(new Error("Apple Pay SDK unable to load within 5000ms")):setTimeout(n,100))};n()}constructor(t){this.walletButton=t,this.paymentMethod=t.paymentMethod,this.options=t.options,this.style=this.options.wallets.applePay.style,this.futurePaymentOptions=this.options.wallets.applePay.futurePaymentOptions,this.supportedNetworks=g.filter(e=>t.supportedNetworks.filter(t=>t.toLowerCase()===e.toLowerCase()).length>0),this.applePaySDKUrl=y.getConfigValue("APPLEPAY_SDKURL"),this.tokenNotificationURL=y.getConfigValue("TOKENURLNOTIFICATION"),this.applePaySettings={merchantIdApplePay:this.paymentMethod.merchantInfo.applePayPSPEnabled?this.paymentMethod.client.pcct:y.getConfigValue("APPLEPAY_MERCHANTID"),currencyCode:"USD",countryCode:"US",merchantCapabilities:["supports3DS"]},this.options.debitCardOnly&&this.applePaySettings.merchantCapabilities.push("supportsDebit"),this.applePayStyle=`\n    /*\n    Apple Pay Style\n    */\n    apple-pay-button {\n    --apple-pay-button-width: ${this.style.width};\n    --apple-pay-button-height: ${this.style.height};\n    --apple-pay-button-border-radius: ${this.style.borderRadius};\n    --apple-pay-button-padding: 0px 0px;\n    --apple-pay-button-box-sizing: border-box;\n    }\n    `,f.ensureApplePaySDKLoaded(this.applePaySDKUrl)}logTrace(t,e={}){this.walletButton.logTrace(t,{pcct:this.paymentMethod.client.pcct,...e})}logException(t,e={}){this.walletButton.logException(t,{pcct:this.paymentMethod.client.pcct,...e})}startApplePaySession(t){const e=new ApplePaySession(10,t);this.handleApplePayEvents(e),e.begin()}handleApplePayEvents(t){const e={startDate:"",endDate:"",frequency:"",type:""},i={nameOnCard:"",paymentData:"",paymentMethod:"",transactionIdentifier:"",appleRecurrenceData:e},n={addressLine1:"",isSaved:this.options.isSaved,postalCode:"",countryCode:"USA",applePay:i,idType:this.options.idType,id:this.options.id,debitCardOnly:this.options.debitCardOnly};t.onvalidatemerchant=e=>{const i={appleUrl:e.validationURL,body:{merchantIdentifier:this.applePaySettings.merchantIdApplePay,domainName:this.options.merchantDomain??window.location.hostname,displayName:this.walletButton.customerName}};this.logTrace("Create apple pay session",{applePaySession:i,message:"Apple pay session"}),this.paymentMethod.client.controllerRPC.invoke("getApplePaySession",this.paymentMethod.client.pcct,i).then(e=>{t.completeMerchantValidation(JSON.parse(e))}).catch(t=>{this.logException(t,{applePaySession:i,message:"Error occured in apple pay session endpoint"})})},t.onpaymentauthorized=o=>{if(i.paymentData=o.payment.token.paymentData,i.paymentMethod=o.payment.token.paymentMethod,i.transactionIdentifier=o.payment.token.transactionIdentifier,i.nameOnCard=`${o.payment.billingContact.givenName} ${o.payment.billingContact.familyName}`,n.addressLine1=o.payment.billingContact.addressLines[0],n.postalCode=o.payment.billingContact.postalCode,n.deferredUse=this.options.deferredUse,n.isSaved=this.options.deferredUse?this.options.deferredUse:this.options.isSaved,n.email=this.options.email??o.payment.shippingContact.emailAddress,this.options.deferredUse){e.startDate=this.futurePaymentOptions.recurringPaymentStartDate,e.endDate=this.futurePaymentOptions.recurringPaymentEndDate,e.frequency=this.futurePaymentOptions.frequency,e.type="onetime"===this.futurePaymentOptions.type?"oneTime":this.futurePaymentOptions.type;Object.values(e).some(t=>null!=t&&""!==t)||(i.appleRecurrenceData=null)}else i.appleRecurrenceData=null;this.logTrace("Apple pay tokenize"),this.paymentMethod.client.controllerRPC.invoke("tokenizeCardData",this.paymentMethod.client.pcct,n).then(e=>{e&&e.error?(t.completePayment(ApplePaySession.STATUS_FAILURE),this.walletButton.onPaymentMethod({error:e.error})):(this.walletButton.onPaymentMethod({paymentData:{paymentMethodToken:e.paymentMethodToken,isTest:e.isTest,paymentMethodType:e.paymentMethodType,nameOnCard:e.nameOnCard,bin:e.bin,last4:e.last4,expireMonth:e.expireMonth,expireYear:e.expireYear,addressLine1:e.addressLine1,postalCode:e.postalCode,brand:e.brand,countryCode:e.countryCode,isSaved:e.isSaved,deferredUse:e.deferredUse,quickCheckout:e.quickCheckout,isSwiped:e.isSwiped,isApplePay:"ApplePay"===e.digitalWallet,amount:this.options.amount,digitalWallet:e.digitalWallet,phone:o.payment.shippingContact?.phoneNumber||null,email:o.payment.shippingContact?.email||null,address:{addressLine1:o.payment.billingContact.addressLines[0],addressLine2:o.payment.billingContact.addressLines[1]??null,postalCode:o.payment.billingContact.postalCode,country:o.payment.billingContact.countryCode,city:o.payment.billingContact.locality,state:o.payment.billingContact.administrativeArea}},success:!0}),t.completePayment(ApplePaySession.STATUS_SUCCESS),this.logTrace("Apple pay tokenize success"))}).catch(e=>{t.completePayment(ApplePaySession.STATUS_FAILURE),this.walletButton.onPaymentMethod({error:e}),this.logException(e,{message:"Apple pay tokenize failed"})})},t.oncancel=t=>{const e={event:t,message:"Error occured in apple pay session endpoint"};this.logTrace("Apple pay session canceled ",e)}}static getIntervalValues(t){const e={daily:["day",1],weekly:["day",7],everyotherweek:["day",14],monthly:["month",1],quarterly:["month",3],annually:["year",1]},i=t?.toLowerCase();if(e[i])return e[i];throw new Error(`Invalid frequency: "${t}"`)}static validateDates(t,e){const i=new Date(t),n=e?new Date(e):null;if(Number.isNaN(i.getTime()))throw new Error("Start date is invalid");if(i<new Date)throw new Error("Start date is less than current date");if(n){if(Number.isNaN(n.getTime()))throw new Error("End date is invalid");if(i>n)throw new Error("Start date is greater than end date")}return!0}static getPaymentType(t){const e=t?.toLowerCase();return"recurring"===e?"recurring":"onetime"===e?"deferred":null}buildDeferredPaymentModel(t){return{deferredPaymentRequest:{paymentDescription:this.futurePaymentOptions.paymentDescription,deferredBilling:{label:"Deferred",amount:this.options.amount,paymentTiming:t,deferredPaymentDate:this.futurePaymentOptions.recurringPaymentStartDate},billingAgreement:"",managementURL:this.futurePaymentOptions.managementURL,tokenNotificationURL:this.tokenNotificationURL}}}buildRecurringPaymentModel(t){let e,i;try{[e,i]=f.getIntervalValues(this.futurePaymentOptions.frequency),f.validateDates(this.futurePaymentOptions.recurringPaymentStartDate,this.futurePaymentOptions.recurringPaymentEndDate)}catch(t){throw this.logException(t,{message:"Invalid Apple Pay recurring setup"}),t}return{recurringPaymentRequest:{paymentDescription:this.futurePaymentOptions.paymentDescription,regularBilling:{label:"Recurring",amount:this.options.amount,paymentTiming:t,recurringPaymentStartDate:this.futurePaymentOptions.recurringPaymentStartDate,recurringPaymentEndDate:this.futurePaymentOptions.recurringPaymentEndDate,recurringPaymentIntervalUnit:e,recurringPaymentIntervalCount:i},billingAgreement:"",managementURL:this.futurePaymentOptions.managementURL,tokenNotificationURL:this.tokenNotificationURL}}}buildApplePayModel(){const t={currencyCode:this.applePaySettings.currencyCode,countryCode:this.applePaySettings.countryCode,merchantCapabilities:this.applePaySettings.merchantCapabilities,supportedNetworks:this.supportedNetworks,requiredBillingContactFields:["name","postalAddress"],total:{label:this.walletButton.customerName,amount:this.options.amount,type:"final"},requiredShippingContactFields:["email"]};if(!0===this.options.deferredUse){const e=f.getPaymentType(this.futurePaymentOptions.type);"deferred"===e?Object.assign(t,this.buildDeferredPaymentModel(e)):"recurring"===e?Object.assign(t,this.buildRecurringPaymentModel(e)):this.logTrace("Invalid Apple Pay type for deferred use!")}return t}async checkApplePayAvailability(){try{return await f.sdkReadyPromise,!!window.ApplePaySession&&(!!window.ApplePaySession.canMakePayments&&window.ApplePaySession.canMakePayments())}catch(t){return this.logException(t,{message:"Apple Pay checkApplePayAvailability failed"}),!1}}render(t){this.checkApplePayAvailability().then(e=>{if(!e)return;t.querySelectorAll("apple-pay-button").forEach(t=>{t.parentNode&&t.parentNode.removeChild(t)});const i=this.buildApplePayModel();if(!i)return;const n=(this.paymentMethod.merchantInfo.acceptDonations??!1)&&"NP"===this.paymentMethod.merchantInfo.customerType,o="donate"===this.style.buttonType?.toLowerCase()&&n?this.style.buttonType??"plain":"plain",a=document.createElement("apple-pay-button");a.setAttribute("buttonstyle",this.style.color),a.setAttribute("type",o),a.setAttribute("locale","en-US");const s="apple-pay-button-style",r=document.getElementById(s);r&&r.parentNode&&r.parentNode.removeChild(r);const l=document.createElement("style");l.id=s,l.innerHTML=this.applePayStyle;const c=document.querySelector("script");c&&c.parentNode?c.parentNode.insertBefore(l,c):document.head.appendChild(l),a.addEventListener("click",()=>{this.startApplePaySession(i)}),t.appendChild(a),this.logTrace("Apple pay initialized",{options:this.options})})}}const w={apiVersion:2,apiVersionMinor:0},b=["AMEX","DISCOVER","MASTERCARD","VISA"],P=["PAN_ONLY","CRYPTOGRAM_3DS"];class C{static sdkReadyPromise=null;constructor(t){this.isInitializing=!1,this.walletButton=t,this.paymentMethod=t.paymentMethod,this.controllerRPC=this.paymentMethod.client.controllerRPC,this.supportedNetworks=t.supportedNetworks,this.style=t.options.wallets.googlePay.style,this.options=t.options,this.googlePayEnvironment=y.getConfigValue("GOOGLEPAY_ENVIRONMENT");const e=y.getConfigValue("GOOGLEPAY_SDKURL");C.sdkReadyPromise||(C.sdkReadyPromise=new Promise((t,i)=>{if(document.querySelector(`script[src="${e}"]`))t();else{const n=document.createElement("script");n.async=!0,n.onload=()=>t(),n.onerror=i,n.src=e,document.body.appendChild(n)}})),C.sdkReadyPromise.then(()=>{this.configureGooglePayClient()}).catch(t=>{this.logException(t,{message:"Google Pay SDK failed to load"})})}logTrace(t,e={}){this.walletButton.logTrace(t,{pcct:this.paymentMethod.client.pcct,...e})}logException(t,e={}){this.walletButton.logException(t,{pcct:this.paymentMethod.client.pcct,...e})}async configureGooglePayClient(){if(this.isInitializing)return;this.isInitializing=!0;await this.waitForGooglePaySDK()&&(this.paymentsClient=new google.payments.api.PaymentsClient({environment:this.googlePayEnvironment,paymentDataCallbacks:{onPaymentAuthorized:t=>this.onPaymentAuthorized(t)}}),this.isInitializing=!1)}waitForGooglePaySDK(t=2e3,e=20){const i=Date.now(),n=o=>{if(!(window.google&&window.google.payments&&window.google.payments.api))return Date.now()-i>=t?(this.logException(new Error("[GooglePay] SDK initialization timeout"),{message:"[GooglePay] SDK timeout"}),void o(!1)):void setTimeout(()=>n(o),e);o(!0)};return new Promise(n)}onPaymentAuthorized(t){return new Promise(e=>{this.logTrace("Google Pay tokenize");const i={addressLine1:t.paymentMethodData.info.billingAddress.address1,isSaved:this.options.isSaved,deferredUse:this.options.deferredUse,postalCode:t.paymentMethodData.info.billingAddress.postalCode,countryCode:"USA",googlePay:{nameOnCard:t.paymentMethodData.info.billingAddress.name,billingAddress:{addressLine1:t.paymentMethodData.info.billingAddress.address1,addressLine2:t.paymentMethodData.info.billingAddress.address2,addressLine3:t.paymentMethodData.info.billingAddress.address3,city:t.paymentMethodData.info.billingAddress.locality,state:t.paymentMethodData.info.billingAddress.administrativeArea,postalCode:t.paymentMethodData.info.billingAddress.postalCode},paymentData:JSON.parse(t.paymentMethodData.tokenizationData.token),cardBrand:t.paymentMethodData.info.cardNetwork,last4:t.paymentMethodData.info.cardDetails},idType:this.options.idType,id:this.options.id,debitCardOnly:this.options.debitCardOnly,email:this.options.email??t.email};this.controllerRPC.invoke("tokenizeCardData",this.paymentMethod.client.pcct,i).then(i=>{i&&i.error?(e({transactionState:"ERROR"}),this.walletButton.onPaymentMethod({error:i.error})):(this.walletButton.onPaymentMethod({paymentData:{paymentMethodToken:i.paymentMethodToken,isTest:i.isTest,paymentMethodType:i.paymentMethodType,nameOnCard:i.nameOnCard,bin:i.bin,last4:i.last4,expireMonth:i.expireMonth,expireYear:i.expireYear,brand:i.brand,isSaved:i.isSaved,deferredUse:i.deferredUse,quickCheckout:i.quickCheckout,isSwiped:i.isSwiped,isApplePay:"ApplePay"===i.digitalWallet,amount:this.options.amount,digitalWallet:i.digitalWallet,phone:t.paymentMethodData.info.billingAddress.phoneNumber,email:t.email,address:{addressLine1:t.paymentMethodData.info.billingAddress.address1,addressLine2:t.paymentMethodData.info.billingAddress.address2,postalCode:t.paymentMethodData.info.billingAddress.postalCode,country:t.paymentMethodData.info.billingAddress.countryCode,city:t.paymentMethodData.info.billingAddress.locality,state:t.paymentMethodData.info.billingAddress.administrativeArea}},success:!0}),e({transactionState:"SUCCESS"}),this.logTrace("Google Pay tokenize success"))}).catch(t=>{e({transactionState:"ERROR"}),this.walletButton.onPaymentMethod({error:t}),this.logException(t,{message:"Google Pay tokenize failed"})})})}waitForPaymentsClient(t=5e3,e=100){const i=Date.now(),n=(o,a)=>{this.paymentsClient?o():Date.now()-i>=t?a(new Error("[GooglePay] PaymentsClient initialization timeout")):setTimeout(()=>n(o,a),e)};return new Promise(n)}async render(t){if(!this.paymentsClient)try{await this.waitForPaymentsClient()}catch(t){return void this.logException(t,{message:"Timeout waiting for Google Pay SDK"})}t.querySelectorAll(".google-pay-button-container").forEach(t=>{t.parentNode&&t.parentNode.removeChild(t)});const e={type:"PAYMENT_GATEWAY",parameters:{gateway:"vanco",gatewayMerchantId:this.paymentMethod.client.pcct}},i=!0===this.options.debitCardOnly,n={type:"CARD",parameters:{allowedAuthMethods:P,allowedCardNetworks:b.filter(t=>this.supportedNetworks.filter(e=>e.toLowerCase()===t.toLowerCase()).length>0),allowCreditCards:!i,allowPrepaidCards:!0,billingAddressRequired:!0,billingAddressParameters:{format:"FULL",phoneNumberRequired:!0}},tokenizationSpecification:e},o={...w,allowedPaymentMethods:[{...n}]};this.paymentsClient.isReadyToPay(o).then(e=>{if(e.result){const e={...w,merchantInfo:{merchantId:C.getFirstNonEmpty(this.options.wallets.googlePay?.merchantId,this.paymentMethod.merchantInfo.googleMerchantID),merchantName:this.walletButton.customerName},callbackIntents:["PAYMENT_AUTHORIZATION"],transactionInfo:{countryCode:"US",currencyCode:"USD",totalPriceStatus:"FINAL",totalPrice:this.options.amount.toString()},emailRequired:!0,allowedPaymentMethods:[n]};this.paymentsClient.prefetchPaymentData(e);const i=document.createElement("div");i.className="google-pay-button-container",this.style.width&&(i.style.width=this.style.width),this.style.height&&(i.style.height=this.style.height);let o="default";if(this.style.color)switch(this.style.color.toLowerCase()){case"black":o="black";break;case"white":case"white-outline":o="white";break;default:o="default"}const a=this.paymentsClient.createButton({buttonType:this.style.buttonType??"short",buttonColor:o,buttonRadius:parseInt(this.style.borderRadius,10),buttonSizeMode:"fill",onClick:()=>{try{this.paymentsClient.loadPaymentData(e).then(()=>{}).catch(t=>{this.logException(t,{message:"Google Pay loadPaymentData"})})}catch(t){this.logException(t,{message:"Google Pay onClick"})}},allowedPaymentMethods:[n]});i.appendChild(a),t.appendChild(i)}}).catch(t=>{this.logException(t,{message:"Google Pay isReadyToPay"})})}static getFirstNonEmpty(...t){return t.find(t=>null!=t&&""!==t)}}class S{constructor(t,e,i){this.paymentMethod=t,this.element=e,this.options=i,this.isDestroyed=!1,this.supportedNetworks=[],this.appleButtonEnabled=!1,this.samsungButtonEnabled=!1,this.googleButtonEnabled=!1,this.onPaymentMethod=this.onPaymentMethod.bind(this),this.callbacks={},this.customerName="",this.renderTimeout=null,this.applePayButton=null,this.googlePayButton=null,t.merchantInfo&&this.updateMerchantInfo(t.merchantInfo)}on(t,e){if("function"!=typeof e)throw new Error("callback must be a function");this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(e)}emit(t,...e){(this.callbacks[t]||[]).forEach(t=>{t(...e)})}onPaymentMethod(t){t&&t.error?this.emit("paymentmethod",S.normalizeError(t.error)):this.emit("paymentmethod",t)}static normalizeError(t){return t&&t.type?{error:t}:{error:{type:"unknown_error",message:t?.message??"An error has occurred. Please try again.",errors:[]}}}logTrace(t,e={}){const i={pcct:this.paymentMethod.client.pcct,href:window.location.href};this.paymentMethod.client.logTrace(t,{...i,...e})}logException(t,e={}){this.paymentMethod.client.logException(t,{pcct:this.paymentMethod.client.pcct,...e})}updateMerchantInfo(t){if(this.isDestroyed)return;this.logTrace("MerchantInfo for digital wallet",{merchantInfo:t});let e=[];if(t.amexAllowed&&(e=[...e,"amex"]),t.discoverAllowed&&(e=[...e,"discover"]),t.mastercardAllowed&&(e=[...e,"mastercard"]),t.visaAllowed&&(e=[...e,"visa"]),this.options.cardBrandsAllowed.length>0){const t=this.options.cardBrandsAllowed.map(t=>t.toLowerCase());e=e.filter(e=>t.includes(e.toLowerCase()))}this.supportedNetworks=e,t.applePayAllowed&&(this.appleButtonEnabled=t.applePayAllowed),t.samsungPayAllowed&&(this.samsungButtonEnabled=t.samsungPayAllowed),t.googlePayAllowed&&(this.googleButtonEnabled=t.googlePayAllowed),t.customerName&&(this.customerName=t.customerName),this.createElement()}createElement(){this.isDestroyed||(this.renderTimeout&&clearTimeout(this.renderTimeout),this.renderTimeout=setTimeout(()=>{this.createElementInternal()},500))}createElementInternal(){this.isDestroyed||(this.appleButtonEnabled&&(this.createApplePayButton(),this.logTrace("Element created for apple pay")),this.googleButtonEnabled&&(this.createGooglePayButton(),this.logTrace("Element created for google pay")),this.walletContainer())}clearApplePayButton(){if(!this.element)return;this.element.querySelectorAll("apple-pay-button").forEach(t=>{t.parentNode&&t.parentNode.removeChild(t)});const t=document.getElementById("apple-pay-button-style");t&&t.parentNode&&t.parentNode.removeChild(t)}clearGooglePayButton(){this.element&&this.element.querySelectorAll(".google-pay-button-container").forEach(t=>{t.parentNode&&t.parentNode.removeChild(t)})}createApplePayButton(){const t=new f(this);this.applePayButton=t,t.render(this.element)}createGooglePayButton(){const t=this.paymentMethod.merchantInfo.googleMerchantID,e=this.options.wallets?.googlePay?.merchantId;if(!t&&!e){const t="merchantId is required for Google Pay transactions.";throw this.logTrace(t,this.options),new Error(t)}const i=new C(this);this.googlePayButton=i,i.render(this.element)}walletContainer(){if(0===(this.appleButtonEnabled?1:0)+(this.googleButtonEnabled?1:0)+(this.samsungButtonEnabled?1:0))return;const{layoutDirection:t,gap:e}=this.options.containerStyle,i=this.options.wallets?.applePay?.style?.width||this.options.wallets?.googlePay?.style?.width||this.options.wallets?.samsungPay?.style?.width;let n="";n="column"===t?["display: flex","flex-direction: column","width: 100%","align-items: "+(i?"center":"stretch"),`gap: ${e}`].join("; "):i?["display: flex","flex-direction: row","width: 100%","align-items: center",`gap: ${e}`].join("; "):["display: grid","width: 100%","grid-auto-flow: column","grid-auto-columns: 1fr","align-items: center",`gap: ${e}`].join("; "),this.element.setAttribute("style",n)}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.renderTimeout&&(clearTimeout(this.renderTimeout),this.renderTimeout=null),this.element&&(this.clearApplePayButton(),this.clearGooglePayButton(),this.element.removeAttribute("style")),this.applePayButton=null,this.googlePayButton=null,this.callbacks={})}createPublicApi(){return{on:this.on.bind(this)}}}const E=S;class T{static transposeOptions(t,e){const i=JSON.parse(JSON.stringify(t));return i.version||i.amount?T.normalizeNewStructure(i,e):T.normalizeOldStructure(i,e)}static normalizeNewStructure(t,e){const i={...t};return i.version=t.version??"1.0",i.isSaved=t.isSaved??!1,i.deferredUse=t.deferredUse??!1,i.id=t.id??null,i.idType=t.idType??null,i.email=t.email?.trim()||null,i.cardBrandsAllowed=t.cardBrandsAllowed??[],i.debitCardOnly=t.debitCardOnly??!1,i.containerStyle={gap:i.containerStyle?.gap||"10px",layoutDirection:i.containerStyle?.layoutDirection||"row"},i.wallets=i.wallets||{},i.wallets.applePay=T.normalizeWalletConfig(e,t.wallets?.applePay,{futurePaymentOptions:t.wallets?.applePay?.futurePaymentOptions||{}}),i.wallets.googlePay=T.normalizeWalletConfig(e,t.wallets?.googlePay,{merchantId:t.wallets?.googlePay?.merchantId}),i.wallets.samsungPay=T.normalizeWalletConfig(e,t.wallets?.samsungPay),i}static normalizeOldStructure(t,e){const i=T.normalizeStyle(e,t.style);return{version:"1.0",amount:t.total?.amount,merchantDomain:null,containerStyle:{layoutDirection:"row",gap:"10px"},isSaved:t.isSaved??!1,deferredUse:t.deferredUse??!1,id:t.id??null,idType:t.idType??null,email:t.email??null,cardBrandsAllowed:[],debitCardOnly:!1,wallets:{applePay:{style:i,futurePaymentOptions:t.deferredUse?{type:t.type,paymentDescription:t.paymentDescription,recurringPaymentStartDate:t.recurringPaymentStartDate,recurringPaymentEndDate:t.recurringPaymentEndDate,frequency:t.frequency,managementURL:t.managementURL}:{}},googlePay:{merchantId:t.merchantId,style:i},samsungPay:{style:i}}}}static normalizeWalletConfig(t,e,i={}){return{...e||{},style:T.normalizeStyle(t,e?.style||{}),...i}}static normalizeStyle(t,e={}){return{color:e.color||"black",height:`${Math.max(parseInt(e.height,10)||0,40)}px`,...e.width&&T.calculateWidth(e.width),borderRadius:T.calculateRadius(e.borderRadius,t),buttonType:e.buttonType}}static calculateWidth(t){if("string"==typeof t&&t.trim().endsWith("%"))return{width:t};const e=parseInt(t,10)||0;return{width:`${Math.max(e,100)}px`}}static calculateRadius(t,e){if("string"==typeof t&&t.trim().endsWith("em")){return parseFloat(t)*(parseFloat(window.getComputedStyle(e).fontSize)||16)+"px"}return"string"==typeof t&&t.trim().endsWith("px")?t:`${parseInt(t,10)||0}px`}}const v=T;let M=0;function A(){return M+=1,`hexeaSecureFrame${M}`}let D=0;const k="card",x="echeck",I=[k,x,"wallet"],N=t=>{t&&"function"==typeof t.destroy&&t.destroy()};const R=class{constructor(t,e){if(-1===I.indexOf(e))throw new Error(`Payment method type "${e}" is not supported. Supported types: ${I.join(", ")}`);D+=1,this.name=`pm${D}`,this.client=t,this.type=e,this.fields=[],this.walletButton=void 0,this.merchantInfo=null,this.isDestroyed=!1}field(t,e,i={}){const n=A(),o=new m(this,t,e,{...i,frameID:n,controllerFrameID:this.client.controllerFrameID});return this.fields.push(o),o.createPublicApi()}button(t,e,i={}){if("string"!=typeof t)throw new Error("Invalid button type.");N(this.walletButton);const n=v.transposeOptions(i,e),o=new E(this,e,{...n});return this.walletButton=o,o.createPublicApi()}buttons(t,e={}){N(this.walletButton);const i=v.transposeOptions(e,t),n=new E(this,t,{...i});return this.walletButton=n,n.createPublicApi()}updateMerchantInfo(t){this.merchantInfo=t,this.walletButton&&this.walletButton.updateMerchantInfo(t)}async tokenize(t,e,i={}){try{let n=null;return this.type===k?n=await this.client.controllerRPC.invoke("submit",this.name,i,t,e):this.type===x&&(n=await this.client.controllerRPC.invoke("submitEcheck",i,t,e)),n}catch(t){throw t}}registerFrame(t){this.client.registerPaymentMethodFrame(this.name,{name:t.getFrameID(),type:t.type})}unregisterFrame(t){this.client.unregisterPaymentMethodFrame(this.name,{name:t.getFrameID(),type:t.type})}destroy(){this.isDestroyed||(this.isDestroyed=!0,Array.isArray(this.fields)&&this.fields.forEach(t=>{try{N(t)}catch(e){this.logTrace("[PaymentMethod] Failed to destroy field",{fieldType:t&&t.type,error:e})}}),N(this.walletButton),this.fields=[],this.walletButton=void 0)}createPublicApi(){return{name:this.name,type:this.type,field:this.field.bind(this),button:this.button.bind(this),buttons:this.buttons.bind(this)}}isValidIdType(t){return"idsId"===t||"partnerPayerRef"===t}isValidString(t){return"string"==typeof t&&""!==t.trim()}logTrace(t,e={}){this.client.logTrace(t,{pcct:this.client.pcct,...e})}logException(t,e={}){this.client.logException(t,{pcct:this.client.pcct,...e})}};const O=class{constructor(t){this.rpc=t}async logTrace(t,e={}){try{this.rpc&&await this.rpc.invoke("logTrace",t,e)}catch(t){}}async logException(t,e={}){try{if(this.rpc){let i;i=t instanceof Error?{message:t.message,stack:t.stack}:t,await this.rpc.invoke("logException",i,e)}}catch(t){}}async logEvent(t,e={}){try{this.rpc&&await this.rpc.invoke("logEvent",t,e)}catch(t){}}};function F(t,e,i){return i(t)?t:e}function B(t){return`${t}/assets/loader.min.js`}const L=class{constructor(t){this.monitor=t,this.logTrace=t.logTrace,this.logException=t.logException,this.fieldName=t.fieldName,this.config=t.config,this.deviceContext=null}async initialize(t){const{monitor:e,config:i}=this,{monitoringKey:n,pcct:o}=e;try{if(!i.apiSubdomain){const t=new Error("[TransactionMonitor] API subdomain is not configured.");return void this.logException(t,{fieldName:this.fieldName,monitoringKey:n,pcct:o})}const a=await function(t){const{config:e,logException:i,fieldName:n,monitoringKey:o,pcct:a}=t,{apiSubdomain:s}=e,r=B(s);return document.querySelector(`script[src*="${r}"]`)?Promise.resolve(!0):new Promise(e=>{const s=document.createElement("script");s.type="text/javascript",s.async=!0,s.src=`https://${r}`,s.onload=()=>{try{if(t.disposed||t.startOutcomeSettled)return void e(!1);e(!0)}catch(t){const s=t instanceof Error?t:new Error("[TransactionMonitor] Unexpected error during SDK initialization.");i(s,{fieldName:n,monitoringKey:o,pcct:a}),e(!1)}},s.onerror=()=>{const t=new Error("[TransactionMonitor] SDK load failed.");i(t,{fieldName:n,monitoringKey:o,pcct:a}),s.parentNode&&s.parentNode.removeChild(s),e(!1)};const l=document.getElementsByTagName("script")[0];l&&l.parentNode?l.parentNode.insertBefore(s,l):(document.head||document.getElementsByTagName("head")[0]||document.documentElement).appendChild(s)})}(e);if(!a||e.disposed||e.startOutcomeSettled)return;try{const a=Math.min(e.timeouts.sdkAttachTimeoutMs,e.timeouts.sessionUpdateTimeoutMs),s=await function(t,e=5e3,i=50){const{config:n,logException:o,fieldName:a}=t,s=Date.now(),r=l=>{if(t.disposed||t.startOutcomeSettled)return void l(!1);const c=window[n.sdkGlobalName];if(c&&"function"==typeof c.createContext)l(!0);else{if(Date.now()-s>=e){const t=new Error("[TransactionMonitor] SDK initialization timeout");return o(t,{maxWaitTime:e,fieldName:a}),void l(!1)}setTimeout(()=>r(l),i)}};return new Promise(r)}(e,a);if(!s||e.disposed||e.startOutcomeSettled)return;const r={clientId:i.clientId,sessionKey:n,flow:i.flow,environment:i.environment,parentElement:i.parentElement,partnerId:o,apiSubdomain:i.apiSubdomain,pixelSubdomain:i.pixelSubdomain,onConfigUpdate:(i,o,a)=>{if(e.disposed||e.startOutcomeSettled)return void this.logTrace("[TransactionMonitor] onConfigUpdate skipped",{fieldName:this.fieldName,monitoringKey:n,disposed:e.disposed,startOutcomeSettled:e.startOutcomeSettled});const s=this.configUpdateOutcome(i,o,a);t(s)}},l=window[i.sdkGlobalName];this.deviceContext=l.createContext(r),this.logTrace("[TransactionMonitor] Context created successfully:",{config:this.deviceContext.config,monitoringKey:n,pcct:o})}catch(t){this.logException(t,{fieldName:this.fieldName,monitoringKey:n,pcct:o,message:"[TransactionMonitor] Error creating context"})}}finally{null==this.deviceContext&&t(!1)}}configUpdateOutcome(t,e,i){const{monitoringKey:n,pcct:o,fieldName:a,config:s}=this.monitor,r=s?.onDeviceResponseCallback;switch(t){case"SESSION_UPDATE_FAILED":return this.logException(i||new Error(`[TransactionMonitor] Session update failed event: ${t}`),{fieldName:a,data:e,monitoringKey:n,pcct:o}),!1;case"SESSION_UPDATED":if(this.logTrace(`[TransactionMonitor] Session updated event: ${t}`,{fieldName:a,data:e,monitoringKey:n,pcct:o}),r)try{r(e)}catch(t){this.logException(t,{fieldName:a,monitoringKey:n,pcct:o,message:"[TransactionMonitor] Error calling onDeviceResponseCallback"})}return!0;case"SESSION_NO_UPDATE":if(this.logTrace(`[TransactionMonitor] No session update applied event: ${t}`,{fieldName:a,data:e,monitoringKey:n,pcct:o,error:i}),r)try{r(e)}catch(t){this.logException(t,{fieldName:a,monitoringKey:n,pcct:o,message:"[TransactionMonitor] Error calling onDeviceResponseCallback"})}return!0;default:return this.logTrace(`[TransactionMonitor] Config update event: ${t}`,{fieldName:a,data:e,error:i}),!1}}unbind(){const{deviceContext:t}=this;if(t&&"function"==typeof t.unbind)try{t.unbind()}catch(t){"function"==typeof this.logException&&this.logException(t,{fieldName:this.fieldName,message:"[TransactionMonitor] deviceContext.unbind failed"})}this.deviceContext=null}};const U=class{constructor(t,e,i={}){this.pcct=t,this.logger=e;const{logTrace:n,logException:o}=(a=()=>this.logger,{logTrace:function(t,e={}){const i=a();i&&"function"==typeof i.logTrace&&i.logTrace(t,e)},logException:function(t,e={}){const i=a();i&&"function"==typeof i.logException&&i.logException(t,e)}});var a;this.logTrace=n,this.logException=o,this.monitoringKey=i.monitoringKey,this.fieldName=i.fieldName||"";const s=function(t={}){const e={clientId:t.clientId,environment:t.environment,apiSubdomain:t.apiSubdomain,pixelSubdomain:t.pixelSubdomain,flow:t.flow||t.fieldName||"",parentElement:t.parentElement||document.body,sdkGlobalName:t.sdkGlobalName||"_Sardine"};return"function"==typeof t.onDeviceResponse&&(e.onDeviceResponseCallback=t.onDeviceResponse),{config:e,timeouts:{sessionUpdateTimeoutMs:F(t.sessionUpdateTimeoutMs,25e3,t=>"number"==typeof t&&Number.isFinite(t)&&t>0),sdkAttachTimeoutMs:F(t.sdkAttachTimeoutMs,5e3,t=>"number"==typeof t&&Number.isFinite(t)&&t>0),deferredFailureRetryDelayMs:F(t.deferredFailureRetryDelayMs,2e3,t=>"number"==typeof t&&Number.isFinite(t)&&t>0),maxDeferredFailureRetries:F(t.maxDeferredFailureRetries,2,t=>"number"==typeof t&&Number.isInteger(t)&&t>=0)}}}(i);this.config=s.config,this.timeouts=s.timeouts,this.sdkContext=new L(this),this.inFlightStartPromise=null,this.lastStartPromise=null,this.disposed=!1,this.remainingAutoRetriesAfterFailure=0,this.bootstrapRunPromise=null,this.startOutcomeSettled=!1,this.startOutcomeResolve=null,this.startTimeoutId=null}async startWithAutoRetry(){return!!await this.start()||this.continueDeferredFailureRetries()}async start(){if(this.inFlightStartPromise)return this.inFlightStartPromise;if(this.disposed){const t=Promise.resolve(!1);return this.lastStartPromise=t,t}if(!this.monitoringKey||!this.pcct){const t=new Error("[TransactionMonitor] monitoringKey and pcct are required");this.logException(t,{fieldName:this.fieldName,monitoringKey:this.monitoringKey,pcct:this.pcct});const e=Promise.resolve(!1);return this.lastStartPromise=e,e}return this.remainingAutoRetriesAfterFailure=this.timeouts.maxDeferredFailureRetries,this.runStartBootstrap()}async continueDeferredFailureRetries(){if(this.disposed||this.remainingAutoRetriesAfterFailure<=0)return!1;if(this.remainingAutoRetriesAfterFailure-=1,await new Promise(t=>{setTimeout(t,this.timeouts.deferredFailureRetryDelayMs)}),this.disposed)return!1;return!!await this.retryStart()||this.continueDeferredFailureRetries()}async retryStart(){const t=this.inFlightStartPromise??this.lastStartPromise;let e;if(t)try{e=await t}catch{e=void 0}return!0===e||!(!this.monitoringKey||!this.pcct)&&(this.logTrace("[TransactionMonitor] Retrying start",{fieldName:this.fieldName,monitoringKey:this.monitoringKey,pcct:this.pcct}),this.runStartBootstrap())}dispose(){this.disposed||(this.disposed=!0,this.logTrace("[TransactionMonitor] dispose",{fieldName:this.fieldName}),this.disposeStartLifecycle(),this.monitoringKey=null,this.pcct=null)}runStartBootstrap(){null!==this.startTimeoutId&&(clearTimeout(this.startTimeoutId),this.startTimeoutId=null);const t=new Promise(t=>{this.startOutcomeResolve=t});return this.startOutcomeSettled=!1,this.inFlightStartPromise=t,this.lastStartPromise=t,this.runStartBootstrapPipeline().catch(t=>{this.logException(t,{monitoringKey:this.monitoringKey,pcct:this.pcct,message:"[TransactionMonitor] Start bootstrap pipeline failed"}),this.settleStartOutcome(!1)}),t}async runStartBootstrapPipeline(){if(this.bootstrapRunPromise)try{await this.bootstrapRunPromise}catch{}this.unbindAndStripLoader(),this.scheduleStartTimeoutWatchdog();const t=this.sdkContext.initialize(t=>this.settleStartOutcome(t)).catch(t=>{this.logException(t,{monitoringKey:this.monitoringKey,pcct:this.pcct,message:"[TransactionMonitor] Error starting session"}),this.settleStartOutcome(!1)});this.bootstrapRunPromise=t.finally(()=>{this.bootstrapRunPromise===t&&(this.bootstrapRunPromise=null)})}scheduleStartTimeoutWatchdog(){this.startTimeoutId=setTimeout(()=>{this.startTimeoutId=null,this.disposed||this.startOutcomeSettled||(this.logException(new Error("[TransactionMonitor] Start timed out!"),{fieldName:this.fieldName,timeoutMs:this.timeouts.sessionUpdateTimeoutMs,monitoringKey:this.monitoringKey,pcct:this.pcct}),this.settleStartOutcome(!1),this.unbindAndStripLoader())},this.timeouts.sessionUpdateTimeoutMs)}settleStartOutcome(t){if(this.startOutcomeSettled)return;const e=this.startOutcomeResolve;null!==this.startTimeoutId&&(clearTimeout(this.startTimeoutId),this.startTimeoutId=null),this.startOutcomeSettled=!0,this.startOutcomeResolve=null,this.inFlightStartPromise=null,e&&e(t)}disposeStartLifecycle(){null!==this.startTimeoutId&&(clearTimeout(this.startTimeoutId),this.startTimeoutId=null),this.remainingAutoRetriesAfterFailure=0,this.bootstrapRunPromise=null,!this.startOutcomeSettled&&this.startOutcomeResolve&&this.settleStartOutcome(!1),this.startOutcomeResolve=null,this.startOutcomeSettled=!0,this.inFlightStartPromise=null,this.lastStartPromise=null,this.unbindAndStripLoader()}unbindAndStripLoader(){this.sdkContext.unbind(),function(t){if(!t||!t.apiSubdomain)return;const e=`script[src*="${B(t.apiSubdomain)}"]`;document.querySelectorAll(e).forEach(t=>t.remove());const i=t.sdkGlobalName;if("string"==typeof i&&i.length>0)try{delete window[i]}catch(t){}}(this.config)}},z="hexeaDivCaptchaContainer",$="html_element",K="hexeaRecaptchaOnload",q="data-hexea-recaptcha";let G,j="",_=0,W=Promise.resolve(),V=null,H=!1;function Y(){return"undefined"!=typeof grecaptcha&&"function"==typeof grecaptcha.render}function J(){if(null!=G&&"undefined"!=typeof grecaptcha&&"function"==typeof grecaptcha.reset)try{grecaptcha.reset(G)}catch(t){}}function X(){setTimeout(J,0)}function Q(t,e){null!=t&&Object.keys(e).forEach(i=>{Object.assign(t.style,{[i]:e[i]})})}function Z(){J(),G=void 0;const t=document.getElementById(z);return!!t&&(t.parentNode&&t.remove(),!0)}async function tt(t,e){_+=1;const i=_;Z()&&await new Promise(t=>{setTimeout(t,420)}),H||(H=!0,document.addEventListener("submit",X));const n=document.createElement("div");n.id=z,Q(n,{margin:"15px 0","z-index":"inherit"});const o=document.createElement("div");o.className="hexea-captcha-inner";const a=document.createElement("div");a.id=$,Q(a,{"z-index":"99999"}),o.appendChild(a),n.appendChild(o);const s=document.getElementById("g-recaptcha");Q(o,{display:"flex",justifyContent:"center","z-index":9999}),2===e&&null!==s?(Q(document.getElementById("iFrameResizer0"),{height:"500px!important"}),s.parentNode.insertBefore(n,s)):(Q(n,{margin:"0 0"}),Q(o,{position:"fixed",left:0,top:0,width:"100%",height:"100%","align-items":"center","align-content":"stretch",background:"rgba(0,0,0,0.5)"}),document.body.appendChild(n));let r=null;const l=t=>{if(i!==_)return;if(""!==t)return j=t,G=void 0,function(t){const e=t,i=()=>{e.parentNode&&(Q(e,{visibility:"hidden",opacity:"0","pointer-events":"none"}),setTimeout(()=>{e.parentNode&&e.remove()},300))};"function"==typeof requestAnimationFrame?requestAnimationFrame(()=>{requestAnimationFrame(i)}):setTimeout(()=>{setTimeout(i,0)},0)}(n),!0;r||(r=document.createTextNode('Please check "I\'m not a robot"'),o.appendChild(r))};if(await(Y()?Promise.resolve():V||(V=new Promise(t=>{let e,i=!1;const n=()=>{clearTimeout(e)},o=()=>{if(i)return;i=!0,n();const e=document.querySelector(`script[${q}]`);e&&e.remove(),V=null,t()};window[K]=()=>{i||(i=!0,n(),t())};let a=document.querySelector(`script[${q}]`);a||(a=document.createElement("script"),a.setAttribute(q,"true"),a.setAttribute("src",`https://www.google.com/recaptcha/api.js?onload=${encodeURIComponent(K)}&render=explicit`),a.setAttribute("async","true"),a.setAttribute("defer","true"),a.addEventListener("error",o),document.body.appendChild(a)),e=setTimeout(o,3e4)}),V)),!Y())return;const c=()=>{i===_&&(G=grecaptcha.render($,{sitekey:t,callback:l,size:"normal"}))};"function"==typeof grecaptcha.ready?grecaptcha.ready(c):c()}class et{static clearToken(){j=""}static tearDown(){Z()}static getToken(){return j}static waitForToken(t=18e4,e=100){const i=Date.now(),n=o=>{if(""!==j)return void o();Date.now()-i>=t?o():setTimeout(()=>n(o),e)};return new Promise(n)}static async loadDocument(t,e=1){const i=W.then(()=>tt(t,e));W=i.catch(()=>{}),await i}}const it=new class{generate(){return function(){const t=new Uint8Array(16);crypto.getRandomValues(t),t[6]=15&t[6]|64,t[8]=63&t[8]|128;const e=Array.from(t,t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}()}key(){const t=new Uint8Array(12);return crypto.getRandomValues(t),Array.from(t,t=>t.toString(16).padStart(2,"0")).join("")}},nt="PCCT is not recognized",ot="HEXEA_MERCHANT_INFO_TIMEOUT";class at{constructor(t,e){if("string"!=typeof t||!t.trim())throw new Error("PCCT is required");const i=null==e?{}:e;this.merchantInfoGetMaxWaitMs="number"==typeof i.merchantInfoGetMaxWaitMs?i.merchantInfoGetMaxWaitMs:15e3,this.pcct=t.trim(),this.paymentMethods={},this.controllerFrame=null,this.controllerFrameID=null,this.controllerRPC=null,this.logger=null,this.merchantInfo=null,this.envHelper=y,this.hexeaOrigin=this.envHelper.getConfigValue("HEXEA_JS","https://js.connexpointstage.com"),this.hexeaInstanceId=it.generate(),this.transactionMonitor=null,this.merchantInfoFetchPromise=null,this.isDestroyed=!1,this.tokenizingPmNames=new Set,this.createControllerFrame()}deconstructor(){this.destroy()}destroy(){if(!this.isDestroyed){this.isDestroyed=!0;try{this.controllerRPC&&this.controllerRPC.unbind&&this.controllerRPC.unbind(),Object.keys(this.paymentMethods).forEach(t=>{const e=this.paymentMethods[t];e&&"function"==typeof e.destroy&&e.destroy()}),this.controllerFrame&&this.controllerFrame.parentNode&&this.controllerFrame.parentNode.removeChild(this.controllerFrame),this.controllerFrame=null,this.controllerRPC=null,this.transactionMonitor&&"function"==typeof this.transactionMonitor.dispose&&this.transactionMonitor.dispose(),this.transactionMonitor=null,this.logger=null,this.paymentMethods={},this.merchantInfo=null,this.merchantInfoFetchPromise=null,this.tokenizingPmNames.clear()}catch(t){}}}paymentMethod(t){const e=new R(this,t);return this.paymentMethods[e.name]=e,this.ensureMerchantConfigLoaded().then(()=>{this.merchantInfo&&e.updateMerchantInfo(this.merchantInfo)}).catch(t=>{this.logException(t,{message:"Error loading merchant config",pcct:this.pcct})}),e.createPublicApi()}async validateIFrame(){if(this.isDestroyed)return!1;let t=!1;const e=document.querySelectorAll('iframe[name^="hexeaSecureFrame"]');for(let i=0;i<e.length;i+=1){const n=document.getElementsByName(e[i].name)[0];if(null!==n){const e=n.contentWindow.document.getElementById("USBHID");if(null!=e){t=!0;break}}}return t}async waitForMerchantInfo(t){const e=this.ensureMerchantConfigLoaded();let i;const n=new Promise((t,e)=>{i=setTimeout(()=>{const t=new Error("This is taking longer than expected. Please try again in a moment.");t.code=ot,e(t)},this.merchantInfoGetMaxWaitMs)});try{await Promise.race([e,n])}catch(e){const i=e&&e.code===ot;throw this.logException(e,{message:i?"Merchant info request timed out":"Error waiting for merchant info",paymentMethodType:t.type,pcct:this.pcct}),e}finally{clearTimeout(i)}}async tokenize(t,e){const i=this.paymentMethods[t.name];if(!i)throw new a("The payment method provided to Tokenize was not created by this instance of Hexea()");if(this.tokenizingPmNames.has(i.name))return this.logTrace(`[Hexea] Tokenize request rejected due to ongoing tokenize for pm:${i.name}`,{pcct:this.pcct}),Promise.reject(new Error("We are still finishing your last request. Please try again in a moment."));this.tokenizingPmNames.add(i.name);try{await this.waitForMerchantInfo(i);const t=await this.resolveRecaptchaForCardTokenize(i),n=e?{...e}:{};return n.referrerUrl=document.location.href,this.logTrace(`[Hexea] tokenize pm method called for pcct:${this.pcct}`,{pcct:this.pcct,captcha_Token:t,billing:n}),await i.tokenize(this.pcct,t,n)}finally{this.tokenizingPmNames.delete(i.name)}}async resolveRecaptchaForCardTokenize(t){if(!this.merchantInfo||!("captchaEnabled"in this.merchantInfo))return"";if(0===this.merchantInfo.captchaEnabled||t.type!==k)return"";const e=await this.getAdminDomainInfo();if(!0===e.isAdminPage)return e.token;et.clearToken(),await et.loadDocument(this.envHelper.getConfigValue("SITEKEYVALUE"),this.merchantInfo.captchaEnabled),setTimeout(()=>{const t=document.getElementById("hexeaCardUIBody");if(t){const e=t.querySelectorAll("div"),i=e[e.length-3];i&&(i.style.zIndex="999999",i.style.transform="scale(0.88)",i.style.transformOrigin="top",i.style.top="0px")}},1e3),await et.waitForToken();const i=et.getToken();return""===i&&(this.logTrace("Captcha token not received within timeout period."),et.tearDown()),i}async getAdminDomainInfo(){const t=at.getDeviceType();return this.controllerRPC.invoke("checkIfIsAdminDomain",this.pcct,t)}static getDeviceType(){const t=window.navigator.standalone,e=window.navigator.userAgent.toLowerCase();return/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(window.navigator.userAgent)&&!t||e.includes("wv")?"mobileDevice":window.location.href}ensureMerchantConfigLoaded(){return this.merchantInfo?Promise.resolve():(this.merchantInfoFetchPromise||(this.merchantInfoFetchPromise=(async()=>{try{const{merchantInfo:t,serverConfig:e}=await this.controllerRPC.invoke("getConfig",[this.pcct]);if(!t||"object"!=typeof t)throw new Error(nt);this.merchantInfo=t,this.envHelper.setConfig(e)}catch(t){if(t instanceof Error&&t.message===nt)throw t;throw new Error("Failed to get merchant info")}finally{this.merchantInfoFetchPromise=null}})()),this.merchantInfoFetchPromise)}startTransactionMonitor(t,e){if(!this.transactionMonitor)try{const i=window.location.pathname,n=i.length>15?i.slice(0,15):i,o={clientId:y.getConfigValue("MONITORINGCLIENTID"),environment:y.getConfigValue("MONITORINGENVIRONMENT"),apiSubdomain:y.getConfigValue("APISUBDOMAIN"),pixelSubdomain:y.getConfigValue("PIXELSUBDOMAIN"),monitoringKey:t,fieldName:`Main:${n}`,onDeviceResponse:t=>{const e=t?.deviceId;this.controllerRPC&&null!=e&&this.controllerRPC.invoke("logDeviceResponse",e).catch(t=>{this.logException(t instanceof Error?t:new Error(String(t)),{message:"[Hexea] logDeviceResponse RPC failed",pcct:this.pcct})})}},a=new U(e,this.logger,o);this.transactionMonitor=a,a.startWithAutoRetry().catch(t=>{this.logException(t instanceof Error?t:new Error(String(t)),{message:"[Hexea] TransactionMonitor startWithAutoRetry failed",pcct:this.pcct})})}catch(t){this.logException(t,{message:"[Hexea] Error starting TransactionMonitor",pcct:this.pcct})}}createControllerFrame(){this.controllerFrameID=A();const t=document.createElement("iframe");t.title="Secure payment method input frame",t.style.visibility="hidden",t.style.width="0px",t.style.height="0px";const{origin:e}=window.location,i="mobileDevice"===at.getDeviceType();let n=`?origin=${encodeURIComponent(e)}&uid=${this.hexeaInstanceId}&pcct=${this.pcct}&ts=${Date.now()}`;i&&(n+="&m=1");const o=`${this.hexeaOrigin}/hexea/controller${n}`;t.src=o,t.name=this.controllerFrameID,document.body.appendChild(t),this.controllerFrame=t,this.controllerRPC=new l(t.contentWindow,this.hexeaOrigin),this.logger=new O(this.controllerRPC),this.logTrace("[Hexea] controller iFrame created",{controllerUrl:o,href:window.location.href})}registerPaymentMethodFrame(t,e){this.controllerRPC.invoke("registerPaymentMethodFrame",t,e).then(t=>{const i=t&&t.monitoringKey?t.monitoringKey:null;i&&e.type===d&&this.startTransactionMonitor(i,this.pcct)}).catch(i=>{this.logException(i instanceof Error?i:new Error(String(i)),{message:"[Hexea] registerPaymentMethodFrame RPC failed",pcct:this.pcct,group:t,field:e&&e.name})})}unregisterPaymentMethodFrame(t,e){if(this.controllerRPC)return this.controllerRPC.invoke("unregisterPaymentMethodFrame",t,e)}logTrace(t,e={}){this.logger&&this.logger.logTrace&&this.logger.logTrace(t,e)}logException(t,e={}){this.logger&&this.logger.logException&&this.logger.logException(t,e)}createPublicApi(){return{paymentMethod:this.paymentMethod.bind(this),tokenize:this.tokenize.bind(this),destroy:this.destroy.bind(this)}}}const st=at;function rt(...t){return new st(...t).createPublicApi()}let lt;"undefined"!=typeof window?lt=window:void 0!==t.g&&(lt=t.g),lt&&lt.document&&!lt.Hexea&&(lt.Hexea=rt);const ct=rt;return e=e.default})());