@primer-io/primer-js 1.0.0 → 1.0.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/CHANGELOG.md +6 -0
- package/dist/custom-elements.json +279 -279
- package/dist/jsx/index.d.ts +31 -31
- package/dist/primer-loader.js +3 -3
- package/dist/vscode.html-custom-data.json +26 -26
- package/dist/web-types.json +67 -67
- package/package.json +1 -1
package/dist/primer-loader.js
CHANGED
|
@@ -33,7 +33,7 @@ import{a as _a,b as d,c as k}from"./chunks/chunk.DV3REKZU.js";var wa=class{const
|
|
|
33
33
|
--apple-pay-button-width: 100%;
|
|
34
34
|
--apple-pay-button-height: ${a}px;
|
|
35
35
|
}
|
|
36
|
-
`,e.appendChild(i);let n=document.createElement("apple-pay-button"),o=this.clientOptions?.buttonStyle??this.clientOptions?.buttonOptions?.buttonStyle;o&&n.setAttribute("buttonstyle",o);let s=this.clientOptions?.buttonType??this.clientOptions?.buttonOptions?.type??"plain";s&&n.setAttribute("type",s),n.setAttribute("locale",this.context.locale),n.addEventListener("click",this.handleClick.bind(this)),document.body.appendChild(n),setTimeout(()=>{e.appendChild(n)},0)}async handleClick(){if(!this.disabled)try{this.onStartPromise=this.callbacks.onStart(),kt({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:B.APPLE_PAY}),this.applePaySession=new ApplePaySession(An,uc(this.context,this.config)),this.applePaySession.onvalidatemerchant=this.handleValidateMerchant.bind(this),this.applePaySession.onpaymentauthorized=this.handlePaymentAuthorized.bind(this),this.applePaySession.onpaymentmethodselected=this.handlePaymentMethodSelected.bind(this),this.applePaySession.onshippingcontactselected=this.handleShippingContactSelected.bind(this),this.applePaySession.onshippingmethodselected=this.handleShippingMethodSelected.bind(this),this.applePaySession.oncancel=this.handleCancel.bind(this),this.applePaySession.begin()}catch(e){C.errorWithDatadog("Error initiating Apple Pay session",{error:e})}}async handleValidateMerchant(e){if(this.applePaySession)try{let{action:a}=await this.onStartPromise;if(a==="abort")return void this.abort(new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let{data:i,error:n}=await this.context.coreApi.createApplePaySession({validationUrl:e.validationURL,paymentMethodConfigId:this.config.id,merchantDomain:this.context.clientOptions.merchantDomain??window.location.hostname});if(!this.applePaySession)return;if(n||!i)throw n??new G({message:"Failed to validate merchant",code:q.REQUEST_ERROR,paymentMethod:B.APPLE_PAY});this.applePaySession.completeMerchantValidation(i)}catch(a){C.warn("Apple Pay merchant validation failed:",a),this.abort()}}async handlePaymentMethodSelected(e){if(this.applePaySession)try{this.applePaySession.completePaymentMethodSelection(Jr(this.context,this.config))}catch(a){C.errorWithDatadog("Error handling payment method selection",{error:a}),this.abort()}}async handlePaymentAuthorized(e){if(!this.applePaySession)return;let a=[new ApplePayError("unknown",void 0,this.context.translate(ca.UNKNOWN_ERROR,ua.UNKNOWN_ERROR))];try{if(this.clientOptions?.billingOptions?.requiredBillingContactFields?.includes("postalAddress")){let s=Zr(e.payment.billingContact);if(s){if(!s.firstName||!s.lastName)throw a=[new ApplePayError("billingContactInvalid","name",this.context.translate(ca.MISSING_FIRST_OR_LAST_NAME,ua.MISSING_FIRST_OR_LAST_NAME))],new G({message:"Billing contact must include first and last name",code:It.MISSING_PARAMETER,paymentMethod:B.APPLE_PAY,suggestion:"Ensure Apple Pay requiredBillingContactFields includes name fields"});let{error:l}=await this.context.clientSessionApi.setBillingAddress(s);l&&C.errorWithDatadog("Error setting billing address from Apple Pay",{error:l})}}let i=Zr(e.payment.shippingContact);if(i){let{error:s}=await this.context.clientSessionApi.setShippingAddress(i,e.payment.shippingContact?.phoneNumber,e.payment.shippingContact?.emailAddress);if(s)throw s}let{data:n,error:o}=await this.context.pciApi.postApplePayPaymentInstruments({paymentMethodConfigId:this.config.id,token:e.payment.token});if(o||!n)throw a=[new ApplePayError("unknown",void 0,this.context.translate(ca.FAILED_TO_TOKENIZE,ua.FAILED_TO_TOKENIZE))],o??new Error("Failed to tokenize Apple Pay payment");this.applePaySession.completePayment(ApplePaySession.STATUS_SUCCESS),this.callbacks.onFinish(n),this.applePaySession=null}catch(i){let n=i instanceof G||i instanceof z?i:new G({message:"Error handling payment authorization",code:F.PAYMENT_FAILED,paymentMethod:B.APPLE_PAY,error:i instanceof Error?i:new Error(String(i))});C.errorWithDatadog("Apple Pay payment authorization failed",{error:n}),this.applePaySession&&(this.applePaySession.completePayment({status:ApplePaySession.STATUS_FAILURE,errors:a}),this.applePaySession=null),this.callbacks.onFinish(void 0,n)}}async handleShippingContactSelected(e){if(this.applePaySession)try{let{data:a,error:i}=await this.context.clientSessionApi.setShippingAddress(Zr(e.shippingContact),e.shippingContact?.phoneNumber,e.shippingContact?.emailAddress);if(!this.applePaySession)return;if(!a||i)throw i??new G({message:"Failed to set shipping address",code:q.REQUEST_ERROR,paymentMethod:B.APPLE_PAY});this.applePaySession.completeShippingContactSelection(Jr(this.context,this.config))}catch(a){C.errorWithDatadog("Error handling shipping contact selection",{error:a}),this.abort()}}async handleShippingMethodSelected(e){if(!this.applePaySession)return;let a=this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options;try{if(this.clientOptions?.shippingOptions?.requireShippingMethod&&a){let{data:i,error:n}=await this.context.clientSessionApi.selectShippingMethod(e.shippingMethod.identifier);if(!i||n)throw n??new G({message:"Failed to select shipping method",code:q.REQUEST_ERROR,paymentMethod:B.APPLE_PAY})}if(!this.applePaySession)return;this.applePaySession.completeShippingMethodSelection(Jr(this.context,this.config))}catch(i){C.errorWithDatadog("Error handling shipping method selection",{error:i}),this.abort();return}}handleCancel(){this.applePaySession=null,this.context.clientSessionApi.unselectPaymentMethod(),C.info("Apple Pay payment was cancelled by the user")}abort(e){this.context.clientSessionApi.unselectPaymentMethod(),this.applePaySession?.abort(),this.applePaySession=null,this.callbacks.onFinish(void 0,e??new Error("Apple Pay payment aborted"))}},za=class extends mt{constructor(){super(...arguments);k(this,"blikCode","")}setBlikCode(e){this.blikCode=e}getBlikCode(){return this.blikCode}clearBlikCode(){this.blikCode=""}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let a=await this.tokenize();this.callbacks.onFinish(a)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){if(!/^\d{6}$/.test(this.blikCode))throw new z({message:"BLIK code must be exactly 6 digits",code:F.TOKENIZATION_ERROR,paymentMethod:this.config.type});let e={type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:this.context.locale,platform:ao()?"MOBILE_WEB":"WEB",browserInfo:Si(),blikCode:this.blikCode}};try{let{error:a,data:i}=await this.context.pciApi.postBlikPaymentInstruments(e);if(this.clearBlikCode(),a||!i)throw a??new z({message:"Unable to tokenize BLIK payment method",code:F.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}catch(a){throw this.clearBlikCode(),a}}async createPayment(e){let a=await super.createPayment(e),i=a.requiredAction?.clientToken;if(!i)throw new Be({message:"No client token provided for BLIK payment",code:bn.MISSING_CLIENT_TOKEN,response:{id:a.id,data:a}});let n=Ht(i);if(!this.isValidBlikClientToken(n))throw new Be({message:"Invalid BLIK client token: missing statusUrl or incorrect intent",code:bn.INVALID_CLIENT_TOKEN,response:{id:a.id,data:a}});let{promise:o,abort:s}=this.pollStatus(n.statusUrl),l=await o;if(s(),"error"in l)throw l.error;let c=l.id;if(!c){let m=await this.context.pciApi.getResumeStatus(n.statusUrl);if(m.error||!m.data?.id)throw m.error??new Error("Unable to get resume token");c=m.data.id}return await this.resumePayment(a.id,c)}pollStatus(e){let a=!0,i=1e3,n=864e5,o=Date.now();return{promise:new Promise(async s=>{for(;a;){if(Date.now()-o>=n)return void s({error:new Error("BLIK payment polling timed out after 24 hours")});let{data:l,error:c}=await this.context.pciApi.getResumeStatus(e);if(c)return void s({error:c instanceof Error?c:new Error(String(c))});if(l?.status==="COMPLETE")return void s({id:l.id});await Yt(i)}}),abort:()=>{a=!1}}}isValidBlikClientToken(e){if(typeof e!="object"||e===null)return!1;let a=e;return!(a.intent!=="ADYEN_BLIK_REDIRECTION"||!("statusUrl"in a)||typeof a.statusUrl!="string"||!a.statusUrl)}},lo="https://sdk.primer.io/web/hosted-pages/v0.0.23",si=!1,mc=`${lo}/api-controller.html`,hc=`${lo}/hosted-input.html`,gc="https://goat-assets.production.core.primer.io";function co(r,t,e){let a={checkoutSessionId:r,name:t};e!==void 0&&(a.defaultValue=e);try{return btoa(JSON.stringify(a))}catch{let{defaultValue:n,...o}=a;return btoa(JSON.stringify(o))}}hi("../../node_modules/card-validator/dist/index.js");var ce={cardNumber:"cardNumber",cardSecurityCode:"cardSecurityCode",cardExpiryDate:"cardExpiryDate",cardholderName:"cardholderName"},Mn="cardSecurityCodeRecapture";Object.values(ce);function yc({networks:r,source:t},e){let a=e,i=new Set(a.map(m=>Ja(m).backend)),n=r.map(m=>({...m,allowed:i.has(m.network)})).sort((m,g)=>m.allowed?a.indexOf(m.network)-a.indexOf(g.network):1),o=n.filter(m=>m.allowed),s=t==="REMOTE"&&o.length>1,[l,...c]=n;return{cardNetworkChangeEventData:{detectedCardNetworks:{items:n.map(Oa),preferred:o.length?Oa(o[0]):void 0},...s&&{selectableCardNetworks:{items:o.map(Oa),preferred:o.length?Oa(o[0]):void 0}},source:t},binDataAvailableEventData:{preferred:l,alternatives:c,status:t==="REMOTE"?"complete":"partial"}}}function Oa({network:r,displayName:t,allowed:e}){return{network:r,displayName:t,allowed:e}}function uo(r,t){return{cardNumber:da(r,ce.cardNumber),cardSecurityCode:da(r,ce.cardSecurityCode),cardExpiryDate:da(r,ce.cardExpiryDate),cardholderName:da(r,ce.cardholderName,t?.cardholderName)}}function da(r,t,e){let a=document.createElement("iframe"),i=co(r,t,e);return a.src=`${hc}#${i}`,a.setAttribute("tabindex","0"),a.setAttribute("frameBorder","0"),a.style.border="none",a.style.boxSizing="border-box",a.style.height="20px",a.style.width="100%",a.style.colorScheme="auto",a}var ja=class extends mt{constructor(e,a){super(e,a);k(this,"iframes");this.iframes=uo(a.checkoutSessionId)}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let a=await this.tokenize();this.callbacks.onFinish(a)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){let{error:e,data:a}=await this.context.pciApi.postCardPaymentInstruments();if(e||!a)throw e??new z({code:F.TOKENIZATION_ERROR,message:"Unable to tokenize payment method",paymentMethod:B.PAYMENT_CARD});return a}};function fc(r){if(!r)return{};let t=r.indexOf(" ");return t===-1?{firstName:r}:{firstName:r.substring(0,t),lastName:r.substring(t+1)}}function qr(r){let{firstName:t,lastName:e}=fc(r.name);return{firstName:t||null,lastName:e||null,addressLine1:r.address1||null,addressLine2:r.address2||null,city:r.locality||null,state:r.administrativeArea||null,postalCode:r.postalCode||null,countryCode:r.countryCode||null}}function En(r){return r.map(t=>({id:t.id,label:t.name,description:t.description||""}))}var Tn=2,Pn=0,vc="https://pay.google.com/gp/p/js/pay.js",Sc={AMEX:"AMEX",DISCOVER:"DISCOVER",INTERAC:"INTERAC",JCB:"JCB",MASTERCARD:"MASTERCARD",VISA:"VISA"},Nn=["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],Ga={FEE:"fee_label_fallback",ITEM:"item_label_fallback",SHIPPING:"shipping",SUBTOTAL:"subtotal"},Ka={FEE:"Fee",ITEM:"Item",SHIPPING:"Shipping",SUBTOTAL:"Subtotal"},bc="buy",Ac="black",Cc="fill",Wa=class extends mt{constructor(){super(...arguments);k(this,"disabled",!1);k(this,"client",null)}async setDisabled(e){this.disabled=e}translate(e,a){return this.context.translate?.(e,a)??a}async tokenize(){throw new z({code:F.TOKENIZATION_ERROR,message:"Google Pay does not support direct tokenization",paymentMethod:B.GOOGLE_PAY})}async loadGooglePayScript(){if(typeof google<"u"&&google.payments?.api?.PaymentsClient)return!0;try{return await ro(vc),!0}catch{return C.error("Failed to load Google Pay script"),!1}}async setup(){let{countryCode:e,currencyCode:a}=this.context.configuration.clientSession.order;if(!e)throw new G({code:It.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing country code",paymentMethod:B.GOOGLE_PAY});if(!a)throw new G({code:It.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing currency code",paymentMethod:B.GOOGLE_PAY});if(!await this.loadGooglePayScript())return C.error("Google Pay script failed to load"),!1;let n=this.context.configuration.env==="PRODUCTION"?"PRODUCTION":"TEST";this.client=new google.payments.api.PaymentsClient({environment:n,...this.needsPaymentDataCallbacks()&&{paymentDataCallbacks:{onPaymentDataChanged:s=>this.handlePaymentDataChanged(s)}}});try{let{result:s,paymentMethodPresent:l}=await this.client.isReadyToPay(this.buildIsReadyToPayRequest());if(!s)return C.info("Google Pay is not available in this browser/device"),!1;if(this.clientOptions?.existingPaymentMethodRequired&&l===!1)return C.info("Google Pay: existingPaymentMethodRequired is true but no existing payment method is available"),!1}catch(s){return C.error("Google Pay isReadyToPay check failed",{error:s}),!1}let o=this.context.onClientConfigurationUpdate(s=>{let l=s.clientSession?.order;(!l||!l.totalOrderAmount||!l.currencyCode)&&C.warn("Google Pay: Order details are missing or incomplete after client session update. Ensure order details (totalOrderAmount, currencyCode, countryCode) are always provided.")});return this.context.subscribeToTeardown(o),!0}needsPaymentDataCallbacks(){return!!(this.clientOptions?.requireShippingMethod||this.shouldCaptureShippingAddress)}buildIsReadyToPayRequest(){return{apiVersion:Tn,apiVersionMinor:Pn,allowedPaymentMethods:[this.allowedPaymentMethod],existingPaymentMethodRequired:this.clientOptions?.existingPaymentMethodRequired}}async render(e){if(!this.client)return void C.error("Google Pay client not initialized. Call setup() first.");let a=this.client.createButton({buttonType:this.clientOptions?.buttonType??bc,buttonColor:this.clientOptions?.buttonColor??Ac,buttonSizeMode:this.clientOptions?.buttonSizeMode??Cc,buttonRadius:this.clientOptions?.buttonRadius,buttonLocale:this.clientOptions?.buttonLocale,buttonBorderType:this.clientOptions?.buttonBorderType,onClick:i=>this.handleClick(i),buttonRootNode:e instanceof ShadowRoot?e:void 0});e.appendChild(a)}async handleClick(e){if(!this.client)return void C.error("Google Pay client not available");let a=this.callbacks.onStart();kt({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:B.GOOGLE_PAY});try{let i=await this.client.loadPaymentData(this.buildPaymentDataRequest()),{action:n}=await a;if(n==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type});await this.processPaymentData(i)}catch(i){if(i.statusCode==="CANCELED")return void this.context.clientSessionApi.unselectPaymentMethod();C.errorWithDatadog("Google Pay error",{error:i}),this.context.clientSessionApi.unselectPaymentMethod(),this.callbacks.onFinish(void 0,i)}}get clientOptions(){return this.context.clientOptions.googlePay}get shouldCaptureShippingAddress(){return!!(this.clientOptions?.captureShippingAddress||this.clientOptions?.shippingAddressParameters)}async processPaymentData(e){if(this.clientOptions?.captureBillingAddress&&await this.updateBillingAddress(e),(this.shouldCaptureShippingAddress||this.clientOptions?.requireShippingMethod||this.clientOptions?.emailRequired)&&await this.updateShippingDetails(e),this.clientOptions?.requireShippingMethod){let n=e.shippingOptionData?.id;n&&await this.context.clientSessionApi.selectShippingMethod(n)}let{data:a,error:i}=await this.context.pciApi.postGooglePayPaymentInstruments({flow:"GATEWAY",network:e.paymentMethodData.info?.cardNetwork??"OTHER",merchant_id:this.config.options.merchantId,encrypted_payload:Va.encode(e.paymentMethodData.tokenizationData.token)});if(i||!a)throw this.callbacks.onFinish(void 0,i),i??new z({code:F.TOKENIZATION_ERROR,message:"Failed to tokenize payment data",paymentMethod:B.GOOGLE_PAY});this.callbacks.onFinish(a)}async updateBillingAddress(e){let a=e.paymentMethodData.info?.billingAddress;if(a){let i=qr(a);await this.context.clientSessionApi.setBillingAddress(i)}else C.warn("Google Pay: Could not retrieve billing address from payment data")}async updateShippingDetails(e){let a=e.shippingAddress,i=e.email,n=a?.phoneNumber;if(a||n||i){let o=a?qr(a):void 0;await this.context.clientSessionApi.setShippingAddress(o,n,i)}else C.warn("Google Pay: No shipping address, phone number, or email found in payment data")}async handlePaymentDataChanged(e){let a=e.callbackTrigger;try{if(a==="SHIPPING_OPTION"){let i=e.shippingOptionData?.id;return i&&await this.context.clientSessionApi.selectShippingMethod(i),{newTransactionInfo:this.getCurrentTransactionInfo()}}if(a==="SHIPPING_ADDRESS"||a==="INITIALIZE"){let i=e.shippingAddress;if(i){let s=qr(i);await this.context.clientSessionApi.setShippingAddress(s)}let n=this.getShippingModule(),o=n?.shippingMethods||[];return{...this.clientOptions?.requireShippingMethod&&o.length>0&&{newShippingOptionParameters:{shippingOptions:En(o),defaultSelectedOptionId:n?.selectedShippingMethod||o[0]?.id}},newTransactionInfo:this.getCurrentTransactionInfo()}}return{newTransactionInfo:this.getCurrentTransactionInfo()}}catch(i){return C.errorWithDatadog("Google Pay: Error handling payment data change",{error:i}),{error:{reason:"OTHER_ERROR",message:"An error occurred while processing your request",intent:a==="SHIPPING_OPTION"?"SHIPPING_OPTION":"SHIPPING_ADDRESS"}}}}getShippingModule(){return this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options}getCurrentTransactionInfo(){let{countryCode:e,currencyCode:a,totalOrderAmount:i}=this.context.configuration.clientSession.order;return{countryCode:e,currencyCode:a,displayItems:this.getDisplayItems(),totalPriceStatus:"FINAL",totalPrice:sa(i,a),totalPriceLabel:"Total"}}getDisplayItems(){let e=this.context.configuration.clientSession.order,{currencyCode:a,merchantAmount:i,lineItems:n,fees:o,shipping:s}=e,l=this.clientOptions?.requireShippingMethod,c=[];return i?(c.push({label:this.translate(Ga.SUBTOTAL,Ka.SUBTOTAL),type:"SUBTOTAL",price:sa(i,a)}),c):(n&&n.length>0&&n.forEach(m=>{c.push({label:m.description||this.translate(Ga.ITEM,Ka.ITEM),type:"LINE_ITEM",price:sa(m.amount,a)})}),o&&o.length>0&&o.filter(m=>m.amount!==0).forEach(m=>{c.push({label:m.type||m.description||this.translate(Ga.FEE,Ka.FEE),type:"LINE_ITEM",price:sa(m.amount,a)})}),l&&s&&s.amount!==0&&c.push({label:s.methodName||this.translate(Ga.SHIPPING,Ka.SHIPPING),type:"LINE_ITEM",price:sa(s.amount,a)}),c)}get allowedCardNetworks(){let e=this.context.configuration.clientSession.paymentMethod?.orderedAllowedCardNetworks;if(!e||e.length===0)return Nn;let a=e.map(i=>Sc[i]).filter(i=>!!i);return a.length>0?a:Nn}get allowedPaymentMethod(){let e=this.clientOptions?.captureBillingAddress;return{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:this.allowedCardNetworks,...e&&{billingAddressRequired:!0,billingAddressParameters:{format:"FULL"}}}}}buildPaymentDataRequest(){let e=this.clientOptions?.shippingAddressParameters,a=this.clientOptions?.emailRequired,i=this.clientOptions?.requireShippingMethod,n=this.getShippingModule(),o=n?.shippingMethods,s=n?.selectedShippingMethod;return{apiVersion:Tn,apiVersionMinor:Pn,...a&&{emailRequired:!0},...(this.shouldCaptureShippingAddress||i)&&{shippingAddressRequired:!0,...e&&{shippingAddressParameters:{...e.allowedCountryCodes&&{allowedCountryCodes:e.allowedCountryCodes},...e.phoneNumberRequired&&{phoneNumberRequired:!0}}}},...i&&{shippingOptionRequired:!0,...o&&o.length>0&&{shippingOptionParameters:{shippingOptions:En(o),defaultSelectedOptionId:s||o[0]?.id}}},...this.needsPaymentDataCallbacks()&&{callbackIntents:[...i?["SHIPPING_ADDRESS","SHIPPING_OPTION"]:["SHIPPING_ADDRESS"]]},transactionInfo:this.getCurrentTransactionInfo(),merchantInfo:{merchantId:this.config.options.merchantId,merchantName:this.config.options.merchantName},allowedPaymentMethods:[{...this.allowedPaymentMethod,tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:"primer",gatewayMerchantId:this.config.options.merchantId}}}]}}};function Mc(r,t){var e={};for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&t.indexOf(a)<0&&(e[a]=r[a]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,a=Object.getOwnPropertySymbols(r);i<a.length;i++)t.indexOf(a[i])<0&&Object.prototype.propertyIsEnumerable.call(r,a[i])&&(e[a[i]]=r[a[i]]);return e}function Ec(r,t){var e=document.querySelector('script[src="'.concat(r,'"]'));if(e===null)return null;var a=po(r,t),i=e.cloneNode();if(delete i.dataset.uidAuto,Object.keys(i.dataset).length!==Object.keys(a.dataset).length)return null;var n=!0;return Object.keys(i.dataset).forEach(function(o){i.dataset[o]!==a.dataset[o]&&(n=!1)}),n?e:null}function Tc(r){var t=r.url,e=r.attributes,a=r.onSuccess,i=r.onError,n=po(t,e);n.onerror=i,n.onload=a,document.head.insertBefore(n,document.head.firstElementChild)}function Pc(r){var t=r.sdkBaseUrl,e=r.environment,a=Mc(r,["sdkBaseUrl","environment"]),i=t||kc(e),n=a,o=Object.keys(n).filter(function(c){return n[c]!==void 0&&n[c]!==null&&n[c]!==""}).reduce(function(c,m){var g=n[m].toString();return m=Nc(m),m.substring(0,4)==="data"||m==="crossorigin"?c.attributes[m]=g:c.queryParams[m]=g,c},{queryParams:{},attributes:{}}),s=o.queryParams,l=o.attributes;return s["merchant-id"]&&s["merchant-id"].indexOf(",")!==-1&&(l["data-merchant-id"]=s["merchant-id"],s["merchant-id"]="*"),{url:"".concat(i,"?").concat(Ic(s)),attributes:l}}function Nc(r){var t=function(e,a){return(a?"-":"")+e.toLowerCase()};return r.replace(/[A-Z]+(?![a-z])|[A-Z]/g,t)}function Ic(r){var t="";return Object.keys(r).forEach(function(e){t.length!==0&&(t+="&"),t+=e+"="+r[e]}),t}function kc(r){return r==="sandbox"?"https://www.sandbox.paypal.com/sdk/js":"https://www.paypal.com/sdk/js"}function po(r,t){t===void 0&&(t={});var e=document.createElement("script");return e.src=r,Object.keys(t).forEach(function(a){e.setAttribute(a,t[a]),a==="data-csp-nonce"&&e.setAttribute("nonce",t["data-csp-nonce"])}),e}function Lc(r,t){if(t===void 0&&(t=Promise),mo(r,t),typeof document>"u")return t.resolve(null);var e=Pc(r),a=e.url,i=e.attributes,n=i["data-namespace"]||"paypal",o=In(n);return i["data-js-sdk-library"]||(i["data-js-sdk-library"]="paypal-js"),Ec(a,i)&&o?t.resolve(o):Rc({url:a,attributes:i},t).then(function(){var s=In(n);if(s)return s;throw new Error("The window.".concat(n," global variable is not available."))})}function Rc(r,t){t===void 0&&(t=Promise),mo(r,t);var e=r.url,a=r.attributes;if(typeof e!="string"||e.length===0)throw new Error("Invalid url.");if(a!==void 0&&typeof a!="object")throw new Error("Expected attributes to be an object.");return new t(function(i,n){if(typeof document>"u")return i();Tc({url:e,attributes:a,onSuccess:function(){return i()},onError:function(){var o=new Error('The script "'.concat(e,'" failed to load. Check the HTTP status code and response body in DevTools to learn more.'));return n(o)}})})}function In(r){return window[r]}function mo(r,t){if(typeof r!="object"||r===null)throw new Error("Expected an options object.");var e=r.environment;if(e&&e!=="production"&&e!=="sandbox")throw new Error('The `environment` option must be either "production" or "sandbox".');if(t!==void 0&&typeof t!="function")throw new Error("Expected PromisePonyfill to be a function.")}var Fa=new Map,kn={getOrCreateNamespace(r){let t=Fa.get(r);return t?t.namespace:Te()},getInstance(r){return Fa.get(r)?.instance??null},storeInstance(r,t,e){Fa.set(r,{instance:t,namespace:e})},hasInstance(r){return Fa.has(r)}};async function xc({context:r,configId:t,paymentMethodType:e,callbacks:a}){try{let{action:i}=await a.onStart();if(i==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:e});let{data:n,error:o}=await r.coreApi.createPaypalBillingAgreement({paymentMethodConfigId:t});if(o||!n){let s=o?.message??"Failed to create billing agreement";throw new G({message:s,code:F.PAYMENT_FAILED,paymentMethod:e})}return n.tokenId}catch(i){throw C.errorWithDatadog("PayPal billing agreement creation failed:",{error:i}),a.onFinish(void 0,i),i instanceof G||i instanceof z?i:new G({message:"Failed to create billing agreement",code:F.PAYMENT_FAILED,paymentMethod:e})}}async function _c({context:r,configId:t,paymentMethodType:e,callbacks:a,data:i}){try{let n=i.billingToken;if(!n)throw new z({message:"Billing token not provided",code:F.TOKENIZATION_ERROR,paymentMethod:e});let{data:o,error:s}=await r.coreApi.confirmPaypalBillingAgreement({paymentMethodConfigId:t,tokenId:n});if(s||!o){let h=s?.message??"Failed to confirm billing agreement";throw new z({message:h,code:F.TOKENIZATION_ERROR,paymentMethod:e})}let l=o,c={paypalBillingAgreementId:l.billingAgreementId,shippingAddress:l.shippingAddress,externalPayerInfo:l.externalPayerInfo},{error:m,data:g}=await r.pciApi.postPaypalPaymentInstruments(c,{tokenType:"MULTI_USE",paymentFlow:"VAULT"});if(m||!g){let h=m?.message??"Unable to vault PayPal payment method";throw new z({message:h,code:F.TOKENIZATION_ERROR,paymentMethod:e})}a.onFinish(g)}catch(n){throw C.errorWithDatadog("PayPal billing agreement approval failed:",{error:n}),a.onFinish(void 0,n),n instanceof z||n instanceof G?n:new z({message:"Failed to approve billing agreement",code:F.TOKENIZATION_ERROR,paymentMethod:e})}}var wc="gold",Dc="black",Bc="rect",Oc="paypal",Gc="vertical",ho="horizontal",Ln=2,Rn=["paypal","paylater"],go={default:{color:wc},card:{validColors:["black","white"],defaultColor:Dc}};function Kc(r){if(!r)return;let t=go[r];if(t&&"validColors"in t)return t}function Fc(r,t){let e=Kc(t);if(!e)return r??go.default.color;let a=r??e.defaultColor;return e.validColors.includes(a)?a:(C.warn(`PayPal: Invalid color "${a}" for ${t} button. Only supports: ${e.validColors.join(", ")}. Falling back to "${e.defaultColor}".`),e.defaultColor)}var Uc=25,Vc=55;function Hc(r){return parseFloat(r)||0}function Yc(r){let t=Hc(r);return Math.max(Uc,Math.min(Vc,t))}function $c(r,t,e){let a=t?r?.[t]:void 0,i=a?.tagline??r?.tagline??!1,n=i?ho:Gc,o,s=a?.height??r?.height;s!=null?o=s:e!=null&&(o=Yc(String(e)));let l=a?.borderRadius??r?.borderRadius,c=a?.disableMaxWidth??r?.disableMaxWidth,m=a?.color??r?.color;return{color:Fc(m,t),shape:a?.shape??r?.shape??Bc,label:a?.label??r?.label??Oc,layout:a?.layout??r?.layout??n,tagline:i,...o!=null&&{height:o},...l!=null&&{borderRadius:l},...c!=null&&{disableMaxWidth:c}}}function zc(r,t,e,a){let i={style:r,onInit:e.onInit,onClick:e.onClick,onCancel:e.onCancel,onError:e.onError};return t&&a?(i.createBillingAgreement=a.createBillingAgreement,i.onApprove=a.onApprove):i.onApprove=e.onApprove,i}function jc(r){if(!r)return;let t={first_name:r.firstName,last_name:r.lastName,address_line_1:r.addressLine1??"",address_line_2:r.addressLine2,city:r.city??"",state:r.state,postal_code:r.postalCode??"",country_code:r.countryCode??""},{address_line_1:e,city:a,postal_code:i,country_code:n}=t;if(!(!e||!a||!i||!n))return t}function Wc(r){if(!r)return null;let t=r.purchase_units?.[0]?.shipping;if(!t?.address)return null;let e=t.address,a=t.name;return{firstName:a?.given_name,lastName:a?.surname,addressLine1:e.address_line_1,addressLine2:e.address_line_2,city:e.admin_area_2,state:e.admin_area_1,postalCode:e.postal_code,countryCode:e.country_code}}function Zc(r,t,e){let{order:{currencyCode:a,merchantAmount:i,totalOrderAmount:n,shipping:o,lineItems:s=[],fees:l=[]},customer:c}=r;if(!a)throw new G({message:"Currency code is not provided",code:It.MISSING_PARAMETER,paymentMethod:e});let m={amount:i??n,currencyCode:a,paymentMethodConfigId:t,amountBreakdown:{}},g=c?.shippingAddress,h=jc(g);h&&(m.shipping_address=h);let T=!s.some(M=>!M.name&&!M.description);if(T&&(m.items=s.map(M=>{let{name:_,description:x,taxAmount:E,amount:L,quantity:K}=M,j=E?Math.floor(E/K):0;return{name:x||_||"",unit_amount:{value:L,currency_code:a},quantity:K.toString(),tax:{value:j,currency_code:a}}})),T&&s.length){let M=s.reduce((de,{amount:U,quantity:De})=>de+U*De,0),_=l?.reduce?.((de,{amount:U})=>de+(U??0),0),x=s?.reduce((de,{discountAmount:U})=>de+(U??0),0),E=s?.reduce((de,{taxAmount:U})=>de+(U??0),0),L=o?.amount??0,K=_??0,j=M+E+L+K-x;m.amountBreakdown={item_total:{value:M,currency_code:a},tax_total:{value:E,currency_code:a},handling:{value:K,currency_code:a},shipping:{value:L,currency_code:a},discount:{value:x,currency_code:a}},m.amount=j}return m}async function Jc({context:r,configId:t,paymentMethodType:e,callbacks:a,skipOnStartCallback:i=!1}){try{if(!i){let{action:s}=await a.onStart();if(s==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:e})}let{data:n,error:o}=await r.coreApi.createPaypalOrder(Zc(r.configuration.clientSession,t,e));if(o||!n){let s=o?.message??"Unable to create PayPal order";throw new G({message:s,code:F.PAYMENT_FAILED,paymentMethod:e})}return n.orderId}catch(n){throw a.onFinish(void 0,n),n}}async function qc({context:r,paymentMethodType:t,callbacks:e,data:a,actions:i,deferredOnStartCallback:n=!1}){if(n){let{action:g}=await e.onStart();if(g==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:t})}let o=null;try{o=await i?.order?.get()??null}catch(g){C.warn("Failed to get PayPal order details",g)}let s=Wc(o),l={external_payer_info:{email:o?.payer?.email_address,external_payer_id:a.payerID??void 0,first_name:o?.payer?.name?.given_name,last_name:o?.payer?.name?.surname},paypal_order_id:a.orderID,paypal_status:o?.status};s&&(l.shipping_address=s);let{error:c,data:m}=await r.pciApi.postPaypalPaymentInstruments(l);if(c||!m){let g=c?.message??"Unable to create payment instrument";throw new z({message:g,code:F.TOKENIZATION_ERROR,paymentMethod:t})}e.onFinish(m)}var Qc=["buttons","funding-eligibility"],xn=[],_n="paypal";function yo(r){if(!r?.length)return;r.includes(_n)&&C.warn("PayPal: Cannot disable paypal funding source");let t=r.filter(e=>e!==_n);return t.length>0?t:void 0}var Xc="authorize";function eu(r,t,e){return(r??t==="PREFER_VAULT")&&e}function wn({isVaultFlow:r,configIntent:t}){return r?"tokenize":t??Xc}function tu(r,t,e,a){let{clientId:i,intent:n}=t.options,o=r.configuration.clientSession.order.currencyCode,s=r.clientOptions.paypal?.disableFunding??(xn.length>0?xn:void 0),l=yo(s),c=r.clientOptions?.paypal?.enableFunding,m={dataNamespace:e,clientId:i,currency:o,components:Qc,...l&&l.length>0?{disableFunding:l}:{},...c&&c.length>0?{enableFunding:c}:{},integrationDate:r.clientOptions.paypal?.integrationDate,debug:r.clientOptions.paypal?.debug};return(si||r.decodedClientToken.env==="SANDBOX"||r.decodedClientToken.env==="STAGING")&&(m.buyerCountry=r.clientOptions?.paypal?.buyerCountry),a?(m.vault="true",m.intent=wn({isVaultFlow:!0,configIntent:n})):(m.vault="false",m.intent=wn({isVaultFlow:!1,configIntent:n})),m}var Za=class extends mt{constructor(e,a){super(e,a);k(this,"paypalInstance");k(this,"dataNamespace");k(this,"isVaultFlow",!1);k(this,"isSetupComplete",!1);k(this,"setupPromise");k(this,"eligibleFundingSources",[]);k(this,"currentFundingSource",null);k(this,"onStartDeferred",!1);k(this,"disabled",!1);this.dataNamespace=kn.getOrCreateNamespace(e.id),this.context.onClientConfigurationUpdate(async()=>{C.info("PayPal: Client session updated, refreshing PayPal buttons");try{await this.setup()}catch(i){C.warn("PayPal: Failed to refresh on client session update:",i)}})}async setDisabled(e){this.disabled=e}async tokenize(){throw new z({message:"PayPal does not support direct tokenization",code:F.TOKENIZATION_ERROR,paymentMethod:B.PAYPAL})}async setup(){let{clientId:e}=this.config.options;return this.setupPromise?(C.info("PayPal setup already in progress, waiting..."),this.setupPromise):this.isSetupComplete&&this.paypalInstance?.Buttons?(C.info("PayPal setup already completed, skipping"),!0):e?(this.setupPromise=(async()=>{try{let a=this.context.clientOptions.paypal?.vault,i=this.context.clientOptions.paypal?.paymentFlow,n=this.context.configuration.clientSession.paymentMethod?.vaultOnSuccess??!1;this.isVaultFlow=eu(a,i,n);let o=tu(this.context,this.config,this.dataNamespace,this.isVaultFlow);C.debug("%c PAYPAL %c Script Configuration ","background: #0070BA; color: #ffffff; font-weight: bold; padding: 4px 12px; border-radius: 3px 0 0 3px; font-size: 14px;","background: #003087; color: #ffffff; padding: 4px 12px; border-radius: 0 3px 3px 0; font-size: 14px;",o);let s=await Lc(o);if(!s)return C.warn("Failed to load PayPal SDK"),!1;this.paypalInstance=s,kn.storeInstance(this.config.id,s,this.dataNamespace);let l=this.context.clientOptions.paypal?.enableFunding,c=yo(this.context.clientOptions.paypal?.disableFunding),g=(s.getFundingSources?.()??[]).filter(h=>s?.isFundingEligible?.(h));return C.debug("PayPal: Eligible funding sources from PayPal SDK:",g),this.eligibleFundingSources=this.filterFundingSources(g,l,c),(l?.length||c?.length)&&(C.debug("PayPal: Primer SDK options:",{enableFunding:l??[],disableFunding:c??[]}),C.debug("PayPal: Funding sources after Primer SDK filter:",this.eligibleFundingSources)),this.eligibleFundingSources.length===0?(C.warn("PayPal: No funding sources are eligible with current configuration"),!1):!0}catch(a){return C.warn("PayPal setup failed:",{error:a}),this.setupPromise=void 0,!1}})(),this.setupPromise):(C.warn("PayPal clientId is required"),!1)}async render(e,a){let{Buttons:i}=this.paypalInstance;if(!i)throw new G({message:"PayPal Buttons component not available",code:It.INVALID_USAGE,paymentMethod:B.PAYPAL});let n=this.context.clientOptions.paypal?.style,o=a?.style?.buttonHeight,s=n?.layout===ho,l={onInit:this.handleInit.bind(this),onClick:this.handleClick.bind(this),onApprove:this.handleApprove.bind(this),onCancel:this.handleCancel.bind(this),onError:this.handleError.bind(this)},c=this.isVaultFlow?{createBillingAgreement:()=>xc({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks}),onApprove:M=>_c({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks,data:M})}:void 0,m=this.eligibleFundingSources,g=[];for(let M of m){let _=$c(n,M,o),x=zc(_,this.isVaultFlow,l,c);this.isVaultFlow||(x.createOrder=this.handleCreateOrder.bind(this));let E=i({...x,fundingSource:M});E.isEligible()?g.push({button:E,fundingSource:M}):C.debug(`PayPal: Button for "${M}" is not eligible with current config`)}if(g.length===0)throw C.warn("PayPal: No buttons were eligible to render with current configuration"),new G({message:"No PayPal buttons eligible to render",code:It.INVALID_USAGE,paymentMethod:B.PAYPAL});let h=s&&g.length>Ln?this.selectButtonsForHorizontalLayout(g):g;s&&this.applyHorizontalLayoutStyles(e,h.length);let T=h.map(({button:M})=>M.render(e));await Promise.all(T)}selectButtonsForHorizontalLayout(e){let a=new Set(Rn),i=Rn.map(o=>e.find(s=>s.fundingSource===o)).filter(o=>o!==void 0),n=e.filter(o=>!a.has(o.fundingSource));return[...i,...n].slice(0,Ln)}applyHorizontalLayoutStyles(e,a){e.style.display="grid",e.style.gridTemplateColumns=`repeat(${a}, 1fr)`,e.style.gap="10px"}handleInit(e,a){let{clientSession:i}=this.context.configuration,n=!!i.order.currencyCode,o=!!i.order.totalOrderAmount||!!i.order.merchantAmount;if(!n||!o){C.warn("PayPal button disabled: missing currency or amount"),a.disable();return}a.enable()}handleClick(e,a){return this.currentFundingSource=e.fundingSource??null,kt({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:"PAYPAL"}),a.resolve()}async handleCreateOrder(){let e=this.currentFundingSource==="card";return this.onStartDeferred=e,Jc({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks,skipOnStartCallback:e})}async handleApprove(e,a){let i=this.onStartDeferred;return this.onStartDeferred=!1,qc({context:this.context,paymentMethodType:this.config.type,callbacks:this.callbacks,data:e,actions:a,deferredOnStartCallback:i})}handleCancel(){this.context.clientSessionApi.unselectPaymentMethod(),this.callbacks.onFinish(void 0,new G({message:"The PayPal payment was cancelled by the user.",paymentMethod:B.PAYPAL}))}handleError(e){C.errorWithDatadog("PayPal error:",e),this.callbacks.onFinish(void 0,e)}filterFundingSources(e,a,i){return e.filter(n=>!(a?.length&&!a.includes(n)||i?.includes(n)))}};function Dn(r,t,e){if(!r)return null;let a={id:r.id,orderId:r.orderId};return t?.paymentInstrumentData&&e&&(a.paymentMethodData={paymentMethodType:e,...t.paymentInstrumentData}),a}var fo=(r,t,e,a,i)=>{let n=e;if(t?.status==="FAILED"&&(n=new G({code:F.PAYMENT_FAILED,message:`The payment "${t.id}" was created but failed to be processed. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.checkoutOutcome==="CHECKOUT_FAILURE"&&(n=new G({code:F.PAYMENT_FAILED,message:`The payment "${t.id}" was created but failed to be processed. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.status==="PENDING"&&!t.requiredAction?.clientToken&&(n=new G({code:F.PAYMENT_FAILED,message:`The payment "${t.id}" ended up in a "PENDING" state without any required action. The SDK does not know how to handle this state. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.status==="SUCCESS"&&t.checkoutOutcome!=="CHECKOUT_FAILURE"||t?.status==="PENDING"&&t.showSuccessCheckoutOnPendingPayment||t?.checkoutOutcome==="CHECKOUT_COMPLETE")return void r.onCheckoutComplete?.({payment:Dn(t,a,i)});r.onCheckoutFail?.(n||new G({code:F.PAYMENT_FAILED,message:`The payment${t?.id?` "${t.id}"`:""} is in an inconsistent state without any required action. The SDK does not know how to handle this state. Please contact Primer.`}),{payment:Dn(t,a,i)??void 0})},au=async(r,t)=>{let e=t.config.type;if(!r.onBeforePaymentCreate)return{action:"continue"};let a=setTimeout(()=>{C.warn("onBeforePaymentCreate did not resolve within 10 seconds. Primer SDK will remain in a loading state until `continuePaymentCreation` or `abortPaymentCreation` is called.")},1e4);return new Promise(i=>{r.onBeforePaymentCreate({paymentMethodType:e},{continuePaymentCreation:n=>{clearTimeout(a),C.log(`Continuing payment creation for ${e}`),n?.idempotencyKey&&t.setIdempotencyKey(n.idempotencyKey),r.onPaymentCreationStart?.(),i({action:"continue"})},abortPaymentCreation:()=>{clearTimeout(a),C.log(`Aborting payment creation for ${e}`),i({action:"abort"})}})})};async function ma(r,t,e){if(t.setCallbacks({onStart:()=>(t.context.clientSessionApi.selectPaymentMethod(t.config.type),kt({eventName:"PAYMENT_PROCESSING_STARTED",paymentMethod:t.config.type}),au(r,t)),onFinish:(a,i)=>{Bn(r,t,a,i)}}),!e)return t.start();{let a,i;try{i=await t.tokenizeVaulted(e.id)}catch(n){a=n}return Bn(r,t,i,a)}}async function Bn(r,t,e,a){let i;if(e&&!a)try{i=await t.createPayment(e),i.status!=="FAILED"&&(i=await t.handleRequiredAction(i))}catch(n){a=n}fo(r,i,a,e,t.config.type)}var On=Symbol("PROXY_MARKER");function bi({namespace:r,onMessage:t,sendMessage:e}){function a(i,n){return new Proxy(i,{get(o,s,l){if(s==="then")return null;if(o[On])return Reflect.get(o,s,l);let c=()=>{};return c[On]=!0,a(c,[...n,s])},apply(o,s,l){return new Promise(async(c,m)=>{try{let g=[],h=l.map(x=>{if(typeof x!="function")return x;{let E=Te();return g.push(E),t(L=>{L.namespace===r&&L.sender===Xr.PROVIDER&&L.type===Qr.CALLBACK&&L.id===E&&x(...L.data)}),E}}),T=Te(),M=t(x=>{x.namespace===r&&x.sender===Xr.PROVIDER&&x.type===Qr.APPLY&&x.id===T&&(x.error?m(new Error(x.error)):c(x.data),M?.())}),_={type:Qr.APPLY,sender:Xr.INJECTOR,id:T,path:n,args:h,callbackIds:g,timeStamp:Date.now(),namespace:r};e(_)}catch(g){m(g)}})}})}return a({},[])}var Qr={APPLY:"apply",CALLBACK:"callback"},Xr={PROVIDER:"provider",INJECTOR:"injector"};function li(r,t){let e=t?.input?.base?.height;e&&(r.style.height=typeof e=="number"?`${e}px`:e)}function ru(r,t,e,a={}){let i=r.cardholderName?.defaultValue??r.card?.cardholderName?.defaultValue,n=uo(t.checkoutSessionId,{cardholderName:i});e.iframes=n;let o=[],s="LOCAL",l={[ce.cardNumber]:void 0,[ce.cardExpiryDate]:void 0,[ce.cardSecurityCode]:void 0,[ce.cardholderName]:void 0},c=!1;t.subscribeToTeardown(()=>{c=!0});let m={createHostedInputs:()=>{let g=h=>{let T=new Map;return{getOptions:()=>{},setOptions:M=>{li(e.iframes[h],M.style),e.iframes[h].setAttribute("title",M.ariaLabel||""),l[h]?.setOptions(M)},render:(M,_)=>{let x=e.iframes[h];if(!x)return C.errorWithDatadog(`No iframe found for ${h}`),Promise.resolve();let E;return E=typeof M=="string"?document.getElementById(M):M,E?(li(x,_.style),E.appendChild(x),new Promise(L=>{x.onload=()=>{if(c){C.warn(`Teardown was already called, aborting render for ${h}`),x.remove(),L();return}l[h]=bi({namespace:`${t.checkoutSessionId}-${h}`,onMessage:U=>{let De=oa=>U(oa.data);return window.addEventListener("message",De),()=>window.removeEventListener("message",De)},sendMessage:U=>{x.contentWindow.postMessage(U,"*")}}),e.iframes[h].setAttribute("title",_.ariaLabel||"");let K=r.cardholderName??r.card?.cardholderName,{defaultValue:j,...de}=K??{};l[h].setOptions({..._,orderedAllowedCardNetworks:t.configuration.clientSession.paymentMethod.orderedAllowedCardNetworks,cardholderName:de}),l[h].setBinDataLoadingChange(U=>{U&&a.onCardNetworksLoading?.(),a.onBinDataLoadingChange?.(U)}),l[h].setOnBlur(()=>{try{T.get("blur")?.()}catch(U){C.errorWithDatadog(`Blur listener error for ${h}`,{error:U})}}),l[h].setOnFocus(()=>{try{T.get("focus")?.()}catch(U){C.errorWithDatadog(`Focus listener error for ${h}`,{error:U})}}),l[h].setOnInput(U=>{let De={...U,errorCode:U.error,active:U.focused};try{T.get("input")?.(De),T.get("change")?.(De)}catch(oa){C.errorWithDatadog(`Input listener error for ${h}`,{error:oa})}}),l[h].setOnEnter(()=>{try{T.get("enter")?.()}catch(U){C.errorWithDatadog(`Enter listener error for ${h}`,{error:U})}}),h===ce.cardNumber&&(l[h].setBinDataApiConfig(t.configuration.binDataUrl,t.decodedClientToken.accessToken),l[h].setOnCardNetworksChange((U,De,oa)=>{if(De!==s||iu(o,U)){o=U,s=De;let{cardNetworkChangeEventData:bd,binDataAvailableEventData:Ad}=yc({networks:o,source:s},t.configuration.clientSession.paymentMethod.orderedAllowedCardNetworks);a.onCardNetworksChange?.(bd),a.onBinDataAvailable?.({...Ad,firstDigits:oa})}}))},L()})):(C.error(`Container not found for ${h}:`,M),Promise.resolve())},addEventListener:(M,_)=>{T.set(M,_)},focus:()=>{let M=e.iframes[h];if(M&&M.contentWindow)try{l[h]?.focus()}catch(_){C.errorWithDatadog(`Focus send error for ${h}`,{error:_})}else C.warn(`Focus failed for ${h} - iframe not available`)},blur:()=>{let M=e.iframes[h];if(M&&M.contentWindow)try{l[h]?.blur()}catch(_){C.errorWithDatadog(`Blur send error for ${h}`,{error:_})}},setDisabled:M=>{l[h]?.setDisabled(M)}}};return{cardNumberInput:g(ce.cardNumber),cardholderNameInput:g(ce.cardholderName),expiryInput:g(ce.cardExpiryDate),cvvInput:g(ce.cardSecurityCode)}},removeHostedInputs:()=>{c=!0,e.iframes.cardNumber.remove(),e.iframes.cardSecurityCode.remove(),e.iframes.cardExpiryDate.remove(),e.iframes.cardholderName.remove()},submit:async g=>{if((await m.validate()).valid)return await t.apiController.setPreferredNetwork(g?.cardNetwork),ma(r,e)},validate:async()=>{let g=(await Promise.all(Object.entries(l).map(([T,M])=>M?.getFieldState().then(_=>[T,_]).catch(()=>{})))).filter(T=>T!==void 0),h=[];for(let[T,M]of g)!M.valid&&M.error&&h.push({field:T,name:T,error:M.error,message:M.error});return{valid:h.length===0,validationErrors:h}},reset:()=>{Object.values(l).forEach(g=>{g?.reset()}),t.apiController.setPreferredNetwork(void 0)},setCardholderName:g=>{try{l[ce.cardholderName]?.setCardholderName(g)}catch(h){C.errorWithDatadog("SetCardholderName error",{error:h})}}};return m}function iu(r,t){if(r.length!==t.length)return!0;let e=t.map(({network:a})=>a);return!r.every(({network:a})=>e.includes(a))}function nu(r,t,e){return{createButton:()=>({render:async(a,i)=>{await ma(r,e);let n=typeof a=="string"?document.getElementById(a):a;if(!n)throw new G({code:qd.CONTAINER_NOT_FOUND,message:`Container with id "${a}" not found in the DOM.`});await e.render(n,i)},setDisabled:a=>e.setDisabled(a)})}}function ou(r,t,e){return{start:()=>ma(r,e)}}function su(r,t,e){return{start:async a=>(a?.blikCode&&e.setBlikCode(a.blikCode),ma(r,e))}}function lu(r,t){return{"Content-Type":"application/json","primer-client-token":r,"primer-sdk-client":"WEB","primer-sdk-version":"0.0.0-local","primer-sdk-checkout-session-id":t,"x-api-version":"2.4"}}function du(r,t,e){if(e?.status&&e.status>=400&&e.status<500)return!1;if(e?.status&&e.status>=500)return!0;if(r instanceof Error){let a=r.message.toLowerCase();return a.includes("network")||a.includes("timeout")||a.includes("connection")}return!1}function cu(r){let n=1e3*Math.pow(1.1,r),o=.1*n*(Math.random()-.5);return n=Math.max(0,n+o),Math.min(n,3e4)}var uu={attempts:3,retryCondition:du,delayCalculator:cu,totalTimeout:3e5};async function pu(r,t,e){let a={...uu,...t.retry},i=[],n=Date.now();for(let s=0;s<=a.attempts;s++)try{let l=await r();if(!l.error)return{...l,retryHistory:i.length>0?i:void 0};if(s===a.attempts||!a.retryCondition(l.error,s,l))return{...l,retryHistory:i};let c=a.delayCalculator(s);if(i.push({attempt:s+1,delay:c,error:l.error,timestamp:Date.now()}),Date.now()-n+c>a.totalTimeout)return{...l,error:new Be({message:`Retry total timeout exceeded for ${t.method} ${e}`,code:pa({status:408}),response:l}),retryHistory:i};await Yt(c)}catch(l){i.push({attempt:s+1,delay:0,error:new Be({message:`Request failed for ${t.method} ${e}`,code:q.UNEXPECTED,error:l,response:{id:t.id}}),timestamp:Date.now()})}let o=i[i.length-1]?.error;return{id:t.id,error:o,retryHistory:i}}var zt=class{constructor(t,e="",a={}){k(this,"fetch");k(this,"baseUrl");k(this,"defaultHeaders");this.fetch=t,this.baseUrl=e,this.defaultHeaders=Object.freeze({...a})}setDefaultHeader(t,e){this.defaultHeaders={...this.defaultHeaders,[t]:e}}async executeFetch(t,e){let a={...e,headers:{...this.defaultHeaders,...e?.headers},id:Te()};return e?.retry?pu(()=>this.fetch(t,{...a,retry:void 0}),a,t):this.fetch(t,a)}async get(t,e){return this.executeFetch(t,{...e,method:"GET"})}async post(t,e,a){return this.executeFetch(t,{...a,method:"POST",body:JSON.stringify(e)})}async delete(t,e){return this.executeFetch(t,{...e,method:"DELETE"})}};async function mu(r,t){let e=t.id??Te(),a={id:e};t.headers??(t.headers={}),t.headers["X-Request-Id"]=e;try{let i=await fetch(r,t);if(a.data=await i.json(),a.status=i.status,a.headers=Object.fromEntries(i.headers.entries()),!i.ok){let n=new Be({message:`Request failed for ${t.method} ${r}`,code:pa({backendErrorId:a.data?.error?.errorId,status:a.status}),response:{...a}});a.error=n}}catch(i){let n=new Be({message:`Request failed for ${t.method} ${r}`,code:pa({status:a.status}),response:{...a},error:i});a.error=n}return a}var di=class extends zt{constructor(){super(...arguments);k(this,"configurationSubscribers",new Set);k(this,"_configuration")}async getConfiguration(){let e=await this.get(this.baseUrl);return e.data&&(this._configuration=e.data),e}subscribe(e){return this.configurationSubscribers.add(e),()=>{this.configurationSubscribers.delete(e)}}get configuration(){return this._configuration}set configuration(e){this._configuration=e,this.configurationSubscribers.forEach(a=>a(this._configuration))}},ci=class extends zt{async getPaymentInstruments(){return this.get(`${this.baseUrl}/payment-instruments`)}async postCardPaymentInstruments(){return this.post(`${this.baseUrl}/payment-instruments`,"pci-card-form-data")}async postPaypalPaymentInstruments(t,e){return this.post(`${this.baseUrl}/payment-instruments`,{paymentInstrument:t,...e})}async postPaymentInstruments(t){return this.post(`${this.baseUrl}/payment-instruments`,{paymentInstrument:t})}async postRedirectPaymentInstruments(t){return this.postPaymentInstruments(t)}async postApplePayPaymentInstruments(t){return this.postPaymentInstruments(t)}async postGooglePayPaymentInstruments(t){return this.postPaymentInstruments(t)}async postBlikPaymentInstruments(t){return this.postPaymentInstruments(t)}async postPaymentInstrumentsExchange(t){return this.post(`${this.baseUrl}/payment-instruments/${t}/exchange`,"payment-instrument-exchange")}async postCreatePayment(t,e){return this.post(`${this.baseUrl}/payments`,{paymentMethodToken:t},e?{headers:{"X-Idempotency-Key":e}}:void 0)}async postResumePayment(t,e){return this.post(`${this.baseUrl}/payments/${t}/resume`,{resumeToken:e})}async post3dsAuth(t,e){return this.post(`${this.baseUrl}/3ds/${t}/auth`,e,{retry:{attempts:15}})}async post3dsContinue(t){return this.post(`${this.baseUrl}/3ds/${t}/continue`,{platform:"WEB",status:"FAILURE"})}async get3dsResumeStatus(t){return this.get(t)}async deletePaymentInstrument(t){return this.delete(`${this.baseUrl}/payment-instruments/${t}/vault`)}async postClientSessionActions(t){return this.post(`${this.baseUrl}/client-session/actions`,{actions:t})}async getResumeStatus(t){return this.get(t)}};async function hu(r){return new Promise((t,e)=>{let a=co(r,"api"),i=`${mc}#${a}`,n=document.querySelector(`iframe[src="${i}"]`)??document.createElement("iframe");n.parentElement?t(n):(n.style.display="none",n.onload=()=>t(n),n.onerror=o=>{e(new Error(`Failed to initialize Primer SDK: ${o}`))},n.src=i,document.body.appendChild(n))})}var Nt=class Nt extends zt{constructor(){super(...arguments);k(this,"onClientSessionUpdate");k(this,"onPaymentMethodAction");k(this,"selectedPaymentMethodType",null)}setOnClientSessionUpdate(e){this.onClientSessionUpdate=e}setOnPaymentMethodAction(e){this.onPaymentMethodAction=e}async postClientSessionActions(e){if(e.length===0)return Nt.noActionsResponse;let a=await this.post(`${this.baseUrl}/client-session/actions`,{actions:e}),{data:i}=a;return i&&this.onClientSessionUpdate?.(i),a}async selectPaymentMethod(e,a={}){return this.selectedPaymentMethodType===e||(this.selectedPaymentMethodType=e,this.onPaymentMethodAction?.("PAYMENT_METHOD_SELECTED",{paymentMethodType:e}),e==="PAYMENT_CARD"&&!a.binData)?Nt.noActionsResponse:this.postClientSessionActions([{type:"SELECT_PAYMENT_METHOD",params:{...a,paymentMethodType:e}}])}async unselectPaymentMethod(){return this.onPaymentMethodAction?.("PAYMENT_METHOD_UNSELECTED",{paymentMethodType:this.selectedPaymentMethodType}),this.selectedPaymentMethodType=null,this.postClientSessionActions([{type:"UNSELECT_PAYMENT_METHOD"}])}async selectCardNetwork(e){return this.selectPaymentMethod(B.PAYMENT_CARD,{binData:this.buildCardBinData(e)})}async setBillingAddress(e){let a=this.removeEmptyStringFromObject(e);return Object.values(a).length===0?Nt.noActionsResponse:this.postClientSessionActions([{type:"SET_BILLING_ADDRESS",params:{billingAddress:a}}])}async setShippingAddress(e,a,i){let n=[];return e&&Object.keys(e).some(s=>!!e[s])&&n.push({type:"SET_SHIPPING_ADDRESS",params:{shippingAddress:e}}),a&&n.push({type:"SET_MOBILE_NUMBER",params:{mobileNumber:a}}),i&&n.push({type:"SET_EMAIL_ADDRESS",params:{emailAddress:i}}),this.postClientSessionActions(n)}async selectShippingMethod(e){return this.postClientSessionActions([{type:"SELECT_SHIPPING_METHOD",params:{shippingMethodId:e}}])}async setCustomerDetails({emailAddress:e,firstName:a,lastName:i}){let n=[];return e&&n.push({type:"SET_EMAIL_ADDRESS",params:{emailAddress:e}}),a&&n.push({type:"SET_CUSTOMER_FIRST_NAME",params:{firstName:a}}),i&&n.push({type:"SET_CUSTOMER_LAST_NAME",params:{lastName:i}}),this.postClientSessionActions(n)}buildCardBinData(e){let{backend:a}=Ja(e);return{network:a,issuer_name:null,product_code:a,product_name:a,product_usage_type:"UNKNOWN",account_number_type:"UNKNOWN",issuer_country_code:null,account_funding_type:"UNKNOWN",issuer_currency_code:null,regional_restriction:"UNKNOWN",prepaid_reloadable_indicator:"NOT_APPLICABLE"}}removeEmptyStringFromObject(e){let a={...e};for(let i in a)a[i]===""?delete a[i]:typeof a[i]=="object"&&a[i]!==null&&!Array.isArray(a[i])&&(a[i]=this.removeEmptyStringFromObject(a[i]));return a}};k(Nt,"noActionsResponse",{data:{},error:void 0,headers:{},status:200,id:""});var ui=Nt,pi=class extends zt{async createPaypalOrder(t){return this.post(`${this.baseUrl}/paypal/orders/create`,t,{retry:{attempts:3}})}async createPaypalBillingAgreement(t){return this.post(`${this.baseUrl}/paypal/billing-agreements/create-agreement`,t,{retry:{attempts:3}})}async confirmPaypalBillingAgreement(t){return this.post(`${this.baseUrl}/paypal/billing-agreements/confirm-agreement`,t,{retry:{attempts:3}})}async createApplePaySession(t){return this.post(`${this.baseUrl}/apple-pay/sessions`,t)}};async function gu(r,{locale:t,dialogProvider:e,translate:a,clientOptions:i}){let n=Te(),o=Ht(r),s=await hu(n),l=bi({namespace:`api-controller-${n}`,onMessage:E=>{let L=K=>{if(K.data?.data?.error?.name==="RequestError"){let j=Object.assign(new Be({...K.data.data.error}),K.data.data.error);typeof j.error=="object"&&"message"in j.error&&(j.error=Object.assign(new Error(j.error.message),{stack:j.error.stack})),K.data.data.error=j}return E(K.data)};return window.addEventListener("message",L),()=>window.removeEventListener("message",L)},sendMessage:E=>{s.contentWindow.postMessage(E,"*")}}),c=lu(o.accessToken,n),m=new di(mu,o.configurationUrl,c),g=Date.now(),{error:h}=await m.getConfiguration();if(h||!m.configuration)throw new Error(`Failed to fetch configuration: ${h}`);let T=new ci(l.fetch,m.configuration.pciUrl,c),M=new pi(l.fetch,m.configuration.coreUrl,c),_=new ui(l.fetch,m.configuration.pciUrl,c);_.setOnClientSessionUpdate(E=>{m.configuration=E});let x=new Set;return{get configuration(){return m.configuration},onClientConfigurationUpdate(E){return m.subscribe(E)},checkoutSessionId:n,apiController:l,configurationApi:m,pciApi:T,coreApi:M,clientSessionApi:_,dialogProvider:e,decodedClientToken:o,locale:t||navigator.language||navigator.languages[0]||"en",configurationFetchStartTime:g,translate:a??((E,L)=>L),clientOptions:i,updateClientToken(E){try{let L=Ht(E);m.setDefaultHeader("primer-client-token",L.accessToken),T.setDefaultHeader("primer-client-token",L.accessToken),M.setDefaultHeader("primer-client-token",L.accessToken),_.setDefaultHeader("primer-client-token",L.accessToken)}catch{}},async refreshClientConfiguration(){let{data:E,error:L}=await m.getConfiguration();return L||!E?(C.warn("Failed to refresh client configuration:",L),!1):(m.configuration=E,!0)},subscribeToTeardown(E){return x.add(E),()=>{x.delete(E)}},teardown(){s.remove(),x.forEach(E=>E())}}}var yu=100;function fu({height:r,name:t,url:e="",width:a}){let i=new Set,n=window.open(e,t,Su({height:r,width:a}));if(!n)return;function o(){n?.close(),s()}function s(){i.forEach(l=>l()),i.clear(),window.removeEventListener("beforeunload",o)}return window.addEventListener("beforeunload",o),vu(n).then(s),{close:o,focus(){n.focus()},get isOpen(){return n?.closed===!1},onClose(l){return i.add(l),()=>{i.delete(l)}},setContent(l){n.document.write(l)},setUrl(l){n.location.replace(l)}}}var vu=r=>new Promise(t=>{let e=setInterval(()=>{r.closed&&(clearInterval(e),t())},yu)});function Su(r){let t=bu({parent:{left:window.screenLeft,top:window.screenTop,height:window.outerHeight,width:window.outerWidth},popup:r});return Au(t)}var bu=({parent:r,popup:t})=>({left:r.left+(r.width-t.width)/2,top:r.top+(r.height-t.height)/2,height:t.height,width:t.width}),Au=r=>Object.entries(r).map(t=>t.join("=")).join(","),Cu=({name:r,background:t,logoSrc:e,logoAlt:a,message:i})=>`<html>
|
|
36
|
+
`,e.appendChild(i);let n=document.createElement("apple-pay-button"),o=this.clientOptions?.buttonStyle??this.clientOptions?.buttonOptions?.buttonStyle;o&&n.setAttribute("buttonstyle",o);let s=this.clientOptions?.buttonType??this.clientOptions?.buttonOptions?.type??"plain";s&&n.setAttribute("type",s),n.setAttribute("locale",this.context.locale),n.addEventListener("click",this.handleClick.bind(this)),document.body.appendChild(n),setTimeout(()=>{e.appendChild(n)},0)}async handleClick(){if(!this.disabled)try{this.onStartPromise=this.callbacks.onStart(),kt({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:B.APPLE_PAY}),this.applePaySession=new ApplePaySession(An,uc(this.context,this.config)),this.applePaySession.onvalidatemerchant=this.handleValidateMerchant.bind(this),this.applePaySession.onpaymentauthorized=this.handlePaymentAuthorized.bind(this),this.applePaySession.onpaymentmethodselected=this.handlePaymentMethodSelected.bind(this),this.applePaySession.onshippingcontactselected=this.handleShippingContactSelected.bind(this),this.applePaySession.onshippingmethodselected=this.handleShippingMethodSelected.bind(this),this.applePaySession.oncancel=this.handleCancel.bind(this),this.applePaySession.begin()}catch(e){C.errorWithDatadog("Error initiating Apple Pay session",{error:e})}}async handleValidateMerchant(e){if(this.applePaySession)try{let{action:a}=await this.onStartPromise;if(a==="abort")return void this.abort(new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let{data:i,error:n}=await this.context.coreApi.createApplePaySession({validationUrl:e.validationURL,paymentMethodConfigId:this.config.id,merchantDomain:this.context.clientOptions.merchantDomain??window.location.hostname});if(!this.applePaySession)return;if(n||!i)throw n??new G({message:"Failed to validate merchant",code:q.REQUEST_ERROR,paymentMethod:B.APPLE_PAY});this.applePaySession.completeMerchantValidation(i)}catch(a){C.warn("Apple Pay merchant validation failed:",a),this.abort()}}async handlePaymentMethodSelected(e){if(this.applePaySession)try{this.applePaySession.completePaymentMethodSelection(Jr(this.context,this.config))}catch(a){C.errorWithDatadog("Error handling payment method selection",{error:a}),this.abort()}}async handlePaymentAuthorized(e){if(!this.applePaySession)return;let a=[new ApplePayError("unknown",void 0,this.context.translate(ca.UNKNOWN_ERROR,ua.UNKNOWN_ERROR))];try{if(this.clientOptions?.billingOptions?.requiredBillingContactFields?.includes("postalAddress")){let s=Zr(e.payment.billingContact);if(s){if(!s.firstName||!s.lastName)throw a=[new ApplePayError("billingContactInvalid","name",this.context.translate(ca.MISSING_FIRST_OR_LAST_NAME,ua.MISSING_FIRST_OR_LAST_NAME))],new G({message:"Billing contact must include first and last name",code:It.MISSING_PARAMETER,paymentMethod:B.APPLE_PAY,suggestion:"Ensure Apple Pay requiredBillingContactFields includes name fields"});let{error:l}=await this.context.clientSessionApi.setBillingAddress(s);l&&C.errorWithDatadog("Error setting billing address from Apple Pay",{error:l})}}let i=Zr(e.payment.shippingContact);if(i){let{error:s}=await this.context.clientSessionApi.setShippingAddress(i,e.payment.shippingContact?.phoneNumber,e.payment.shippingContact?.emailAddress);if(s)throw s}let{data:n,error:o}=await this.context.pciApi.postApplePayPaymentInstruments({paymentMethodConfigId:this.config.id,token:e.payment.token});if(o||!n)throw a=[new ApplePayError("unknown",void 0,this.context.translate(ca.FAILED_TO_TOKENIZE,ua.FAILED_TO_TOKENIZE))],o??new Error("Failed to tokenize Apple Pay payment");this.applePaySession.completePayment(ApplePaySession.STATUS_SUCCESS),this.callbacks.onFinish(n),this.applePaySession=null}catch(i){let n=i instanceof G||i instanceof z?i:new G({message:"Error handling payment authorization",code:F.PAYMENT_FAILED,paymentMethod:B.APPLE_PAY,error:i instanceof Error?i:new Error(String(i))});C.errorWithDatadog("Apple Pay payment authorization failed",{error:n}),this.applePaySession&&(this.applePaySession.completePayment({status:ApplePaySession.STATUS_FAILURE,errors:a}),this.applePaySession=null),this.callbacks.onFinish(void 0,n)}}async handleShippingContactSelected(e){if(this.applePaySession)try{let{data:a,error:i}=await this.context.clientSessionApi.setShippingAddress(Zr(e.shippingContact),e.shippingContact?.phoneNumber,e.shippingContact?.emailAddress);if(!this.applePaySession)return;if(!a||i)throw i??new G({message:"Failed to set shipping address",code:q.REQUEST_ERROR,paymentMethod:B.APPLE_PAY});this.applePaySession.completeShippingContactSelection(Jr(this.context,this.config))}catch(a){C.errorWithDatadog("Error handling shipping contact selection",{error:a}),this.abort()}}async handleShippingMethodSelected(e){if(!this.applePaySession)return;let a=this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options;try{if(this.clientOptions?.shippingOptions?.requireShippingMethod&&a){let{data:i,error:n}=await this.context.clientSessionApi.selectShippingMethod(e.shippingMethod.identifier);if(!i||n)throw n??new G({message:"Failed to select shipping method",code:q.REQUEST_ERROR,paymentMethod:B.APPLE_PAY})}if(!this.applePaySession)return;this.applePaySession.completeShippingMethodSelection(Jr(this.context,this.config))}catch(i){C.errorWithDatadog("Error handling shipping method selection",{error:i}),this.abort();return}}handleCancel(){this.applePaySession=null,this.context.clientSessionApi.unselectPaymentMethod(),C.info("Apple Pay payment was cancelled by the user")}abort(e){this.applePaySession?.abort(),this.applePaySession=null,this.callbacks.onFinish(void 0,e??new Error("Apple Pay payment aborted"))}},za=class extends mt{constructor(){super(...arguments);k(this,"blikCode","")}setBlikCode(e){this.blikCode=e}getBlikCode(){return this.blikCode}clearBlikCode(){this.blikCode=""}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let a=await this.tokenize();this.callbacks.onFinish(a)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){if(!/^\d{6}$/.test(this.blikCode))throw new z({message:"BLIK code must be exactly 6 digits",code:F.TOKENIZATION_ERROR,paymentMethod:this.config.type});let e={type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:this.context.locale,platform:ao()?"MOBILE_WEB":"WEB",browserInfo:Si(),blikCode:this.blikCode}};try{let{error:a,data:i}=await this.context.pciApi.postBlikPaymentInstruments(e);if(this.clearBlikCode(),a||!i)throw a??new z({message:"Unable to tokenize BLIK payment method",code:F.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}catch(a){throw this.clearBlikCode(),a}}async createPayment(e){let a=await super.createPayment(e),i=a.requiredAction?.clientToken;if(!i)throw new Be({message:"No client token provided for BLIK payment",code:bn.MISSING_CLIENT_TOKEN,response:{id:a.id,data:a}});let n=Ht(i);if(!this.isValidBlikClientToken(n))throw new Be({message:"Invalid BLIK client token: missing statusUrl or incorrect intent",code:bn.INVALID_CLIENT_TOKEN,response:{id:a.id,data:a}});let{promise:o,abort:s}=this.pollStatus(n.statusUrl),l=await o;if(s(),"error"in l)throw l.error;let c=l.id;if(!c){let m=await this.context.pciApi.getResumeStatus(n.statusUrl);if(m.error||!m.data?.id)throw m.error??new Error("Unable to get resume token");c=m.data.id}return await this.resumePayment(a.id,c)}pollStatus(e){let a=!0,i=1e3,n=864e5,o=Date.now();return{promise:new Promise(async s=>{for(;a;){if(Date.now()-o>=n)return void s({error:new Error("BLIK payment polling timed out after 24 hours")});let{data:l,error:c}=await this.context.pciApi.getResumeStatus(e);if(c)return void s({error:c instanceof Error?c:new Error(String(c))});if(l?.status==="COMPLETE")return void s({id:l.id});await Yt(i)}}),abort:()=>{a=!1}}}isValidBlikClientToken(e){if(typeof e!="object"||e===null)return!1;let a=e;return!(a.intent!=="ADYEN_BLIK_REDIRECTION"||!("statusUrl"in a)||typeof a.statusUrl!="string"||!a.statusUrl)}},lo="https://sdk.primer.io/web/hosted-pages/v0.0.23",si=!1,mc=`${lo}/api-controller.html`,hc=`${lo}/hosted-input.html`,gc="https://goat-assets.production.core.primer.io";function co(r,t,e){let a={checkoutSessionId:r,name:t};e!==void 0&&(a.defaultValue=e);try{return btoa(JSON.stringify(a))}catch{let{defaultValue:n,...o}=a;return btoa(JSON.stringify(o))}}hi("../../node_modules/card-validator/dist/index.js");var ce={cardNumber:"cardNumber",cardSecurityCode:"cardSecurityCode",cardExpiryDate:"cardExpiryDate",cardholderName:"cardholderName"},Mn="cardSecurityCodeRecapture";Object.values(ce);function yc({networks:r,source:t},e){let a=e,i=new Set(a.map(m=>Ja(m).backend)),n=r.map(m=>({...m,allowed:i.has(m.network)})).sort((m,g)=>m.allowed?a.indexOf(m.network)-a.indexOf(g.network):1),o=n.filter(m=>m.allowed),s=t==="REMOTE"&&o.length>1,[l,...c]=n;return{cardNetworkChangeEventData:{detectedCardNetworks:{items:n.map(Oa),preferred:o.length?Oa(o[0]):void 0},...s&&{selectableCardNetworks:{items:o.map(Oa),preferred:o.length?Oa(o[0]):void 0}},source:t},binDataAvailableEventData:{preferred:l,alternatives:c,status:t==="REMOTE"?"complete":"partial"}}}function Oa({network:r,displayName:t,allowed:e}){return{network:r,displayName:t,allowed:e}}function uo(r,t){return{cardNumber:da(r,ce.cardNumber),cardSecurityCode:da(r,ce.cardSecurityCode),cardExpiryDate:da(r,ce.cardExpiryDate),cardholderName:da(r,ce.cardholderName,t?.cardholderName)}}function da(r,t,e){let a=document.createElement("iframe"),i=co(r,t,e);return a.src=`${hc}#${i}`,a.setAttribute("tabindex","0"),a.setAttribute("frameBorder","0"),a.style.border="none",a.style.boxSizing="border-box",a.style.height="20px",a.style.width="100%",a.style.colorScheme="auto",a}var ja=class extends mt{constructor(e,a){super(e,a);k(this,"iframes");this.iframes=uo(a.checkoutSessionId)}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let a=await this.tokenize();this.callbacks.onFinish(a)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){let{error:e,data:a}=await this.context.pciApi.postCardPaymentInstruments();if(e||!a)throw e??new z({code:F.TOKENIZATION_ERROR,message:"Unable to tokenize payment method",paymentMethod:B.PAYMENT_CARD});return a}};function fc(r){if(!r)return{};let t=r.indexOf(" ");return t===-1?{firstName:r}:{firstName:r.substring(0,t),lastName:r.substring(t+1)}}function qr(r){let{firstName:t,lastName:e}=fc(r.name);return{firstName:t||null,lastName:e||null,addressLine1:r.address1||null,addressLine2:r.address2||null,city:r.locality||null,state:r.administrativeArea||null,postalCode:r.postalCode||null,countryCode:r.countryCode||null}}function En(r){return r.map(t=>({id:t.id,label:t.name,description:t.description||""}))}var Tn=2,Pn=0,vc="https://pay.google.com/gp/p/js/pay.js",Sc={AMEX:"AMEX",DISCOVER:"DISCOVER",INTERAC:"INTERAC",JCB:"JCB",MASTERCARD:"MASTERCARD",VISA:"VISA"},Nn=["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],Ga={FEE:"fee_label_fallback",ITEM:"item_label_fallback",SHIPPING:"shipping",SUBTOTAL:"subtotal"},Ka={FEE:"Fee",ITEM:"Item",SHIPPING:"Shipping",SUBTOTAL:"Subtotal"},bc="buy",Ac="black",Cc="fill",Wa=class extends mt{constructor(){super(...arguments);k(this,"disabled",!1);k(this,"client",null)}async setDisabled(e){this.disabled=e}translate(e,a){return this.context.translate?.(e,a)??a}async tokenize(){throw new z({code:F.TOKENIZATION_ERROR,message:"Google Pay does not support direct tokenization",paymentMethod:B.GOOGLE_PAY})}async loadGooglePayScript(){if(typeof google<"u"&&google.payments?.api?.PaymentsClient)return!0;try{return await ro(vc),!0}catch{return C.error("Failed to load Google Pay script"),!1}}async setup(){let{countryCode:e,currencyCode:a}=this.context.configuration.clientSession.order;if(!e)throw new G({code:It.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing country code",paymentMethod:B.GOOGLE_PAY});if(!a)throw new G({code:It.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing currency code",paymentMethod:B.GOOGLE_PAY});if(!await this.loadGooglePayScript())return C.error("Google Pay script failed to load"),!1;let n=this.context.configuration.env==="PRODUCTION"?"PRODUCTION":"TEST";this.client=new google.payments.api.PaymentsClient({environment:n,...this.needsPaymentDataCallbacks()&&{paymentDataCallbacks:{onPaymentDataChanged:s=>this.handlePaymentDataChanged(s)}}});try{let{result:s,paymentMethodPresent:l}=await this.client.isReadyToPay(this.buildIsReadyToPayRequest());if(!s)return C.info("Google Pay is not available in this browser/device"),!1;if(this.clientOptions?.existingPaymentMethodRequired&&l===!1)return C.info("Google Pay: existingPaymentMethodRequired is true but no existing payment method is available"),!1}catch(s){return C.error("Google Pay isReadyToPay check failed",{error:s}),!1}let o=this.context.onClientConfigurationUpdate(s=>{let l=s.clientSession?.order;(!l||!l.totalOrderAmount||!l.currencyCode)&&C.warn("Google Pay: Order details are missing or incomplete after client session update. Ensure order details (totalOrderAmount, currencyCode, countryCode) are always provided.")});return this.context.subscribeToTeardown(o),!0}needsPaymentDataCallbacks(){return!!(this.clientOptions?.requireShippingMethod||this.shouldCaptureShippingAddress)}buildIsReadyToPayRequest(){return{apiVersion:Tn,apiVersionMinor:Pn,allowedPaymentMethods:[this.allowedPaymentMethod],existingPaymentMethodRequired:this.clientOptions?.existingPaymentMethodRequired}}async render(e){if(!this.client)return void C.error("Google Pay client not initialized. Call setup() first.");let a=this.client.createButton({buttonType:this.clientOptions?.buttonType??bc,buttonColor:this.clientOptions?.buttonColor??Ac,buttonSizeMode:this.clientOptions?.buttonSizeMode??Cc,buttonRadius:this.clientOptions?.buttonRadius,buttonLocale:this.clientOptions?.buttonLocale,buttonBorderType:this.clientOptions?.buttonBorderType,onClick:i=>this.handleClick(i),buttonRootNode:e instanceof ShadowRoot?e:void 0});e.appendChild(a)}async handleClick(e){if(!this.client)return void C.error("Google Pay client not available");let a=this.callbacks.onStart();kt({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:B.GOOGLE_PAY});try{let i=await this.client.loadPaymentData(this.buildPaymentDataRequest()),{action:n}=await a;if(n==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type});await this.processPaymentData(i)}catch(i){if(i.statusCode==="CANCELED")return void this.context.clientSessionApi.unselectPaymentMethod();C.errorWithDatadog("Google Pay error",{error:i}),this.callbacks.onFinish(void 0,i)}}get clientOptions(){return this.context.clientOptions.googlePay}get shouldCaptureShippingAddress(){return!!(this.clientOptions?.captureShippingAddress||this.clientOptions?.shippingAddressParameters)}async processPaymentData(e){if(this.clientOptions?.captureBillingAddress&&await this.updateBillingAddress(e),(this.shouldCaptureShippingAddress||this.clientOptions?.requireShippingMethod||this.clientOptions?.emailRequired)&&await this.updateShippingDetails(e),this.clientOptions?.requireShippingMethod){let n=e.shippingOptionData?.id;n&&await this.context.clientSessionApi.selectShippingMethod(n)}let{data:a,error:i}=await this.context.pciApi.postGooglePayPaymentInstruments({flow:"GATEWAY",network:e.paymentMethodData.info?.cardNetwork??"OTHER",merchant_id:this.config.options.merchantId,encrypted_payload:Va.encode(e.paymentMethodData.tokenizationData.token)});if(i||!a)throw this.callbacks.onFinish(void 0,i),i??new z({code:F.TOKENIZATION_ERROR,message:"Failed to tokenize payment data",paymentMethod:B.GOOGLE_PAY});this.callbacks.onFinish(a)}async updateBillingAddress(e){let a=e.paymentMethodData.info?.billingAddress;if(a){let i=qr(a);await this.context.clientSessionApi.setBillingAddress(i)}else C.warn("Google Pay: Could not retrieve billing address from payment data")}async updateShippingDetails(e){let a=e.shippingAddress,i=e.email,n=a?.phoneNumber;if(a||n||i){let o=a?qr(a):void 0;await this.context.clientSessionApi.setShippingAddress(o,n,i)}else C.warn("Google Pay: No shipping address, phone number, or email found in payment data")}async handlePaymentDataChanged(e){let a=e.callbackTrigger;try{if(a==="SHIPPING_OPTION"){let i=e.shippingOptionData?.id;return i&&await this.context.clientSessionApi.selectShippingMethod(i),{newTransactionInfo:this.getCurrentTransactionInfo()}}if(a==="SHIPPING_ADDRESS"||a==="INITIALIZE"){let i=e.shippingAddress;if(i){let s=qr(i);await this.context.clientSessionApi.setShippingAddress(s)}let n=this.getShippingModule(),o=n?.shippingMethods||[];return{...this.clientOptions?.requireShippingMethod&&o.length>0&&{newShippingOptionParameters:{shippingOptions:En(o),defaultSelectedOptionId:n?.selectedShippingMethod||o[0]?.id}},newTransactionInfo:this.getCurrentTransactionInfo()}}return{newTransactionInfo:this.getCurrentTransactionInfo()}}catch(i){return C.errorWithDatadog("Google Pay: Error handling payment data change",{error:i}),{error:{reason:"OTHER_ERROR",message:"An error occurred while processing your request",intent:a==="SHIPPING_OPTION"?"SHIPPING_OPTION":"SHIPPING_ADDRESS"}}}}getShippingModule(){return this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options}getCurrentTransactionInfo(){let{countryCode:e,currencyCode:a,totalOrderAmount:i}=this.context.configuration.clientSession.order;return{countryCode:e,currencyCode:a,displayItems:this.getDisplayItems(),totalPriceStatus:"FINAL",totalPrice:sa(i,a),totalPriceLabel:"Total"}}getDisplayItems(){let e=this.context.configuration.clientSession.order,{currencyCode:a,merchantAmount:i,lineItems:n,fees:o,shipping:s}=e,l=this.clientOptions?.requireShippingMethod,c=[];return i?(c.push({label:this.translate(Ga.SUBTOTAL,Ka.SUBTOTAL),type:"SUBTOTAL",price:sa(i,a)}),c):(n&&n.length>0&&n.forEach(m=>{c.push({label:m.description||this.translate(Ga.ITEM,Ka.ITEM),type:"LINE_ITEM",price:sa(m.amount,a)})}),o&&o.length>0&&o.filter(m=>m.amount!==0).forEach(m=>{c.push({label:m.type||m.description||this.translate(Ga.FEE,Ka.FEE),type:"LINE_ITEM",price:sa(m.amount,a)})}),l&&s&&s.amount!==0&&c.push({label:s.methodName||this.translate(Ga.SHIPPING,Ka.SHIPPING),type:"LINE_ITEM",price:sa(s.amount,a)}),c)}get allowedCardNetworks(){let e=this.context.configuration.clientSession.paymentMethod?.orderedAllowedCardNetworks;if(!e||e.length===0)return Nn;let a=e.map(i=>Sc[i]).filter(i=>!!i);return a.length>0?a:Nn}get allowedPaymentMethod(){let e=this.clientOptions?.captureBillingAddress;return{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:this.allowedCardNetworks,...e&&{billingAddressRequired:!0,billingAddressParameters:{format:"FULL"}}}}}buildPaymentDataRequest(){let e=this.clientOptions?.shippingAddressParameters,a=this.clientOptions?.emailRequired,i=this.clientOptions?.requireShippingMethod,n=this.getShippingModule(),o=n?.shippingMethods,s=n?.selectedShippingMethod;return{apiVersion:Tn,apiVersionMinor:Pn,...a&&{emailRequired:!0},...(this.shouldCaptureShippingAddress||i)&&{shippingAddressRequired:!0,...e&&{shippingAddressParameters:{...e.allowedCountryCodes&&{allowedCountryCodes:e.allowedCountryCodes},...e.phoneNumberRequired&&{phoneNumberRequired:!0}}}},...i&&{shippingOptionRequired:!0,...o&&o.length>0&&{shippingOptionParameters:{shippingOptions:En(o),defaultSelectedOptionId:s||o[0]?.id}}},...this.needsPaymentDataCallbacks()&&{callbackIntents:[...i?["SHIPPING_ADDRESS","SHIPPING_OPTION"]:["SHIPPING_ADDRESS"]]},transactionInfo:this.getCurrentTransactionInfo(),merchantInfo:{merchantId:this.config.options.merchantId,merchantName:this.config.options.merchantName},allowedPaymentMethods:[{...this.allowedPaymentMethod,tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:"primer",gatewayMerchantId:this.config.options.merchantId}}}]}}};function Mc(r,t){var e={};for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&t.indexOf(a)<0&&(e[a]=r[a]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,a=Object.getOwnPropertySymbols(r);i<a.length;i++)t.indexOf(a[i])<0&&Object.prototype.propertyIsEnumerable.call(r,a[i])&&(e[a[i]]=r[a[i]]);return e}function Ec(r,t){var e=document.querySelector('script[src="'.concat(r,'"]'));if(e===null)return null;var a=po(r,t),i=e.cloneNode();if(delete i.dataset.uidAuto,Object.keys(i.dataset).length!==Object.keys(a.dataset).length)return null;var n=!0;return Object.keys(i.dataset).forEach(function(o){i.dataset[o]!==a.dataset[o]&&(n=!1)}),n?e:null}function Tc(r){var t=r.url,e=r.attributes,a=r.onSuccess,i=r.onError,n=po(t,e);n.onerror=i,n.onload=a,document.head.insertBefore(n,document.head.firstElementChild)}function Pc(r){var t=r.sdkBaseUrl,e=r.environment,a=Mc(r,["sdkBaseUrl","environment"]),i=t||kc(e),n=a,o=Object.keys(n).filter(function(c){return n[c]!==void 0&&n[c]!==null&&n[c]!==""}).reduce(function(c,m){var g=n[m].toString();return m=Nc(m),m.substring(0,4)==="data"||m==="crossorigin"?c.attributes[m]=g:c.queryParams[m]=g,c},{queryParams:{},attributes:{}}),s=o.queryParams,l=o.attributes;return s["merchant-id"]&&s["merchant-id"].indexOf(",")!==-1&&(l["data-merchant-id"]=s["merchant-id"],s["merchant-id"]="*"),{url:"".concat(i,"?").concat(Ic(s)),attributes:l}}function Nc(r){var t=function(e,a){return(a?"-":"")+e.toLowerCase()};return r.replace(/[A-Z]+(?![a-z])|[A-Z]/g,t)}function Ic(r){var t="";return Object.keys(r).forEach(function(e){t.length!==0&&(t+="&"),t+=e+"="+r[e]}),t}function kc(r){return r==="sandbox"?"https://www.sandbox.paypal.com/sdk/js":"https://www.paypal.com/sdk/js"}function po(r,t){t===void 0&&(t={});var e=document.createElement("script");return e.src=r,Object.keys(t).forEach(function(a){e.setAttribute(a,t[a]),a==="data-csp-nonce"&&e.setAttribute("nonce",t["data-csp-nonce"])}),e}function Lc(r,t){if(t===void 0&&(t=Promise),mo(r,t),typeof document>"u")return t.resolve(null);var e=Pc(r),a=e.url,i=e.attributes,n=i["data-namespace"]||"paypal",o=In(n);return i["data-js-sdk-library"]||(i["data-js-sdk-library"]="paypal-js"),Ec(a,i)&&o?t.resolve(o):Rc({url:a,attributes:i},t).then(function(){var s=In(n);if(s)return s;throw new Error("The window.".concat(n," global variable is not available."))})}function Rc(r,t){t===void 0&&(t=Promise),mo(r,t);var e=r.url,a=r.attributes;if(typeof e!="string"||e.length===0)throw new Error("Invalid url.");if(a!==void 0&&typeof a!="object")throw new Error("Expected attributes to be an object.");return new t(function(i,n){if(typeof document>"u")return i();Tc({url:e,attributes:a,onSuccess:function(){return i()},onError:function(){var o=new Error('The script "'.concat(e,'" failed to load. Check the HTTP status code and response body in DevTools to learn more.'));return n(o)}})})}function In(r){return window[r]}function mo(r,t){if(typeof r!="object"||r===null)throw new Error("Expected an options object.");var e=r.environment;if(e&&e!=="production"&&e!=="sandbox")throw new Error('The `environment` option must be either "production" or "sandbox".');if(t!==void 0&&typeof t!="function")throw new Error("Expected PromisePonyfill to be a function.")}var Fa=new Map,kn={getOrCreateNamespace(r){let t=Fa.get(r);return t?t.namespace:Te()},getInstance(r){return Fa.get(r)?.instance??null},storeInstance(r,t,e){Fa.set(r,{instance:t,namespace:e})},hasInstance(r){return Fa.has(r)}};async function xc({context:r,configId:t,paymentMethodType:e,callbacks:a}){try{let{action:i}=await a.onStart();if(i==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:e});let{data:n,error:o}=await r.coreApi.createPaypalBillingAgreement({paymentMethodConfigId:t});if(o||!n){let s=o?.message??"Failed to create billing agreement";throw new G({message:s,code:F.PAYMENT_FAILED,paymentMethod:e})}return n.tokenId}catch(i){throw C.errorWithDatadog("PayPal billing agreement creation failed:",{error:i}),a.onFinish(void 0,i),i instanceof G||i instanceof z?i:new G({message:"Failed to create billing agreement",code:F.PAYMENT_FAILED,paymentMethod:e})}}async function _c({context:r,configId:t,paymentMethodType:e,callbacks:a,data:i}){try{let n=i.billingToken;if(!n)throw new z({message:"Billing token not provided",code:F.TOKENIZATION_ERROR,paymentMethod:e});let{data:o,error:s}=await r.coreApi.confirmPaypalBillingAgreement({paymentMethodConfigId:t,tokenId:n});if(s||!o){let h=s?.message??"Failed to confirm billing agreement";throw new z({message:h,code:F.TOKENIZATION_ERROR,paymentMethod:e})}let l=o,c={paypalBillingAgreementId:l.billingAgreementId,shippingAddress:l.shippingAddress,externalPayerInfo:l.externalPayerInfo},{error:m,data:g}=await r.pciApi.postPaypalPaymentInstruments(c,{tokenType:"MULTI_USE",paymentFlow:"VAULT"});if(m||!g){let h=m?.message??"Unable to vault PayPal payment method";throw new z({message:h,code:F.TOKENIZATION_ERROR,paymentMethod:e})}a.onFinish(g)}catch(n){throw C.errorWithDatadog("PayPal billing agreement approval failed:",{error:n}),a.onFinish(void 0,n),n instanceof z||n instanceof G?n:new z({message:"Failed to approve billing agreement",code:F.TOKENIZATION_ERROR,paymentMethod:e})}}var wc="gold",Dc="black",Bc="rect",Oc="paypal",Gc="vertical",ho="horizontal",Ln=2,Rn=["paypal","paylater"],go={default:{color:wc},card:{validColors:["black","white"],defaultColor:Dc}};function Kc(r){if(!r)return;let t=go[r];if(t&&"validColors"in t)return t}function Fc(r,t){let e=Kc(t);if(!e)return r??go.default.color;let a=r??e.defaultColor;return e.validColors.includes(a)?a:(C.warn(`PayPal: Invalid color "${a}" for ${t} button. Only supports: ${e.validColors.join(", ")}. Falling back to "${e.defaultColor}".`),e.defaultColor)}var Uc=25,Vc=55;function Hc(r){return parseFloat(r)||0}function Yc(r){let t=Hc(r);return Math.max(Uc,Math.min(Vc,t))}function $c(r,t,e){let a=t?r?.[t]:void 0,i=a?.tagline??r?.tagline??!1,n=i?ho:Gc,o,s=a?.height??r?.height;s!=null?o=s:e!=null&&(o=Yc(String(e)));let l=a?.borderRadius??r?.borderRadius,c=a?.disableMaxWidth??r?.disableMaxWidth,m=a?.color??r?.color;return{color:Fc(m,t),shape:a?.shape??r?.shape??Bc,label:a?.label??r?.label??Oc,layout:a?.layout??r?.layout??n,tagline:i,...o!=null&&{height:o},...l!=null&&{borderRadius:l},...c!=null&&{disableMaxWidth:c}}}function zc(r,t,e,a){let i={style:r,onInit:e.onInit,onClick:e.onClick,onCancel:e.onCancel,onError:e.onError};return t&&a?(i.createBillingAgreement=a.createBillingAgreement,i.onApprove=a.onApprove):i.onApprove=e.onApprove,i}function jc(r){if(!r)return;let t={first_name:r.firstName,last_name:r.lastName,address_line_1:r.addressLine1??"",address_line_2:r.addressLine2,city:r.city??"",state:r.state,postal_code:r.postalCode??"",country_code:r.countryCode??""},{address_line_1:e,city:a,postal_code:i,country_code:n}=t;if(!(!e||!a||!i||!n))return t}function Wc(r){if(!r)return null;let t=r.purchase_units?.[0]?.shipping;if(!t?.address)return null;let e=t.address,a=t.name;return{firstName:a?.given_name,lastName:a?.surname,addressLine1:e.address_line_1,addressLine2:e.address_line_2,city:e.admin_area_2,state:e.admin_area_1,postalCode:e.postal_code,countryCode:e.country_code}}function Zc(r,t,e){let{order:{currencyCode:a,merchantAmount:i,totalOrderAmount:n,shipping:o,lineItems:s=[],fees:l=[]},customer:c}=r;if(!a)throw new G({message:"Currency code is not provided",code:It.MISSING_PARAMETER,paymentMethod:e});let m={amount:i??n,currencyCode:a,paymentMethodConfigId:t,amountBreakdown:{}},g=c?.shippingAddress,h=jc(g);h&&(m.shipping_address=h);let T=!s.some(M=>!M.name&&!M.description);if(T&&(m.items=s.map(M=>{let{name:_,description:x,taxAmount:E,amount:L,quantity:K}=M,j=E?Math.floor(E/K):0;return{name:x||_||"",unit_amount:{value:L,currency_code:a},quantity:K.toString(),tax:{value:j,currency_code:a}}})),T&&s.length){let M=s.reduce((de,{amount:U,quantity:De})=>de+U*De,0),_=l?.reduce?.((de,{amount:U})=>de+(U??0),0),x=s?.reduce((de,{discountAmount:U})=>de+(U??0),0),E=s?.reduce((de,{taxAmount:U})=>de+(U??0),0),L=o?.amount??0,K=_??0,j=M+E+L+K-x;m.amountBreakdown={item_total:{value:M,currency_code:a},tax_total:{value:E,currency_code:a},handling:{value:K,currency_code:a},shipping:{value:L,currency_code:a},discount:{value:x,currency_code:a}},m.amount=j}return m}async function Jc({context:r,configId:t,paymentMethodType:e,callbacks:a,skipOnStartCallback:i=!1}){try{if(!i){let{action:s}=await a.onStart();if(s==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:e})}let{data:n,error:o}=await r.coreApi.createPaypalOrder(Zc(r.configuration.clientSession,t,e));if(o||!n){let s=o?.message??"Unable to create PayPal order";throw new G({message:s,code:F.PAYMENT_FAILED,paymentMethod:e})}return n.orderId}catch(n){throw a.onFinish(void 0,n),n}}async function qc({context:r,paymentMethodType:t,callbacks:e,data:a,actions:i,deferredOnStartCallback:n=!1}){if(n){let{action:g}=await e.onStart();if(g==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:t})}let o=null;try{o=await i?.order?.get()??null}catch(g){C.warn("Failed to get PayPal order details",g)}let s=Wc(o),l={external_payer_info:{email:o?.payer?.email_address,external_payer_id:a.payerID??void 0,first_name:o?.payer?.name?.given_name,last_name:o?.payer?.name?.surname},paypal_order_id:a.orderID,paypal_status:o?.status};s&&(l.shipping_address=s);let{error:c,data:m}=await r.pciApi.postPaypalPaymentInstruments(l);if(c||!m){let g=c?.message??"Unable to create payment instrument";throw new z({message:g,code:F.TOKENIZATION_ERROR,paymentMethod:t})}e.onFinish(m)}var Qc=["buttons","funding-eligibility"],xn=[],_n="paypal";function yo(r){if(!r?.length)return;r.includes(_n)&&C.warn("PayPal: Cannot disable paypal funding source");let t=r.filter(e=>e!==_n);return t.length>0?t:void 0}var Xc="authorize";function eu(r,t,e){return(r??t==="PREFER_VAULT")&&e}function wn({isVaultFlow:r,configIntent:t}){return r?"tokenize":t??Xc}function tu(r,t,e,a){let{clientId:i,intent:n}=t.options,o=r.configuration.clientSession.order.currencyCode,s=r.clientOptions.paypal?.disableFunding??(xn.length>0?xn:void 0),l=yo(s),c=r.clientOptions?.paypal?.enableFunding,m={dataNamespace:e,clientId:i,currency:o,components:Qc,...l&&l.length>0?{disableFunding:l}:{},...c&&c.length>0?{enableFunding:c}:{},integrationDate:r.clientOptions.paypal?.integrationDate,debug:r.clientOptions.paypal?.debug};return(si||r.decodedClientToken.env==="SANDBOX"||r.decodedClientToken.env==="STAGING")&&(m.buyerCountry=r.clientOptions?.paypal?.buyerCountry),a?(m.vault="true",m.intent=wn({isVaultFlow:!0,configIntent:n})):(m.vault="false",m.intent=wn({isVaultFlow:!1,configIntent:n})),m}var Za=class extends mt{constructor(e,a){super(e,a);k(this,"paypalInstance");k(this,"dataNamespace");k(this,"isVaultFlow",!1);k(this,"isSetupComplete",!1);k(this,"setupPromise");k(this,"eligibleFundingSources",[]);k(this,"currentFundingSource",null);k(this,"onStartDeferred",!1);k(this,"disabled",!1);this.dataNamespace=kn.getOrCreateNamespace(e.id),this.context.onClientConfigurationUpdate(async()=>{C.info("PayPal: Client session updated, refreshing PayPal buttons");try{await this.setup()}catch(i){C.warn("PayPal: Failed to refresh on client session update:",i)}})}async setDisabled(e){this.disabled=e}async tokenize(){throw new z({message:"PayPal does not support direct tokenization",code:F.TOKENIZATION_ERROR,paymentMethod:B.PAYPAL})}async setup(){let{clientId:e}=this.config.options;return this.setupPromise?(C.info("PayPal setup already in progress, waiting..."),this.setupPromise):this.isSetupComplete&&this.paypalInstance?.Buttons?(C.info("PayPal setup already completed, skipping"),!0):e?(this.setupPromise=(async()=>{try{let a=this.context.clientOptions.paypal?.vault,i=this.context.clientOptions.paypal?.paymentFlow,n=this.context.configuration.clientSession.paymentMethod?.vaultOnSuccess??!1;this.isVaultFlow=eu(a,i,n);let o=tu(this.context,this.config,this.dataNamespace,this.isVaultFlow);C.debug("%c PAYPAL %c Script Configuration ","background: #0070BA; color: #ffffff; font-weight: bold; padding: 4px 12px; border-radius: 3px 0 0 3px; font-size: 14px;","background: #003087; color: #ffffff; padding: 4px 12px; border-radius: 0 3px 3px 0; font-size: 14px;",o);let s=await Lc(o);if(!s)return C.warn("Failed to load PayPal SDK"),!1;this.paypalInstance=s,kn.storeInstance(this.config.id,s,this.dataNamespace);let l=this.context.clientOptions.paypal?.enableFunding,c=yo(this.context.clientOptions.paypal?.disableFunding),g=(s.getFundingSources?.()??[]).filter(h=>s?.isFundingEligible?.(h));return C.debug("PayPal: Eligible funding sources from PayPal SDK:",g),this.eligibleFundingSources=this.filterFundingSources(g,l,c),(l?.length||c?.length)&&(C.debug("PayPal: Primer SDK options:",{enableFunding:l??[],disableFunding:c??[]}),C.debug("PayPal: Funding sources after Primer SDK filter:",this.eligibleFundingSources)),this.eligibleFundingSources.length===0?(C.warn("PayPal: No funding sources are eligible with current configuration"),!1):!0}catch(a){return C.warn("PayPal setup failed:",{error:a}),this.setupPromise=void 0,!1}})(),this.setupPromise):(C.warn("PayPal clientId is required"),!1)}async render(e,a){let{Buttons:i}=this.paypalInstance;if(!i)throw new G({message:"PayPal Buttons component not available",code:It.INVALID_USAGE,paymentMethod:B.PAYPAL});let n=this.context.clientOptions.paypal?.style,o=a?.style?.buttonHeight,s=n?.layout===ho,l={onInit:this.handleInit.bind(this),onClick:this.handleClick.bind(this),onApprove:this.handleApprove.bind(this),onCancel:this.handleCancel.bind(this),onError:this.handleError.bind(this)},c=this.isVaultFlow?{createBillingAgreement:()=>xc({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks}),onApprove:M=>_c({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks,data:M})}:void 0,m=this.eligibleFundingSources,g=[];for(let M of m){let _=$c(n,M,o),x=zc(_,this.isVaultFlow,l,c);this.isVaultFlow||(x.createOrder=this.handleCreateOrder.bind(this));let E=i({...x,fundingSource:M});E.isEligible()?g.push({button:E,fundingSource:M}):C.debug(`PayPal: Button for "${M}" is not eligible with current config`)}if(g.length===0)throw C.warn("PayPal: No buttons were eligible to render with current configuration"),new G({message:"No PayPal buttons eligible to render",code:It.INVALID_USAGE,paymentMethod:B.PAYPAL});let h=s&&g.length>Ln?this.selectButtonsForHorizontalLayout(g):g;s&&this.applyHorizontalLayoutStyles(e,h.length);let T=h.map(({button:M})=>M.render(e));await Promise.all(T)}selectButtonsForHorizontalLayout(e){let a=new Set(Rn),i=Rn.map(o=>e.find(s=>s.fundingSource===o)).filter(o=>o!==void 0),n=e.filter(o=>!a.has(o.fundingSource));return[...i,...n].slice(0,Ln)}applyHorizontalLayoutStyles(e,a){e.style.display="grid",e.style.gridTemplateColumns=`repeat(${a}, 1fr)`,e.style.gap="10px"}handleInit(e,a){let{clientSession:i}=this.context.configuration,n=!!i.order.currencyCode,o=!!i.order.totalOrderAmount||!!i.order.merchantAmount;if(!n||!o){C.warn("PayPal button disabled: missing currency or amount"),a.disable();return}a.enable()}handleClick(e,a){return this.currentFundingSource=e.fundingSource??null,kt({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:"PAYPAL"}),a.resolve()}async handleCreateOrder(){let e=this.currentFundingSource==="card";return this.onStartDeferred=e,Jc({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks,skipOnStartCallback:e})}async handleApprove(e,a){let i=this.onStartDeferred;return this.onStartDeferred=!1,qc({context:this.context,paymentMethodType:this.config.type,callbacks:this.callbacks,data:e,actions:a,deferredOnStartCallback:i})}handleCancel(){this.context.clientSessionApi.unselectPaymentMethod(),this.callbacks.onFinish(void 0,new G({message:"The PayPal payment was cancelled by the user.",paymentMethod:B.PAYPAL}))}handleError(e){C.errorWithDatadog("PayPal error:",e),this.callbacks.onFinish(void 0,e)}filterFundingSources(e,a,i){return e.filter(n=>!(a?.length&&!a.includes(n)||i?.includes(n)))}};function Dn(r,t,e){if(!r)return null;let a={id:r.id,orderId:r.orderId};return t?.paymentInstrumentData&&e&&(a.paymentMethodData={paymentMethodType:e,...t.paymentInstrumentData}),a}var fo=(r,t,e,a,i)=>{let n=e;if(t?.status==="FAILED"&&(n=new G({code:F.PAYMENT_FAILED,message:`The payment "${t.id}" was created but failed to be processed. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.checkoutOutcome==="CHECKOUT_FAILURE"&&(n=new G({code:F.PAYMENT_FAILED,message:`The payment "${t.id}" was created but failed to be processed. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.status==="PENDING"&&!t.requiredAction?.clientToken&&(n=new G({code:F.PAYMENT_FAILED,message:`The payment "${t.id}" ended up in a "PENDING" state without any required action. The SDK does not know how to handle this state. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.status==="SUCCESS"&&t.checkoutOutcome!=="CHECKOUT_FAILURE"||t?.status==="PENDING"&&t.showSuccessCheckoutOnPendingPayment||t?.checkoutOutcome==="CHECKOUT_COMPLETE")return void r.onCheckoutComplete?.({payment:Dn(t,a,i)});r.onCheckoutFail?.(n||new G({code:F.PAYMENT_FAILED,message:`The payment${t?.id?` "${t.id}"`:""} is in an inconsistent state without any required action. The SDK does not know how to handle this state. Please contact Primer.`}),{payment:Dn(t,a,i)??void 0})},au=async(r,t)=>{let e=t.config.type;if(!r.onBeforePaymentCreate)return{action:"continue"};let a=setTimeout(()=>{C.warn("onBeforePaymentCreate did not resolve within 10 seconds. Primer SDK will remain in a loading state until `continuePaymentCreation` or `abortPaymentCreation` is called.")},1e4);return new Promise(i=>{r.onBeforePaymentCreate({paymentMethodType:e},{continuePaymentCreation:n=>{clearTimeout(a),C.log(`Continuing payment creation for ${e}`),n?.idempotencyKey&&t.setIdempotencyKey(n.idempotencyKey),r.onPaymentCreationStart?.(),i({action:"continue"})},abortPaymentCreation:()=>{clearTimeout(a),C.log(`Aborting payment creation for ${e}`),i({action:"abort"})}})})};async function ma(r,t,e){if(t.setCallbacks({onStart:()=>(t.context.clientSessionApi.selectPaymentMethod(t.config.type),kt({eventName:"PAYMENT_PROCESSING_STARTED",paymentMethod:t.config.type}),au(r,t)),onFinish:(a,i)=>{Bn(r,t,a,i)}}),!e)return t.start();{let a,i;try{i=await t.tokenizeVaulted(e.id)}catch(n){a=n}return Bn(r,t,i,a)}}async function Bn(r,t,e,a){let i;if(e&&!a)try{if(i=await t.createPayment(e),i.cancelled)return;i.status!=="FAILED"&&(i=await t.handleRequiredAction(i))}catch(n){a=n}fo(r,i,a,e,t.config.type)}var On=Symbol("PROXY_MARKER");function bi({namespace:r,onMessage:t,sendMessage:e}){function a(i,n){return new Proxy(i,{get(o,s,l){if(s==="then")return null;if(o[On])return Reflect.get(o,s,l);let c=()=>{};return c[On]=!0,a(c,[...n,s])},apply(o,s,l){return new Promise(async(c,m)=>{try{let g=[],h=l.map(x=>{if(typeof x!="function")return x;{let E=Te();return g.push(E),t(L=>{L.namespace===r&&L.sender===Xr.PROVIDER&&L.type===Qr.CALLBACK&&L.id===E&&x(...L.data)}),E}}),T=Te(),M=t(x=>{x.namespace===r&&x.sender===Xr.PROVIDER&&x.type===Qr.APPLY&&x.id===T&&(x.error?m(new Error(x.error)):c(x.data),M?.())}),_={type:Qr.APPLY,sender:Xr.INJECTOR,id:T,path:n,args:h,callbackIds:g,timeStamp:Date.now(),namespace:r};e(_)}catch(g){m(g)}})}})}return a({},[])}var Qr={APPLY:"apply",CALLBACK:"callback"},Xr={PROVIDER:"provider",INJECTOR:"injector"};function li(r,t){let e=t?.input?.base?.height;e&&(r.style.height=typeof e=="number"?`${e}px`:e)}function ru(r,t,e,a={}){let i=r.cardholderName?.defaultValue??r.card?.cardholderName?.defaultValue,n=uo(t.checkoutSessionId,{cardholderName:i});e.iframes=n;let o=[],s="LOCAL",l={[ce.cardNumber]:void 0,[ce.cardExpiryDate]:void 0,[ce.cardSecurityCode]:void 0,[ce.cardholderName]:void 0},c=!1;t.subscribeToTeardown(()=>{c=!0});let m={createHostedInputs:()=>{let g=h=>{let T=new Map;return{getOptions:()=>{},setOptions:M=>{li(e.iframes[h],M.style),e.iframes[h].setAttribute("title",M.ariaLabel||""),l[h]?.setOptions(M)},render:(M,_)=>{let x=e.iframes[h];if(!x)return C.errorWithDatadog(`No iframe found for ${h}`),Promise.resolve();let E;return E=typeof M=="string"?document.getElementById(M):M,E?(li(x,_.style),E.appendChild(x),new Promise(L=>{x.onload=()=>{if(c){C.warn(`Teardown was already called, aborting render for ${h}`),x.remove(),L();return}l[h]=bi({namespace:`${t.checkoutSessionId}-${h}`,onMessage:U=>{let De=oa=>U(oa.data);return window.addEventListener("message",De),()=>window.removeEventListener("message",De)},sendMessage:U=>{x.contentWindow.postMessage(U,"*")}}),e.iframes[h].setAttribute("title",_.ariaLabel||"");let K=r.cardholderName??r.card?.cardholderName,{defaultValue:j,...de}=K??{};l[h].setOptions({..._,orderedAllowedCardNetworks:t.configuration.clientSession.paymentMethod.orderedAllowedCardNetworks,cardholderName:de}),l[h].setBinDataLoadingChange(U=>{U&&a.onCardNetworksLoading?.(),a.onBinDataLoadingChange?.(U)}),l[h].setOnBlur(()=>{try{T.get("blur")?.()}catch(U){C.errorWithDatadog(`Blur listener error for ${h}`,{error:U})}}),l[h].setOnFocus(()=>{try{T.get("focus")?.()}catch(U){C.errorWithDatadog(`Focus listener error for ${h}`,{error:U})}}),l[h].setOnInput(U=>{let De={...U,errorCode:U.error,active:U.focused};try{T.get("input")?.(De),T.get("change")?.(De)}catch(oa){C.errorWithDatadog(`Input listener error for ${h}`,{error:oa})}}),l[h].setOnEnter(()=>{try{T.get("enter")?.()}catch(U){C.errorWithDatadog(`Enter listener error for ${h}`,{error:U})}}),h===ce.cardNumber&&(l[h].setBinDataApiConfig(t.configuration.binDataUrl,t.decodedClientToken.accessToken),l[h].setOnCardNetworksChange((U,De,oa)=>{if(De!==s||iu(o,U)){o=U,s=De;let{cardNetworkChangeEventData:bd,binDataAvailableEventData:Ad}=yc({networks:o,source:s},t.configuration.clientSession.paymentMethod.orderedAllowedCardNetworks);a.onCardNetworksChange?.(bd),a.onBinDataAvailable?.({...Ad,firstDigits:oa})}}))},L()})):(C.error(`Container not found for ${h}:`,M),Promise.resolve())},addEventListener:(M,_)=>{T.set(M,_)},focus:()=>{let M=e.iframes[h];if(M&&M.contentWindow)try{l[h]?.focus()}catch(_){C.errorWithDatadog(`Focus send error for ${h}`,{error:_})}else C.warn(`Focus failed for ${h} - iframe not available`)},blur:()=>{let M=e.iframes[h];if(M&&M.contentWindow)try{l[h]?.blur()}catch(_){C.errorWithDatadog(`Blur send error for ${h}`,{error:_})}},setDisabled:M=>{l[h]?.setDisabled(M)}}};return{cardNumberInput:g(ce.cardNumber),cardholderNameInput:g(ce.cardholderName),expiryInput:g(ce.cardExpiryDate),cvvInput:g(ce.cardSecurityCode)}},removeHostedInputs:()=>{c=!0,e.iframes.cardNumber.remove(),e.iframes.cardSecurityCode.remove(),e.iframes.cardExpiryDate.remove(),e.iframes.cardholderName.remove()},submit:async g=>{if((await m.validate()).valid)return await t.apiController.setPreferredNetwork(g?.cardNetwork),ma(r,e)},validate:async()=>{let g=(await Promise.all(Object.entries(l).map(([T,M])=>M?.getFieldState().then(_=>[T,_]).catch(()=>{})))).filter(T=>T!==void 0),h=[];for(let[T,M]of g)!M.valid&&M.error&&h.push({field:T,name:T,error:M.error,message:M.error});return{valid:h.length===0,validationErrors:h}},reset:()=>{Object.values(l).forEach(g=>{g?.reset()}),t.apiController.setPreferredNetwork(void 0)},setCardholderName:g=>{try{l[ce.cardholderName]?.setCardholderName(g)}catch(h){C.errorWithDatadog("SetCardholderName error",{error:h})}}};return m}function iu(r,t){if(r.length!==t.length)return!0;let e=t.map(({network:a})=>a);return!r.every(({network:a})=>e.includes(a))}function nu(r,t,e){return{createButton:()=>({render:async(a,i)=>{await ma(r,e);let n=typeof a=="string"?document.getElementById(a):a;if(!n)throw new G({code:qd.CONTAINER_NOT_FOUND,message:`Container with id "${a}" not found in the DOM.`});await e.render(n,i)},setDisabled:a=>e.setDisabled(a)})}}function ou(r,t,e){return{start:()=>ma(r,e)}}function su(r,t,e){return{start:async a=>(a?.blikCode&&e.setBlikCode(a.blikCode),ma(r,e))}}function lu(r,t){return{"Content-Type":"application/json","primer-client-token":r,"primer-sdk-client":"WEB","primer-sdk-version":"0.0.0-local","primer-sdk-checkout-session-id":t,"x-api-version":"2.4"}}function du(r,t,e){if(e?.status&&e.status>=400&&e.status<500)return!1;if(e?.status&&e.status>=500)return!0;if(r instanceof Error){let a=r.message.toLowerCase();return a.includes("network")||a.includes("timeout")||a.includes("connection")}return!1}function cu(r){let n=1e3*Math.pow(1.1,r),o=.1*n*(Math.random()-.5);return n=Math.max(0,n+o),Math.min(n,3e4)}var uu={attempts:3,retryCondition:du,delayCalculator:cu,totalTimeout:3e5};async function pu(r,t,e){let a={...uu,...t.retry},i=[],n=Date.now();for(let s=0;s<=a.attempts;s++)try{let l=await r();if(!l.error)return{...l,retryHistory:i.length>0?i:void 0};if(s===a.attempts||!a.retryCondition(l.error,s,l))return{...l,retryHistory:i};let c=a.delayCalculator(s);if(i.push({attempt:s+1,delay:c,error:l.error,timestamp:Date.now()}),Date.now()-n+c>a.totalTimeout)return{...l,error:new Be({message:`Retry total timeout exceeded for ${t.method} ${e}`,code:pa({status:408}),response:l}),retryHistory:i};await Yt(c)}catch(l){i.push({attempt:s+1,delay:0,error:new Be({message:`Request failed for ${t.method} ${e}`,code:q.UNEXPECTED,error:l,response:{id:t.id}}),timestamp:Date.now()})}let o=i[i.length-1]?.error;return{id:t.id,error:o,retryHistory:i}}var zt=class{constructor(t,e="",a={}){k(this,"fetch");k(this,"baseUrl");k(this,"defaultHeaders");this.fetch=t,this.baseUrl=e,this.defaultHeaders=Object.freeze({...a})}setDefaultHeader(t,e){this.defaultHeaders={...this.defaultHeaders,[t]:e}}async executeFetch(t,e){let a={...e,headers:{...this.defaultHeaders,...e?.headers},id:Te()};return e?.retry?pu(()=>this.fetch(t,{...a,retry:void 0}),a,t):this.fetch(t,a)}async get(t,e){return this.executeFetch(t,{...e,method:"GET"})}async post(t,e,a){return this.executeFetch(t,{...a,method:"POST",body:JSON.stringify(e)})}async delete(t,e){return this.executeFetch(t,{...e,method:"DELETE"})}};async function mu(r,t){let e=t.id??Te(),a={id:e};t.headers??(t.headers={}),t.headers["X-Request-Id"]=e;try{let i=await fetch(r,t);if(a.data=await i.json(),a.status=i.status,a.headers=Object.fromEntries(i.headers.entries()),!i.ok){let n=new Be({message:`Request failed for ${t.method} ${r}`,code:pa({backendErrorId:a.data?.error?.errorId,status:a.status}),response:{...a}});a.error=n}}catch(i){let n=new Be({message:`Request failed for ${t.method} ${r}`,code:pa({status:a.status}),response:{...a},error:i});a.error=n}return a}var di=class extends zt{constructor(){super(...arguments);k(this,"configurationSubscribers",new Set);k(this,"_configuration")}async getConfiguration(){let e=await this.get(this.baseUrl);return e.data&&(this._configuration=e.data),e}subscribe(e){return this.configurationSubscribers.add(e),()=>{this.configurationSubscribers.delete(e)}}get configuration(){return this._configuration}set configuration(e){this._configuration=e,this.configurationSubscribers.forEach(a=>a(this._configuration))}},ci=class extends zt{async getPaymentInstruments(){return this.get(`${this.baseUrl}/payment-instruments`)}async postCardPaymentInstruments(){return this.post(`${this.baseUrl}/payment-instruments`,"pci-card-form-data")}async postPaypalPaymentInstruments(t,e){return this.post(`${this.baseUrl}/payment-instruments`,{paymentInstrument:t,...e})}async postPaymentInstruments(t){return this.post(`${this.baseUrl}/payment-instruments`,{paymentInstrument:t})}async postRedirectPaymentInstruments(t){return this.postPaymentInstruments(t)}async postApplePayPaymentInstruments(t){return this.postPaymentInstruments(t)}async postGooglePayPaymentInstruments(t){return this.postPaymentInstruments(t)}async postBlikPaymentInstruments(t){return this.postPaymentInstruments(t)}async postPaymentInstrumentsExchange(t){return this.post(`${this.baseUrl}/payment-instruments/${t}/exchange`,"payment-instrument-exchange")}async postCreatePayment(t,e){return this.post(`${this.baseUrl}/payments`,{paymentMethodToken:t},e?{headers:{"X-Idempotency-Key":e}}:void 0)}async postResumePayment(t,e){return this.post(`${this.baseUrl}/payments/${t}/resume`,{resumeToken:e})}async post3dsAuth(t,e){return this.post(`${this.baseUrl}/3ds/${t}/auth`,e,{retry:{attempts:15}})}async post3dsContinue(t){return this.post(`${this.baseUrl}/3ds/${t}/continue`,{platform:"WEB",status:"FAILURE"})}async get3dsResumeStatus(t){return this.get(t)}async deletePaymentInstrument(t){return this.delete(`${this.baseUrl}/payment-instruments/${t}/vault`)}async postClientSessionActions(t){return this.post(`${this.baseUrl}/client-session/actions`,{actions:t})}async getResumeStatus(t){return this.get(t)}};async function hu(r){return new Promise((t,e)=>{let a=co(r,"api"),i=`${mc}#${a}`,n=document.querySelector(`iframe[src="${i}"]`)??document.createElement("iframe");n.parentElement?t(n):(n.style.display="none",n.onload=()=>t(n),n.onerror=o=>{e(new Error(`Failed to initialize Primer SDK: ${o}`))},n.src=i,document.body.appendChild(n))})}var Nt=class Nt extends zt{constructor(){super(...arguments);k(this,"onClientSessionUpdate");k(this,"onPaymentMethodAction");k(this,"selectedPaymentMethodType",null)}setOnClientSessionUpdate(e){this.onClientSessionUpdate=e}setOnPaymentMethodAction(e){this.onPaymentMethodAction=e}async postClientSessionActions(e){if(e.length===0)return Nt.noActionsResponse;let a=await this.post(`${this.baseUrl}/client-session/actions`,{actions:e}),{data:i}=a;return i&&this.onClientSessionUpdate?.(i),a}async selectPaymentMethod(e,a={}){return this.selectedPaymentMethodType===e||(this.selectedPaymentMethodType=e,this.onPaymentMethodAction?.("PAYMENT_METHOD_SELECTED",{paymentMethodType:e}),e==="PAYMENT_CARD"&&!a.binData)?Nt.noActionsResponse:this.postClientSessionActions([{type:"SELECT_PAYMENT_METHOD",params:{...a,paymentMethodType:e}}])}async unselectPaymentMethod(){return this.onPaymentMethodAction?.("PAYMENT_METHOD_UNSELECTED",{paymentMethodType:this.selectedPaymentMethodType}),this.selectedPaymentMethodType=null,this.postClientSessionActions([{type:"UNSELECT_PAYMENT_METHOD"}])}async selectCardNetwork(e){return this.selectPaymentMethod(B.PAYMENT_CARD,{binData:this.buildCardBinData(e)})}async setBillingAddress(e){let a=this.removeEmptyStringFromObject(e);return Object.values(a).length===0?Nt.noActionsResponse:this.postClientSessionActions([{type:"SET_BILLING_ADDRESS",params:{billingAddress:a}}])}async setShippingAddress(e,a,i){let n=[];return e&&Object.keys(e).some(s=>!!e[s])&&n.push({type:"SET_SHIPPING_ADDRESS",params:{shippingAddress:e}}),a&&n.push({type:"SET_MOBILE_NUMBER",params:{mobileNumber:a}}),i&&n.push({type:"SET_EMAIL_ADDRESS",params:{emailAddress:i}}),this.postClientSessionActions(n)}async selectShippingMethod(e){return this.postClientSessionActions([{type:"SELECT_SHIPPING_METHOD",params:{shippingMethodId:e}}])}async setCustomerDetails({emailAddress:e,firstName:a,lastName:i}){let n=[];return e&&n.push({type:"SET_EMAIL_ADDRESS",params:{emailAddress:e}}),a&&n.push({type:"SET_CUSTOMER_FIRST_NAME",params:{firstName:a}}),i&&n.push({type:"SET_CUSTOMER_LAST_NAME",params:{lastName:i}}),this.postClientSessionActions(n)}buildCardBinData(e){let{backend:a}=Ja(e);return{network:a,issuer_name:null,product_code:a,product_name:a,product_usage_type:"UNKNOWN",account_number_type:"UNKNOWN",issuer_country_code:null,account_funding_type:"UNKNOWN",issuer_currency_code:null,regional_restriction:"UNKNOWN",prepaid_reloadable_indicator:"NOT_APPLICABLE"}}removeEmptyStringFromObject(e){let a={...e};for(let i in a)a[i]===""?delete a[i]:typeof a[i]=="object"&&a[i]!==null&&!Array.isArray(a[i])&&(a[i]=this.removeEmptyStringFromObject(a[i]));return a}};k(Nt,"noActionsResponse",{data:{},error:void 0,headers:{},status:200,id:""});var ui=Nt,pi=class extends zt{async createPaypalOrder(t){return this.post(`${this.baseUrl}/paypal/orders/create`,t,{retry:{attempts:3}})}async createPaypalBillingAgreement(t){return this.post(`${this.baseUrl}/paypal/billing-agreements/create-agreement`,t,{retry:{attempts:3}})}async confirmPaypalBillingAgreement(t){return this.post(`${this.baseUrl}/paypal/billing-agreements/confirm-agreement`,t,{retry:{attempts:3}})}async createApplePaySession(t){return this.post(`${this.baseUrl}/apple-pay/sessions`,t)}};async function gu(r,{locale:t,dialogProvider:e,translate:a,clientOptions:i}){let n=Te(),o=Ht(r),s=await hu(n),l=bi({namespace:`api-controller-${n}`,onMessage:E=>{let L=K=>{if(K.data?.data?.error?.name==="RequestError"){let j=Object.assign(new Be({...K.data.data.error}),K.data.data.error);typeof j.error=="object"&&"message"in j.error&&(j.error=Object.assign(new Error(j.error.message),{stack:j.error.stack})),K.data.data.error=j}return E(K.data)};return window.addEventListener("message",L),()=>window.removeEventListener("message",L)},sendMessage:E=>{s.contentWindow.postMessage(E,"*")}}),c=lu(o.accessToken,n),m=new di(mu,o.configurationUrl,c),g=Date.now(),{error:h}=await m.getConfiguration();if(h||!m.configuration)throw new Error(`Failed to fetch configuration: ${h}`);let T=new ci(l.fetch,m.configuration.pciUrl,c),M=new pi(l.fetch,m.configuration.coreUrl,c),_=new ui(l.fetch,m.configuration.pciUrl,c);_.setOnClientSessionUpdate(E=>{m.configuration=E});let x=new Set;return{get configuration(){return m.configuration},onClientConfigurationUpdate(E){return m.subscribe(E)},checkoutSessionId:n,apiController:l,configurationApi:m,pciApi:T,coreApi:M,clientSessionApi:_,dialogProvider:e,decodedClientToken:o,locale:t||navigator.language||navigator.languages[0]||"en",configurationFetchStartTime:g,translate:a??((E,L)=>L),clientOptions:i,updateClientToken(E){try{let L=Ht(E);m.setDefaultHeader("primer-client-token",L.accessToken),T.setDefaultHeader("primer-client-token",L.accessToken),M.setDefaultHeader("primer-client-token",L.accessToken),_.setDefaultHeader("primer-client-token",L.accessToken)}catch{}},async refreshClientConfiguration(){let{data:E,error:L}=await m.getConfiguration();return L||!E?(C.warn("Failed to refresh client configuration:",L),!1):(m.configuration=E,!0)},subscribeToTeardown(E){return x.add(E),()=>{x.delete(E)}},teardown(){s.remove(),x.forEach(E=>E())}}}var yu=100;function fu({height:r,name:t,url:e="",width:a}){let i=new Set,n=window.open(e,t,Su({height:r,width:a}));if(!n)return;function o(){n?.close(),s()}function s(){i.forEach(l=>l()),i.clear(),window.removeEventListener("beforeunload",o)}return window.addEventListener("beforeunload",o),vu(n).then(s),{close:o,focus(){n.focus()},get isOpen(){return n?.closed===!1},onClose(l){return i.add(l),()=>{i.delete(l)}},setContent(l){n.document.write(l)},setUrl(l){n.location.replace(l)}}}var vu=r=>new Promise(t=>{let e=setInterval(()=>{r.closed&&(clearInterval(e),t())},yu)});function Su(r){let t=bu({parent:{left:window.screenLeft,top:window.screenTop,height:window.outerHeight,width:window.outerWidth},popup:r});return Au(t)}var bu=({parent:r,popup:t})=>({left:r.left+(r.width-t.width)/2,top:r.top+(r.height-t.height)/2,height:t.height,width:t.width}),Au=r=>Object.entries(r).map(t=>t.join("=")).join(","),Cu=({name:r,background:t,logoSrc:e,logoAlt:a,message:i})=>`<html>
|
|
37
37
|
<head>
|
|
38
38
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
39
39
|
<style>
|
|
@@ -141,9 +141,9 @@ import{a as _a,b as d,c as k}from"./chunks/chunk.DV3REKZU.js";var wa=class{const
|
|
|
141
141
|
</div>
|
|
142
142
|
</body>
|
|
143
143
|
</html>
|
|
144
|
-
`,mi=class extends mt{constructor(){super(...arguments);k(this,"popup");k(this,"shouldRedirect",!1);k(this,"dialogPromise")}async start(){try{let e=this.callbacks.onStart();(this.config.forceRedirect||this.context.clientOptions.redirect?.forceRedirect||Jd())&&(this.shouldRedirect=!0);let a=document.createElement("div");a.setAttribute("style","display: flex; flex-direction: column; gap: var(--primer-size-xlarge);");let i=document.createElement("div");i.setAttribute("style",`display: flex;margin:auto;padding:calc(var(--primer-size-small)*0.5);height: var(--primer-size-xlarge);background-color: ${this.backgroundColor};border-radius:var(--primer-radius-small);`);let n=document.createElement("img");n.src=this.logoSrc,i.appendChild(n),a.appendChild(i);let o=document.createElement("p");o.setAttribute("style","max-width: 300px;text-align: center;"),o.innerText=this.context.translate("paymentMethodPopupOverlayDescription","Having trouble viewing the {paymentMethodName} payment page? We'll help you find it!").replace("{paymentMethodName}",this.config.name),a.appendChild(o),this.dialogPromise=this.context.dialogProvider.show({htmlContent:a,showCloseButton:!0,size:"flex",cta:{label:this.context.translate("paymentMethodPopupOverlayBringBackThePaymentPage","Bring back the payment page"),icon:"chevron-left",onClick:()=>{this.popup?.focus()}}}),this.shouldRedirect||(this.openPopup(),this.popup&&await Yt(300),this.popup?.isOpen||(this.shouldRedirect=!0));let{action:s}=await e;if(s==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type});let l=await this.tokenize();this.callbacks.onFinish(l)}catch(e){this.context.dialogProvider.close(),this.popup?.close(),this.callbacks.onFinish(void 0,e)}}async tokenize(){let{error:e,data:a}=await this.context.pciApi.postRedirectPaymentInstruments({type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:this.context.locale,platform:ao()?"MOBILE_WEB":"WEB",browserInfo:Si(),merchantRedirectUrl:this.context.clientOptions.redirect?.returnUrl}});if(e||!a)throw e??new z({message:"Unable to tokenize payment method",code:F.TOKENIZATION_ERROR});return a}async createPayment(e){try{let a=await super.createPayment(e),i=a.requiredAction?.clientToken;if(!i)throw new z({message:"No client token provided"});let n=Ht(i);if(!zd(n,this.config.type))throw new z({message:"Invalid client token"});if(this.shouldRedirect)return kt({eventName:"PAYMENT_REDIRECT_TO_THIRD_PARTY",paymentMethod:this.config.type,redirectDestinationUrl:n.redirectUrl}),window.location.assign(n.redirectUrl),Promise.resolve(a);if(!this.popup?.isOpen)return this.unselect(),this.context.dialogProvider.close(),a;this.popup?.setUrl(n.redirectUrl);let o=(this.dialogPromise??Promise.resolve()).then(()=>({id:"",popupClosed:!0})),s=new Promise(h=>{this.popup?.onClose(()=>{C.debug("Popup closed"),h({id:"",popupClosed:!0})})}),{promise:l,abort:c}=this.pollStatus(n.statusUrl),m=await Promise.race([o,s,l]);if(c(),this.popup?.close(),this.context.dialogProvider.close(),"error"in m)throw m.error;if("popupClosed"in m&&m.popupClosed&&!this.context.clientOptions.redirect?.resumePaymentOnPopupClosure)return this.unselect(),a;let g=m.id;if(!g){let h=await this.context.pciApi.getResumeStatus(n.statusUrl);if(h.error||!h.data?.id)throw h.error??new Error("Unable to get resume token");g=h.data.id}return await this.resumePayment(a.id,g)}catch(a){throw this.context.dialogProvider.close(),this.popup?.close(),a}}unselect(){this.context.clientSessionApi.unselectPaymentMethod()}pollStatus(e){let a=!0;return{promise:new Promise(async i=>{for(;a;){let{data:n,error:o}=await this.context.pciApi.getResumeStatus(e);if(o)return void i({error:o});if(await Yt(1e3),n?.status==="COMPLETE")return void i({id:n.id})}}),abort:()=>{C.debug("Polling aborted"),a=!1}}}openPopup(){let{name:e,displayMetadata:{popup:a}}=this.config;this.popup=fu({name:e,height:a?.height??500,width:a?.width??1e3}),this.popup?.setContent(Cu({name:e,background:this.backgroundColor,logoSrc:this.logoSrc,logoAlt:e,message:`Loading ${e}...`}))}get backgroundColor(){let{displayMetadata:{button:e,overlay:a}}=this.config;return a?.backgroundColor.colored||e?.backgroundColor.colored||a?.backgroundColor.light||e?.backgroundColor.light||a?.backgroundColor.dark||e?.backgroundColor.dark||"#FFFFFF"}get logoSrc(){let{displayMetadata:{button:e,overlay:a}}=this.config;return a?.logo.colored||e?.iconUrl.colored||a?.logo.light||e?.iconUrl.light||a?.logo.dark||e?.iconUrl.dark}},Mu=[B.ADYEN_AFFIRM,B.ADYEN_BANCONTACT_CARD,B.ADYEN_BANCONTACT_PAYCONIQ,B.ADYEN_EPS,B.ADYEN_KLARNA,B.ADYEN_MBWAY,B.ADYEN_MULTIBANCO,B.GO_CARDLESS,B.KLARNA,B.MOLLIE_GIFT_CARD,B.NETS,B.OMISE_PROMPTPAY,B.PAY_NL_KAARTDIRECT,B.PAY_NL_PAYPAL,B.RAPYD_FAST,B.RAPYD_PROMPTPAY,B.STRIPE_ACH,B.XFERS_PAYNOW];async function Eu(r,t){let e=r.configuration.paymentMethods.filter(({type:i})=>!t||t.includes(i)).map(i=>{if(Mu.includes(i.type))return C.warn(`Payment method ${i.type} is not supported in sdk core.`),null;if(C.debug("Initializing payment method:",i.type),i.implementationType==="WEB_REDIRECT")return new mi(i,r);if(i.type===B.PAYMENT_CARD)return new ja(i,r);if(i.type===B.PAYPAL)return new Za(i,r);if(i.type===B.APPLE_PAY)return new $a(i,r);if(i.type===B.GOOGLE_PAY)return new Wa(i,r);if(i.type===B.ADYEN_BLIK)return new za(i,r)}).map(async i=>{if(!i)return null;try{return await i.setup()?i:null}catch(n){return C.warn(`Failed to initialize payment method ${i.config.type}:`,n),null}});return(await Promise.all(e)).filter(i=>!!i)}function Tu(r,t,e){if(!t.configuration.clientSession.customer?.customerId)throw new G({message:"You must provide a `customerId` in the client session to use the Vault Manager."});let a=[];return{async fetchVaultedPaymentMethods(){let{data:i,error:n}=await t.pciApi.getPaymentInstruments();if(n)throw n;if(!i)throw new G({code:Ba.VAULT_ERROR,message:"Missing vaulted payment methods data"});return a=i.data,a},async deleteVaultedPaymentMethod(i){if(!a.find(s=>s.id===i))throw new G({code:Ba.VAULT_ERROR,message:"deleteVaultedPaymentMethod: the id provided doesn't match any vaulted payment method"});let{error:o}=await t.pciApi.deletePaymentInstrument(i);if(o)throw o;a=a.filter(s=>s.id!==i)},async startPaymentFlow(i){let n=a.find(s=>s.id===i);if(!n)throw new G({code:Ba.VAULT_ERROR,message:"startPaymentFlow: the id provided doesn't match any vaulted payment method"});let o=e.find(s=>s.config.type===n.paymentMethodType);if(!o)throw new z({code:Ba.TOKENIZATION_ERROR,message:`Payment instrument type ${n.paymentInstrumentType} is not recognized or not supported.`});await ma(r,o,n)},async createCvvInput(i){let n={blur:new Set,change:new Set,focus:new Set},o,s=da(t.checkoutSessionId,Mn);await new Promise(h=>{s.onload=()=>{h()},(typeof i.container=="string"?document.querySelector(i.container):i.container)?.appendChild(s)}),li(s,i.style),s.setAttribute("title",i.ariaLabel||"");let l=bi({namespace:`${t.checkoutSessionId}-${Mn}`,onMessage:h=>{let T=M=>h(M.data);return window.addEventListener("message",T),()=>window.removeEventListener("message",T)},sendMessage:h=>{s.contentWindow.postMessage(h,"*")}});function c(h,T){h!=="metadata"&&n[h].add(T)}l.setOnFocus(()=>{n.focus.forEach(h=>h())}),l.setOnBlur(()=>{n.blur.forEach(h=>h())}),l.setOnInput(h=>{o=h,n.change.forEach(T=>T())}),l.setCardNetwork(i.cardNetwork??""),l.setOptions({placeholder:i.placeholder??"123",ariaLabel:i.ariaLabel??"CVV",style:i.style});function m(){s.parentNode&&s.remove()}let g=t.subscribeToTeardown(m);return{frame:s,remove:()=>{g(),m()},get metadata(){return{error:o?.error??"cvvRequired",errorCode:o?.error??"cvvRequired",valid:o?.valid??!1,active:o?.focused??!1,dirty:o?.dirty??!1,touched:o?.touched??!1,submitted:!0}},addEventListener:c,addListener:c,removeListener(h,T){h!=="metadata"&&n[h].delete(T)},blur(){l.blur()},focus(){l.focus()},validate(){l.getFieldState().then(h=>{o=h,n.change.forEach(T=>T(o))})}}}}}async function vo(r,t){C.debug("createHeadless",t);let e=await gu(r,{locale:t.locale,dialogProvider:t.dialogProvider,translate:t.translate,clientOptions:{paypal:t.paypal,applePay:t.applePay,googlePay:t.googlePay,merchantDomain:t.merchantDomain,redirect:t.redirect}}),a=await Eu(e,t.enabledPaymentMethods);t.onClientSessionUpdate?.(e.configuration.clientSession),e.onClientConfigurationUpdate(async n=>{t.onClientSessionUpdate?.(n.clientSession)}),t.onPaymentMethodAction&&e.clientSessionApi.setOnPaymentMethodAction(t.onPaymentMethodAction);let i={environment:si?"LOCAL":e.decodedClientToken.env,primerAccountId:e.configuration.primerAccountId,checkoutSessionId:e.checkoutSessionId,clientSessionId:e.configuration.clientSession?.clientSessionId,clientSessionToken:r,sdkVersion:t.sdkVersion,configurationFetchStartTime:e.configurationFetchStartTime};return Rd({environment:si?"LOCAL":e.decodedClientToken.env,primerAccountId:i.primerAccountId||"",checkoutSessionId:i.checkoutSessionId,clientSessionId:i.clientSessionId||"",clientSessionToken:i.clientSessionToken,sdkVersion:i.sdkVersion||"",userAgent:typeof navigator<"u"?navigator.userAgent:"unknown"}),t.onAvailablePaymentMethodsLoad?.(a.map(n=>({type:n.config.type,managerType:n.config.type===B.PAYMENT_CARD?Wr.CARD:n.config.implementationType==="NATIVE_SDK"?Wr.NATIVE:Wr.REDIRECT}))),{start:async()=>{if(e.decodedClientToken.intent==="REDIRECTION_END"){let{data:n,error:o}=await e.pciApi.postResumePayment(e.decodedClientToken.paymentId,e.decodedClientToken.resumeToken);fo(t,n,o)}},createPaymentMethodManager:async(n,o)=>{let s=a.find(({config:l})=>l.type===n);return s?s instanceof ja?ru(t,e,s,o):s instanceof Za||s instanceof $a||s instanceof Wa?nu(t,e,s):s instanceof za?su(t,e,s):ou(t,e,s):(C.warn(`Payment method ${n} not found`),null)},getSDKUtilities:()=>({getCardNetworkAsset:Gn,getUIOrderAmount:()=>{let{merchantAmount:n,totalOrderAmount:o,currencyCode:s}=e.configuration.clientSession.order;return io(e.locale,n??o,s)},getCDNAssets:async n=>{let o=a.find(({config:c})=>c.type===n);if(!o)return;let{backgroundColor:s,iconUrl:l}=o.config.displayMetadata?.button||{};return{assets:{icon:l?.colored||""},colors:{background:s?.colored||"",main:s?.colored||""},description:o.config.name||null,is_primer_app:!1,name:o.config.name,website:null,goatCdnUrl:""}},getPaymentMethodConfiguration:n=>a.find(({config:o})=>o.type===n)?.config,setBillingAddress:async n=>{let{error:o,data:s}=await e.clientSessionApi.setBillingAddress(n);if(o||!s)throw o||new G({message:"Failed to set billing address"})}}),getAnalyticsUtils:()=>i,createVaultManager(){return Tu(t,e,a)},getAssetsManager:()=>({getCardNetworkAsset:Gn,getPaymentMethodAsset:async n=>{let o=a.find(({config:m})=>m.type===n);if(!o)return null;let{backgroundColor:s,iconUrl:l,text:c}=o.config.displayMetadata?.button||{};return{backgroundColor:s,iconUrl:l,paymentMethodName:c,buttonText:c,displayName:o.config.name}}}),refreshClientSession:e.refreshClientConfiguration,getConfiguration:()=>e.configuration,teardown:()=>e.teardown()}}var Gn=r=>{let{asset:t,display:e}=Ja(r);return{cardUrl:`${gc}/brand/card/${t}.svg`,displayName:e}},Pu=new Set(["paymentMethodType","last4Digits","network","accountNumberLastFourDigits","bankName"]);function Wt(r){let{id:t,orderId:e,paymentMethodData:a}=r,i={id:t,orderId:e};if(!a||typeof a!="object")return i;let n={};for(let[o,s]of Object.entries(a))Pu.has(o)&&(n[o]=s);return i.paymentMethodData=n,i}var Nu={PAYMENT_CARD:{fields:["last4Digits","network","cardholderName","expirationMonth","expirationYear"]},PAYPAL_BILLING_AGREEMENT:{path:"externalPayerInfo",fields:["externalPayerId","email","firstName","lastName"]},KLARNA_CUSTOMER_TOKEN:{path:"sessionData.billingAddress",fields:["email","firstName","lastName","phoneNumber"]},AUTOMATED_CLEARING_HOUSE:{fields:["accountNumberLastFourDigits","bankName","accountType"]}};function Iu(r,t){let e=r;for(let a of t.split(".")){if(!e||typeof e!="object")return;e=e[a]}return e&&typeof e=="object"?e:void 0}function ku(r,t){if(!r)return;let e={};for(let a of t)r[a]!==void 0&&(e[a]=r[a]);return Object.keys(e).length>0?e:void 0}function So(r){let{id:t,analyticsId:e,paymentMethodType:a,paymentInstrumentType:i,paymentInstrumentData:n,userDescription:o}=r,s=Nu[i],l;if(s&&n&&typeof n=="object"){let c=s.path?Iu(n,s.path):n;l=ku(c,s.fields)}return{id:t,analyticsId:e,paymentMethodType:a,paymentInstrumentType:i,...o&&{userDescription:o},...l&&{paymentInstrumentData:l}}}var Zt=class{constructor(t){(this.host=t).addController(this)}hostConnected(){}dispatchEvent(t,e){this.host.dispatchEvent(new CustomEvent(t,{detail:e,bubbles:!0,composed:!0}))}dispatchSdkState(t){this.dispatchEvent("primer:state-change",t)}dispatchPaymentMethods(t){this.dispatchEvent("primer:methods-update",t)}dispatchCheckoutInitialized(t){this.dispatchEvent("primer:ready",t)}dispatchCardNetworkChange(t){this.dispatchEvent("primer:card-network-change",t)}dispatchBinDataAvailable(t){this.dispatchEvent("primer:bin-data-available",t)}dispatchBinDataLoadingChange(t){this.dispatchEvent("primer:bin-data-loading-change",{loading:t})}dispatchCardSubmit(t){this.dispatchEvent("primer:card-submit",{source:t})}dispatchFormSubmitSuccess(t){this.dispatchEvent("primer:card-success",{result:t})}dispatchFormSubmitErrors(t){this.dispatchEvent("primer:card-error",{errors:t})}dispatchPaymentCancel(t){let e=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:payment-cancel",{...t,timestamp:e})}handleExternalCardSubmit(t){this.dispatchCardSubmit(t.source)}dispatchPaymentStart(t,e){let a=Math.floor(Date.now()/1e3),i=!1,n=new CustomEvent("primer:payment-start",{detail:{paymentMethodType:t,abortPaymentCreation:()=>{i=!0,e.abortPaymentCreation()},continuePaymentCreation:o=>{i=!0,e.continuePaymentCreation(o)},timestamp:a},bubbles:!0,composed:!0,cancelable:!0});return this.host.dispatchEvent(n),n.defaultPrevented?!0:i}dispatchPaymentSuccess(t,e){let a=Wt(t),i=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:payment-success",{payment:a,paymentMethodType:e,timestamp:i})}dispatchPaymentFailure(t,e,a){let i=Math.floor(Date.now()/1e3),n=a?Wt(a):void 0;this.dispatchEvent("primer:payment-failure",{error:t,payment:n,paymentMethodType:e,timestamp:i})}dispatchVaultMethodsUpdate(t,e){let a=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:vault-methods-update",{vaultedPayments:t,cvvRecapture:e,timestamp:a})}dispatchVaultSelectionChange(t){let e=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:vault-selection-change",{paymentMethodId:t,timestamp:e})}dispatchVaultSubmit(t){this.dispatchEvent("primer:vault-submit",{source:t})}handleExternalVaultSubmit(t){this.dispatchVaultSubmit(t.source)}dispatchShowOtherPaymentsToggle(t,e){this.dispatchEvent("primer:show-other-payments-toggle",{action:t,source:e})}handleExternalShowOtherPaymentsToggle(t){this.dispatchShowOtherPaymentsToggle(t.action,t.source)}dispatchShowOtherPaymentsToggled(t){this.dispatchEvent("primer:show-other-payments-toggled",{expanded:t})}};var ht=class extends Event{constructor(t,e,a,i){super("context-request",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=e,this.callback=a,this.subscribe=i??!1}};var Jt=class{constructor(t,e,a,i){if(this.subscribe=!1,this.provided=!1,this.value=void 0,this.t=(n,o)=>{this.unsubscribe&&(this.unsubscribe!==o&&(this.provided=!1,this.unsubscribe()),this.subscribe||this.unsubscribe()),this.value=n,this.host.requestUpdate(),this.provided&&!this.subscribe||(this.provided=!0,this.callback&&this.callback(n,o)),this.unsubscribe=o},this.host=t,e.context!==void 0){let n=e;this.context=n.context,this.callback=n.callback,this.subscribe=n.subscribe??!1}else this.context=e,this.callback=a,this.subscribe=i??!1;this.host.addController(this)}hostConnected(){this.dispatchRequest()}hostDisconnected(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=void 0)}dispatchRequest(){this.host.dispatchEvent(new ht(this.context,this.host,this.t,this.subscribe))}};var Qa=class{get value(){return this.o}set value(t){this.setValue(t)}setValue(t,e=!1){let a=e||!Object.is(t,this.o);this.o=t,a&&this.updateObservers()}constructor(t){this.subscriptions=new Map,this.updateObservers=()=>{for(let[e,{disposer:a}]of this.subscriptions)e(this.o,a)},t!==void 0&&(this.value=t)}addCallback(t,e,a){if(!a)return void t(this.value);this.subscriptions.has(t)||this.subscriptions.set(t,{disposer:()=>{this.subscriptions.delete(t)},consumerHost:e});let{disposer:i}=this.subscriptions.get(t);t(this.value,i)}clearCallbacks(){this.subscriptions.clear()}};var Ai=class extends Event{constructor(t,e){super("context-provider",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=e}},W=class extends Qa{constructor(t,e,a){super(e.context!==void 0?e.initialValue:a),this.onContextRequest=i=>{if(i.context!==this.context)return;let n=i.contextTarget??i.composedPath()[0];n!==this.host&&(i.stopPropagation(),this.addCallback(i.callback,n,i.subscribe))},this.onProviderRequest=i=>{if(i.context!==this.context||(i.contextTarget??i.composedPath()[0])===this.host)return;let n=new Set;for(let[o,{consumerHost:s}]of this.subscriptions)n.has(o)||(n.add(o),s.dispatchEvent(new ht(this.context,s,o,!0)));i.stopPropagation()},this.host=t,e.context!==void 0?this.context=e.context:this.context=e,this.attachListeners(),this.host.addController?.(this)}attachListeners(){this.host.addEventListener("context-request",this.onContextRequest),this.host.addEventListener("context-provider",this.onProviderRequest)}hostConnected(){this.host.dispatchEvent(new Ai(this.context,this.host))}};function A({context:r,subscribe:t}){return(e,a)=>{typeof a=="object"?a.addInitializer((function(){new Jt(this,{context:r,callback:i=>{e.set.call(this,i)},subscribe:t})})):e.constructor.addInitializer((i=>{new Jt(i,{context:r,callback:n=>{i[a]=n},subscribe:t})}))}}var gt=Symbol("analytics-context");var Ve=Symbol("events-context");var Xa="cardNetworksContext";var ge="clientOptionsContext";var qt="computedStylesContext";var $="headlessInstanceContext";var er="configuration";var tr="klarnaCategoriesContext";var Z="managerContext";var yt="paymentMethodsContext";var J="sdkStateContext";var ye="vaultManagerContext";var He="vaultManagerCvvContext";function Lu(r,t,e,a){let i=r,n=e;return{dispatch:o=>{let s=i,l=t(i,o,n);rr(s,l)?i=l:(i=l,a(l))},getState:()=>Object.freeze({...i}),setCallbacks:o=>{n={...n,...o}}}}function rr(r,t,e=0,a=10){if(e>a)return r===t;if(r===t)return!0;if(r==null||t==null||typeof r!="object"||typeof t!="object")return!1;let i=Object.keys(r);if(i.length!==Object.keys(t).length)return!1;for(let n of i){if(!(n in t))return!1;let o=r[n],s=t[n];if(typeof o=="object"&&o!==null&&(typeof s=="object"&&s!==null)){if(!rr(o,s,e+1,a))return!1}else if(o!==s)return!1}return!0}function Ci(r){return(t,e,a)=>{let i=r[e.type];if(!i)throw new Error(`No handler for action type: ${e.type}`);return i(t,e,a)}}var Lt=class{constructor(t,e,a,i,n=()=>{this.host.requestUpdate()}){this.host=t;this.stateHandler=n;this.host.addController(this),this._dispatcher=Lu(e,a,i,o=>{this.stateHandler(o)})}get currentState(){return this._dispatcher.getState()}dispatch(t){this._dispatcher.dispatch(t)}setCallbacks(t){this._dispatcher.setCallbacks(t)}hostConnected(){}hostDisconnected(){}},ar=class{constructor(t){this.host=t;this._controllers=[];"addController"in this.host&&this.host.addController(this)}addController(t){this._controllers.push(t)}hostConnected(){this._controllers.forEach(t=>{t.hostConnected&&t.hostConnected()})}hostDisconnected(){this._controllers.forEach(t=>{t.hostDisconnected&&t.hostDisconnected()})}};var bo={isSuccessful:!1,isProcessing:!1,isLoading:!1,primerJsError:null,paymentFailure:null},Ao=bo;function Ru(r,t){switch(t.type){case"SET_LOADING":return{...r,isLoading:t.payload};case"SET_PROCESSING":return{...r,isProcessing:t.payload,...t.payload&&{primerJsError:null,paymentFailure:null}};case"SET_SUCCESS":return{...r,isSuccessful:t.payload};case"SET_PRIMER_JS_ERROR":return{...r,primerJsError:t.payload};case"SET_PAYMENT_FAILURE":return{...r,isProcessing:!1,paymentFailure:t.payload};case"COMPLETE_PROCESSING":return{...r,isProcessing:!1,isSuccessful:!0};case"RESET":return{isSuccessful:!1,isProcessing:!1,isLoading:!1,primerJsError:null,paymentFailure:null};default:return r}}var ir=class extends Lt{constructor(t){super(t,bo,Ru,null,e=>{t.sdkContextController.setSdkState(e),t.primerEventsController.dispatchSdkState(e)})}setLoading(t){this.dispatch({type:"SET_LOADING",payload:t})}setProcessing(t){this.dispatch({type:"SET_PROCESSING",payload:t})}setSuccess(t){this.dispatch({type:"SET_SUCCESS",payload:t})}setPrimerJsError(t){this.dispatch({type:"SET_PRIMER_JS_ERROR",payload:t})}setPaymentFailure(t){this.dispatch({type:"SET_PAYMENT_FAILURE",payload:t})}completeProcessing(){this.dispatch({type:"COMPLETE_PROCESSING"})}reset(){this.dispatch({type:"RESET"})}startLoading(){this.setLoading(!0)}completeLoading(){this.setLoading(!1)}startProcessing(){this.setProcessing(!0)}stopProcessing(){this.setProcessing(!1)}resetError(){this.setPrimerJsError(null),this.setPaymentFailure(null)}forceCompleteLoading(){this.setLoading(!1)}};var nr=class{constructor(t){this.sdkStateProvider=null;this.paymentMethodsProvider=null;this.paymentManagerProvider=null;this.cardNetworksContext=null;this.vaultManagerCvvProvider=null;this.clientOptionsContext=null;this.headlessUtilsProvider=null;this.configurationProvider=null;this.klarnaCategoriesProvider=null;this.computedStylesProvider=null;this.analyticsProvider=null;this.eventsProvider=null;(this.host=t).addController(this),this.sdkStateProvider=new W(t,{context:J,initialValue:Ao}),this.paymentMethodsProvider=new W(t,{context:yt,initialValue:null}),this.paymentManagerProvider=new W(t,{context:Z,initialValue:new Map}),this.cardNetworksContext=new W(t,{context:Xa,initialValue:null}),this.vaultManagerProvider=new W(t,{context:ye,initialValue:null}),this.vaultManagerCvvProvider=new W(t,{context:He,initialValue:null}),this.clientOptionsContext=new W(t,{context:ge,initialValue:null}),this.klarnaCategoriesProvider=new W(t,{context:tr,initialValue:{categories:[],isLoading:!0}}),this.headlessUtilsProvider=new W(t,{context:$,initialValue:null}),this.configurationProvider=new W(t,{context:er,initialValue:null}),this.computedStylesProvider=new W(t,{context:qt,initialValue:null}),this.analyticsProvider=new W(t,{context:gt,initialValue:null}),this.eventsProvider=new W(t,{context:Ve,initialValue:null})}hostConnected(){}setSdkState(t){this.sdkStateProvider?.setValue(t)}setPaymentMethods(t){this.paymentMethodsProvider?.setValue(t)}setPaymentManagers(t){this.paymentManagerProvider?.setValue(t)}setCardNetworks(t){this.cardNetworksContext?.setValue(t)}setVaultManager(t){this.vaultManagerProvider?.setValue(t)}setKlarnaCategories(t){this.klarnaCategoriesProvider?.setValue(t)}setClientOptions(t){this.clientOptionsContext?.setValue(t)}setHeadlessUtils(t){this.headlessUtilsProvider?.setValue(t)}setConfiguration(t){this.configurationProvider?.setValue(t)}setAnalyticsUtils(t){this.analyticsProvider?.setValue(t)}getAnalyticsUtils(){return this.analyticsProvider?.value}setComputedStyles(t){this.computedStylesProvider?.setValue(t)}setVaultManagerCvv(t){this.vaultManagerCvvProvider?.setValue(t)}setEventsController(t){this.eventsProvider?.setValue(t)}};var Mi=class{constructor(){k(this,"context",null)}initialize(t){this.context=t,P.debug("Session context initialized:",{checkoutSessionId:t.checkoutSessionId,clientSessionId:t.clientSessionId,primerAccountId:t.primerAccountId,environment:t.environment})}getContext(){return this.context}clear(){P.debug("Session context cleared"),this.context=null}isInitialized(){return this.context!==null}setSdkInitStartTime(t){this.context&&(this.context.sdkInitStartTime=t)}getSdkInitStartTime(){return this.context?.sdkInitStartTime}},Ye=new Mi;var xu={LOCAL:"https://analytics.dev.data.primer.io/v1/sdk-logs",DEV:"https://analytics.dev.data.primer.io/v1/sdk-logs",STAGING:"https://analytics.staging.data.primer.io/v1/sdk-logs",SANDBOX:"https://analytics.sandbox.data.primer.io/v1/sdk-logs",PRODUCTION:"https://analytics.production.data.primer.io/v1/sdk-logs"};function Co(r,t={}){let e=Ye.getContext();if(!e&&!t?.environment)return;let i={message:r instanceof Error?r.message:typeof r=="string"?r:JSON.stringify(r)};r instanceof Error&&r.stack&&(i.stack=r.stack),e?Object.assign(i,{primer:{checkout_session_id:e.checkoutSessionId,client_session_id:e.clientSessionId,primer_account_id:e.primerAccountId},user_agent:e.userAgent}):(t?.checkoutSessionId&&Object.assign(i,{primer:{checkout_session_id:t.checkoutSessionId}}),t?.clientSessionId&&Object.assign(i,{primer:{client_session_id:t.clientSessionId}}),t?.primerAccountId&&Object.assign(i,{primer:{primer_account_id:t.primerAccountId}}),t?.userAgent&&Object.assign(i,{user_agent:t.userAgent})),t?.metadata&&Object.assign(i,t.metadata),t.status&&(i.status=t.status);let n={message:JSON.stringify(i),hostname:typeof window<"u"?window.location.hostname:"unknown",service:"web-sdk",ddsource:"lambda",ddtags:`env:${e?.environment||t?.environment},version:${e?.sdkVersion||t?.sdkVersion}`};_u(n,{environment:e?.environment||t?.environment,clientSessionToken:e?.clientSessionToken||t?.clientSessionToken})}var Mo=(r,t={})=>Co(r,{...t,status:"error"});function Eo(r){let t={event:"CHECKOUT_INITIALIZED"};r!==void 0&&(t.init_duration_ms=r),Co("Checkout initialized",{status:"info",metadata:t})}function _u(r,{environment:t,clientSessionToken:e}){if(t==="LOCAL"||r.hostname==="localhost"){P.debug("\u{1F436}\u{1F436}\u{1F436} [Datadog Log] \u{1F436}\u{1F436}\u{1F436}",r);return}let a=xu[t||"LOCAL"];if(!a){P.warn("No logging endpoint configured for current environment");return}fetch(a,{method:"POST",headers:{"Content-Type":"application/json",...e&&{Authorization:`Bearer ${e}`}},body:JSON.stringify(r)}).catch(i=>{P.error("Failed to send log event:",i)})}var H=class H{static _log(t,e,...a){H.enabled&&a.forEach(i=>{i instanceof Error&&i.toJSON})}static log(t,...e){H._log("log",t,...e)}static info(t,...e){H._log("info",t,...e)}static warn(t,...e){H._log("warn",t,...e)}static error(t,...e){H._log("error",t,...e)}static debug(t,...e){this._log("debug",t,...e)}static errorWithDatadog(t,e){let{error:a,status:i="error"}=e||{};if(H.enabled){a instanceof Error&&a.toJSON;try{let n={status:i,metadata:{sdkOptions:H.sdkOptions,clientToken:H.clientToken,error:a}};Mo(t,n)}catch{H.enabled}}}static setSdkOptions(t){H.sdkOptions=t}static setClientToken(t){H.clientToken=t}};k(H,"enabled",!0),k(H,"sdkOptions"),k(H,"clientToken"),k(H,"defaultFont","font-family: Consolas, monospace; font-size: 12px;"),k(H,"brandTag","[PRIMER]"),k(H,"brandStyle",`background: #24292e; color: #ffffff; padding: 2px 6px; border-radius: 3px; font-weight: bold; margin-right: 4px; ${H.defaultFont}`),k(H,"styles",{log:`color: #4CAF50; ${H.defaultFont}`,info:`color: #2196F3; ${H.defaultFont}`,warn:`color: #FF9800; ${H.defaultFont}`,error:`color: #F44336; ${H.defaultFont}`,debug:`color: #9C27B0; ${H.defaultFont}`});var P=H;var Rt=class Rt{constructor(t){(this.host=t).addController(this)}processCustomStyles(t){try{let e=JSON.parse(t);this.applyStyles(e)}catch(e){P.error("Error parsing customStyles property.",e instanceof Error?e:new Error(String(e)))}}isValidCssProperty(t){return/^[a-zA-Z][a-zA-Z0-9]*$/.test(t)}isValidCssValue(t){let a=/^[\w\s#.,%()\-+/!]+$/.test(t);return a||P.warn(`Rejected potentially unsafe CSS value: ${t}`),a}getCssVarName(t){let e=Rt.cssVarCache.get(t);return e||(e=`--${t.replace(/([A-Z])/g,(a,i)=>`-${i.toLowerCase()}`)}`,Rt.cssVarCache.set(t,e)),e}applyStyles(t){let e=[];for(let a of Object.keys(t)){let i=t[a];if(!i)continue;if(!this.isValidCssProperty(a)){P.warn(`Skipping invalid CSS property name: ${a}`);continue}if(!this.isValidCssValue(i))continue;let n=this.getCssVarName(a);e.push([n,i])}if(e.length>0)for(let[a,i]of e)this.host.style.setProperty(a,i)}removeStyle(t){let e=this.getCssVarName(t);this.host.style.removeProperty(e)}clearAllStyles(){for(let t of Rt.cssVarCache.keys()){let e=Rt.cssVarCache.get(t);e&&this.host.style.removeProperty(e)}}hostDisconnected(){}};Rt.cssVarCache=new Map;var or=Rt;var sr=globalThis,dr=sr.ShadowRoot&&(sr.ShadyCSS===void 0||sr.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Po=Symbol(),To=new WeakMap,lr=class{constructor(t,e,a){if(this._$cssResult$=!0,a!==Po)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o,e=this.t;if(dr&&t===void 0){let a=e!==void 0&&e.length===1;a&&(t=To.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),a&&To.set(e,t))}return t}toString(){return this.cssText}},No=r=>new lr(typeof r=="string"?r:r+"",void 0,Po);var Ei=(r,t)=>{if(dr)r.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let a=document.createElement("style"),i=sr.litNonce;i!==void 0&&a.setAttribute("nonce",i),a.textContent=e.cssText,r.appendChild(a)}},cr=dr?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let e="";for(let a of t.cssRules)e+=a.cssText;return No(e)})(r):r;var{is:wu,defineProperty:Du,getOwnPropertyDescriptor:Bu,getOwnPropertyNames:Ou,getOwnPropertySymbols:Gu,getPrototypeOf:Ku}=Object,ft=globalThis,Io=ft.trustedTypes,Fu=Io?Io.emptyScript:"",Uu=ft.reactiveElementPolyfillSupport,ha=(r,t)=>r,Ti={toAttribute(r,t){switch(t){case Boolean:r=r?Fu:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,t){let e=r;switch(t){case Boolean:e=r!==null;break;case Number:e=r===null?null:Number(r);break;case Object:case Array:try{e=JSON.parse(r)}catch{e=null}}return e}},ur=(r,t)=>!wu(r,t),ko={attribute:!0,type:String,converter:Ti,reflect:!1,hasChanged:ur};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),ft.litPropertyMetadata??(ft.litPropertyMetadata=new WeakMap);var xt=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??(this.l=[])).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=ko){if(e.state&&(e.attribute=!1),this._$Ei(),this.elementProperties.set(t,e),!e.noAccessor){let a=Symbol(),i=this.getPropertyDescriptor(t,a,e);i!==void 0&&Du(this.prototype,t,i)}}static getPropertyDescriptor(t,e,a){let{get:i,set:n}=Bu(this.prototype,t)??{get(){return this[e]},set(o){this[e]=o}};return{get(){return i?.call(this)},set(o){let s=i?.call(this);n.call(this,o),this.requestUpdate(t,s,a)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??ko}static _$Ei(){if(this.hasOwnProperty(ha("elementProperties")))return;let t=Ku(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(ha("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(ha("properties"))){let e=this.properties,a=[...Ou(e),...Gu(e)];for(let i of a)this.createProperty(i,e[i])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[a,i]of e)this.elementProperties.set(a,i)}this._$Eh=new Map;for(let[e,a]of this.elementProperties){let i=this._$Eu(e,a);i!==void 0&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let e=[];if(Array.isArray(t)){let a=new Set(t.flat(1/0).reverse());for(let i of a)e.unshift(cr(i))}else t!==void 0&&e.push(cr(t));return e}static _$Eu(t,e){let a=e.attribute;return a===!1?void 0:typeof a=="string"?a:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((t=>t(this)))}addController(t){(this._$EO??(this._$EO=new Set)).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,e=this.constructor.elementProperties;for(let a of e.keys())this.hasOwnProperty(a)&&(t.set(a,this[a]),delete this[a]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Ei(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach((t=>t.hostConnected?.()))}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach((t=>t.hostDisconnected?.()))}attributeChangedCallback(t,e,a){this._$AK(t,a)}_$EC(t,e){let a=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,a);if(i!==void 0&&a.reflect===!0){let n=(a.converter?.toAttribute!==void 0?a.converter:Ti).toAttribute(e,a.type);this._$Em=t,n==null?this.removeAttribute(i):this.setAttribute(i,n),this._$Em=null}}_$AK(t,e){let a=this.constructor,i=a._$Eh.get(t);if(i!==void 0&&this._$Em!==i){let n=a.getPropertyOptions(i),o=typeof n.converter=="function"?{fromAttribute:n.converter}:n.converter?.fromAttribute!==void 0?n.converter:Ti;this._$Em=i,this[i]=o.fromAttribute(e,n.type),this._$Em=null}}requestUpdate(t,e,a){if(t!==void 0){if(a??(a=this.constructor.getPropertyOptions(t)),!(a.hasChanged??ur)(this[t],e))return;this.P(t,e,a)}this.isUpdatePending===!1&&(this._$ES=this._$ET())}P(t,e,a){this._$AL.has(t)||this._$AL.set(t,e),a.reflect===!0&&this._$Em!==t&&(this._$Ej??(this._$Ej=new Set)).add(t)}async _$ET(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(let[i,n]of this._$Ep)this[i]=n;this._$Ep=void 0}let a=this.constructor.elementProperties;if(a.size>0)for(let[i,n]of a)n.wrapped!==!0||this._$AL.has(i)||this[i]===void 0||this.P(i,this[i],n)}let t=!1,e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach((a=>a.hostUpdate?.())),this.update(e)):this._$EU()}catch(a){throw t=!1,this._$EU(),a}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EU(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Ej&&(this._$Ej=this._$Ej.forEach((e=>this._$EC(e,this[e])))),this._$EU()}updated(t){}firstUpdated(t){}};xt.elementStyles=[],xt.shadowRootOptions={mode:"open"},xt[ha("elementProperties")]=new Map,xt[ha("finalized")]=new Map,Uu?.({ReactiveElement:xt}),(ft.reactiveElementVersions??(ft.reactiveElementVersions=[])).push("2.0.4");var vt={INITIAL:0,PENDING:1,COMPLETE:2,ERROR:3},w=Symbol(),O=class{get taskComplete(){return this.t||(this.i===1?this.t=new Promise(((t,e)=>{this.o=t,this.h=e})):this.i===3?this.t=Promise.reject(this.l):this.t=Promise.resolve(this.u)),this.t}constructor(t,e,a){this.p=0,this.i=0,(this._=t).addController(this);let i=typeof e=="object"?e:{task:e,args:a};this.v=i.task,this.j=i.args,this.m=i.argsEqual??Lo,this.k=i.onComplete,this.A=i.onError,this.autoRun=i.autoRun??!0,"initialValue"in i&&(this.u=i.initialValue,this.i=2,this.O=this.T?.())}hostUpdate(){this.autoRun===!0&&this.S()}hostUpdated(){this.autoRun==="afterUpdate"&&this.S()}T(){if(this.j===void 0)return;let t=this.j();if(!Array.isArray(t))throw Error("The args function must return an array");return t}async S(){let t=this.T(),e=this.O;this.O=t,t===e||t===void 0||e!==void 0&&this.m(e,t)||await this.run(t)}async run(t){let e,a;t??(t=this.T()),this.O=t,this.i===1?this.q?.abort():(this.t=void 0,this.o=void 0,this.h=void 0),this.i=1,this.autoRun==="afterUpdate"?queueMicrotask((()=>this._.requestUpdate())):this._.requestUpdate();let i=++this.p;this.q=new AbortController;let n=!1;try{e=await this.v(t,{signal:this.q.signal})}catch(o){n=!0,a=o}if(this.p===i){if(e===w)this.i=0;else{if(n===!1){try{this.k?.(e)}catch{}this.i=2,this.o?.(e)}else{try{this.A?.(a)}catch{}this.i=3,this.h?.(a)}this.u=e,this.l=a}this._.requestUpdate()}}abort(t){this.i===1&&this.q?.abort(t)}get value(){return this.u}get error(){return this.l}get status(){return this.i}render(t){switch(this.i){case 0:return t.initial?.();case 1:return t.pending?.();case 2:return t.complete?.(this.value);case 3:return t.error?.(this.error);default:throw Error("Unexpected status: "+this.i)}}},Lo=(r,t)=>r===t||r.length===t.length&&r.every(((e,a)=>!ur(e,t[a])));var Vu={SET_LOADING:(r,t)=>({...r,isLoading:t.payload}),SET_UPDATING:(r,t)=>({...r,isUpdating:t.payload}),INITIALIZE_VAULT_MANAGER:(r,t,e)=>({...r,enabled:t.vaultEnabled,cvvRecapture:t.cvvRecapture,showEmptyState:t.showEmptyState,headless:t.headless,deleteVaultedPaymentMethod:e.deleteVaultedPaymentMethod,startVaultedPaymentFlow:e.startVaultedPaymentFlow,createCvvInput:e.createCvvInput}),UPDATE_PAYMENT_METHODS:(r,t)=>({...r,vaultedPaymentMethods:t.payload,isLoading:!1,isUpdating:!1}),SET_ERROR:r=>({...r,isLoading:!1,isUpdating:!1}),DISABLE:r=>({...r,enabled:!1}),RESET:()=>Ro},Hu={INITIALIZE_CVV:(r,t,e)=>({...r,setCvvInput:e.setCvvInput,setSelectedVaultedPaymentMethod:e.setSelectedVaultedPaymentMethod}),SET_FORM_DIRTY:(r,t)=>({...r,formIsDirty:t.payload}),SET_CVV_INPUT:(r,t)=>({...r,cvvInput:t.payload}),SET_SELECTED_VAULTED_PAYMENT_METHOD:(r,t)=>({...r,selectedVaultedPaymentMethod:t.payload}),RESET_CVV:()=>xo},Yu=Ci(Vu),$u=Ci(Hu),Ro={enabled:!1,isLoading:!1,isUpdating:!1,cvvRecapture:!1,showEmptyState:!1,headless:!1,vaultedPaymentMethods:[],createCvvInput:null,deleteVaultedPaymentMethod:()=>Promise.resolve(),startVaultedPaymentFlow:()=>Promise.resolve()},xo={cvvInput:null,formIsDirty:!1,setCvvInput:()=>{},selectedVaultedPaymentMethod:null,setSelectedVaultedPaymentMethod:()=>{}},Pi=class extends Lt{constructor(t,e){super(t,Ro,Yu,e,a=>{t.sdkContextController.setVaultManager(a)})}setLoading(t){this.dispatch({type:"SET_LOADING",payload:t})}setUpdating(t){this.dispatch({type:"SET_UPDATING",payload:t})}initializeVaultManager(t,e,a,i,n){this.dispatch({type:"INITIALIZE_VAULT_MANAGER",payload:t,vaultEnabled:e,cvvRecapture:a,showEmptyState:i,headless:n})}updatePaymentMethods(t){this.dispatch({type:"UPDATE_PAYMENT_METHODS",payload:t})}setError(t){this.dispatch({type:"SET_ERROR",payload:t})}disable(){this.dispatch({type:"DISABLE"})}reset(){this.dispatch({type:"RESET"})}},Ni=class extends Lt{constructor(t,e){super(t,xo,$u,e,a=>{t.sdkContextController.setVaultManagerCvv(a)})}initializeCvv(t){this.dispatch({type:"INITIALIZE_CVV",createCvvInput:t})}setFormDirty(t){this.dispatch({type:"SET_FORM_DIRTY",payload:t})}setCvvInputState(t){this.dispatch({type:"SET_CVV_INPUT",payload:t})}setSelectedPaymentMethod(t){this.dispatch({type:"SET_SELECTED_VAULTED_PAYMENT_METHOD",payload:t})}resetCvv(){this.dispatch({type:"RESET_CVV"})}},ga=class extends ar{constructor(e){super(e);this._vaultManager=null;this._options=null;this.createVaultManagerFn=null;this.createCvvInput=e=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");return this._vaultManager.createCvvInput(e)};this.deleteVaultedPaymentMethod=async e=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");try{this.coreController.updatePaymentMethods(this.vaultManagerState.vaultedPaymentMethods),await this._vaultManager.deleteVaultedPaymentMethod(e),await this.fetchVaultedPaymentMethods()}catch(a){let i=a instanceof Error?a:new Error("Failed to delete payment method");throw this.coreController.setError(i),this.host.sdkStateController.setPrimerJsError(i),a}};this.setCvvInput=e=>{this.itemController.setCvvInputState(e)};this.startVaultedPaymentFlow=async()=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");let e=this.vaultItemState.selectedVaultedPaymentMethod,a=this.vaultManagerState.cvvRecapture,i=this.vaultItemState.cvvInput;if(!e||a&&(!i||i.metadata.error)){this.itemController.setFormDirty(!0);return}this.host.sdkStateController.startProcessing();try{await this._vaultManager.startPaymentFlow(e.id,a?{cvv:i.valueToken}:void 0)}catch(n){P.errorWithDatadog("VaultManagerController: Error starting vaulted payment flow",{error:n});let o=n instanceof Error?n:new Error("Failed to start vaulted payment flow");this.coreController.setError(o),this.host.sdkStateController.setPrimerJsError(o),this.host.sdkStateController.stopProcessing()}};this.setSelectedVaultedPaymentMethod=e=>{this.itemController.setSelectedPaymentMethod(e),this.itemController.setFormDirty(!1),this.host.primerEventsController.dispatchVaultSelectionChange(e?.id??null)};this.startVaultPaymentById=async(e,a)=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");let i=this.vaultManagerState.vaultedPaymentMethods.find(n=>n.id===e);if(!i)throw new Error(`Payment method not found: ${e}`);this.setSelectedVaultedPaymentMethod(i),this.host.sdkStateController.startProcessing();try{await this._vaultManager.startPaymentFlow(e,a?.cvv?{cvv:a.cvv}:void 0)}catch(n){P.errorWithDatadog("VaultManagerController: Error starting vaulted payment flow",{error:n});let o=n instanceof Error?n:new Error("Failed to start vaulted payment flow");throw this.coreController.setError(o),this.host.sdkStateController.setPrimerJsError(o),this.host.sdkStateController.stopProcessing(),n}};this.coreController=new Pi(e,{deleteVaultedPaymentMethod:this.deleteVaultedPaymentMethod.bind(this),startVaultedPaymentFlow:this.startVaultedPaymentFlow.bind(this),createCvvInput:this.createCvvInput}),this.itemController=new Ni(e,{setCvvInput:this.setCvvInput.bind(this),setSelectedVaultedPaymentMethod:this.setSelectedVaultedPaymentMethod.bind(this)}),this.addController(this.coreController),this.addController(this.itemController),new O(this.host,{task:async([a,i])=>{if(!a||!i?.vaultEnabled)return this.coreController.disable(),w;this.coreController.setLoading(!0);try{let n=a();this._vaultManager=n,this.coreController.initializeVaultManager(n,i.vaultEnabled,!!i.captureVaultedCardCvv,i.showEmptyState??!1,i.headless??!1),this.itemController.initializeCvv(n.createCvvInput),await this.fetchVaultedPaymentMethods(!0),P.log("VaultManagerController: Vault initialized successfully",{coreState:this.coreController.currentState,cvvState:this.itemController.currentState})}catch(n){P.errorWithDatadog("VaultManagerController: Failed to initialize vault",{error:n});let o=n instanceof Error?n:new Error("Unknown error");this.coreController.setError(o),this.host.sdkStateController.setPrimerJsError(o)}return this._vaultManager},args:()=>[this.createVaultManagerFn,this.options]})}initializeVaultManager(e,a){this.createVaultManagerFn=e,this.options=a??null}get vaultManager(){return this._vaultManager}set vaultManager(e){this._vaultManager=e,this.host.requestUpdate()}get options(){return this._options}set options(e){this._options=e,this.host.requestUpdate()}get vaultManagerState(){return this.coreController.currentState}get vaultItemState(){return this.itemController.currentState}hostDisconnected(){super.hostDisconnected(),this.vaultManager=null,this.coreController.reset()}createVaultedPaymentsArray(e){return e.map(a=>So(a))}updatePaymentMethodsWithEvents(e){this.coreController.updatePaymentMethods(e);let a=this.createVaultedPaymentsArray(e);this.host.primerEventsController.dispatchVaultMethodsUpdate(a,this.vaultManagerState.cvvRecapture),this.host.primerJS?.handleVaultedMethodsUpdate(a,this.vaultManagerState.cvvRecapture),P.log("VaultManagerController: Dispatched vault methods update",{methodCount:e.length,filteredMethodCount:a.length})}async fetchVaultedPaymentMethods(e){if(!this._vaultManager)throw new Error("Vault manager not initialized");try{e||this.coreController.setUpdating(!0);let a=await this._vaultManager.fetchVaultedPaymentMethods();return P.log("VaultManagerController: Fetched payment methods",a),this.updatePaymentMethodsWithEvents(a),a}catch(a){let i=a instanceof Error?a:new Error("Failed to fetch payment methods");throw this.coreController.setError(i),this.host.sdkStateController.setPrimerJsError(i),a}}};var _o=()=>wo.randomUUID?.()||zu(),zu=()=>("10000000-1000-4000-8000"+-1e11).replace(/[018]/g,r=>(r^ju()>>r/4).toString(16)),ju=()=>(wo.getRandomValues?.(new Uint8Array(1))[0]??Math.random()*16)&15,wo=typeof crypto<"u"?crypto:{};var Wu={LOCAL:"https://analytics.sandbox.data.primer.io/v1/sdk-analytic-events",DEV:"https://analytics.dev.data.primer.io/v1/sdk-analytic-events",STAGING:"https://analytics.staging.data.primer.io/v1/sdk-analytic-events",SANDBOX:"https://analytics.sandbox.data.primer.io/v1/sdk-analytic-events",PRODUCTION:"https://analytics.production.data.primer.io/v1/sdk-analytic-events"},Ii=class{sendEvent(t){let e=Ye.getContext();if(!e)return;let a={id:_o(),timestamp:Math.floor(Date.now()/1e3),sdkType:"WEB",eventName:t.eventName,checkoutSessionId:e.checkoutSessionId,clientSessionId:e.clientSessionId,primerAccountId:e.primerAccountId,sdkVersion:e.sdkVersion,userAgent:e.userAgent,eventType:t.eventType,userLocale:t.userLocale,paymentMethod:t.paymentMethod,paymentId:t.paymentId,redirectDestinationUrl:t.redirectDestinationUrl,threedsProvider:t.threedsProvider,threedsResponse:t.threedsResponse};Ju(a,e)}},Zu=new Ii;function Do(r){let t={...r,userAgent:r.userAgent||(typeof navigator<"u"?navigator.userAgent:"")};Ye.initialize(t)}function Q(r){Zu.sendEvent(r)}function Bo(){Ye.clear()}async function Ju(r,{environment:t,clientSessionToken:e}){if(t==="LOCAL"){P.debug(`Analytics event ${r.eventName}:`,r);return}let a=Wu[t];return fetch(a,{method:"POST",headers:{"Content-Type":"application/json",...e&&{Authorization:`Bearer ${e}`}},body:JSON.stringify(r)}).catch(i=>{P.error("Failed to send analytics event:",i)})}var ya="lit-localize-status";var Oo=r=>typeof r!="string"&&"strTag"in r,pr=(r,t,e)=>{let a=r[0];for(let i=1;i<r.length;i++)a+=t[e?e[i-1]:i-1],a+=r[i];return a};var fa=(r=>Oo(r)?pr(r.strings,r.values):r);var b=fa,Go=!1;function ki(r){if(Go)throw new Error("lit-localize can only be configured once");b=r,Go=!0}var Li=class{constructor(t){this.__litLocalizeEventHandler=e=>{e.detail.status==="ready"&&this.host.requestUpdate()},this.host=t}hostConnected(){window.addEventListener(ya,this.__litLocalizeEventHandler)}hostDisconnected(){window.removeEventListener(ya,this.__litLocalizeEventHandler)}},qu=r=>r.addController(new Li(r)),Ko=qu;var D=()=>(r,t)=>(r.addInitializer(Ko),r);var va=class{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._resolve=t,this._reject=e})}resolve(t){this.settled=!0,this._resolve(t)}reject(t){this.settled=!0,this._reject(t)}};var tt=[];for(let r=0;r<256;r++)tt[r]=(r>>4&15).toString(16)+(r&15).toString(16);function Fo(r){let t=0,e=8997,a=0,i=33826,n=0,o=40164,s=0,l=52210;for(let c=0;c<r.length;c++)e^=r.charCodeAt(c),t=e*435,a=i*435,n=o*435,s=l*435,n+=e<<8,s+=i<<8,a+=t>>>16,e=t&65535,n+=a>>>16,i=a&65535,l=s+(n>>>16)&65535,o=n&65535;return tt[l>>8]+tt[l&255]+tt[o>>8]+tt[o&255]+tt[i>>8]+tt[i&255]+tt[e>>8]+tt[e&255]}var Qu="",Xu="h",ep="s";function Uo(r,t){return(t?Xu:ep)+Fo(typeof r=="string"?r:r.join(Qu))}var Vo=new WeakMap,Ho=new Map;function Yo(r,t,e){if(r){let a=e?.id??tp(t),i=r[a];if(i){if(typeof i=="string")return i;if("strTag"in i)return pr(i.strings,t.values,i.values);{let n=Vo.get(i);return n===void 0&&(n=i.values,Vo.set(i,n)),{...i,values:n.map(o=>t.values[o])}}}}return fa(t)}function tp(r){let t=typeof r=="string"?r:r.strings,e=Ho.get(t);return e===void 0&&(e=Uo(t,typeof r!="string"&&!("strTag"in r)),Ho.set(t,e)),e}function Ri(r){window.dispatchEvent(new CustomEvent(ya,{detail:r}))}var hr="",xi,$o,gr,_i,zo,_t=new va;_t.resolve();var mr=0,jo=r=>(ki(((t,e)=>Yo(zo,t,e))),hr=$o=r.sourceLocale,gr=new Set(r.targetLocales),gr.add(r.sourceLocale),_i=r.loadLocale,{getLocale:ap,setLocale:rp}),ap=()=>hr,rp=r=>{if(r===(xi??hr))return _t.promise;if(!gr||!_i)throw new Error("Internal error");if(!gr.has(r))throw new Error("Invalid locale code");mr++;let t=mr;return xi=r,_t.settled&&(_t=new va),Ri({status:"loading",loadingLocale:r}),(r===$o?Promise.resolve({templates:void 0}):_i(r)).then(a=>{mr===t&&(hr=r,xi=void 0,zo=a.templates,Ri({status:"ready",readyLocale:r}),_t.resolve())},a=>{mr===t&&(Ri({status:"error",errorLocale:r,errorMessage:a.toString()}),_t.reject(a))}),_t.promise};var wi="en",Di=["ar","bg","ca","cs","da","de","el","en-GB","es","es-AR","es-MX","et-EE","fi-FI","fr","he","hr","hu","id","it","ja","ko","lt","lt-LT","lv","lv-LV","ms","nb","nl","nl_NL","pl","pt","pt-BR","ro","ru","sk","sl","sr-RS","sv","th","tr","uk-UA","vi","zf","zh-CN","zh-HK","zh-TW"],Bi="You must call `loadLocale` first to set up the localized template.",yr,fr,Wo=r=>{let t=jo({sourceLocale:wi,targetLocales:Di,loadLocale:r});yr=t.getLocale,fr=t.setLocale};var Oi=r=>{Wo(r)},Gi=r=>{if(!fr)throw new Error(Bi);return fr(r)},Ki=()=>{if(!yr)throw new Error(Bi);return yr()};var Sa=new Set(Di);Sa.add(wi);var Fi=r=>{if(typeof r!="string")return!1;if(r==="en")return!0;let t=r.replace("_","-");if(Sa.has(t))return!0;let e=t.split("-")[0];return!!Sa.has(e)},vr=()=>navigator.language||navigator.languages[0]||"en",Qt=r=>{let t=r.replace("_","-"),e=t.split("-")[0];return e==="en"?"en-GB":Sa.has(t)?t:Sa.has(e)?e:"en-GB"};var Sr=globalThis,br=Sr.ShadowRoot&&(Sr.ShadyCSS===void 0||Sr.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Ui=Symbol(),Zo=new WeakMap,ba=class{constructor(t,e,a){if(this._$cssResult$=!0,a!==Ui)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o,e=this.t;if(br&&t===void 0){let a=e!==void 0&&e.length===1;a&&(t=Zo.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),a&&Zo.set(e,t))}return t}toString(){return this.cssText}},fe=r=>new ba(typeof r=="string"?r:r+"",void 0,Ui),f=(r,...t)=>{let e=r.length===1?r[0]:t.reduce(((a,i,n)=>a+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+r[n+1]),r[0]);return new ba(e,r,Ui)},Jo=(r,t)=>{if(br)r.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let a=document.createElement("style"),i=Sr.litNonce;i!==void 0&&a.setAttribute("nonce",i),a.textContent=e.cssText,r.appendChild(a)}},Vi=br?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let e="";for(let a of t.cssRules)e+=a.cssText;return fe(e)})(r):r;var{is:ip,defineProperty:np,getOwnPropertyDescriptor:op,getOwnPropertyNames:sp,getOwnPropertySymbols:lp,getPrototypeOf:dp}=Object,St=globalThis,qo=St.trustedTypes,cp=qo?qo.emptyScript:"",up=St.reactiveElementPolyfillSupport,Aa=(r,t)=>r,Ca={toAttribute(r,t){switch(t){case Boolean:r=r?cp:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,t){let e=r;switch(t){case Boolean:e=r!==null;break;case Number:e=r===null?null:Number(r);break;case Object:case Array:try{e=JSON.parse(r)}catch{e=null}}return e}},Ar=(r,t)=>!ip(r,t),Qo={attribute:!0,type:String,converter:Ca,reflect:!1,useDefault:!1,hasChanged:Ar};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),St.litPropertyMetadata??(St.litPropertyMetadata=new WeakMap);var at=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??(this.l=[])).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=Qo){if(e.state&&(e.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){let a=Symbol(),i=this.getPropertyDescriptor(t,a,e);i!==void 0&&np(this.prototype,t,i)}}static getPropertyDescriptor(t,e,a){let{get:i,set:n}=op(this.prototype,t)??{get(){return this[e]},set(o){this[e]=o}};return{get:i,set(o){let s=i?.call(this);n?.call(this,o),this.requestUpdate(t,s,a)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Qo}static _$Ei(){if(this.hasOwnProperty(Aa("elementProperties")))return;let t=dp(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Aa("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Aa("properties"))){let e=this.properties,a=[...sp(e),...lp(e)];for(let i of a)this.createProperty(i,e[i])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[a,i]of e)this.elementProperties.set(a,i)}this._$Eh=new Map;for(let[e,a]of this.elementProperties){let i=this._$Eu(e,a);i!==void 0&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let e=[];if(Array.isArray(t)){let a=new Set(t.flat(1/0).reverse());for(let i of a)e.unshift(Vi(i))}else t!==void 0&&e.push(Vi(t));return e}static _$Eu(t,e){let a=e.attribute;return a===!1?void 0:typeof a=="string"?a:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((t=>t(this)))}addController(t){(this._$EO??(this._$EO=new Set)).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,e=this.constructor.elementProperties;for(let a of e.keys())this.hasOwnProperty(a)&&(t.set(a,this[a]),delete this[a]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Jo(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach((t=>t.hostConnected?.()))}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach((t=>t.hostDisconnected?.()))}attributeChangedCallback(t,e,a){this._$AK(t,a)}_$ET(t,e){let a=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,a);if(i!==void 0&&a.reflect===!0){let n=(a.converter?.toAttribute!==void 0?a.converter:Ca).toAttribute(e,a.type);this._$Em=t,n==null?this.removeAttribute(i):this.setAttribute(i,n),this._$Em=null}}_$AK(t,e){let a=this.constructor,i=a._$Eh.get(t);if(i!==void 0&&this._$Em!==i){let n=a.getPropertyOptions(i),o=typeof n.converter=="function"?{fromAttribute:n.converter}:n.converter?.fromAttribute!==void 0?n.converter:Ca;this._$Em=i,this[i]=o.fromAttribute(e,n.type)??this._$Ej?.get(i)??null,this._$Em=null}}requestUpdate(t,e,a){if(t!==void 0){let i=this.constructor,n=this[t];if(a??(a=i.getPropertyOptions(t)),!((a.hasChanged??Ar)(n,e)||a.useDefault&&a.reflect&&n===this._$Ej?.get(t)&&!this.hasAttribute(i._$Eu(t,a))))return;this.C(t,e,a)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,e,{useDefault:a,reflect:i,wrapped:n},o){a&&!(this._$Ej??(this._$Ej=new Map)).has(t)&&(this._$Ej.set(t,o??e??this[t]),n!==!0||o!==void 0)||(this._$AL.has(t)||(this.hasUpdated||a||(e=void 0),this._$AL.set(t,e)),i===!0&&this._$Em!==t&&(this._$Eq??(this._$Eq=new Set)).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(let[i,n]of this._$Ep)this[i]=n;this._$Ep=void 0}let a=this.constructor.elementProperties;if(a.size>0)for(let[i,n]of a){let{wrapped:o}=n,s=this[i];o!==!0||this._$AL.has(i)||s===void 0||this.C(i,void 0,n,s)}}let t=!1,e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach((a=>a.hostUpdate?.())),this.update(e)):this._$EM()}catch(a){throw t=!1,this._$EM(),a}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&(this._$Eq=this._$Eq.forEach((e=>this._$ET(e,this[e])))),this._$EM()}updated(t){}firstUpdated(t){}};at.elementStyles=[],at.shadowRootOptions={mode:"open"},at[Aa("elementProperties")]=new Map,at[Aa("finalized")]=new Map,up?.({ReactiveElement:at}),(St.reactiveElementVersions??(St.reactiveElementVersions=[])).push("2.1.0");var Ea=globalThis,Cr=Ea.trustedTypes,Xo=Cr?Cr.createPolicy("lit-html",{createHTML:r=>r}):void 0,Yi="$lit$",rt=`lit$${Math.random().toFixed(9).slice(2)}$`,$i="?"+rt,pp=`<${$i}>`,Bt=document,Ta=()=>Bt.createComment(""),Pa=r=>r===null||typeof r!="object"&&typeof r!="function",zi=Array.isArray,ns=r=>zi(r)||typeof r?.[Symbol.iterator]=="function",Hi=`[
|
|
144
|
+
`,mi=class extends mt{constructor(){super(...arguments);k(this,"popup");k(this,"shouldRedirect",!1);k(this,"dialogPromise")}async start(){try{let e=this.callbacks.onStart();(this.config.forceRedirect||this.context.clientOptions.redirect?.forceRedirect||Jd())&&(this.shouldRedirect=!0);let a=document.createElement("div");a.setAttribute("style","display: flex; flex-direction: column; gap: var(--primer-size-xlarge);");let i=document.createElement("div");i.setAttribute("style",`display: flex;margin:auto;padding:calc(var(--primer-size-small)*0.5);height: var(--primer-size-xlarge);background-color: ${this.backgroundColor};border-radius:var(--primer-radius-small);`);let n=document.createElement("img");n.src=this.logoSrc,i.appendChild(n),a.appendChild(i);let o=document.createElement("p");o.setAttribute("style","max-width: 300px;text-align: center;"),o.innerText=this.context.translate("paymentMethodPopupOverlayDescription","Having trouble viewing the {paymentMethodName} payment page? We'll help you find it!").replace("{paymentMethodName}",this.config.name),a.appendChild(o),this.dialogPromise=this.context.dialogProvider.show({htmlContent:a,showCloseButton:!0,size:"flex",cta:{label:this.context.translate("paymentMethodPopupOverlayBringBackThePaymentPage","Bring back the payment page"),icon:"chevron-left",onClick:()=>{this.popup?.focus()}}}),this.shouldRedirect||(this.openPopup(),this.popup&&await Yt(300),this.popup?.isOpen||(this.shouldRedirect=!0));let{action:s}=await e;if(s==="abort")throw new G({message:"Payment creation aborted",code:F.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type});let l=await this.tokenize();this.callbacks.onFinish(l)}catch(e){this.context.dialogProvider.close(),this.popup?.close(),this.callbacks.onFinish(void 0,e)}}async tokenize(){let{error:e,data:a}=await this.context.pciApi.postRedirectPaymentInstruments({type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:this.context.locale,platform:ao()?"MOBILE_WEB":"WEB",browserInfo:Si(),merchantRedirectUrl:this.context.clientOptions.redirect?.returnUrl}});if(e||!a)throw e??new z({message:"Unable to tokenize payment method",code:F.TOKENIZATION_ERROR});return a}async createPayment(e){try{let a=await super.createPayment(e),i=a.requiredAction?.clientToken;if(!i)throw new z({message:"No client token provided"});let n=Ht(i);if(!zd(n,this.config.type))throw new z({message:"Invalid client token"});if(this.shouldRedirect)return kt({eventName:"PAYMENT_REDIRECT_TO_THIRD_PARTY",paymentMethod:this.config.type,redirectDestinationUrl:n.redirectUrl}),window.location.assign(n.redirectUrl),Promise.resolve(a);if(!this.popup?.isOpen)return this.unselect(),this.context.dialogProvider.close(),{...a,cancelled:!0};this.popup?.setUrl(n.redirectUrl);let o=(this.dialogPromise??Promise.resolve()).then(()=>({id:"",popupClosed:!0})),s=new Promise(h=>{this.popup?.onClose(()=>{C.debug("Popup closed"),h({id:"",popupClosed:!0})})}),{promise:l,abort:c}=this.pollStatus(n.statusUrl),m=await Promise.race([o,s,l]);if(c(),this.popup?.close(),this.context.dialogProvider.close(),"error"in m)throw m.error;if("popupClosed"in m&&m.popupClosed&&!this.context.clientOptions.redirect?.resumePaymentOnPopupClosure)return this.unselect(),{...a,cancelled:!0};let g=m.id;if(!g){let h=await this.context.pciApi.getResumeStatus(n.statusUrl);if(h.error||!h.data?.id)throw h.error??new Error("Unable to get resume token");g=h.data.id}return await this.resumePayment(a.id,g)}catch(a){throw this.context.dialogProvider.close(),this.popup?.close(),a}}unselect(){this.context.clientSessionApi.unselectPaymentMethod()}pollStatus(e){let a=!0;return{promise:new Promise(async i=>{for(;a;){let{data:n,error:o}=await this.context.pciApi.getResumeStatus(e);if(o)return void i({error:o});if(await Yt(1e3),n?.status==="COMPLETE")return void i({id:n.id})}}),abort:()=>{C.debug("Polling aborted"),a=!1}}}openPopup(){let{name:e,displayMetadata:{popup:a}}=this.config;this.popup=fu({name:e,height:a?.height??500,width:a?.width??1e3}),this.popup?.setContent(Cu({name:e,background:this.backgroundColor,logoSrc:this.logoSrc,logoAlt:e,message:`Loading ${e}...`}))}get backgroundColor(){let{displayMetadata:{button:e,overlay:a}}=this.config;return a?.backgroundColor.colored||e?.backgroundColor.colored||a?.backgroundColor.light||e?.backgroundColor.light||a?.backgroundColor.dark||e?.backgroundColor.dark||"#FFFFFF"}get logoSrc(){let{displayMetadata:{button:e,overlay:a}}=this.config;return a?.logo.colored||e?.iconUrl.colored||a?.logo.light||e?.iconUrl.light||a?.logo.dark||e?.iconUrl.dark}},Mu=[B.ADYEN_AFFIRM,B.ADYEN_BANCONTACT_CARD,B.ADYEN_BANCONTACT_PAYCONIQ,B.ADYEN_EPS,B.ADYEN_KLARNA,B.ADYEN_MBWAY,B.ADYEN_MULTIBANCO,B.GO_CARDLESS,B.KLARNA,B.MOLLIE_GIFT_CARD,B.NETS,B.OMISE_PROMPTPAY,B.PAY_NL_KAARTDIRECT,B.PAY_NL_PAYPAL,B.RAPYD_FAST,B.RAPYD_PROMPTPAY,B.STRIPE_ACH,B.XFERS_PAYNOW];async function Eu(r,t){let e=r.configuration.paymentMethods.filter(({type:i})=>!t||t.includes(i)).map(i=>{if(Mu.includes(i.type))return C.warn(`Payment method ${i.type} is not supported in sdk core.`),null;if(C.debug("Initializing payment method:",i.type),i.implementationType==="WEB_REDIRECT")return new mi(i,r);if(i.type===B.PAYMENT_CARD)return new ja(i,r);if(i.type===B.PAYPAL)return new Za(i,r);if(i.type===B.APPLE_PAY)return new $a(i,r);if(i.type===B.GOOGLE_PAY)return new Wa(i,r);if(i.type===B.ADYEN_BLIK)return new za(i,r)}).map(async i=>{if(!i)return null;try{return await i.setup()?i:null}catch(n){return C.warn(`Failed to initialize payment method ${i.config.type}:`,n),null}});return(await Promise.all(e)).filter(i=>!!i)}function Tu(r,t,e){if(!t.configuration.clientSession.customer?.customerId)throw new G({message:"You must provide a `customerId` in the client session to use the Vault Manager."});let a=[];return{async fetchVaultedPaymentMethods(){let{data:i,error:n}=await t.pciApi.getPaymentInstruments();if(n)throw n;if(!i)throw new G({code:Ba.VAULT_ERROR,message:"Missing vaulted payment methods data"});return a=i.data,a},async deleteVaultedPaymentMethod(i){if(!a.find(s=>s.id===i))throw new G({code:Ba.VAULT_ERROR,message:"deleteVaultedPaymentMethod: the id provided doesn't match any vaulted payment method"});let{error:o}=await t.pciApi.deletePaymentInstrument(i);if(o)throw o;a=a.filter(s=>s.id!==i)},async startPaymentFlow(i){let n=a.find(s=>s.id===i);if(!n)throw new G({code:Ba.VAULT_ERROR,message:"startPaymentFlow: the id provided doesn't match any vaulted payment method"});let o=e.find(s=>s.config.type===n.paymentMethodType);if(!o)throw new z({code:Ba.TOKENIZATION_ERROR,message:`Payment instrument type ${n.paymentInstrumentType} is not recognized or not supported.`});await ma(r,o,n)},async createCvvInput(i){let n={blur:new Set,change:new Set,focus:new Set},o,s=da(t.checkoutSessionId,Mn);await new Promise(h=>{s.onload=()=>{h()},(typeof i.container=="string"?document.querySelector(i.container):i.container)?.appendChild(s)}),li(s,i.style),s.setAttribute("title",i.ariaLabel||"");let l=bi({namespace:`${t.checkoutSessionId}-${Mn}`,onMessage:h=>{let T=M=>h(M.data);return window.addEventListener("message",T),()=>window.removeEventListener("message",T)},sendMessage:h=>{s.contentWindow.postMessage(h,"*")}});function c(h,T){h!=="metadata"&&n[h].add(T)}l.setOnFocus(()=>{n.focus.forEach(h=>h())}),l.setOnBlur(()=>{n.blur.forEach(h=>h())}),l.setOnInput(h=>{o=h,n.change.forEach(T=>T())}),l.setCardNetwork(i.cardNetwork??""),l.setOptions({placeholder:i.placeholder??"123",ariaLabel:i.ariaLabel??"CVV",style:i.style});function m(){s.parentNode&&s.remove()}let g=t.subscribeToTeardown(m);return{frame:s,remove:()=>{g(),m()},get metadata(){return{error:o?.error??"cvvRequired",errorCode:o?.error??"cvvRequired",valid:o?.valid??!1,active:o?.focused??!1,dirty:o?.dirty??!1,touched:o?.touched??!1,submitted:!0}},addEventListener:c,addListener:c,removeListener(h,T){h!=="metadata"&&n[h].delete(T)},blur(){l.blur()},focus(){l.focus()},validate(){l.getFieldState().then(h=>{o=h,n.change.forEach(T=>T(o))})}}}}}async function vo(r,t){C.debug("createHeadless",t);let e=await gu(r,{locale:t.locale,dialogProvider:t.dialogProvider,translate:t.translate,clientOptions:{paypal:t.paypal,applePay:t.applePay,googlePay:t.googlePay,merchantDomain:t.merchantDomain,redirect:t.redirect}}),a=await Eu(e,t.enabledPaymentMethods);t.onClientSessionUpdate?.(e.configuration.clientSession),e.onClientConfigurationUpdate(async n=>{t.onClientSessionUpdate?.(n.clientSession)}),t.onPaymentMethodAction&&e.clientSessionApi.setOnPaymentMethodAction(t.onPaymentMethodAction);let i={environment:si?"LOCAL":e.decodedClientToken.env,primerAccountId:e.configuration.primerAccountId,checkoutSessionId:e.checkoutSessionId,clientSessionId:e.configuration.clientSession?.clientSessionId,clientSessionToken:r,sdkVersion:t.sdkVersion,configurationFetchStartTime:e.configurationFetchStartTime};return Rd({environment:si?"LOCAL":e.decodedClientToken.env,primerAccountId:i.primerAccountId||"",checkoutSessionId:i.checkoutSessionId,clientSessionId:i.clientSessionId||"",clientSessionToken:i.clientSessionToken,sdkVersion:i.sdkVersion||"",userAgent:typeof navigator<"u"?navigator.userAgent:"unknown"}),t.onAvailablePaymentMethodsLoad?.(a.map(n=>({type:n.config.type,managerType:n.config.type===B.PAYMENT_CARD?Wr.CARD:n.config.implementationType==="NATIVE_SDK"?Wr.NATIVE:Wr.REDIRECT}))),{start:async()=>{if(e.decodedClientToken.intent==="REDIRECTION_END"){let{data:n,error:o}=await e.pciApi.postResumePayment(e.decodedClientToken.paymentId,e.decodedClientToken.resumeToken);fo(t,n,o)}},createPaymentMethodManager:async(n,o)=>{let s=a.find(({config:l})=>l.type===n);return s?s instanceof ja?ru(t,e,s,o):s instanceof Za||s instanceof $a||s instanceof Wa?nu(t,e,s):s instanceof za?su(t,e,s):ou(t,e,s):(C.warn(`Payment method ${n} not found`),null)},getSDKUtilities:()=>({getCardNetworkAsset:Gn,getUIOrderAmount:()=>{let{merchantAmount:n,totalOrderAmount:o,currencyCode:s}=e.configuration.clientSession.order;return io(e.locale,n??o,s)},getCDNAssets:async n=>{let o=a.find(({config:c})=>c.type===n);if(!o)return;let{backgroundColor:s,iconUrl:l}=o.config.displayMetadata?.button||{};return{assets:{icon:l?.colored||""},colors:{background:s?.colored||"",main:s?.colored||""},description:o.config.name||null,is_primer_app:!1,name:o.config.name,website:null,goatCdnUrl:""}},getPaymentMethodConfiguration:n=>a.find(({config:o})=>o.type===n)?.config,setBillingAddress:async n=>{let{error:o,data:s}=await e.clientSessionApi.setBillingAddress(n);if(o||!s)throw o||new G({message:"Failed to set billing address"})}}),getAnalyticsUtils:()=>i,createVaultManager(){return Tu(t,e,a)},getAssetsManager:()=>({getCardNetworkAsset:Gn,getPaymentMethodAsset:async n=>{let o=a.find(({config:m})=>m.type===n);if(!o)return null;let{backgroundColor:s,iconUrl:l,text:c}=o.config.displayMetadata?.button||{};return{backgroundColor:s,iconUrl:l,paymentMethodName:c,buttonText:c,displayName:o.config.name}}}),refreshClientSession:e.refreshClientConfiguration,getConfiguration:()=>e.configuration,teardown:()=>e.teardown()}}var Gn=r=>{let{asset:t,display:e}=Ja(r);return{cardUrl:`${gc}/brand/card/${t}.svg`,displayName:e}},Pu=new Set(["paymentMethodType","last4Digits","network","accountNumberLastFourDigits","bankName"]);function Wt(r){let{id:t,orderId:e,paymentMethodData:a}=r,i={id:t,orderId:e};if(!a||typeof a!="object")return i;let n={};for(let[o,s]of Object.entries(a))Pu.has(o)&&(n[o]=s);return i.paymentMethodData=n,i}var Nu={PAYMENT_CARD:{fields:["last4Digits","network","cardholderName","expirationMonth","expirationYear"]},PAYPAL_BILLING_AGREEMENT:{path:"externalPayerInfo",fields:["externalPayerId","email","firstName","lastName"]},KLARNA_CUSTOMER_TOKEN:{path:"sessionData.billingAddress",fields:["email","firstName","lastName","phoneNumber"]},AUTOMATED_CLEARING_HOUSE:{fields:["accountNumberLastFourDigits","bankName","accountType"]}};function Iu(r,t){let e=r;for(let a of t.split(".")){if(!e||typeof e!="object")return;e=e[a]}return e&&typeof e=="object"?e:void 0}function ku(r,t){if(!r)return;let e={};for(let a of t)r[a]!==void 0&&(e[a]=r[a]);return Object.keys(e).length>0?e:void 0}function So(r){let{id:t,analyticsId:e,paymentMethodType:a,paymentInstrumentType:i,paymentInstrumentData:n,userDescription:o}=r,s=Nu[i],l;if(s&&n&&typeof n=="object"){let c=s.path?Iu(n,s.path):n;l=ku(c,s.fields)}return{id:t,analyticsId:e,paymentMethodType:a,paymentInstrumentType:i,...o&&{userDescription:o},...l&&{paymentInstrumentData:l}}}var Zt=class{constructor(t){(this.host=t).addController(this)}hostConnected(){}dispatchEvent(t,e){this.host.dispatchEvent(new CustomEvent(t,{detail:e,bubbles:!0,composed:!0}))}dispatchSdkState(t){this.dispatchEvent("primer:state-change",t)}dispatchPaymentMethods(t){this.dispatchEvent("primer:methods-update",t)}dispatchCheckoutInitialized(t){this.dispatchEvent("primer:ready",t)}dispatchCardNetworkChange(t){this.dispatchEvent("primer:card-network-change",t)}dispatchBinDataAvailable(t){this.dispatchEvent("primer:bin-data-available",t)}dispatchBinDataLoadingChange(t){this.dispatchEvent("primer:bin-data-loading-change",{loading:t})}dispatchCardSubmit(t){this.dispatchEvent("primer:card-submit",{source:t})}dispatchFormSubmitSuccess(t){this.dispatchEvent("primer:card-success",{result:t})}dispatchFormSubmitErrors(t){this.dispatchEvent("primer:card-error",{errors:t})}dispatchPaymentCancel(t){let e=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:payment-cancel",{...t,timestamp:e})}handleExternalCardSubmit(t){this.dispatchCardSubmit(t.source)}dispatchPaymentStart(t,e){let a=Math.floor(Date.now()/1e3),i=!1,n=new CustomEvent("primer:payment-start",{detail:{paymentMethodType:t,abortPaymentCreation:()=>{i=!0,e.abortPaymentCreation()},continuePaymentCreation:o=>{i=!0,e.continuePaymentCreation(o)},timestamp:a},bubbles:!0,composed:!0,cancelable:!0});return this.host.dispatchEvent(n),n.defaultPrevented?!0:i}dispatchPaymentSuccess(t,e){let a=Wt(t),i=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:payment-success",{payment:a,paymentMethodType:e,timestamp:i})}dispatchPaymentFailure(t,e,a){let i=Math.floor(Date.now()/1e3),n=a?Wt(a):void 0;this.dispatchEvent("primer:payment-failure",{error:t,payment:n,paymentMethodType:e,timestamp:i})}dispatchVaultMethodsUpdate(t,e){let a=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:vault-methods-update",{vaultedPayments:t,cvvRecapture:e,timestamp:a})}dispatchVaultSelectionChange(t){let e=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:vault-selection-change",{paymentMethodId:t,timestamp:e})}dispatchVaultSubmit(t){this.dispatchEvent("primer:vault-submit",{source:t})}handleExternalVaultSubmit(t){this.dispatchVaultSubmit(t.source)}dispatchShowOtherPaymentsToggle(t,e){this.dispatchEvent("primer:show-other-payments-toggle",{action:t,source:e})}handleExternalShowOtherPaymentsToggle(t){this.dispatchShowOtherPaymentsToggle(t.action,t.source)}dispatchShowOtherPaymentsToggled(t){this.dispatchEvent("primer:show-other-payments-toggled",{expanded:t})}};var ht=class extends Event{constructor(t,e,a,i){super("context-request",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=e,this.callback=a,this.subscribe=i??!1}};var Jt=class{constructor(t,e,a,i){if(this.subscribe=!1,this.provided=!1,this.value=void 0,this.t=(n,o)=>{this.unsubscribe&&(this.unsubscribe!==o&&(this.provided=!1,this.unsubscribe()),this.subscribe||this.unsubscribe()),this.value=n,this.host.requestUpdate(),this.provided&&!this.subscribe||(this.provided=!0,this.callback&&this.callback(n,o)),this.unsubscribe=o},this.host=t,e.context!==void 0){let n=e;this.context=n.context,this.callback=n.callback,this.subscribe=n.subscribe??!1}else this.context=e,this.callback=a,this.subscribe=i??!1;this.host.addController(this)}hostConnected(){this.dispatchRequest()}hostDisconnected(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=void 0)}dispatchRequest(){this.host.dispatchEvent(new ht(this.context,this.host,this.t,this.subscribe))}};var Qa=class{get value(){return this.o}set value(t){this.setValue(t)}setValue(t,e=!1){let a=e||!Object.is(t,this.o);this.o=t,a&&this.updateObservers()}constructor(t){this.subscriptions=new Map,this.updateObservers=()=>{for(let[e,{disposer:a}]of this.subscriptions)e(this.o,a)},t!==void 0&&(this.value=t)}addCallback(t,e,a){if(!a)return void t(this.value);this.subscriptions.has(t)||this.subscriptions.set(t,{disposer:()=>{this.subscriptions.delete(t)},consumerHost:e});let{disposer:i}=this.subscriptions.get(t);t(this.value,i)}clearCallbacks(){this.subscriptions.clear()}};var Ai=class extends Event{constructor(t,e){super("context-provider",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=e}},W=class extends Qa{constructor(t,e,a){super(e.context!==void 0?e.initialValue:a),this.onContextRequest=i=>{if(i.context!==this.context)return;let n=i.contextTarget??i.composedPath()[0];n!==this.host&&(i.stopPropagation(),this.addCallback(i.callback,n,i.subscribe))},this.onProviderRequest=i=>{if(i.context!==this.context||(i.contextTarget??i.composedPath()[0])===this.host)return;let n=new Set;for(let[o,{consumerHost:s}]of this.subscriptions)n.has(o)||(n.add(o),s.dispatchEvent(new ht(this.context,s,o,!0)));i.stopPropagation()},this.host=t,e.context!==void 0?this.context=e.context:this.context=e,this.attachListeners(),this.host.addController?.(this)}attachListeners(){this.host.addEventListener("context-request",this.onContextRequest),this.host.addEventListener("context-provider",this.onProviderRequest)}hostConnected(){this.host.dispatchEvent(new Ai(this.context,this.host))}};function A({context:r,subscribe:t}){return(e,a)=>{typeof a=="object"?a.addInitializer((function(){new Jt(this,{context:r,callback:i=>{e.set.call(this,i)},subscribe:t})})):e.constructor.addInitializer((i=>{new Jt(i,{context:r,callback:n=>{i[a]=n},subscribe:t})}))}}var gt=Symbol("analytics-context");var Ve=Symbol("events-context");var Xa="cardNetworksContext";var ge="clientOptionsContext";var qt="computedStylesContext";var $="headlessInstanceContext";var er="configuration";var tr="klarnaCategoriesContext";var Z="managerContext";var yt="paymentMethodsContext";var J="sdkStateContext";var ye="vaultManagerContext";var He="vaultManagerCvvContext";function Lu(r,t,e,a){let i=r,n=e;return{dispatch:o=>{let s=i,l=t(i,o,n);rr(s,l)?i=l:(i=l,a(l))},getState:()=>Object.freeze({...i}),setCallbacks:o=>{n={...n,...o}}}}function rr(r,t,e=0,a=10){if(e>a)return r===t;if(r===t)return!0;if(r==null||t==null||typeof r!="object"||typeof t!="object")return!1;let i=Object.keys(r);if(i.length!==Object.keys(t).length)return!1;for(let n of i){if(!(n in t))return!1;let o=r[n],s=t[n];if(typeof o=="object"&&o!==null&&(typeof s=="object"&&s!==null)){if(!rr(o,s,e+1,a))return!1}else if(o!==s)return!1}return!0}function Ci(r){return(t,e,a)=>{let i=r[e.type];if(!i)throw new Error(`No handler for action type: ${e.type}`);return i(t,e,a)}}var Lt=class{constructor(t,e,a,i,n=()=>{this.host.requestUpdate()}){this.host=t;this.stateHandler=n;this.host.addController(this),this._dispatcher=Lu(e,a,i,o=>{this.stateHandler(o)})}get currentState(){return this._dispatcher.getState()}dispatch(t){this._dispatcher.dispatch(t)}setCallbacks(t){this._dispatcher.setCallbacks(t)}hostConnected(){}hostDisconnected(){}},ar=class{constructor(t){this.host=t;this._controllers=[];"addController"in this.host&&this.host.addController(this)}addController(t){this._controllers.push(t)}hostConnected(){this._controllers.forEach(t=>{t.hostConnected&&t.hostConnected()})}hostDisconnected(){this._controllers.forEach(t=>{t.hostDisconnected&&t.hostDisconnected()})}};var bo={isSuccessful:!1,isProcessing:!1,isLoading:!1,primerJsError:null,paymentFailure:null},Ao=bo;function Ru(r,t){switch(t.type){case"SET_LOADING":return{...r,isLoading:t.payload};case"SET_PROCESSING":return{...r,isProcessing:t.payload,...t.payload&&{primerJsError:null,paymentFailure:null}};case"SET_SUCCESS":return{...r,isSuccessful:t.payload};case"SET_PRIMER_JS_ERROR":return{...r,primerJsError:t.payload};case"SET_PAYMENT_FAILURE":return{...r,isProcessing:!1,paymentFailure:t.payload};case"COMPLETE_PROCESSING":return{...r,isProcessing:!1,isSuccessful:!0};case"RESET":return{isSuccessful:!1,isProcessing:!1,isLoading:!1,primerJsError:null,paymentFailure:null};default:return r}}var ir=class extends Lt{constructor(t){super(t,bo,Ru,null,e=>{t.sdkContextController.setSdkState(e),t.primerEventsController.dispatchSdkState(e)})}setLoading(t){this.dispatch({type:"SET_LOADING",payload:t})}setProcessing(t){this.dispatch({type:"SET_PROCESSING",payload:t})}setSuccess(t){this.dispatch({type:"SET_SUCCESS",payload:t})}setPrimerJsError(t){this.dispatch({type:"SET_PRIMER_JS_ERROR",payload:t})}setPaymentFailure(t){this.dispatch({type:"SET_PAYMENT_FAILURE",payload:t})}completeProcessing(){this.dispatch({type:"COMPLETE_PROCESSING"})}reset(){this.dispatch({type:"RESET"})}startLoading(){this.setLoading(!0)}completeLoading(){this.setLoading(!1)}startProcessing(){this.setProcessing(!0)}stopProcessing(){this.setProcessing(!1)}resetError(){this.setPrimerJsError(null),this.setPaymentFailure(null)}forceCompleteLoading(){this.setLoading(!1)}};var nr=class{constructor(t){this.sdkStateProvider=null;this.paymentMethodsProvider=null;this.paymentManagerProvider=null;this.cardNetworksContext=null;this.vaultManagerCvvProvider=null;this.clientOptionsContext=null;this.headlessUtilsProvider=null;this.configurationProvider=null;this.klarnaCategoriesProvider=null;this.computedStylesProvider=null;this.analyticsProvider=null;this.eventsProvider=null;(this.host=t).addController(this),this.sdkStateProvider=new W(t,{context:J,initialValue:Ao}),this.paymentMethodsProvider=new W(t,{context:yt,initialValue:null}),this.paymentManagerProvider=new W(t,{context:Z,initialValue:new Map}),this.cardNetworksContext=new W(t,{context:Xa,initialValue:null}),this.vaultManagerProvider=new W(t,{context:ye,initialValue:null}),this.vaultManagerCvvProvider=new W(t,{context:He,initialValue:null}),this.clientOptionsContext=new W(t,{context:ge,initialValue:null}),this.klarnaCategoriesProvider=new W(t,{context:tr,initialValue:{categories:[],isLoading:!0}}),this.headlessUtilsProvider=new W(t,{context:$,initialValue:null}),this.configurationProvider=new W(t,{context:er,initialValue:null}),this.computedStylesProvider=new W(t,{context:qt,initialValue:null}),this.analyticsProvider=new W(t,{context:gt,initialValue:null}),this.eventsProvider=new W(t,{context:Ve,initialValue:null})}hostConnected(){}setSdkState(t){this.sdkStateProvider?.setValue(t)}setPaymentMethods(t){this.paymentMethodsProvider?.setValue(t)}setPaymentManagers(t){this.paymentManagerProvider?.setValue(t)}setCardNetworks(t){this.cardNetworksContext?.setValue(t)}setVaultManager(t){this.vaultManagerProvider?.setValue(t)}setKlarnaCategories(t){this.klarnaCategoriesProvider?.setValue(t)}setClientOptions(t){this.clientOptionsContext?.setValue(t)}setHeadlessUtils(t){this.headlessUtilsProvider?.setValue(t)}setConfiguration(t){this.configurationProvider?.setValue(t)}setAnalyticsUtils(t){this.analyticsProvider?.setValue(t)}getAnalyticsUtils(){return this.analyticsProvider?.value}setComputedStyles(t){this.computedStylesProvider?.setValue(t)}setVaultManagerCvv(t){this.vaultManagerCvvProvider?.setValue(t)}setEventsController(t){this.eventsProvider?.setValue(t)}};var Mi=class{constructor(){k(this,"context",null)}initialize(t){this.context=t,P.debug("Session context initialized:",{checkoutSessionId:t.checkoutSessionId,clientSessionId:t.clientSessionId,primerAccountId:t.primerAccountId,environment:t.environment})}getContext(){return this.context}clear(){P.debug("Session context cleared"),this.context=null}isInitialized(){return this.context!==null}setSdkInitStartTime(t){this.context&&(this.context.sdkInitStartTime=t)}getSdkInitStartTime(){return this.context?.sdkInitStartTime}},Ye=new Mi;var xu={LOCAL:"https://analytics.dev.data.primer.io/v1/sdk-logs",DEV:"https://analytics.dev.data.primer.io/v1/sdk-logs",STAGING:"https://analytics.staging.data.primer.io/v1/sdk-logs",SANDBOX:"https://analytics.sandbox.data.primer.io/v1/sdk-logs",PRODUCTION:"https://analytics.production.data.primer.io/v1/sdk-logs"};function Co(r,t={}){let e=Ye.getContext();if(!e&&!t?.environment)return;let i={message:r instanceof Error?r.message:typeof r=="string"?r:JSON.stringify(r)};r instanceof Error&&r.stack&&(i.stack=r.stack),e?Object.assign(i,{primer:{checkout_session_id:e.checkoutSessionId,client_session_id:e.clientSessionId,primer_account_id:e.primerAccountId},user_agent:e.userAgent}):(t?.checkoutSessionId&&Object.assign(i,{primer:{checkout_session_id:t.checkoutSessionId}}),t?.clientSessionId&&Object.assign(i,{primer:{client_session_id:t.clientSessionId}}),t?.primerAccountId&&Object.assign(i,{primer:{primer_account_id:t.primerAccountId}}),t?.userAgent&&Object.assign(i,{user_agent:t.userAgent})),t?.metadata&&Object.assign(i,t.metadata),t.status&&(i.status=t.status);let n={message:JSON.stringify(i),hostname:typeof window<"u"?window.location.hostname:"unknown",service:"web-sdk",ddsource:"lambda",ddtags:`env:${e?.environment||t?.environment},version:${e?.sdkVersion||t?.sdkVersion}`};_u(n,{environment:e?.environment||t?.environment,clientSessionToken:e?.clientSessionToken||t?.clientSessionToken})}var Mo=(r,t={})=>Co(r,{...t,status:"error"});function Eo(r){let t={event:"CHECKOUT_INITIALIZED"};r!==void 0&&(t.init_duration_ms=r),Co("Checkout initialized",{status:"info",metadata:t})}function _u(r,{environment:t,clientSessionToken:e}){if(t==="LOCAL"||r.hostname==="localhost"){P.debug("\u{1F436}\u{1F436}\u{1F436} [Datadog Log] \u{1F436}\u{1F436}\u{1F436}",r);return}let a=xu[t||"LOCAL"];if(!a){P.warn("No logging endpoint configured for current environment");return}fetch(a,{method:"POST",headers:{"Content-Type":"application/json",...e&&{Authorization:`Bearer ${e}`}},body:JSON.stringify(r)}).catch(i=>{P.error("Failed to send log event:",i)})}var H=class H{static _log(t,e,...a){H.enabled&&a.forEach(i=>{i instanceof Error&&i.toJSON})}static log(t,...e){H._log("log",t,...e)}static info(t,...e){H._log("info",t,...e)}static warn(t,...e){H._log("warn",t,...e)}static error(t,...e){H._log("error",t,...e)}static debug(t,...e){this._log("debug",t,...e)}static errorWithDatadog(t,e){let{error:a,status:i="error"}=e||{};if(H.enabled){a instanceof Error&&a.toJSON;try{let n={status:i,metadata:{sdkOptions:H.sdkOptions,clientToken:H.clientToken,error:a}};Mo(t,n)}catch{H.enabled}}}static setSdkOptions(t){H.sdkOptions=t}static setClientToken(t){H.clientToken=t}};k(H,"enabled",!0),k(H,"sdkOptions"),k(H,"clientToken"),k(H,"defaultFont","font-family: Consolas, monospace; font-size: 12px;"),k(H,"brandTag","[PRIMER]"),k(H,"brandStyle",`background: #24292e; color: #ffffff; padding: 2px 6px; border-radius: 3px; font-weight: bold; margin-right: 4px; ${H.defaultFont}`),k(H,"styles",{log:`color: #4CAF50; ${H.defaultFont}`,info:`color: #2196F3; ${H.defaultFont}`,warn:`color: #FF9800; ${H.defaultFont}`,error:`color: #F44336; ${H.defaultFont}`,debug:`color: #9C27B0; ${H.defaultFont}`});var P=H;var Rt=class Rt{constructor(t){(this.host=t).addController(this)}processCustomStyles(t){try{let e=JSON.parse(t);this.applyStyles(e)}catch(e){P.error("Error parsing customStyles property.",e instanceof Error?e:new Error(String(e)))}}isValidCssProperty(t){return/^[a-zA-Z][a-zA-Z0-9]*$/.test(t)}isValidCssValue(t){let a=/^[\w\s#.,%()\-+/!]+$/.test(t);return a||P.warn(`Rejected potentially unsafe CSS value: ${t}`),a}getCssVarName(t){let e=Rt.cssVarCache.get(t);return e||(e=`--${t.replace(/([A-Z])/g,(a,i)=>`-${i.toLowerCase()}`)}`,Rt.cssVarCache.set(t,e)),e}applyStyles(t){let e=[];for(let a of Object.keys(t)){let i=t[a];if(!i)continue;if(!this.isValidCssProperty(a)){P.warn(`Skipping invalid CSS property name: ${a}`);continue}if(!this.isValidCssValue(i))continue;let n=this.getCssVarName(a);e.push([n,i])}if(e.length>0)for(let[a,i]of e)this.host.style.setProperty(a,i)}removeStyle(t){let e=this.getCssVarName(t);this.host.style.removeProperty(e)}clearAllStyles(){for(let t of Rt.cssVarCache.keys()){let e=Rt.cssVarCache.get(t);e&&this.host.style.removeProperty(e)}}hostDisconnected(){}};Rt.cssVarCache=new Map;var or=Rt;var sr=globalThis,dr=sr.ShadowRoot&&(sr.ShadyCSS===void 0||sr.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Po=Symbol(),To=new WeakMap,lr=class{constructor(t,e,a){if(this._$cssResult$=!0,a!==Po)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o,e=this.t;if(dr&&t===void 0){let a=e!==void 0&&e.length===1;a&&(t=To.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),a&&To.set(e,t))}return t}toString(){return this.cssText}},No=r=>new lr(typeof r=="string"?r:r+"",void 0,Po);var Ei=(r,t)=>{if(dr)r.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let a=document.createElement("style"),i=sr.litNonce;i!==void 0&&a.setAttribute("nonce",i),a.textContent=e.cssText,r.appendChild(a)}},cr=dr?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let e="";for(let a of t.cssRules)e+=a.cssText;return No(e)})(r):r;var{is:wu,defineProperty:Du,getOwnPropertyDescriptor:Bu,getOwnPropertyNames:Ou,getOwnPropertySymbols:Gu,getPrototypeOf:Ku}=Object,ft=globalThis,Io=ft.trustedTypes,Fu=Io?Io.emptyScript:"",Uu=ft.reactiveElementPolyfillSupport,ha=(r,t)=>r,Ti={toAttribute(r,t){switch(t){case Boolean:r=r?Fu:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,t){let e=r;switch(t){case Boolean:e=r!==null;break;case Number:e=r===null?null:Number(r);break;case Object:case Array:try{e=JSON.parse(r)}catch{e=null}}return e}},ur=(r,t)=>!wu(r,t),ko={attribute:!0,type:String,converter:Ti,reflect:!1,hasChanged:ur};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),ft.litPropertyMetadata??(ft.litPropertyMetadata=new WeakMap);var xt=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??(this.l=[])).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=ko){if(e.state&&(e.attribute=!1),this._$Ei(),this.elementProperties.set(t,e),!e.noAccessor){let a=Symbol(),i=this.getPropertyDescriptor(t,a,e);i!==void 0&&Du(this.prototype,t,i)}}static getPropertyDescriptor(t,e,a){let{get:i,set:n}=Bu(this.prototype,t)??{get(){return this[e]},set(o){this[e]=o}};return{get(){return i?.call(this)},set(o){let s=i?.call(this);n.call(this,o),this.requestUpdate(t,s,a)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??ko}static _$Ei(){if(this.hasOwnProperty(ha("elementProperties")))return;let t=Ku(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(ha("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(ha("properties"))){let e=this.properties,a=[...Ou(e),...Gu(e)];for(let i of a)this.createProperty(i,e[i])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[a,i]of e)this.elementProperties.set(a,i)}this._$Eh=new Map;for(let[e,a]of this.elementProperties){let i=this._$Eu(e,a);i!==void 0&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let e=[];if(Array.isArray(t)){let a=new Set(t.flat(1/0).reverse());for(let i of a)e.unshift(cr(i))}else t!==void 0&&e.push(cr(t));return e}static _$Eu(t,e){let a=e.attribute;return a===!1?void 0:typeof a=="string"?a:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((t=>t(this)))}addController(t){(this._$EO??(this._$EO=new Set)).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,e=this.constructor.elementProperties;for(let a of e.keys())this.hasOwnProperty(a)&&(t.set(a,this[a]),delete this[a]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Ei(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach((t=>t.hostConnected?.()))}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach((t=>t.hostDisconnected?.()))}attributeChangedCallback(t,e,a){this._$AK(t,a)}_$EC(t,e){let a=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,a);if(i!==void 0&&a.reflect===!0){let n=(a.converter?.toAttribute!==void 0?a.converter:Ti).toAttribute(e,a.type);this._$Em=t,n==null?this.removeAttribute(i):this.setAttribute(i,n),this._$Em=null}}_$AK(t,e){let a=this.constructor,i=a._$Eh.get(t);if(i!==void 0&&this._$Em!==i){let n=a.getPropertyOptions(i),o=typeof n.converter=="function"?{fromAttribute:n.converter}:n.converter?.fromAttribute!==void 0?n.converter:Ti;this._$Em=i,this[i]=o.fromAttribute(e,n.type),this._$Em=null}}requestUpdate(t,e,a){if(t!==void 0){if(a??(a=this.constructor.getPropertyOptions(t)),!(a.hasChanged??ur)(this[t],e))return;this.P(t,e,a)}this.isUpdatePending===!1&&(this._$ES=this._$ET())}P(t,e,a){this._$AL.has(t)||this._$AL.set(t,e),a.reflect===!0&&this._$Em!==t&&(this._$Ej??(this._$Ej=new Set)).add(t)}async _$ET(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(let[i,n]of this._$Ep)this[i]=n;this._$Ep=void 0}let a=this.constructor.elementProperties;if(a.size>0)for(let[i,n]of a)n.wrapped!==!0||this._$AL.has(i)||this[i]===void 0||this.P(i,this[i],n)}let t=!1,e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach((a=>a.hostUpdate?.())),this.update(e)):this._$EU()}catch(a){throw t=!1,this._$EU(),a}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EU(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Ej&&(this._$Ej=this._$Ej.forEach((e=>this._$EC(e,this[e])))),this._$EU()}updated(t){}firstUpdated(t){}};xt.elementStyles=[],xt.shadowRootOptions={mode:"open"},xt[ha("elementProperties")]=new Map,xt[ha("finalized")]=new Map,Uu?.({ReactiveElement:xt}),(ft.reactiveElementVersions??(ft.reactiveElementVersions=[])).push("2.0.4");var vt={INITIAL:0,PENDING:1,COMPLETE:2,ERROR:3},w=Symbol(),O=class{get taskComplete(){return this.t||(this.i===1?this.t=new Promise(((t,e)=>{this.o=t,this.h=e})):this.i===3?this.t=Promise.reject(this.l):this.t=Promise.resolve(this.u)),this.t}constructor(t,e,a){this.p=0,this.i=0,(this._=t).addController(this);let i=typeof e=="object"?e:{task:e,args:a};this.v=i.task,this.j=i.args,this.m=i.argsEqual??Lo,this.k=i.onComplete,this.A=i.onError,this.autoRun=i.autoRun??!0,"initialValue"in i&&(this.u=i.initialValue,this.i=2,this.O=this.T?.())}hostUpdate(){this.autoRun===!0&&this.S()}hostUpdated(){this.autoRun==="afterUpdate"&&this.S()}T(){if(this.j===void 0)return;let t=this.j();if(!Array.isArray(t))throw Error("The args function must return an array");return t}async S(){let t=this.T(),e=this.O;this.O=t,t===e||t===void 0||e!==void 0&&this.m(e,t)||await this.run(t)}async run(t){let e,a;t??(t=this.T()),this.O=t,this.i===1?this.q?.abort():(this.t=void 0,this.o=void 0,this.h=void 0),this.i=1,this.autoRun==="afterUpdate"?queueMicrotask((()=>this._.requestUpdate())):this._.requestUpdate();let i=++this.p;this.q=new AbortController;let n=!1;try{e=await this.v(t,{signal:this.q.signal})}catch(o){n=!0,a=o}if(this.p===i){if(e===w)this.i=0;else{if(n===!1){try{this.k?.(e)}catch{}this.i=2,this.o?.(e)}else{try{this.A?.(a)}catch{}this.i=3,this.h?.(a)}this.u=e,this.l=a}this._.requestUpdate()}}abort(t){this.i===1&&this.q?.abort(t)}get value(){return this.u}get error(){return this.l}get status(){return this.i}render(t){switch(this.i){case 0:return t.initial?.();case 1:return t.pending?.();case 2:return t.complete?.(this.value);case 3:return t.error?.(this.error);default:throw Error("Unexpected status: "+this.i)}}},Lo=(r,t)=>r===t||r.length===t.length&&r.every(((e,a)=>!ur(e,t[a])));var Vu={SET_LOADING:(r,t)=>({...r,isLoading:t.payload}),SET_UPDATING:(r,t)=>({...r,isUpdating:t.payload}),INITIALIZE_VAULT_MANAGER:(r,t,e)=>({...r,enabled:t.vaultEnabled,cvvRecapture:t.cvvRecapture,showEmptyState:t.showEmptyState,headless:t.headless,deleteVaultedPaymentMethod:e.deleteVaultedPaymentMethod,startVaultedPaymentFlow:e.startVaultedPaymentFlow,createCvvInput:e.createCvvInput}),UPDATE_PAYMENT_METHODS:(r,t)=>({...r,vaultedPaymentMethods:t.payload,isLoading:!1,isUpdating:!1}),SET_ERROR:r=>({...r,isLoading:!1,isUpdating:!1}),DISABLE:r=>({...r,enabled:!1}),RESET:()=>Ro},Hu={INITIALIZE_CVV:(r,t,e)=>({...r,setCvvInput:e.setCvvInput,setSelectedVaultedPaymentMethod:e.setSelectedVaultedPaymentMethod}),SET_FORM_DIRTY:(r,t)=>({...r,formIsDirty:t.payload}),SET_CVV_INPUT:(r,t)=>({...r,cvvInput:t.payload}),SET_SELECTED_VAULTED_PAYMENT_METHOD:(r,t)=>({...r,selectedVaultedPaymentMethod:t.payload}),RESET_CVV:()=>xo},Yu=Ci(Vu),$u=Ci(Hu),Ro={enabled:!1,isLoading:!1,isUpdating:!1,cvvRecapture:!1,showEmptyState:!1,headless:!1,vaultedPaymentMethods:[],createCvvInput:null,deleteVaultedPaymentMethod:()=>Promise.resolve(),startVaultedPaymentFlow:()=>Promise.resolve()},xo={cvvInput:null,formIsDirty:!1,setCvvInput:()=>{},selectedVaultedPaymentMethod:null,setSelectedVaultedPaymentMethod:()=>{}},Pi=class extends Lt{constructor(t,e){super(t,Ro,Yu,e,a=>{t.sdkContextController.setVaultManager(a)})}setLoading(t){this.dispatch({type:"SET_LOADING",payload:t})}setUpdating(t){this.dispatch({type:"SET_UPDATING",payload:t})}initializeVaultManager(t,e,a,i,n){this.dispatch({type:"INITIALIZE_VAULT_MANAGER",payload:t,vaultEnabled:e,cvvRecapture:a,showEmptyState:i,headless:n})}updatePaymentMethods(t){this.dispatch({type:"UPDATE_PAYMENT_METHODS",payload:t})}setError(t){this.dispatch({type:"SET_ERROR",payload:t})}disable(){this.dispatch({type:"DISABLE"})}reset(){this.dispatch({type:"RESET"})}},Ni=class extends Lt{constructor(t,e){super(t,xo,$u,e,a=>{t.sdkContextController.setVaultManagerCvv(a)})}initializeCvv(t){this.dispatch({type:"INITIALIZE_CVV",createCvvInput:t})}setFormDirty(t){this.dispatch({type:"SET_FORM_DIRTY",payload:t})}setCvvInputState(t){this.dispatch({type:"SET_CVV_INPUT",payload:t})}setSelectedPaymentMethod(t){this.dispatch({type:"SET_SELECTED_VAULTED_PAYMENT_METHOD",payload:t})}resetCvv(){this.dispatch({type:"RESET_CVV"})}},ga=class extends ar{constructor(e){super(e);this._vaultManager=null;this._options=null;this.createVaultManagerFn=null;this.createCvvInput=e=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");return this._vaultManager.createCvvInput(e)};this.deleteVaultedPaymentMethod=async e=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");try{this.coreController.updatePaymentMethods(this.vaultManagerState.vaultedPaymentMethods),await this._vaultManager.deleteVaultedPaymentMethod(e),await this.fetchVaultedPaymentMethods()}catch(a){let i=a instanceof Error?a:new Error("Failed to delete payment method");throw this.coreController.setError(i),this.host.sdkStateController.setPrimerJsError(i),a}};this.setCvvInput=e=>{this.itemController.setCvvInputState(e)};this.startVaultedPaymentFlow=async()=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");let e=this.vaultItemState.selectedVaultedPaymentMethod,a=this.vaultManagerState.cvvRecapture,i=this.vaultItemState.cvvInput;if(!e||a&&(!i||i.metadata.error)){this.itemController.setFormDirty(!0);return}this.host.sdkStateController.startProcessing();try{await this._vaultManager.startPaymentFlow(e.id,a?{cvv:i.valueToken}:void 0)}catch(n){P.errorWithDatadog("VaultManagerController: Error starting vaulted payment flow",{error:n});let o=n instanceof Error?n:new Error("Failed to start vaulted payment flow");this.coreController.setError(o),this.host.sdkStateController.setPrimerJsError(o),this.host.sdkStateController.stopProcessing()}};this.setSelectedVaultedPaymentMethod=e=>{this.itemController.setSelectedPaymentMethod(e),this.itemController.setFormDirty(!1),this.host.primerEventsController.dispatchVaultSelectionChange(e?.id??null)};this.startVaultPaymentById=async(e,a)=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");let i=this.vaultManagerState.vaultedPaymentMethods.find(n=>n.id===e);if(!i)throw new Error(`Payment method not found: ${e}`);this.setSelectedVaultedPaymentMethod(i),this.host.sdkStateController.startProcessing();try{await this._vaultManager.startPaymentFlow(e,a?.cvv?{cvv:a.cvv}:void 0)}catch(n){P.errorWithDatadog("VaultManagerController: Error starting vaulted payment flow",{error:n});let o=n instanceof Error?n:new Error("Failed to start vaulted payment flow");throw this.coreController.setError(o),this.host.sdkStateController.setPrimerJsError(o),this.host.sdkStateController.stopProcessing(),n}};this.coreController=new Pi(e,{deleteVaultedPaymentMethod:this.deleteVaultedPaymentMethod.bind(this),startVaultedPaymentFlow:this.startVaultedPaymentFlow.bind(this),createCvvInput:this.createCvvInput}),this.itemController=new Ni(e,{setCvvInput:this.setCvvInput.bind(this),setSelectedVaultedPaymentMethod:this.setSelectedVaultedPaymentMethod.bind(this)}),this.addController(this.coreController),this.addController(this.itemController),new O(this.host,{task:async([a,i])=>{if(!a||!i?.vaultEnabled)return this.coreController.disable(),w;this.coreController.setLoading(!0);try{let n=a();this._vaultManager=n,this.coreController.initializeVaultManager(n,i.vaultEnabled,!!i.captureVaultedCardCvv,i.showEmptyState??!1,i.headless??!1),this.itemController.initializeCvv(n.createCvvInput),await this.fetchVaultedPaymentMethods(!0),P.log("VaultManagerController: Vault initialized successfully",{coreState:this.coreController.currentState,cvvState:this.itemController.currentState})}catch(n){P.errorWithDatadog("VaultManagerController: Failed to initialize vault",{error:n});let o=n instanceof Error?n:new Error("Unknown error");this.coreController.setError(o),this.host.sdkStateController.setPrimerJsError(o)}return this._vaultManager},args:()=>[this.createVaultManagerFn,this.options]})}initializeVaultManager(e,a){this.createVaultManagerFn=e,this.options=a??null}get vaultManager(){return this._vaultManager}set vaultManager(e){this._vaultManager=e,this.host.requestUpdate()}get options(){return this._options}set options(e){this._options=e,this.host.requestUpdate()}get vaultManagerState(){return this.coreController.currentState}get vaultItemState(){return this.itemController.currentState}hostDisconnected(){super.hostDisconnected(),this.vaultManager=null,this.coreController.reset()}createVaultedPaymentsArray(e){return e.map(a=>So(a))}updatePaymentMethodsWithEvents(e){this.coreController.updatePaymentMethods(e);let a=this.createVaultedPaymentsArray(e);this.host.primerEventsController.dispatchVaultMethodsUpdate(a,this.vaultManagerState.cvvRecapture),this.host.primerJS?.handleVaultedMethodsUpdate(a,this.vaultManagerState.cvvRecapture),P.log("VaultManagerController: Dispatched vault methods update",{methodCount:e.length,filteredMethodCount:a.length})}async fetchVaultedPaymentMethods(e){if(!this._vaultManager)throw new Error("Vault manager not initialized");try{e||this.coreController.setUpdating(!0);let a=await this._vaultManager.fetchVaultedPaymentMethods();return P.log("VaultManagerController: Fetched payment methods",a),this.updatePaymentMethodsWithEvents(a),a}catch(a){let i=a instanceof Error?a:new Error("Failed to fetch payment methods");throw this.coreController.setError(i),this.host.sdkStateController.setPrimerJsError(i),a}}};var _o=()=>wo.randomUUID?.()||zu(),zu=()=>("10000000-1000-4000-8000"+-1e11).replace(/[018]/g,r=>(r^ju()>>r/4).toString(16)),ju=()=>(wo.getRandomValues?.(new Uint8Array(1))[0]??Math.random()*16)&15,wo=typeof crypto<"u"?crypto:{};var Wu={LOCAL:"https://analytics.sandbox.data.primer.io/v1/sdk-analytic-events",DEV:"https://analytics.dev.data.primer.io/v1/sdk-analytic-events",STAGING:"https://analytics.staging.data.primer.io/v1/sdk-analytic-events",SANDBOX:"https://analytics.sandbox.data.primer.io/v1/sdk-analytic-events",PRODUCTION:"https://analytics.production.data.primer.io/v1/sdk-analytic-events"},Ii=class{sendEvent(t){let e=Ye.getContext();if(!e)return;let a={id:_o(),timestamp:Math.floor(Date.now()/1e3),sdkType:"WEB",eventName:t.eventName,checkoutSessionId:e.checkoutSessionId,clientSessionId:e.clientSessionId,primerAccountId:e.primerAccountId,sdkVersion:e.sdkVersion,userAgent:e.userAgent,eventType:t.eventType,userLocale:t.userLocale,paymentMethod:t.paymentMethod,paymentId:t.paymentId,redirectDestinationUrl:t.redirectDestinationUrl,threedsProvider:t.threedsProvider,threedsResponse:t.threedsResponse};Ju(a,e)}},Zu=new Ii;function Do(r){let t={...r,userAgent:r.userAgent||(typeof navigator<"u"?navigator.userAgent:"")};Ye.initialize(t)}function Q(r){Zu.sendEvent(r)}function Bo(){Ye.clear()}async function Ju(r,{environment:t,clientSessionToken:e}){if(t==="LOCAL"){P.debug(`Analytics event ${r.eventName}:`,r);return}let a=Wu[t];return fetch(a,{method:"POST",headers:{"Content-Type":"application/json",...e&&{Authorization:`Bearer ${e}`}},body:JSON.stringify(r)}).catch(i=>{P.error("Failed to send analytics event:",i)})}var ya="lit-localize-status";var Oo=r=>typeof r!="string"&&"strTag"in r,pr=(r,t,e)=>{let a=r[0];for(let i=1;i<r.length;i++)a+=t[e?e[i-1]:i-1],a+=r[i];return a};var fa=(r=>Oo(r)?pr(r.strings,r.values):r);var b=fa,Go=!1;function ki(r){if(Go)throw new Error("lit-localize can only be configured once");b=r,Go=!0}var Li=class{constructor(t){this.__litLocalizeEventHandler=e=>{e.detail.status==="ready"&&this.host.requestUpdate()},this.host=t}hostConnected(){window.addEventListener(ya,this.__litLocalizeEventHandler)}hostDisconnected(){window.removeEventListener(ya,this.__litLocalizeEventHandler)}},qu=r=>r.addController(new Li(r)),Ko=qu;var D=()=>(r,t)=>(r.addInitializer(Ko),r);var va=class{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._resolve=t,this._reject=e})}resolve(t){this.settled=!0,this._resolve(t)}reject(t){this.settled=!0,this._reject(t)}};var tt=[];for(let r=0;r<256;r++)tt[r]=(r>>4&15).toString(16)+(r&15).toString(16);function Fo(r){let t=0,e=8997,a=0,i=33826,n=0,o=40164,s=0,l=52210;for(let c=0;c<r.length;c++)e^=r.charCodeAt(c),t=e*435,a=i*435,n=o*435,s=l*435,n+=e<<8,s+=i<<8,a+=t>>>16,e=t&65535,n+=a>>>16,i=a&65535,l=s+(n>>>16)&65535,o=n&65535;return tt[l>>8]+tt[l&255]+tt[o>>8]+tt[o&255]+tt[i>>8]+tt[i&255]+tt[e>>8]+tt[e&255]}var Qu="",Xu="h",ep="s";function Uo(r,t){return(t?Xu:ep)+Fo(typeof r=="string"?r:r.join(Qu))}var Vo=new WeakMap,Ho=new Map;function Yo(r,t,e){if(r){let a=e?.id??tp(t),i=r[a];if(i){if(typeof i=="string")return i;if("strTag"in i)return pr(i.strings,t.values,i.values);{let n=Vo.get(i);return n===void 0&&(n=i.values,Vo.set(i,n)),{...i,values:n.map(o=>t.values[o])}}}}return fa(t)}function tp(r){let t=typeof r=="string"?r:r.strings,e=Ho.get(t);return e===void 0&&(e=Uo(t,typeof r!="string"&&!("strTag"in r)),Ho.set(t,e)),e}function Ri(r){window.dispatchEvent(new CustomEvent(ya,{detail:r}))}var hr="",xi,$o,gr,_i,zo,_t=new va;_t.resolve();var mr=0,jo=r=>(ki(((t,e)=>Yo(zo,t,e))),hr=$o=r.sourceLocale,gr=new Set(r.targetLocales),gr.add(r.sourceLocale),_i=r.loadLocale,{getLocale:ap,setLocale:rp}),ap=()=>hr,rp=r=>{if(r===(xi??hr))return _t.promise;if(!gr||!_i)throw new Error("Internal error");if(!gr.has(r))throw new Error("Invalid locale code");mr++;let t=mr;return xi=r,_t.settled&&(_t=new va),Ri({status:"loading",loadingLocale:r}),(r===$o?Promise.resolve({templates:void 0}):_i(r)).then(a=>{mr===t&&(hr=r,xi=void 0,zo=a.templates,Ri({status:"ready",readyLocale:r}),_t.resolve())},a=>{mr===t&&(Ri({status:"error",errorLocale:r,errorMessage:a.toString()}),_t.reject(a))}),_t.promise};var wi="en",Di=["ar","bg","ca","cs","da","de","el","en-GB","es","es-AR","es-MX","et-EE","fi-FI","fr","he","hr","hu","id","it","ja","ko","lt","lt-LT","lv","lv-LV","ms","nb","nl","nl_NL","pl","pt","pt-BR","ro","ru","sk","sl","sr-RS","sv","th","tr","uk-UA","vi","zf","zh-CN","zh-HK","zh-TW"],Bi="You must call `loadLocale` first to set up the localized template.",yr,fr,Wo=r=>{let t=jo({sourceLocale:wi,targetLocales:Di,loadLocale:r});yr=t.getLocale,fr=t.setLocale};var Oi=r=>{Wo(r)},Gi=r=>{if(!fr)throw new Error(Bi);return fr(r)},Ki=()=>{if(!yr)throw new Error(Bi);return yr()};var Sa=new Set(Di);Sa.add(wi);var Fi=r=>{if(typeof r!="string")return!1;if(r==="en")return!0;let t=r.replace("_","-");if(Sa.has(t))return!0;let e=t.split("-")[0];return!!Sa.has(e)},vr=()=>navigator.language||navigator.languages[0]||"en",Qt=r=>{let t=r.replace("_","-"),e=t.split("-")[0];return e==="en"?"en-GB":Sa.has(t)?t:Sa.has(e)?e:"en-GB"};var Sr=globalThis,br=Sr.ShadowRoot&&(Sr.ShadyCSS===void 0||Sr.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Ui=Symbol(),Zo=new WeakMap,ba=class{constructor(t,e,a){if(this._$cssResult$=!0,a!==Ui)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o,e=this.t;if(br&&t===void 0){let a=e!==void 0&&e.length===1;a&&(t=Zo.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),a&&Zo.set(e,t))}return t}toString(){return this.cssText}},fe=r=>new ba(typeof r=="string"?r:r+"",void 0,Ui),f=(r,...t)=>{let e=r.length===1?r[0]:t.reduce(((a,i,n)=>a+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+r[n+1]),r[0]);return new ba(e,r,Ui)},Jo=(r,t)=>{if(br)r.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let a=document.createElement("style"),i=Sr.litNonce;i!==void 0&&a.setAttribute("nonce",i),a.textContent=e.cssText,r.appendChild(a)}},Vi=br?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let e="";for(let a of t.cssRules)e+=a.cssText;return fe(e)})(r):r;var{is:ip,defineProperty:np,getOwnPropertyDescriptor:op,getOwnPropertyNames:sp,getOwnPropertySymbols:lp,getPrototypeOf:dp}=Object,St=globalThis,qo=St.trustedTypes,cp=qo?qo.emptyScript:"",up=St.reactiveElementPolyfillSupport,Aa=(r,t)=>r,Ca={toAttribute(r,t){switch(t){case Boolean:r=r?cp:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,t){let e=r;switch(t){case Boolean:e=r!==null;break;case Number:e=r===null?null:Number(r);break;case Object:case Array:try{e=JSON.parse(r)}catch{e=null}}return e}},Ar=(r,t)=>!ip(r,t),Qo={attribute:!0,type:String,converter:Ca,reflect:!1,useDefault:!1,hasChanged:Ar};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),St.litPropertyMetadata??(St.litPropertyMetadata=new WeakMap);var at=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??(this.l=[])).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=Qo){if(e.state&&(e.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){let a=Symbol(),i=this.getPropertyDescriptor(t,a,e);i!==void 0&&np(this.prototype,t,i)}}static getPropertyDescriptor(t,e,a){let{get:i,set:n}=op(this.prototype,t)??{get(){return this[e]},set(o){this[e]=o}};return{get:i,set(o){let s=i?.call(this);n?.call(this,o),this.requestUpdate(t,s,a)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Qo}static _$Ei(){if(this.hasOwnProperty(Aa("elementProperties")))return;let t=dp(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Aa("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Aa("properties"))){let e=this.properties,a=[...sp(e),...lp(e)];for(let i of a)this.createProperty(i,e[i])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[a,i]of e)this.elementProperties.set(a,i)}this._$Eh=new Map;for(let[e,a]of this.elementProperties){let i=this._$Eu(e,a);i!==void 0&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let e=[];if(Array.isArray(t)){let a=new Set(t.flat(1/0).reverse());for(let i of a)e.unshift(Vi(i))}else t!==void 0&&e.push(Vi(t));return e}static _$Eu(t,e){let a=e.attribute;return a===!1?void 0:typeof a=="string"?a:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((t=>t(this)))}addController(t){(this._$EO??(this._$EO=new Set)).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,e=this.constructor.elementProperties;for(let a of e.keys())this.hasOwnProperty(a)&&(t.set(a,this[a]),delete this[a]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Jo(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach((t=>t.hostConnected?.()))}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach((t=>t.hostDisconnected?.()))}attributeChangedCallback(t,e,a){this._$AK(t,a)}_$ET(t,e){let a=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,a);if(i!==void 0&&a.reflect===!0){let n=(a.converter?.toAttribute!==void 0?a.converter:Ca).toAttribute(e,a.type);this._$Em=t,n==null?this.removeAttribute(i):this.setAttribute(i,n),this._$Em=null}}_$AK(t,e){let a=this.constructor,i=a._$Eh.get(t);if(i!==void 0&&this._$Em!==i){let n=a.getPropertyOptions(i),o=typeof n.converter=="function"?{fromAttribute:n.converter}:n.converter?.fromAttribute!==void 0?n.converter:Ca;this._$Em=i,this[i]=o.fromAttribute(e,n.type)??this._$Ej?.get(i)??null,this._$Em=null}}requestUpdate(t,e,a){if(t!==void 0){let i=this.constructor,n=this[t];if(a??(a=i.getPropertyOptions(t)),!((a.hasChanged??Ar)(n,e)||a.useDefault&&a.reflect&&n===this._$Ej?.get(t)&&!this.hasAttribute(i._$Eu(t,a))))return;this.C(t,e,a)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,e,{useDefault:a,reflect:i,wrapped:n},o){a&&!(this._$Ej??(this._$Ej=new Map)).has(t)&&(this._$Ej.set(t,o??e??this[t]),n!==!0||o!==void 0)||(this._$AL.has(t)||(this.hasUpdated||a||(e=void 0),this._$AL.set(t,e)),i===!0&&this._$Em!==t&&(this._$Eq??(this._$Eq=new Set)).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(let[i,n]of this._$Ep)this[i]=n;this._$Ep=void 0}let a=this.constructor.elementProperties;if(a.size>0)for(let[i,n]of a){let{wrapped:o}=n,s=this[i];o!==!0||this._$AL.has(i)||s===void 0||this.C(i,void 0,n,s)}}let t=!1,e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach((a=>a.hostUpdate?.())),this.update(e)):this._$EM()}catch(a){throw t=!1,this._$EM(),a}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&(this._$Eq=this._$Eq.forEach((e=>this._$ET(e,this[e])))),this._$EM()}updated(t){}firstUpdated(t){}};at.elementStyles=[],at.shadowRootOptions={mode:"open"},at[Aa("elementProperties")]=new Map,at[Aa("finalized")]=new Map,up?.({ReactiveElement:at}),(St.reactiveElementVersions??(St.reactiveElementVersions=[])).push("2.1.0");var Ea=globalThis,Cr=Ea.trustedTypes,Xo=Cr?Cr.createPolicy("lit-html",{createHTML:r=>r}):void 0,Yi="$lit$",rt=`lit$${Math.random().toFixed(9).slice(2)}$`,$i="?"+rt,pp=`<${$i}>`,Bt=document,Ta=()=>Bt.createComment(""),Pa=r=>r===null||typeof r!="object"&&typeof r!="function",zi=Array.isArray,ns=r=>zi(r)||typeof r?.[Symbol.iterator]=="function",Hi=`[
|
|
145
145
|
\f\r]`,Ma=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,es=/-->/g,ts=/>/g,wt=RegExp(`>|${Hi}(?:([^\\s"'>=/]+)(${Hi}*=${Hi}*(?:[^
|
|
146
|
-
\f\r"'\`<>=]|("|')|))|$)`,"g"),as=/'/g,rs=/"/g,os=/^(?:script|style|textarea|title)$/i,ji=r=>(t,...e)=>({_$litType$:r,strings:t,values:e}),p=ji(1),Oe=ji(2),Oy=ji(3),ve=Symbol.for("lit-noChange"),y=Symbol.for("lit-nothing"),is=new WeakMap,Dt=Bt.createTreeWalker(Bt,129);function ss(r,t){if(!zi(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return Xo!==void 0?Xo.createHTML(t):t}var ls=(r,t)=>{let e=r.length-1,a=[],i,n=t===2?"<svg>":t===3?"<math>":"",o=Ma;for(let s=0;s<e;s++){let l=r[s],c,m,g=-1,h=0;for(;h<l.length&&(o.lastIndex=h,m=o.exec(l),m!==null);)h=o.lastIndex,o===Ma?m[1]==="!--"?o=es:m[1]!==void 0?o=ts:m[2]!==void 0?(os.test(m[2])&&(i=RegExp("</"+m[2],"g")),o=wt):m[3]!==void 0&&(o=wt):o===wt?m[0]===">"?(o=i??Ma,g=-1):m[1]===void 0?g=-2:(g=o.lastIndex-m[2].length,c=m[1],o=m[3]===void 0?wt:m[3]==='"'?rs:as):o===rs||o===as?o=wt:o===es||o===ts?o=Ma:(o=wt,i=void 0);let T=o===wt&&r[s+1].startsWith("/>")?" ":"";n+=o===Ma?l+pp:g>=0?(a.push(c),l.slice(0,g)+Yi+l.slice(g)+rt+T):l+rt+(g===-2?s:T)}return[ss(r,n+(r[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),a]},Na=class r{constructor({strings:t,_$litType$:e},a){let i;this.parts=[];let n=0,o=0,s=t.length-1,l=this.parts,[c,m]=ls(t,e);if(this.el=r.createElement(c,a),Dt.currentNode=this.el.content,e===2||e===3){let g=this.el.content.firstChild;g.replaceWith(...g.childNodes)}for(;(i=Dt.nextNode())!==null&&l.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let g of i.getAttributeNames())if(g.endsWith(Yi)){let h=m[o++],T=i.getAttribute(g).split(rt),M=/([.?@])?(.*)/.exec(h);l.push({type:1,index:n,name:M[2],strings:T,ctor:M[1]==="."?Er:M[1]==="?"?Tr:M[1]==="@"?Pr:Gt}),i.removeAttribute(g)}else g.startsWith(rt)&&(l.push({type:6,index:n}),i.removeAttribute(g));if(os.test(i.tagName)){let g=i.textContent.split(rt),h=g.length-1;if(h>0){i.textContent=Cr?Cr.emptyScript:"";for(let T=0;T<h;T++)i.append(g[T],Ta()),Dt.nextNode(),l.push({type:2,index:++n});i.append(g[h],Ta())}}}else if(i.nodeType===8)if(i.data===$i)l.push({type:2,index:n});else{let g=-1;for(;(g=i.data.indexOf(rt,g+1))!==-1;)l.push({type:7,index:n}),g+=rt.length-1}n++}}static createElement(t,e){let a=Bt.createElement("template");return a.innerHTML=t,a}};function Ot(r,t,e=r,a){if(t===ve)return t;let i=a!==void 0?e._$Co?.[a]:e._$Cl,n=Pa(t)?void 0:t._$litDirective$;return i?.constructor!==n&&(i?._$AO?.(!1),n===void 0?i=void 0:(i=new n(r),i._$AT(r,e,a)),a!==void 0?(e._$Co??(e._$Co=[]))[a]=i:e._$Cl=i),i!==void 0&&(t=Ot(r,i._$AS(r,t.values),i,a)),t}var Mr=class{constructor(t,e){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){let{el:{content:e},parts:a}=this._$AD,i=(t?.creationScope??Bt).importNode(e,!0);Dt.currentNode=i;let n=Dt.nextNode(),o=0,s=0,l=a[0];for(;l!==void 0;){if(o===l.index){let c;l.type===2?c=new Xt(n,n.nextSibling,this,t):l.type===1?c=new l.ctor(n,l.name,l.strings,this,t):l.type===6&&(c=new Nr(n,this,t)),this._$AV.push(c),l=a[++s]}o!==l?.index&&(n=Dt.nextNode(),o++)}return Dt.currentNode=Bt,i}p(t){let e=0;for(let a of this._$AV)a!==void 0&&(a.strings!==void 0?(a._$AI(t,a,e),e+=a.strings.length-2):a._$AI(t[e])),e++}},Xt=class r{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,e,a,i){this.type=2,this._$AH=y,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=a,this.options=i,this._$Cv=i?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,e=this._$AM;return e!==void 0&&t?.nodeType===11&&(t=e.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,e=this){t=Ot(this,t,e),Pa(t)?t===y||t==null||t===""?(this._$AH!==y&&this._$AR(),this._$AH=y):t!==this._$AH&&t!==ve&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):ns(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==y&&Pa(this._$AH)?this._$AA.nextSibling.data=t:this.T(Bt.createTextNode(t)),this._$AH=t}$(t){let{values:e,_$litType$:a}=t,i=typeof a=="number"?this._$AC(t):(a.el===void 0&&(a.el=Na.createElement(ss(a.h,a.h[0]),this.options)),a);if(this._$AH?._$AD===i)this._$AH.p(e);else{let n=new Mr(i,this),o=n.u(this.options);n.p(e),this.T(o),this._$AH=n}}_$AC(t){let e=is.get(t.strings);return e===void 0&&is.set(t.strings,e=new Na(t)),e}k(t){zi(this._$AH)||(this._$AH=[],this._$AR());let e=this._$AH,a,i=0;for(let n of t)i===e.length?e.push(a=new r(this.O(Ta()),this.O(Ta()),this,this.options)):a=e[i],a._$AI(n),i++;i<e.length&&(this._$AR(a&&a._$AB.nextSibling,i),e.length=i)}_$AR(t=this._$AA.nextSibling,e){for(this._$AP?.(!1,!0,e);t&&t!==this._$AB;){let a=t.nextSibling;t.remove(),t=a}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},Gt=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,a,i,n){this.type=1,this._$AH=y,this._$AN=void 0,this.element=t,this.name=e,this._$AM=i,this.options=n,a.length>2||a[0]!==""||a[1]!==""?(this._$AH=Array(a.length-1).fill(new String),this.strings=a):this._$AH=y}_$AI(t,e=this,a,i){let n=this.strings,o=!1;if(n===void 0)t=Ot(this,t,e,0),o=!Pa(t)||t!==this._$AH&&t!==ve,o&&(this._$AH=t);else{let s=t,l,c;for(t=n[0],l=0;l<n.length-1;l++)c=Ot(this,s[a+l],e,l),c===ve&&(c=this._$AH[l]),o||(o=!Pa(c)||c!==this._$AH[l]),c===y?t=y:t!==y&&(t+=(c??"")+n[l+1]),this._$AH[l]=c}o&&!i&&this.j(t)}j(t){t===y?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Er=class extends Gt{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===y?void 0:t}},Tr=class extends Gt{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==y)}},Pr=class extends Gt{constructor(t,e,a,i,n){super(t,e,a,i,n),this.type=5}_$AI(t,e=this){if((t=Ot(this,t,e,0)??y)===ve)return;let a=this._$AH,i=t===y&&a!==y||t.capture!==a.capture||t.once!==a.once||t.passive!==a.passive,n=t!==y&&(a===y||i);i&&this.element.removeEventListener(this.name,this,a),n&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},Nr=class{constructor(t,e,a){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=a}get _$AU(){return this._$AM._$AU}_$AI(t){Ot(this,t)}},ds={M:Yi,P:rt,A:$i,C:1,L:ls,R:Mr,D:ns,V:Ot,I:Xt,H:Gt,N:Tr,U:Pr,B:Er,F:Nr},mp=Ea.litHtmlPolyfillSupport;mp?.(Na,Xt),(Ea.litHtmlVersions??(Ea.litHtmlVersions=[])).push("3.3.0");var cs=(r,t,e)=>{let a=e?.renderBefore??t,i=a._$litPart$;if(i===void 0){let n=e?.renderBefore??null;a._$litPart$=i=new Xt(t.insertBefore(Ta(),n),n,void 0,e??{})}return i._$AI(r),i};var Ia=globalThis,v=class extends at{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var e;let t=super.createRenderRoot();return(e=this.renderOptions).renderBefore??(e.renderBefore=t.firstChild),t}update(t){let e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=cs(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return ve}};v._$litElement$=!0,v.finalized=!0,Ia.litElementHydrateSupport?.({LitElement:v});var hp=Ia.litElementPolyfillSupport;hp?.({LitElement:v});(Ia.litElementVersions??(Ia.litElementVersions=[])).push("4.2.0");var S=r=>(t,e)=>{e!==void 0?e.addInitializer((()=>{customElements.define(r,t)})):customElements.define(r,t)};var gp={attribute:!0,type:String,converter:Ca,reflect:!1,hasChanged:Ar},yp=(r=gp,t,e)=>{let{kind:a,metadata:i}=e,n=globalThis.litPropertyMetadata.get(i);if(n===void 0&&globalThis.litPropertyMetadata.set(i,n=new Map),a==="setter"&&((r=Object.create(r)).wrapped=!0),n.set(e.name,r),a==="accessor"){let{name:o}=e;return{set(s){let l=t.get.call(this);t.set.call(this,s),this.requestUpdate(o,l,r)},init(s){return s!==void 0&&this.C(o,void 0,r,s),s}}}if(a==="setter"){let{name:o}=e;return function(s){let l=this[o];t.call(this,s),this.requestUpdate(o,l,r)}}throw Error("Unsupported decorator location: "+a)};function u(r){return(t,e)=>typeof e=="object"?yp(r,t,e):((a,i,n)=>{let o=i.hasOwnProperty(n);return i.constructor.createProperty(n,a),o?Object.getOwnPropertyDescriptor(i,n):void 0})(r,t,e)}function N(r){return u({...r,state:!0,attribute:!1})}var Kt=(r,t,e)=>(e.configurable=!0,e.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(r,t,e),e);function Le(r,t){return(e,a,i)=>{let n=o=>o.renderRoot?.querySelector(r)??null;if(t){let{get:o,set:s}=typeof a=="object"?e:i??(()=>{let l=Symbol();return{get(){return this[l]},set(c){this[l]=c}}})();return Kt(e,a,{get(){let l=o.call(this);return l===void 0&&(l=n(this),(l!==null||this.hasUpdated)&&s.call(this,l)),l}})}return Kt(e,a,{get(){return n(this)}})}}function R(r,t,e){return r?t(r):e?.(r)}var I=f` * { box-sizing: border-box; } `,us=f` :host { display: block; isolation: isolate; position: relative; width: 100%; //Keep the CSS loader in the same position - check css-loader-inline.ts min-height: 64px; } `;var ps="https://sdk.primer.io/web/v2-latest/Primer.min.js",Se="20px";var Ir=class{constructor(t){this.paymentMethods=null;this.paymentManagers=null;this.vaultController=null;this.headlessInstance=t,this.vault={createCvvInput:e=>this.createCvvInputInternal(e),startPayment:(e,a)=>this.startVaultPaymentInternal(e,a),delete:e=>this.deleteVaultPaymentMethod(e)}}setPaymentMethods(t){this.paymentMethods=t}setPaymentManagers(t){this.paymentManagers=t}setVaultController(t){this.vaultController=t}async createCvvInputInternal(t){return this.vaultController?this.vaultController.createCvvInput(t):(P.warn("PrimerJS: Vault not available - createCvvInput cannot be called"),null)}async startVaultPaymentInternal(t,e){if(!this.vaultController)throw new Error("Vault manager not initialized");return this.vaultController.startVaultPaymentById(t,e)}async deleteVaultPaymentMethod(t){if(!this.vaultController)throw new Error("Vault manager not initialized");return this.vaultController.deleteVaultedPaymentMethod(t)}async createCvvInput(t){return this.vault.createCvvInput(t)}async startVaultPayment(t,e){return this.vault.startPayment(t,e)}async refreshSession(){if(!this.headlessInstance){P.errorWithDatadog("PrimerJS: Cannot refresh session: Headless instance not available");return}try{await this.headlessInstance.refreshClientSession()}catch(t){throw P.errorWithDatadog("PrimerJS: Error refreshing client session",{error:t}),t}}getPaymentMethods(){return this.paymentMethods?this.paymentMethods:(P.warn("PrimerJS: Payment methods not available"),[])}handlePaymentStart(){this.onPaymentStart&&this.onPaymentStart()}handleVaultedMethodsUpdate(t,e){if(this.onVaultedMethodsUpdate){let a=Math.floor(Date.now()/1e3);this.onVaultedMethodsUpdate({vaultedPayments:t,cvvRecapture:e,timestamp:a})}}setCardholderName(t){if(!this.paymentManagers){P.warn("PrimerJS: Payment managers not available - setCardholderName cannot be called yet");return}let e=this.paymentManagers.get("PAYMENT_CARD");if(!e||e.type!=="PAYMENT_CARD"){P.warn("PrimerJS: Card payment manager not available");return}try{e.manager.setCardholderName(t)}catch(a){P.errorWithDatadog("PrimerJS: Error setting cardholder name",{error:a})}}};var kr=typeof window<"u"&&typeof window.document<"u";function fp(r){return document.querySelector(`script[src^="${r}"]`)}function vp(r,t){let e=document.createElement("script");return e.setAttribute("src",r),e.setAttribute("async",""),e.setAttribute("crossorigin","anonymous"),t&&e.setAttribute("type","module"),e}function ms(r,t=!1){if(!kr)throw new Error("Cannot load script in server environment");let e=fp(r)??vp(r,t);return new Promise((a,i)=>{e.onload=()=>{a()},e.onerror=()=>{i(new Error(`Failed to load script: ${r}`))},e.parentNode||document.head.appendChild(e)})}var hs=f` :host { display: contents; } .cta-button { display: block; margin: auto; } `;var ne=class extends v{constructor(){super(...arguments);this.size="large";this.showCloseButton=!1;this.open=!1}openDialog(){this.open=!0}closeDialog(){let e=()=>{this.open=!1,this.removeEventListener("primer:dialog-close",e)};this.addEventListener("primer:dialog-close",e),this.dialog.startExitAnimation()}connectedCallback(){super.connectedCallback(),this.open||this.openDialog()}updated(e){super.updated(e),e.has("open")&&this.open&&this.onOpen&&this.onOpen(),e.has("open")&&this.open&&this.onContentRendered&&this.updateComplete.then(()=>{requestAnimationFrame(()=>{this.onContentRendered?.()})})}render(){return this.open?p`<primer-dialog .open=${this.open} size=${this.size} .showCloseButton=${this.showCloseButton} @primer:dialog-close="${()=>{this.open=!1}}" ><slot></slot>${this.cta?p`<primer-button @click=${this.cta.onClick} class="cta-button">${this.cta.icon?p`<primer-icon name="${this.cta.icon}" size="sm" color="var(--primer-color-background-outlined-default)" ></primer-icon>`:y} ${this.cta.label}</primer-button>`:y}</primer-dialog>`:y}};ne.styles=[I,hs],d([u({type:String})],ne.prototype,"size",2),d([u({type:Boolean})],ne.prototype,"showCloseButton",2),d([u({type:Object})],ne.prototype,"onOpen",2),d([u({type:Object})],ne.prototype,"onContentRendered",2),d([u({type:Object})],ne.prototype,"cta",2),d([N()],ne.prototype,"open",2),d([Le("primer-dialog")],ne.prototype,"dialog",2),ne=d([S("primer-portal-dialog"),D()],ne);var Lr=class{constructor(){this.currentDialog=null;this.currentResolver=null}async show(t){return new Promise(e=>{let a=new ne;a.size=t.size??"large",a.showCloseButton=t.showCloseButton??!1,a.onContentRendered=t.onContentReady,a.cta=t.cta;let i=()=>{a.remove(),this.currentDialog=null,this.currentResolver=null,e({success:!1})};a.addEventListener("primer:dialog-close",i),this.currentDialog=a,this.currentResolver=e,document.body.appendChild(a),a.appendChild(t.htmlContent)})}close(){this.currentDialog&&this.currentResolver&&(this.currentDialog.closeDialog(),this.currentResolver({success:!0}),this.currentDialog.remove(),this.currentDialog=null,this.currentResolver=null)}};var Sp=_a({"../../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.TR6QET27.js"),"../../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.EJ7QNYMP.js"),"../../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.7C2IYV2P.js"),"../../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.JT4THDDV.js"),"../../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.EM7SEPAQ.js"),"../../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.K6IE7XOI.js"),"../../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.3CKRNQD5.js"),"../../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.LG2PPT2V.js"),"../../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.47EGLMYC.js"),"../../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.ND7EGZHB.js"),"../../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.6QU35A6L.js"),"../../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.SMVRR5QO.js"),"../../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.BRBL5QIG.js"),"../../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.TPQGZ5V7.js"),"../../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.WWOUUKQI.js"),"../../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.OVEJBPUX.js"),"../../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.YPXJZUYV.js"),"../../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.7LEUFJ5J.js"),"../../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.TFWG6VOU.js"),"../../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.3SV7XLRR.js"),"../../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.P6C656R7.js"),"../../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.VOUHNCJ7.js"),"../../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.AFL7G4NO.js"),"../../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.TRKH4J6L.js"),"../../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.TGTBYQYP.js"),"../../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.HZTEA2Q2.js"),"../../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.QEKTVYHX.js"),"../../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.HRDZEYXV.js"),"../../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.2R7WVAV3.js"),"../../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.KHWKCZMK.js"),"../../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.D6YHYKB6.js"),"../../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.3NGFYB4U.js"),"../../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.LYW2A6VH.js"),"../../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.ILTDKZ2H.js"),"../../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.KJZFKIJM.js"),"../../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.5POYRJGA.js"),"../../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.GN5UGR5G.js"),"../../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.T3II5ZYL.js"),"../../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.63HB4O5X.js"),"../../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.AZ4SQZFW.js"),"../../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.WDGRPXBK.js"),"../../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.GYXXM7FX.js"),"../../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.TBVAKNJJ.js"),"../../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.GGWFQ3Y7.js"),"../../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.NK7PKUS6.js"),"../../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.SQG5YIVQ.js"),"../../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.P2X3B7LC.js")});var ea=null,Wi=null;async function gs(r){if(Wi===r&&ea)return ea;try{return ea=(await Sp(`../../../localization/lit-localize/locales/${r}.ts`)).templates,Wi=r,ea}catch{return r!=="en-GB"?gs("en-GB"):(ea={},Wi=r,ea)}}async function ys(r){let t=await gs(r);return(e,a)=>t[e]??a}var bt={WORLDPAY_IDEAL:"WORLDPAY_IDEAL",AUTOMATED_CLEARING_HOUSE:"AUTOMATED_CLEARING_HOUSE",ADYEN_KLARNA:"ADYEN_KLARNA",ADYEN_BANCONTACT_CARD:"ADYEN_BANCONTACT_CARD",PAY_NL_KAARTDIRECT:"PAY_NL_KAARTDIRECT",ADYEN_EPS:"ADYEN_EPS",ADYEN_BANCONTACT_PAYCONIQ:"ADYEN_BANCONTACT_PAYCONIQ",OMISE_PROMPTPAY:"OMISE_PROMPTPAY",OMISE_TRUEMONEY:"OMISE_TRUEMONEY",ADYEN_MULTIBANCO:"ADYEN_MULTIBANCO",PACYPAY_WECHAT:"PACYPAY_WECHAT",PACYPAY_ALIPAY:"PACYPAY_ALIPAY",ADYEN_MBWAY:"ADYEN_MBWAY",XENDIT_DANA:"XENDIT_DANA",XENDIT_SHOPEEPAY:"XENDIT_SHOPEEPAY",ADYEN_PAYSHOP:"ADYEN_PAYSHOP",ADYEN_PAYTRAIL:"ADYEN_PAYTRAIL",CLEARPAY:"CLEARPAY",RAPYD_FAST:"RAPYD_FAST",RAPYD_PROMPTPAY:"RAPYD_PROMPTPAY",RAPYD_GCASH:"RAPYD_GCASH",RAPYD_POLI:"RAPYD_POLI",RAPYD_GRABPAY:"RAPYD_GRABPAY",PRIMER_PAYPAL:"PRIMER_PAYPAL",TWOC2P:"TWOC2P",NETS:"NETS",STRIPE_ACH:"STRIPE_ACH",STRIPE_GIROPAY:"STRIPE_GIROPAY",MOLLIE_GIROPAY:"MOLLIE_GIROPAY",MOLLIE_EPS:"MOLLIE_EPS",PAY_NL_EPS:"PAY_NL_EPS",PAY_NL_P24:"PAY_NL_P24",MOLLIE_P24:"MOLLIE_P24",MOLLIE_SOFORT:"MOLLIE_SOFORT",COINBASE:"COINBASE",OPENNODE:"OPENNODE",MOLLIE_GIFT_CARD:"MOLLIE_GIFTCARD",XFERS_PAYNOW:"XFERS_PAYNOW",CARD:"PAYMENT_CARD",APPLE_PAY:"APPLE_PAY",GOOGLE_PAY:"GOOGLE_PAY",PAYPAL:"PAYPAL_ORDER",PAYPAL_VAULTED:"PAYPAL_BILLING_AGREEMENT",GO_CARDLESS:"GOCARDLESS",PAY_NL_IDEAL:"PAY_NL_IDEAL",PAY_NL_SOFORT_BANKING:"PAY_NL_SOFORT_BANKING",PAY_NL_BANCONTACT:"PAY_NL_BANCONTACT",PAY_NL_PAYPAL:"PAY_NL_PAYPAL",PAY_NL_CREDIT_TRANSFER:"PAY_NL_CREDIT_TRANSFER",PAY_NL_DIRECT_DEBIT:"PAY_NL_DIRECT_DEBIT",PAY_NL_GIROPAY:"PAY_NL_GIROPAY",PAY_NL_PAYCONIQ:"PAY_NL_PAYCONIQ",PAY_NL_RIVERTY:"PAY_NL_RIVERTY",HOOLAH:"HOOLAH",ADYEN_BLIK:"ADYEN_BLIK",ADYEN_VIPPS:"ADYEN_VIPPS",ADYEN_GIROPAY:"ADYEN_GIROPAY",ADYEN_SOFORT:"ADYEN_SOFORT",ADYEN_IDEAL:"ADYEN_IDEAL",ADYEN_TRUSTLY:"ADYEN_TRUSTLY",ADYEN_ALIPAY:"ADYEN_ALIPAY",ADYEN_TWINT:"ADYEN_TWINT",ADYEN_MOBILEPAY:"ADYEN_MOBILEPAY",MOLLIE_BANCONTACT:"MOLLIE_BANCONTACT",MOLLIE_IDEAL:"MOLLIE_IDEAL",BUCKAROO_GIROPAY:"BUCKAROO_GIROPAY",BUCKAROO_EPS:"BUCKAROO_EPS",BUCKAROO_SOFORT:"BUCKAROO_SOFORT",BUCKAROO_BANCONTACT:"BUCKAROO_BANCONTACT",BUCKAROO_IDEAL:"BUCKAROO_IDEAL",ATOME:"ATOME",KLARNA_CUSTOMER_TOKEN:"KLARNA_CUSTOMER_TOKEN",DLOCAL_PIX:"DLOCAL_PIX",ALMA:"ALMA",ADYEN_CASHAPP:"ADYEN_CASHAPP",ADYEN_AFFIRM:"ADYEN_AFFIRM"},ka={WORLDPAY_IDEAL:"WORLDPAY_IDEAL",STRIPE_ACH:"STRIPE_ACH",STRIPE_IDEAL:"STRIPE_IDEAL",ADYEN_KLARNA:"ADYEN_KLARNA",ADYEN_BANCONTACT_CARD:"ADYEN_BANCONTACT_CARD",PAY_NL_KAARTDIRECT:"PAY_NL_KAARTDIRECT",ADYEN_EPS:"ADYEN_EPS",ADYEN_BANCONTACT_PAYCONIQ:"ADYEN_BANCONTACT_PAYCONIQ",OMISE_PROMPTPAY:"OMISE_PROMPTPAY",OMISE_TRUEMONEY:"OMISE_TRUEMONEY",ADYEN_MULTIBANCO:"ADYEN_MULTIBANCO",PACYPAY_WECHAT:"PACYPAY_WECHAT",PACYPAY_ALIPAY:"PACYPAY_ALIPAY",ADYEN_MBWAY:"ADYEN_MBWAY",XENDIT_DANA:"XENDIT_DANA",XENDIT_SHOPEEPAY:"XENDIT_SHOPEEPAY",ADYEN_PAYSHOP:"ADYEN_PAYSHOP",ADYEN_PAYTRAIL:"ADYEN_PAYTRAIL",CLEARPAY:"CLEARPAY",RAPYD_FAST:"RAPYD_FAST",RAPYD_PROMPTPAY:"RAPYD_PROMPTPAY",RAPYD_GCASH:"RAPYD_GCASH",RAPYD_POLI:"RAPYD_POLI",RAPYD_GRABPAY:"RAPYD_GRABPAY",PRIMER_PAYPAL:"PRIMER_PAYPAL",TWOC2P:"TWOC2P",NETS:"NETS",STRIPE_GIROPAY:"STRIPE_GIROPAY",MOLLIE_GIROPAY:"MOLLIE_GIROPAY",MOLLIE_EPS:"MOLLIE_EPS",PAY_NL_EPS:"PAY_NL_EPS",PAY_NL_P24:"PAY_NL_P24",MOLLIE_P24:"MOLLIE_P24",MOLLIE_SOFORT:"MOLLIE_SOFORT",COINBASE:"COINBASE",OPENNODE:"OPENNODE",MOLLIE_GIFT_CARD:"MOLLIE_GIFTCARD",XFERS_PAYNOW:"XFERS_PAYNOW",PAYMENT_CARD:"PAYMENT_CARD",APPLE_PAY:"APPLE_PAY",GOOGLE_PAY:"GOOGLE_PAY",PAYPAL:"PAYPAL",GO_CARDLESS:"GOCARDLESS",KLARNA:"KLARNA",PAY_NL_IDEAL:"PAY_NL_IDEAL",PAY_NL_SOFORT_BANKING:"PAY_NL_SOFORT_BANKING",PAY_NL_BANCONTACT:"PAY_NL_BANCONTACT",PAY_NL_PAYPAL:"PAY_NL_PAYPAL",PAY_NL_CREDIT_TRANSFER:"PAY_NL_CREDIT_TRANSFER",PAY_NL_DIRECT_DEBIT:"PAY_NL_DIRECT_DEBIT",PAY_NL_GIROPAY:"PAY_NL_GIROPAY",PAY_NL_PAYCONIQ:"PAY_NL_PAYCONIQ",PAY_NL_RIVERTY:"PAY_NL_RIVERTY",HOOLAH:"HOOLAH",ADYEN_BLIK:"ADYEN_BLIK",ADYEN_MOBILEPAY:"ADYEN_MOBILEPAY",ADYEN_VIPPS:"ADYEN_VIPPS",ADYEN_GIROPAY:"ADYEN_GIROPAY",ADYEN_SOFORT:"ADYEN_SOFORT",ADYEN_IDEAL:"ADYEN_IDEAL",ADYEN_TRUSTLY:"ADYEN_TRUSTLY",ADYEN_ALIPAY:"ADYEN_ALIPAY",ADYEN_TWINT:"ADYEN_TWINT",ADYEN_BANK_TRANSFER:"ADYEN_BANK_TRANSFER",MOLLIE_BANCONTACT:"MOLLIE_BANCONTACT",MOLLIE_IDEAL:"MOLLIE_IDEAL",BUCKAROO_GIROPAY:"BUCKAROO_GIROPAY",BUCKAROO_EPS:"BUCKAROO_EPS",BUCKAROO_SOFORT:"BUCKAROO_SOFORT",BUCKAROO_BANCONTACT:"BUCKAROO_BANCONTACT",BUCKAROO_IDEAL:"BUCKAROO_IDEAL",ATOME:"ATOME",DLOCAL_PIX:"DLOCAL_PIX",ALMA:"ALMA",ADYEN_CASHAPP:"ADYEN_CASHAPP",ADYEN_AFFIRM:"ADYEN_AFFIRM"};var Rr=class r extends Error{constructor(t,e){super(e.message),this.name="PrimerClientError",this.code=t,this.diagnosticsId=e.diagnosticsId||null,this.data=e.data,this.isFromDeveloper=e.isFromDeveloper||!1}static fromErrorCode(t,e){return new r(t,e)}};function fs(r,t,e){return r.isDisconnected?!1:(r.host.sdkStateController.currentState.paymentFailure!==null&&Q({eventName:"PAYMENT_REATTEMPTED",paymentMethod:t}),r.host.sdkStateController.startProcessing(),r.host.primerEventsController.dispatchPaymentStart(t,e))}function vs(r,t,e){if(!r.isDisconnected&&(P.info("Payment completed:",t),r.host.sdkStateController.completeProcessing(),r.host.primerEventsController.dispatchPaymentSuccess(t,e),Q({eventName:"PAYMENT_SUCCESS",paymentId:t?.id,paymentMethod:e}),r.primerJS?.onPaymentSuccess)){let a=Math.floor(Date.now()/1e3);r.primerJS.onPaymentSuccess({payment:Wt(t),paymentMethodType:e,timestamp:a})}}function Ss(r,t,e,a){if(r.isDisconnected)return;(s=>typeof s=="object"&&s!==null&&"response"in s&&typeof s.response=="object"&&s.response!==null&&"status"in s.response&&typeof s.response.status=="number")(t)&&t.response.status>=500?P.errorWithDatadog("Payment failed with server error",{error:t}):P.error("Payment failed:",t);let o=t instanceof Rr?{code:t.code||"UNKNOWN_ERROR",message:t.message||"Unknown error occurred",diagnosticsId:t.diagnosticsId,data:t.data}:(()=>{let s=t,l=s instanceof Error&&"code"in s&&typeof s.code=="string"?s.code:"UNKNOWN_ERROR",c=s instanceof Error?s.message:"Unknown error occurred";return{code:l,message:c,data:{error:t}}})();if(r.host.sdkStateController.setPaymentFailure(o),r.host.primerEventsController.dispatchPaymentFailure({code:o.code,message:o.message,diagnosticsId:"diagnosticsId"in o?o.diagnosticsId??void 0:void 0,data:o.data},e,a),Q({eventName:"PAYMENT_FAILURE",paymentId:a?.id,paymentMethod:e}),r.primerJS?.onPaymentFailure){let s=Math.floor(Date.now()/1e3);r.primerJS.onPaymentFailure({error:{code:o.code,message:o.message,diagnosticsId:"diagnosticsId"in o?o.diagnosticsId??void 0:void 0,data:o.data},payment:a?Wt(a):void 0,paymentMethodType:e,timestamp:s})}}var Zi="1.0.0",xr=class{constructor(t){this.createPaymentMethodManager=null;this._paymentsList=[];this.currentSdkInstance=null;this.primerJS=null;this.loadingTimeout=null;this.isDisconnected=!1;(this.host=t).addController(this),this.isDisconnected=!1,this.sdkInstanceTask=new O(t,{args:()=>[this.host.clientToken,this.host.options],task:this.initializeHeadless()}),new O(t,{args:()=>[this.sdkInstanceTask.value,this.paymentsList],task:this.initializeLitContext()})}set paymentsList(t){this._paymentsList=t,this.host.requestUpdate()}get paymentsList(){return this._paymentsList}get primerJSInstance(){return this.primerJS}hostConnected(){this.isDisconnected=!1,this.host.sdkStateController.startLoading(),this.setupLoadingTimeout()}hostDisconnected(){if(this.isDisconnected=!0,this.host.sdkContextController.getAnalyticsUtils()){let e=this.host.sdkStateController.currentState;(e.isProcessing||e.isLoading||this.currentSdkInstance)&&Q({eventName:"PAYMENT_FLOW_EXITED"})}this.cleanupResources()}normalizeOptionsForLegacySdk(t){if(t.sdkCore!==!1)return{...t,sdkCore:!0};let e={...t};if(e.card?.cardholderName){let a={...e.card.cardholderName};a.visible===!1&&(a.required=!1),e.card={...e.card,cardholderName:a}}return e}setupLoadingTimeout(){this.clearLoadingTimeout(),this.loadingTimeout=setTimeout(()=>{this.host.sdkStateController.currentState.isLoading&&(P.warn("Loading timeout reached, resetting SDK state"),Q({eventName:"PAYMENT_FLOW_EXITED",eventType:"timeout"}),this.cleanupResources(),this.host.sdkStateController.completeLoading())},1e4)}clearLoadingTimeout(){this.loadingTimeout!==null&&(clearTimeout(this.loadingTimeout),this.loadingTimeout=null)}cleanupResources(){if(this.clearLoadingTimeout(),this.currentSdkInstance)try{this.paymentsList=[],this.createPaymentMethodManager=null,this.host.sdkStateController.reset(),this.currentSdkInstance.teardown?.(),P.info("SDK instance cleaned up")}catch(t){P.errorWithDatadog("Error cleaning up SDK instance",{error:t})}Bo(),P.setClientToken(void 0),P.setSdkOptions(void 0),this.currentSdkInstance=null,this.primerJS=null}async _loadV2Sdk(t=ps){let e=window;if(e.Primer&&typeof e.Primer.preloadPrimer=="function"){P.info("SDK already loaded, skipping load script"),await e.Primer.preloadPrimer();return}await ms(t),await e.Primer.preloadPrimer()}initializeHeadless(){return async([t,e])=>{if(this.isDisconnected)return P.warn("Component disconnected, aborting SDK initialization"),w;if(!t||!e)return w;this.cleanupResources();let a;try{let i;if(e.sdkCore!==!1){let l=new Lr,c=Qt(e.locale||vr()),m=await ys(c);i={createHeadless:(h,T)=>vo(h,{...T,dialogProvider:l,translate:m,sdkVersion:Zi,locale:c})}}else await this._loadV2Sdk(),i=window.Primer;this.primerJS=new Ir(null),this.primerJS.setVaultController(this.host.vaultManagerController);let n=this.normalizeOptionsForLegacySdk(e);P.setClientToken(t),P.setSdkOptions(n);let o=await i.createHeadless(t,{...n,onAvailablePaymentMethodsLoad:l=>{this.isDisconnected||(P.info("Configuration payment methods:",l),this.paymentsList=l)},onCheckoutComplete:({payment:l})=>{let c=l?.paymentMethodData?.paymentMethodType;vs({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},l,c)},onCheckoutFail:(l,c)=>{let m=c.payment?.paymentMethodData?.paymentMethodType;Ss({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},l,m,c.payment)},onBeforePaymentCreate:(l,c)=>{if(!l.paymentMethodType){P.error("Payment creation started without payment method type"),c?.abortPaymentCreation();return}if(!(fs({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},l.paymentMethodType,c)||this.isDisconnected)){if(this.primerJS?.onPaymentPrepare){this.primerJS.onPaymentPrepare({paymentMethodType:l.paymentMethodType},c);return}c?.continuePaymentCreation()}},onPaymentMethodAction:(l,c)=>{this.isDisconnected||l==="PAYMENT_METHOD_UNSELECTED"&&(this.host.primerEventsController.dispatchPaymentCancel(c),this.host.sdkStateController.stopProcessing())},onPaymentCreationStart:()=>{this.isDisconnected||this.primerJS&&this.primerJS.handlePaymentStart()}});if(this.createPaymentMethodManager=o.createPaymentMethodManager.bind(o),this.currentSdkInstance=o,this.primerJS&&Object.defineProperty(this.primerJS,"headlessInstance",{value:o,writable:!1}),await o.start(),this.isDisconnected)return this.cleanupResources(),w;this.host.sdkContextController.setClientOptions(e),this.primerJS&&this.host.primerEventsController.dispatchCheckoutInitialized(this.primerJS);let s=o.getSDKUtilities();if(a=o.getAnalyticsUtils?.(),a&&(this.host.sdkContextController.setAnalyticsUtils({...a,sdkVersion:Zi}),Do({environment:a.environment,checkoutSessionId:a.checkoutSessionId,clientSessionId:a.clientSessionId||"",primerAccountId:a.primerAccountId||"",sdkVersion:Zi,clientSessionToken:a.clientSessionToken,userAgent:typeof navigator<"u"?navigator.userAgent:""}),a.configurationFetchStartTime&&Ye.setSdkInitStartTime(a.configurationFetchStartTime),Q({eventName:"SDK_INIT_START"})),this.host.sdkContextController.setHeadlessUtils(s),e.sdkCore&&o.getConfiguration){let l=o.getConfiguration();this.host.sdkContextController.setConfiguration(l)}return this.host.vaultManagerController.initializeVaultManager(o.createVaultManager.bind(o),{vaultEnabled:e.vault?.enabled,captureVaultedCardCvv:!!s.getPaymentMethodConfiguration("PAYMENT_CARD")?.options?.captureVaultedCardCvv,showEmptyState:e.vault?.showEmptyState,headless:e.vault?.headless??!1}),o}catch(i){throw i instanceof Error&&(P.errorWithDatadog("SDK initialization error",{error:i,status:"error"}),this.host.sdkStateController.setPrimerJsError(i)),this.cleanupResources(),i}}}initializeLitContext(){return async([t,e])=>{if(this.isDisconnected)return w;if(!t||!e.length)return w;let a=new Map,i=new Map;try{for(let o of e){if(this.isDisconnected)break;let s=await this.initializePaymentMethodManager(o)();o&&s&&(a.set(o.type,o),i.set(o.type,s))}if(this.isDisconnected)return w;let n=Array.from(a.values());return this.host.sdkContextController.setPaymentManagers(i),this.host.sdkContextController.setPaymentMethods(n),this.primerJS&&(this.primerJS.setPaymentMethods(n),this.primerJS.setPaymentManagers(i)),this.host.primerEventsController.dispatchPaymentMethods(n),P.info("Initialized payment methods:",n),a}catch(n){if(n instanceof Error)throw this.host.sdkStateController.setPrimerJsError(n),n;return null}finally{this.clearLoadingTimeout(),this.isDisconnected||(this.host.sdkStateController.completeLoading(),Q({eventName:"SDK_INIT_END"}))}}}initializePaymentMethodManager(t){let{type:e,managerType:a}=t;return async()=>{if(this.isDisconnected||!this.createPaymentMethodManager)return null;if(a==="KLARNA"){let i=await this.createPaymentMethodManager("KLARNA",{onPaymentMethodCategoriesChange:n=>{this.isDisconnected||this.host.sdkContextController.setKlarnaCategories({categories:n,isLoading:!1})}});return i?{type:e,manager:i}:null}try{if(a==="CARD"){let n=await this.createPaymentMethodManager("PAYMENT_CARD",{onBinDataAvailable:o=>{this.isDisconnected||this.host.cardNetworkController.processBinDataAvailableEvent(o)},onCardNetworksChange:o=>{this.isDisconnected||this.host.cardNetworkController.processCardNetworkChangeEvent(o)},onCardNetworksLoading:()=>{this.isDisconnected||this.host.cardNetworkController.setCardNetworksLoading()},onBinDataLoadingChange:o=>{this.isDisconnected||this.host.primerEventsController.dispatchBinDataLoadingChange(o)}});return n?{type:e,manager:n}:null}let i=await this.createPaymentMethodManager(e);return i?{type:e,manager:i}:null}catch(i){return P.errorWithDatadog(`Failed to initialize manager for ${e}`,{error:i}),null}}}};var _r=class{constructor(t){this.host=t,t.addController(this)}_error(t){let{error:e}=t.detail;this.host.sdkStateController.setPaymentFailure({code:"UNKNOWN_ERROR",message:e.message})}_mandateConfirmed(){this.host.sdkStateController.completeProcessing()}_mandateDeclined(){this.host.sdkStateController.setPaymentFailure({code:"UNKNOWN_ERROR",message:"Mandate declined"})}hostConnected(){this.host.addEventListener("primer-ach-error",this._error.bind(this)),this.host.addEventListener("primer-ach-mandate-confirmed",this._mandateConfirmed.bind(this)),this.host.addEventListener("primer-ach-mandate-declined",this._mandateDeclined.bind(this))}hostDisconnected(){this.host.removeEventListener("primer-ach-error",this._error.bind(this)),this.host.removeEventListener("primer-ach-mandate-confirmed",this._mandateConfirmed.bind(this)),this.host.removeEventListener("primer-ach-mandate-declined",this._mandateDeclined.bind(this))}};var bp=_a({"../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.TR6QET27.js"),"../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.EJ7QNYMP.js"),"../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.7C2IYV2P.js"),"../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.JT4THDDV.js"),"../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.EM7SEPAQ.js"),"../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.K6IE7XOI.js"),"../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.3CKRNQD5.js"),"../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.LG2PPT2V.js"),"../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.47EGLMYC.js"),"../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.ND7EGZHB.js"),"../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.6QU35A6L.js"),"../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.SMVRR5QO.js"),"../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.BRBL5QIG.js"),"../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.TPQGZ5V7.js"),"../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.WWOUUKQI.js"),"../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.OVEJBPUX.js"),"../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.YPXJZUYV.js"),"../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.7LEUFJ5J.js"),"../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.TFWG6VOU.js"),"../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.3SV7XLRR.js"),"../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.P6C656R7.js"),"../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.VOUHNCJ7.js"),"../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.AFL7G4NO.js"),"../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.TRKH4J6L.js"),"../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.TGTBYQYP.js"),"../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.HZTEA2Q2.js"),"../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.QEKTVYHX.js"),"../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.HRDZEYXV.js"),"../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.2R7WVAV3.js"),"../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.KHWKCZMK.js"),"../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.D6YHYKB6.js"),"../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.3NGFYB4U.js"),"../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.LYW2A6VH.js"),"../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.ILTDKZ2H.js"),"../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.KJZFKIJM.js"),"../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.5POYRJGA.js"),"../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.GN5UGR5G.js"),"../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.T3II5ZYL.js"),"../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.63HB4O5X.js"),"../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.AZ4SQZFW.js"),"../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.WDGRPXBK.js"),"../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.GYXXM7FX.js"),"../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.TBVAKNJJ.js"),"../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.GGWFQ3Y7.js"),"../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.NK7PKUS6.js"),"../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.SQG5YIVQ.js"),"../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.P2X3B7LC.js")});Oi(r=>bp(`../../localization/lit-localize/locales/${r}.ts`));var Ap={LOADER_DISABLED:"loader-disabled",CUSTOM_STYLES:"custom-styles",CLIENT_TOKEN:"client-token",JS_INIT:"js-initialized"},Pe=class extends v{constructor(){super();this.customStyles="";this.clientToken="";this.options={};this.disableLoader=!1;this._jsInitialized=!1;this.previousLoadingState=!0;this.hasAssignedContent=!1;this._loadingTimeoutId=null;this._eventListenerController=null;this.locale=Qt(vr());this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0,this.requestUpdate()};this.sdkContextController=new nr(this),this.sdkStateController=new ir(this),this.primerEventsController=new Zt(this),this.styleProcessingController=new or(this),this.vaultManagerController=new ga(this),this.cardNetworkController=new wa(this),this.achPaymentEventsController=new _r(this),this.headlessSdkController=new xr(this)}set jsInitialized(e){this.requestUpdate(),this._jsInitialized=e}get jsInitialized(){return this._jsInitialized}get primerJS(){return this.headlessSdkController?.primerJSInstance??void 0}connectedCallback(){super.connectedCallback(),this.sdkContextController.setEventsController(this.primerEventsController),this._eventListenerController=new AbortController,document.addEventListener("primer:card-submit",this.handleExternalCardSubmit.bind(this),{signal:this._eventListenerController.signal}),document.addEventListener("primer:vault-submit",this.handleExternalVaultSubmit.bind(this),{signal:this._eventListenerController.signal}),document.addEventListener("primer:show-other-payments-toggle",this.handleExternalShowOtherPaymentsToggle.bind(this),{signal:this._eventListenerController.signal})}attributeChangedCallback(e,a,i){e===Ap.CUSTOM_STYLES?this.styleProcessingController.processCustomStyles(i):super.attributeChangedCallback(e,a,i)}disconnectedCallback(){this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null),this.sdkStateController?.currentState.isLoading&&this.sdkStateController.forceCompleteLoading(),this._eventListenerController&&(this._eventListenerController.abort(),this._eventListenerController=null),super.disconnectedCallback()}willUpdate(e){e.has("options")&&(this.options?.locale&&(Fi(this.options?.locale)?this.locale=Qt(this.options?.locale):P.warn("\u{1F30E}\u2757 Unsupported locale provided:",this.options?.locale,"- Falling back to system locale")),Gi(this.locale))}updated(){let e=getComputedStyle(this);this.sdkContextController.setComputedStyles(e),this.checkLoadingStateChange()}handleExternalCardSubmit(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:card-submit",e.detail)}handleExternalVaultSubmit(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:vault-submit",e.detail)}handleExternalShowOtherPaymentsToggle(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:show-other-payments-toggle",e.detail)}checkLoadingStateChange(){let e=this.sdkStateController?.currentState.isLoading||!1;if(this.previousLoadingState&&!e){this.jsInitialized=!0,Q({eventName:"CHECKOUT_FLOW_STARTED"});let a=Ye.getSdkInitStartTime(),i=a?Date.now()-a:void 0;Eo(i)}this.previousLoadingState=e,e&&!this._loadingTimeoutId?this._loadingTimeoutId=window.setTimeout(()=>{this.sdkStateController?.currentState.isLoading&&(P.warn("Loading timeout in component, forcing completion"),this.sdkStateController.forceCompleteLoading(),this.jsInitialized=!0),this._loadingTimeoutId=null},1e4):!e&&this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null)}render(){let e=this.sdkStateController.currentState,a=e.isLoading,i=e.primerJsError,n=!a&&!i;return p` ${R(a,()=>y)} ${R(i,()=>p`<primer-checkout-error></primer-checkout-error>`)} ${R(n,()=>p`<slot name="main" @slotchange=${this.onSlotChange}></slot>${R(this.hasAssignedContent,()=>y,()=>p`<primer-main></primer-main>`)} `,()=>y)} `}addEventListener(e,a,i){super.addEventListener(e,a,i)}removeEventListener(e,a,i){super.removeEventListener(e,a,i)}};Pe.styles=[I,us],d([u({type:String,attribute:"custom-styles"})],Pe.prototype,"customStyles",2),d([u({type:String,attribute:"client-token"})],Pe.prototype,"clientToken",2),d([u({type:Object,attribute:!1,hasChanged:(e,a)=>!rr(e,a)})],Pe.prototype,"options",2),d([u({type:Boolean,attribute:"loader-disabled"})],Pe.prototype,"disableLoader",2),d([u({type:Boolean,reflect:!0,attribute:"js-initialized"})],Pe.prototype,"_jsInitialized",2),d([Le("slot")],Pe.prototype,"defaultSlot",2),d([N()],Pe.prototype,"previousLoadingState",2),Pe=d([D(),S("primer-checkout")],Pe);function Cp(r){return document.querySelector(`#${r}`)}function Mp(r,t){let e=document.createElement("style");return e.textContent=r,e.id=t,e}function La(r,t,e=!0){if(!kr||Cp(t))return;let i=Mp(r,t);e&&document.head.firstChild?document.head.insertBefore(i,document.head.firstChild):document.head.appendChild(i)}var bs=`
|
|
146
|
+
\f\r"'\`<>=]|("|')|))|$)`,"g"),as=/'/g,rs=/"/g,os=/^(?:script|style|textarea|title)$/i,ji=r=>(t,...e)=>({_$litType$:r,strings:t,values:e}),p=ji(1),Oe=ji(2),Oy=ji(3),ve=Symbol.for("lit-noChange"),y=Symbol.for("lit-nothing"),is=new WeakMap,Dt=Bt.createTreeWalker(Bt,129);function ss(r,t){if(!zi(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return Xo!==void 0?Xo.createHTML(t):t}var ls=(r,t)=>{let e=r.length-1,a=[],i,n=t===2?"<svg>":t===3?"<math>":"",o=Ma;for(let s=0;s<e;s++){let l=r[s],c,m,g=-1,h=0;for(;h<l.length&&(o.lastIndex=h,m=o.exec(l),m!==null);)h=o.lastIndex,o===Ma?m[1]==="!--"?o=es:m[1]!==void 0?o=ts:m[2]!==void 0?(os.test(m[2])&&(i=RegExp("</"+m[2],"g")),o=wt):m[3]!==void 0&&(o=wt):o===wt?m[0]===">"?(o=i??Ma,g=-1):m[1]===void 0?g=-2:(g=o.lastIndex-m[2].length,c=m[1],o=m[3]===void 0?wt:m[3]==='"'?rs:as):o===rs||o===as?o=wt:o===es||o===ts?o=Ma:(o=wt,i=void 0);let T=o===wt&&r[s+1].startsWith("/>")?" ":"";n+=o===Ma?l+pp:g>=0?(a.push(c),l.slice(0,g)+Yi+l.slice(g)+rt+T):l+rt+(g===-2?s:T)}return[ss(r,n+(r[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),a]},Na=class r{constructor({strings:t,_$litType$:e},a){let i;this.parts=[];let n=0,o=0,s=t.length-1,l=this.parts,[c,m]=ls(t,e);if(this.el=r.createElement(c,a),Dt.currentNode=this.el.content,e===2||e===3){let g=this.el.content.firstChild;g.replaceWith(...g.childNodes)}for(;(i=Dt.nextNode())!==null&&l.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let g of i.getAttributeNames())if(g.endsWith(Yi)){let h=m[o++],T=i.getAttribute(g).split(rt),M=/([.?@])?(.*)/.exec(h);l.push({type:1,index:n,name:M[2],strings:T,ctor:M[1]==="."?Er:M[1]==="?"?Tr:M[1]==="@"?Pr:Gt}),i.removeAttribute(g)}else g.startsWith(rt)&&(l.push({type:6,index:n}),i.removeAttribute(g));if(os.test(i.tagName)){let g=i.textContent.split(rt),h=g.length-1;if(h>0){i.textContent=Cr?Cr.emptyScript:"";for(let T=0;T<h;T++)i.append(g[T],Ta()),Dt.nextNode(),l.push({type:2,index:++n});i.append(g[h],Ta())}}}else if(i.nodeType===8)if(i.data===$i)l.push({type:2,index:n});else{let g=-1;for(;(g=i.data.indexOf(rt,g+1))!==-1;)l.push({type:7,index:n}),g+=rt.length-1}n++}}static createElement(t,e){let a=Bt.createElement("template");return a.innerHTML=t,a}};function Ot(r,t,e=r,a){if(t===ve)return t;let i=a!==void 0?e._$Co?.[a]:e._$Cl,n=Pa(t)?void 0:t._$litDirective$;return i?.constructor!==n&&(i?._$AO?.(!1),n===void 0?i=void 0:(i=new n(r),i._$AT(r,e,a)),a!==void 0?(e._$Co??(e._$Co=[]))[a]=i:e._$Cl=i),i!==void 0&&(t=Ot(r,i._$AS(r,t.values),i,a)),t}var Mr=class{constructor(t,e){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){let{el:{content:e},parts:a}=this._$AD,i=(t?.creationScope??Bt).importNode(e,!0);Dt.currentNode=i;let n=Dt.nextNode(),o=0,s=0,l=a[0];for(;l!==void 0;){if(o===l.index){let c;l.type===2?c=new Xt(n,n.nextSibling,this,t):l.type===1?c=new l.ctor(n,l.name,l.strings,this,t):l.type===6&&(c=new Nr(n,this,t)),this._$AV.push(c),l=a[++s]}o!==l?.index&&(n=Dt.nextNode(),o++)}return Dt.currentNode=Bt,i}p(t){let e=0;for(let a of this._$AV)a!==void 0&&(a.strings!==void 0?(a._$AI(t,a,e),e+=a.strings.length-2):a._$AI(t[e])),e++}},Xt=class r{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,e,a,i){this.type=2,this._$AH=y,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=a,this.options=i,this._$Cv=i?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,e=this._$AM;return e!==void 0&&t?.nodeType===11&&(t=e.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,e=this){t=Ot(this,t,e),Pa(t)?t===y||t==null||t===""?(this._$AH!==y&&this._$AR(),this._$AH=y):t!==this._$AH&&t!==ve&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):ns(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==y&&Pa(this._$AH)?this._$AA.nextSibling.data=t:this.T(Bt.createTextNode(t)),this._$AH=t}$(t){let{values:e,_$litType$:a}=t,i=typeof a=="number"?this._$AC(t):(a.el===void 0&&(a.el=Na.createElement(ss(a.h,a.h[0]),this.options)),a);if(this._$AH?._$AD===i)this._$AH.p(e);else{let n=new Mr(i,this),o=n.u(this.options);n.p(e),this.T(o),this._$AH=n}}_$AC(t){let e=is.get(t.strings);return e===void 0&&is.set(t.strings,e=new Na(t)),e}k(t){zi(this._$AH)||(this._$AH=[],this._$AR());let e=this._$AH,a,i=0;for(let n of t)i===e.length?e.push(a=new r(this.O(Ta()),this.O(Ta()),this,this.options)):a=e[i],a._$AI(n),i++;i<e.length&&(this._$AR(a&&a._$AB.nextSibling,i),e.length=i)}_$AR(t=this._$AA.nextSibling,e){for(this._$AP?.(!1,!0,e);t&&t!==this._$AB;){let a=t.nextSibling;t.remove(),t=a}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},Gt=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,a,i,n){this.type=1,this._$AH=y,this._$AN=void 0,this.element=t,this.name=e,this._$AM=i,this.options=n,a.length>2||a[0]!==""||a[1]!==""?(this._$AH=Array(a.length-1).fill(new String),this.strings=a):this._$AH=y}_$AI(t,e=this,a,i){let n=this.strings,o=!1;if(n===void 0)t=Ot(this,t,e,0),o=!Pa(t)||t!==this._$AH&&t!==ve,o&&(this._$AH=t);else{let s=t,l,c;for(t=n[0],l=0;l<n.length-1;l++)c=Ot(this,s[a+l],e,l),c===ve&&(c=this._$AH[l]),o||(o=!Pa(c)||c!==this._$AH[l]),c===y?t=y:t!==y&&(t+=(c??"")+n[l+1]),this._$AH[l]=c}o&&!i&&this.j(t)}j(t){t===y?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Er=class extends Gt{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===y?void 0:t}},Tr=class extends Gt{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==y)}},Pr=class extends Gt{constructor(t,e,a,i,n){super(t,e,a,i,n),this.type=5}_$AI(t,e=this){if((t=Ot(this,t,e,0)??y)===ve)return;let a=this._$AH,i=t===y&&a!==y||t.capture!==a.capture||t.once!==a.once||t.passive!==a.passive,n=t!==y&&(a===y||i);i&&this.element.removeEventListener(this.name,this,a),n&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},Nr=class{constructor(t,e,a){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=a}get _$AU(){return this._$AM._$AU}_$AI(t){Ot(this,t)}},ds={M:Yi,P:rt,A:$i,C:1,L:ls,R:Mr,D:ns,V:Ot,I:Xt,H:Gt,N:Tr,U:Pr,B:Er,F:Nr},mp=Ea.litHtmlPolyfillSupport;mp?.(Na,Xt),(Ea.litHtmlVersions??(Ea.litHtmlVersions=[])).push("3.3.0");var cs=(r,t,e)=>{let a=e?.renderBefore??t,i=a._$litPart$;if(i===void 0){let n=e?.renderBefore??null;a._$litPart$=i=new Xt(t.insertBefore(Ta(),n),n,void 0,e??{})}return i._$AI(r),i};var Ia=globalThis,v=class extends at{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var e;let t=super.createRenderRoot();return(e=this.renderOptions).renderBefore??(e.renderBefore=t.firstChild),t}update(t){let e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=cs(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return ve}};v._$litElement$=!0,v.finalized=!0,Ia.litElementHydrateSupport?.({LitElement:v});var hp=Ia.litElementPolyfillSupport;hp?.({LitElement:v});(Ia.litElementVersions??(Ia.litElementVersions=[])).push("4.2.0");var S=r=>(t,e)=>{e!==void 0?e.addInitializer((()=>{customElements.define(r,t)})):customElements.define(r,t)};var gp={attribute:!0,type:String,converter:Ca,reflect:!1,hasChanged:Ar},yp=(r=gp,t,e)=>{let{kind:a,metadata:i}=e,n=globalThis.litPropertyMetadata.get(i);if(n===void 0&&globalThis.litPropertyMetadata.set(i,n=new Map),a==="setter"&&((r=Object.create(r)).wrapped=!0),n.set(e.name,r),a==="accessor"){let{name:o}=e;return{set(s){let l=t.get.call(this);t.set.call(this,s),this.requestUpdate(o,l,r)},init(s){return s!==void 0&&this.C(o,void 0,r,s),s}}}if(a==="setter"){let{name:o}=e;return function(s){let l=this[o];t.call(this,s),this.requestUpdate(o,l,r)}}throw Error("Unsupported decorator location: "+a)};function u(r){return(t,e)=>typeof e=="object"?yp(r,t,e):((a,i,n)=>{let o=i.hasOwnProperty(n);return i.constructor.createProperty(n,a),o?Object.getOwnPropertyDescriptor(i,n):void 0})(r,t,e)}function N(r){return u({...r,state:!0,attribute:!1})}var Kt=(r,t,e)=>(e.configurable=!0,e.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(r,t,e),e);function Le(r,t){return(e,a,i)=>{let n=o=>o.renderRoot?.querySelector(r)??null;if(t){let{get:o,set:s}=typeof a=="object"?e:i??(()=>{let l=Symbol();return{get(){return this[l]},set(c){this[l]=c}}})();return Kt(e,a,{get(){let l=o.call(this);return l===void 0&&(l=n(this),(l!==null||this.hasUpdated)&&s.call(this,l)),l}})}return Kt(e,a,{get(){return n(this)}})}}function R(r,t,e){return r?t(r):e?.(r)}var I=f` * { box-sizing: border-box; } `,us=f` :host { display: block; isolation: isolate; position: relative; width: 100%; //Keep the CSS loader in the same position - check css-loader-inline.ts min-height: 64px; } `;var ps="https://sdk.primer.io/web/v2-latest/Primer.min.js",Se="20px";var Ir=class{constructor(t){this.paymentMethods=null;this.paymentManagers=null;this.vaultController=null;this.headlessInstance=t,this.vault={createCvvInput:e=>this.createCvvInputInternal(e),startPayment:(e,a)=>this.startVaultPaymentInternal(e,a),delete:e=>this.deleteVaultPaymentMethod(e)}}setPaymentMethods(t){this.paymentMethods=t}setPaymentManagers(t){this.paymentManagers=t}setVaultController(t){this.vaultController=t}async createCvvInputInternal(t){return this.vaultController?this.vaultController.createCvvInput(t):(P.warn("PrimerJS: Vault not available - createCvvInput cannot be called"),null)}async startVaultPaymentInternal(t,e){if(!this.vaultController)throw new Error("Vault manager not initialized");return this.vaultController.startVaultPaymentById(t,e)}async deleteVaultPaymentMethod(t){if(!this.vaultController)throw new Error("Vault manager not initialized");return this.vaultController.deleteVaultedPaymentMethod(t)}async createCvvInput(t){return this.vault.createCvvInput(t)}async startVaultPayment(t,e){return this.vault.startPayment(t,e)}async refreshSession(){if(!this.headlessInstance){P.errorWithDatadog("PrimerJS: Cannot refresh session: Headless instance not available");return}try{await this.headlessInstance.refreshClientSession()}catch(t){throw P.errorWithDatadog("PrimerJS: Error refreshing client session",{error:t}),t}}getPaymentMethods(){return this.paymentMethods?this.paymentMethods:(P.warn("PrimerJS: Payment methods not available"),[])}handlePaymentStart(){this.onPaymentStart&&this.onPaymentStart()}handleVaultedMethodsUpdate(t,e){if(this.onVaultedMethodsUpdate){let a=Math.floor(Date.now()/1e3);this.onVaultedMethodsUpdate({vaultedPayments:t,cvvRecapture:e,timestamp:a})}}setCardholderName(t){if(!this.paymentManagers){P.warn("PrimerJS: Payment managers not available - setCardholderName cannot be called yet");return}let e=this.paymentManagers.get("PAYMENT_CARD");if(!e||e.type!=="PAYMENT_CARD"){P.warn("PrimerJS: Card payment manager not available");return}try{e.manager.setCardholderName(t)}catch(a){P.errorWithDatadog("PrimerJS: Error setting cardholder name",{error:a})}}};var kr=typeof window<"u"&&typeof window.document<"u";function fp(r){return document.querySelector(`script[src^="${r}"]`)}function vp(r,t){let e=document.createElement("script");return e.setAttribute("src",r),e.setAttribute("async",""),e.setAttribute("crossorigin","anonymous"),t&&e.setAttribute("type","module"),e}function ms(r,t=!1){if(!kr)throw new Error("Cannot load script in server environment");let e=fp(r)??vp(r,t);return new Promise((a,i)=>{e.onload=()=>{a()},e.onerror=()=>{i(new Error(`Failed to load script: ${r}`))},e.parentNode||document.head.appendChild(e)})}var hs=f` :host { display: contents; } .cta-button { display: block; margin: auto; } `;var ne=class extends v{constructor(){super(...arguments);this.size="large";this.showCloseButton=!1;this.open=!1}openDialog(){this.open=!0}closeDialog(){let e=()=>{this.open=!1,this.removeEventListener("primer:dialog-close",e)};this.addEventListener("primer:dialog-close",e),this.dialog.startExitAnimation()}connectedCallback(){super.connectedCallback(),this.open||this.openDialog()}updated(e){super.updated(e),e.has("open")&&this.open&&this.onOpen&&this.onOpen(),e.has("open")&&this.open&&this.onContentRendered&&this.updateComplete.then(()=>{requestAnimationFrame(()=>{this.onContentRendered?.()})})}render(){return this.open?p`<primer-dialog .open=${this.open} size=${this.size} .showCloseButton=${this.showCloseButton} @primer:dialog-close="${()=>{this.open=!1}}" ><slot></slot>${this.cta?p`<primer-button @click=${this.cta.onClick} class="cta-button">${this.cta.icon?p`<primer-icon name="${this.cta.icon}" size="sm" color="var(--primer-color-background-outlined-default)" ></primer-icon>`:y} ${this.cta.label}</primer-button>`:y}</primer-dialog>`:y}};ne.styles=[I,hs],d([u({type:String})],ne.prototype,"size",2),d([u({type:Boolean})],ne.prototype,"showCloseButton",2),d([u({type:Object})],ne.prototype,"onOpen",2),d([u({type:Object})],ne.prototype,"onContentRendered",2),d([u({type:Object})],ne.prototype,"cta",2),d([N()],ne.prototype,"open",2),d([Le("primer-dialog")],ne.prototype,"dialog",2),ne=d([S("primer-portal-dialog"),D()],ne);var Lr=class{constructor(){this.currentDialog=null;this.currentResolver=null}async show(t){return new Promise(e=>{let a=new ne;a.size=t.size??"large",a.showCloseButton=t.showCloseButton??!1,a.onContentRendered=t.onContentReady,a.cta=t.cta;let i=()=>{a.remove(),this.currentDialog=null,this.currentResolver=null,e({success:!1})};a.addEventListener("primer:dialog-close",i),this.currentDialog=a,this.currentResolver=e,document.body.appendChild(a),a.appendChild(t.htmlContent)})}close(){this.currentDialog&&this.currentResolver&&(this.currentDialog.closeDialog(),this.currentResolver({success:!0}),this.currentDialog.remove(),this.currentDialog=null,this.currentResolver=null)}};var Sp=_a({"../../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.TR6QET27.js"),"../../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.EJ7QNYMP.js"),"../../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.7C2IYV2P.js"),"../../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.JT4THDDV.js"),"../../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.EM7SEPAQ.js"),"../../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.K6IE7XOI.js"),"../../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.3CKRNQD5.js"),"../../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.LG2PPT2V.js"),"../../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.47EGLMYC.js"),"../../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.ND7EGZHB.js"),"../../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.6QU35A6L.js"),"../../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.SMVRR5QO.js"),"../../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.BRBL5QIG.js"),"../../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.TPQGZ5V7.js"),"../../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.WWOUUKQI.js"),"../../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.OVEJBPUX.js"),"../../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.YPXJZUYV.js"),"../../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.7LEUFJ5J.js"),"../../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.TFWG6VOU.js"),"../../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.3SV7XLRR.js"),"../../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.P6C656R7.js"),"../../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.VOUHNCJ7.js"),"../../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.AFL7G4NO.js"),"../../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.TRKH4J6L.js"),"../../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.TGTBYQYP.js"),"../../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.HZTEA2Q2.js"),"../../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.QEKTVYHX.js"),"../../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.HRDZEYXV.js"),"../../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.2R7WVAV3.js"),"../../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.KHWKCZMK.js"),"../../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.D6YHYKB6.js"),"../../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.3NGFYB4U.js"),"../../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.LYW2A6VH.js"),"../../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.ILTDKZ2H.js"),"../../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.KJZFKIJM.js"),"../../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.5POYRJGA.js"),"../../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.GN5UGR5G.js"),"../../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.T3II5ZYL.js"),"../../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.63HB4O5X.js"),"../../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.AZ4SQZFW.js"),"../../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.WDGRPXBK.js"),"../../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.GYXXM7FX.js"),"../../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.TBVAKNJJ.js"),"../../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.GGWFQ3Y7.js"),"../../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.NK7PKUS6.js"),"../../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.SQG5YIVQ.js"),"../../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.P2X3B7LC.js")});var ea=null,Wi=null;async function gs(r){if(Wi===r&&ea)return ea;try{return ea=(await Sp(`../../../localization/lit-localize/locales/${r}.ts`)).templates,Wi=r,ea}catch{return r!=="en-GB"?gs("en-GB"):(ea={},Wi=r,ea)}}async function ys(r){let t=await gs(r);return(e,a)=>t[e]??a}var bt={WORLDPAY_IDEAL:"WORLDPAY_IDEAL",AUTOMATED_CLEARING_HOUSE:"AUTOMATED_CLEARING_HOUSE",ADYEN_KLARNA:"ADYEN_KLARNA",ADYEN_BANCONTACT_CARD:"ADYEN_BANCONTACT_CARD",PAY_NL_KAARTDIRECT:"PAY_NL_KAARTDIRECT",ADYEN_EPS:"ADYEN_EPS",ADYEN_BANCONTACT_PAYCONIQ:"ADYEN_BANCONTACT_PAYCONIQ",OMISE_PROMPTPAY:"OMISE_PROMPTPAY",OMISE_TRUEMONEY:"OMISE_TRUEMONEY",ADYEN_MULTIBANCO:"ADYEN_MULTIBANCO",PACYPAY_WECHAT:"PACYPAY_WECHAT",PACYPAY_ALIPAY:"PACYPAY_ALIPAY",ADYEN_MBWAY:"ADYEN_MBWAY",XENDIT_DANA:"XENDIT_DANA",XENDIT_SHOPEEPAY:"XENDIT_SHOPEEPAY",ADYEN_PAYSHOP:"ADYEN_PAYSHOP",ADYEN_PAYTRAIL:"ADYEN_PAYTRAIL",CLEARPAY:"CLEARPAY",RAPYD_FAST:"RAPYD_FAST",RAPYD_PROMPTPAY:"RAPYD_PROMPTPAY",RAPYD_GCASH:"RAPYD_GCASH",RAPYD_POLI:"RAPYD_POLI",RAPYD_GRABPAY:"RAPYD_GRABPAY",PRIMER_PAYPAL:"PRIMER_PAYPAL",TWOC2P:"TWOC2P",NETS:"NETS",STRIPE_ACH:"STRIPE_ACH",STRIPE_GIROPAY:"STRIPE_GIROPAY",MOLLIE_GIROPAY:"MOLLIE_GIROPAY",MOLLIE_EPS:"MOLLIE_EPS",PAY_NL_EPS:"PAY_NL_EPS",PAY_NL_P24:"PAY_NL_P24",MOLLIE_P24:"MOLLIE_P24",MOLLIE_SOFORT:"MOLLIE_SOFORT",COINBASE:"COINBASE",OPENNODE:"OPENNODE",MOLLIE_GIFT_CARD:"MOLLIE_GIFTCARD",XFERS_PAYNOW:"XFERS_PAYNOW",CARD:"PAYMENT_CARD",APPLE_PAY:"APPLE_PAY",GOOGLE_PAY:"GOOGLE_PAY",PAYPAL:"PAYPAL_ORDER",PAYPAL_VAULTED:"PAYPAL_BILLING_AGREEMENT",GO_CARDLESS:"GOCARDLESS",PAY_NL_IDEAL:"PAY_NL_IDEAL",PAY_NL_SOFORT_BANKING:"PAY_NL_SOFORT_BANKING",PAY_NL_BANCONTACT:"PAY_NL_BANCONTACT",PAY_NL_PAYPAL:"PAY_NL_PAYPAL",PAY_NL_CREDIT_TRANSFER:"PAY_NL_CREDIT_TRANSFER",PAY_NL_DIRECT_DEBIT:"PAY_NL_DIRECT_DEBIT",PAY_NL_GIROPAY:"PAY_NL_GIROPAY",PAY_NL_PAYCONIQ:"PAY_NL_PAYCONIQ",PAY_NL_RIVERTY:"PAY_NL_RIVERTY",HOOLAH:"HOOLAH",ADYEN_BLIK:"ADYEN_BLIK",ADYEN_VIPPS:"ADYEN_VIPPS",ADYEN_GIROPAY:"ADYEN_GIROPAY",ADYEN_SOFORT:"ADYEN_SOFORT",ADYEN_IDEAL:"ADYEN_IDEAL",ADYEN_TRUSTLY:"ADYEN_TRUSTLY",ADYEN_ALIPAY:"ADYEN_ALIPAY",ADYEN_TWINT:"ADYEN_TWINT",ADYEN_MOBILEPAY:"ADYEN_MOBILEPAY",MOLLIE_BANCONTACT:"MOLLIE_BANCONTACT",MOLLIE_IDEAL:"MOLLIE_IDEAL",BUCKAROO_GIROPAY:"BUCKAROO_GIROPAY",BUCKAROO_EPS:"BUCKAROO_EPS",BUCKAROO_SOFORT:"BUCKAROO_SOFORT",BUCKAROO_BANCONTACT:"BUCKAROO_BANCONTACT",BUCKAROO_IDEAL:"BUCKAROO_IDEAL",ATOME:"ATOME",KLARNA_CUSTOMER_TOKEN:"KLARNA_CUSTOMER_TOKEN",DLOCAL_PIX:"DLOCAL_PIX",ALMA:"ALMA",ADYEN_CASHAPP:"ADYEN_CASHAPP",ADYEN_AFFIRM:"ADYEN_AFFIRM"},ka={WORLDPAY_IDEAL:"WORLDPAY_IDEAL",STRIPE_ACH:"STRIPE_ACH",STRIPE_IDEAL:"STRIPE_IDEAL",ADYEN_KLARNA:"ADYEN_KLARNA",ADYEN_BANCONTACT_CARD:"ADYEN_BANCONTACT_CARD",PAY_NL_KAARTDIRECT:"PAY_NL_KAARTDIRECT",ADYEN_EPS:"ADYEN_EPS",ADYEN_BANCONTACT_PAYCONIQ:"ADYEN_BANCONTACT_PAYCONIQ",OMISE_PROMPTPAY:"OMISE_PROMPTPAY",OMISE_TRUEMONEY:"OMISE_TRUEMONEY",ADYEN_MULTIBANCO:"ADYEN_MULTIBANCO",PACYPAY_WECHAT:"PACYPAY_WECHAT",PACYPAY_ALIPAY:"PACYPAY_ALIPAY",ADYEN_MBWAY:"ADYEN_MBWAY",XENDIT_DANA:"XENDIT_DANA",XENDIT_SHOPEEPAY:"XENDIT_SHOPEEPAY",ADYEN_PAYSHOP:"ADYEN_PAYSHOP",ADYEN_PAYTRAIL:"ADYEN_PAYTRAIL",CLEARPAY:"CLEARPAY",RAPYD_FAST:"RAPYD_FAST",RAPYD_PROMPTPAY:"RAPYD_PROMPTPAY",RAPYD_GCASH:"RAPYD_GCASH",RAPYD_POLI:"RAPYD_POLI",RAPYD_GRABPAY:"RAPYD_GRABPAY",PRIMER_PAYPAL:"PRIMER_PAYPAL",TWOC2P:"TWOC2P",NETS:"NETS",STRIPE_GIROPAY:"STRIPE_GIROPAY",MOLLIE_GIROPAY:"MOLLIE_GIROPAY",MOLLIE_EPS:"MOLLIE_EPS",PAY_NL_EPS:"PAY_NL_EPS",PAY_NL_P24:"PAY_NL_P24",MOLLIE_P24:"MOLLIE_P24",MOLLIE_SOFORT:"MOLLIE_SOFORT",COINBASE:"COINBASE",OPENNODE:"OPENNODE",MOLLIE_GIFT_CARD:"MOLLIE_GIFTCARD",XFERS_PAYNOW:"XFERS_PAYNOW",PAYMENT_CARD:"PAYMENT_CARD",APPLE_PAY:"APPLE_PAY",GOOGLE_PAY:"GOOGLE_PAY",PAYPAL:"PAYPAL",GO_CARDLESS:"GOCARDLESS",KLARNA:"KLARNA",PAY_NL_IDEAL:"PAY_NL_IDEAL",PAY_NL_SOFORT_BANKING:"PAY_NL_SOFORT_BANKING",PAY_NL_BANCONTACT:"PAY_NL_BANCONTACT",PAY_NL_PAYPAL:"PAY_NL_PAYPAL",PAY_NL_CREDIT_TRANSFER:"PAY_NL_CREDIT_TRANSFER",PAY_NL_DIRECT_DEBIT:"PAY_NL_DIRECT_DEBIT",PAY_NL_GIROPAY:"PAY_NL_GIROPAY",PAY_NL_PAYCONIQ:"PAY_NL_PAYCONIQ",PAY_NL_RIVERTY:"PAY_NL_RIVERTY",HOOLAH:"HOOLAH",ADYEN_BLIK:"ADYEN_BLIK",ADYEN_MOBILEPAY:"ADYEN_MOBILEPAY",ADYEN_VIPPS:"ADYEN_VIPPS",ADYEN_GIROPAY:"ADYEN_GIROPAY",ADYEN_SOFORT:"ADYEN_SOFORT",ADYEN_IDEAL:"ADYEN_IDEAL",ADYEN_TRUSTLY:"ADYEN_TRUSTLY",ADYEN_ALIPAY:"ADYEN_ALIPAY",ADYEN_TWINT:"ADYEN_TWINT",ADYEN_BANK_TRANSFER:"ADYEN_BANK_TRANSFER",MOLLIE_BANCONTACT:"MOLLIE_BANCONTACT",MOLLIE_IDEAL:"MOLLIE_IDEAL",BUCKAROO_GIROPAY:"BUCKAROO_GIROPAY",BUCKAROO_EPS:"BUCKAROO_EPS",BUCKAROO_SOFORT:"BUCKAROO_SOFORT",BUCKAROO_BANCONTACT:"BUCKAROO_BANCONTACT",BUCKAROO_IDEAL:"BUCKAROO_IDEAL",ATOME:"ATOME",DLOCAL_PIX:"DLOCAL_PIX",ALMA:"ALMA",ADYEN_CASHAPP:"ADYEN_CASHAPP",ADYEN_AFFIRM:"ADYEN_AFFIRM"};var Rr=class r extends Error{constructor(t,e){super(e.message),this.name="PrimerClientError",this.code=t,this.diagnosticsId=e.diagnosticsId||null,this.data=e.data,this.isFromDeveloper=e.isFromDeveloper||!1}static fromErrorCode(t,e){return new r(t,e)}};function fs(r,t,e){return r.isDisconnected?!1:(r.host.sdkStateController.currentState.paymentFailure!==null&&Q({eventName:"PAYMENT_REATTEMPTED",paymentMethod:t}),r.host.sdkStateController.startProcessing(),r.host.primerEventsController.dispatchPaymentStart(t,e))}function vs(r,t,e){if(!r.isDisconnected&&(P.info("Payment completed:",t),r.host.sdkStateController.completeProcessing(),r.host.primerEventsController.dispatchPaymentSuccess(t,e),Q({eventName:"PAYMENT_SUCCESS",paymentId:t?.id,paymentMethod:e}),r.primerJS?.onPaymentSuccess)){let a=Math.floor(Date.now()/1e3);r.primerJS.onPaymentSuccess({payment:Wt(t),paymentMethodType:e,timestamp:a})}}function Ss(r,t,e,a){if(r.isDisconnected)return;(s=>typeof s=="object"&&s!==null&&"response"in s&&typeof s.response=="object"&&s.response!==null&&"status"in s.response&&typeof s.response.status=="number")(t)&&t.response.status>=500?P.errorWithDatadog("Payment failed with server error",{error:t}):P.error("Payment failed:",t);let o=t instanceof Rr?{code:t.code||"UNKNOWN_ERROR",message:t.message||"Unknown error occurred",diagnosticsId:t.diagnosticsId,data:t.data}:(()=>{let s=t,l=s instanceof Error&&"code"in s&&typeof s.code=="string"?s.code:"UNKNOWN_ERROR",c=s instanceof Error?s.message:"Unknown error occurred";return{code:l,message:c,data:{error:t}}})();if(r.host.sdkStateController.setPaymentFailure(o),r.host.primerEventsController.dispatchPaymentFailure({code:o.code,message:o.message,diagnosticsId:"diagnosticsId"in o?o.diagnosticsId??void 0:void 0,data:o.data},e,a),Q({eventName:"PAYMENT_FAILURE",paymentId:a?.id,paymentMethod:e}),r.primerJS?.onPaymentFailure){let s=Math.floor(Date.now()/1e3);r.primerJS.onPaymentFailure({error:{code:o.code,message:o.message,diagnosticsId:"diagnosticsId"in o?o.diagnosticsId??void 0:void 0,data:o.data},payment:a?Wt(a):void 0,paymentMethodType:e,timestamp:s})}}var Zi="1.0.1",xr=class{constructor(t){this.createPaymentMethodManager=null;this._paymentsList=[];this.currentSdkInstance=null;this.primerJS=null;this.loadingTimeout=null;this.isDisconnected=!1;(this.host=t).addController(this),this.isDisconnected=!1,this.sdkInstanceTask=new O(t,{args:()=>[this.host.clientToken,this.host.options],task:this.initializeHeadless()}),new O(t,{args:()=>[this.sdkInstanceTask.value,this.paymentsList],task:this.initializeLitContext()})}set paymentsList(t){this._paymentsList=t,this.host.requestUpdate()}get paymentsList(){return this._paymentsList}get primerJSInstance(){return this.primerJS}hostConnected(){this.isDisconnected=!1,this.host.sdkStateController.startLoading(),this.setupLoadingTimeout()}hostDisconnected(){if(this.isDisconnected=!0,this.host.sdkContextController.getAnalyticsUtils()){let e=this.host.sdkStateController.currentState;(e.isProcessing||e.isLoading||this.currentSdkInstance)&&Q({eventName:"PAYMENT_FLOW_EXITED"})}this.cleanupResources()}normalizeOptionsForLegacySdk(t){if(t.sdkCore!==!1)return{...t,sdkCore:!0};let e={...t};if(e.card?.cardholderName){let a={...e.card.cardholderName};a.visible===!1&&(a.required=!1),e.card={...e.card,cardholderName:a}}return e}setupLoadingTimeout(){this.clearLoadingTimeout(),this.loadingTimeout=setTimeout(()=>{this.host.sdkStateController.currentState.isLoading&&(P.warn("Loading timeout reached, resetting SDK state"),Q({eventName:"PAYMENT_FLOW_EXITED",eventType:"timeout"}),this.cleanupResources(),this.host.sdkStateController.completeLoading())},1e4)}clearLoadingTimeout(){this.loadingTimeout!==null&&(clearTimeout(this.loadingTimeout),this.loadingTimeout=null)}cleanupResources(){if(this.clearLoadingTimeout(),this.currentSdkInstance)try{this.paymentsList=[],this.createPaymentMethodManager=null,this.host.sdkStateController.reset(),this.currentSdkInstance.teardown?.(),P.info("SDK instance cleaned up")}catch(t){P.errorWithDatadog("Error cleaning up SDK instance",{error:t})}Bo(),P.setClientToken(void 0),P.setSdkOptions(void 0),this.currentSdkInstance=null,this.primerJS=null}async _loadV2Sdk(t=ps){let e=window;if(e.Primer&&typeof e.Primer.preloadPrimer=="function"){P.info("SDK already loaded, skipping load script"),await e.Primer.preloadPrimer();return}await ms(t),await e.Primer.preloadPrimer()}initializeHeadless(){return async([t,e])=>{if(this.isDisconnected)return P.warn("Component disconnected, aborting SDK initialization"),w;if(!t||!e)return w;this.cleanupResources();let a;try{let i;if(e.sdkCore!==!1){let l=new Lr,c=Qt(e.locale||vr()),m=await ys(c);i={createHeadless:(h,T)=>vo(h,{...T,dialogProvider:l,translate:m,sdkVersion:Zi,locale:c})}}else await this._loadV2Sdk(),i=window.Primer;this.primerJS=new Ir(null),this.primerJS.setVaultController(this.host.vaultManagerController);let n=this.normalizeOptionsForLegacySdk(e);P.setClientToken(t),P.setSdkOptions(n);let o=await i.createHeadless(t,{...n,onAvailablePaymentMethodsLoad:l=>{this.isDisconnected||(P.info("Configuration payment methods:",l),this.paymentsList=l)},onCheckoutComplete:({payment:l})=>{let c=l?.paymentMethodData?.paymentMethodType;vs({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},l,c)},onCheckoutFail:(l,c)=>{let m=c.payment?.paymentMethodData?.paymentMethodType;Ss({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},l,m,c.payment)},onBeforePaymentCreate:(l,c)=>{if(!l.paymentMethodType){P.error("Payment creation started without payment method type"),c?.abortPaymentCreation();return}if(!(fs({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},l.paymentMethodType,c)||this.isDisconnected)){if(this.primerJS?.onPaymentPrepare){this.primerJS.onPaymentPrepare({paymentMethodType:l.paymentMethodType},c);return}c?.continuePaymentCreation()}},onPaymentMethodAction:(l,c)=>{this.isDisconnected||l==="PAYMENT_METHOD_UNSELECTED"&&(this.host.primerEventsController.dispatchPaymentCancel(c),this.host.sdkStateController.stopProcessing())},onPaymentCreationStart:()=>{this.isDisconnected||this.primerJS&&this.primerJS.handlePaymentStart()}});if(this.createPaymentMethodManager=o.createPaymentMethodManager.bind(o),this.currentSdkInstance=o,this.primerJS&&Object.defineProperty(this.primerJS,"headlessInstance",{value:o,writable:!1}),await o.start(),this.isDisconnected)return this.cleanupResources(),w;this.host.sdkContextController.setClientOptions(e),this.primerJS&&this.host.primerEventsController.dispatchCheckoutInitialized(this.primerJS);let s=o.getSDKUtilities();if(a=o.getAnalyticsUtils?.(),a&&(this.host.sdkContextController.setAnalyticsUtils({...a,sdkVersion:Zi}),Do({environment:a.environment,checkoutSessionId:a.checkoutSessionId,clientSessionId:a.clientSessionId||"",primerAccountId:a.primerAccountId||"",sdkVersion:Zi,clientSessionToken:a.clientSessionToken,userAgent:typeof navigator<"u"?navigator.userAgent:""}),a.configurationFetchStartTime&&Ye.setSdkInitStartTime(a.configurationFetchStartTime),Q({eventName:"SDK_INIT_START"})),this.host.sdkContextController.setHeadlessUtils(s),e.sdkCore&&o.getConfiguration){let l=o.getConfiguration();this.host.sdkContextController.setConfiguration(l)}return this.host.vaultManagerController.initializeVaultManager(o.createVaultManager.bind(o),{vaultEnabled:e.vault?.enabled,captureVaultedCardCvv:!!s.getPaymentMethodConfiguration("PAYMENT_CARD")?.options?.captureVaultedCardCvv,showEmptyState:e.vault?.showEmptyState,headless:e.vault?.headless??!1}),o}catch(i){throw i instanceof Error&&(P.errorWithDatadog("SDK initialization error",{error:i,status:"error"}),this.host.sdkStateController.setPrimerJsError(i)),this.cleanupResources(),i}}}initializeLitContext(){return async([t,e])=>{if(this.isDisconnected)return w;if(!t||!e.length)return w;let a=new Map,i=new Map;try{for(let o of e){if(this.isDisconnected)break;let s=await this.initializePaymentMethodManager(o)();o&&s&&(a.set(o.type,o),i.set(o.type,s))}if(this.isDisconnected)return w;let n=Array.from(a.values());return this.host.sdkContextController.setPaymentManagers(i),this.host.sdkContextController.setPaymentMethods(n),this.primerJS&&(this.primerJS.setPaymentMethods(n),this.primerJS.setPaymentManagers(i)),this.host.primerEventsController.dispatchPaymentMethods(n),P.info("Initialized payment methods:",n),a}catch(n){if(n instanceof Error)throw this.host.sdkStateController.setPrimerJsError(n),n;return null}finally{this.clearLoadingTimeout(),this.isDisconnected||(this.host.sdkStateController.completeLoading(),Q({eventName:"SDK_INIT_END"}))}}}initializePaymentMethodManager(t){let{type:e,managerType:a}=t;return async()=>{if(this.isDisconnected||!this.createPaymentMethodManager)return null;if(a==="KLARNA"){let i=await this.createPaymentMethodManager("KLARNA",{onPaymentMethodCategoriesChange:n=>{this.isDisconnected||this.host.sdkContextController.setKlarnaCategories({categories:n,isLoading:!1})}});return i?{type:e,manager:i}:null}try{if(a==="CARD"){let n=await this.createPaymentMethodManager("PAYMENT_CARD",{onBinDataAvailable:o=>{this.isDisconnected||this.host.cardNetworkController.processBinDataAvailableEvent(o)},onCardNetworksChange:o=>{this.isDisconnected||this.host.cardNetworkController.processCardNetworkChangeEvent(o)},onCardNetworksLoading:()=>{this.isDisconnected||this.host.cardNetworkController.setCardNetworksLoading()},onBinDataLoadingChange:o=>{this.isDisconnected||this.host.primerEventsController.dispatchBinDataLoadingChange(o)}});return n?{type:e,manager:n}:null}let i=await this.createPaymentMethodManager(e);return i?{type:e,manager:i}:null}catch(i){return P.errorWithDatadog(`Failed to initialize manager for ${e}`,{error:i}),null}}}};var _r=class{constructor(t){this.host=t,t.addController(this)}_error(t){let{error:e}=t.detail;this.host.sdkStateController.setPaymentFailure({code:"UNKNOWN_ERROR",message:e.message})}_mandateConfirmed(){this.host.sdkStateController.completeProcessing()}_mandateDeclined(){this.host.sdkStateController.setPaymentFailure({code:"UNKNOWN_ERROR",message:"Mandate declined"})}hostConnected(){this.host.addEventListener("primer-ach-error",this._error.bind(this)),this.host.addEventListener("primer-ach-mandate-confirmed",this._mandateConfirmed.bind(this)),this.host.addEventListener("primer-ach-mandate-declined",this._mandateDeclined.bind(this))}hostDisconnected(){this.host.removeEventListener("primer-ach-error",this._error.bind(this)),this.host.removeEventListener("primer-ach-mandate-confirmed",this._mandateConfirmed.bind(this)),this.host.removeEventListener("primer-ach-mandate-declined",this._mandateDeclined.bind(this))}};var bp=_a({"../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.TR6QET27.js"),"../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.EJ7QNYMP.js"),"../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.7C2IYV2P.js"),"../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.JT4THDDV.js"),"../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.EM7SEPAQ.js"),"../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.K6IE7XOI.js"),"../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.3CKRNQD5.js"),"../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.LG2PPT2V.js"),"../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.47EGLMYC.js"),"../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.ND7EGZHB.js"),"../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.6QU35A6L.js"),"../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.SMVRR5QO.js"),"../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.BRBL5QIG.js"),"../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.TPQGZ5V7.js"),"../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.WWOUUKQI.js"),"../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.OVEJBPUX.js"),"../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.YPXJZUYV.js"),"../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.7LEUFJ5J.js"),"../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.TFWG6VOU.js"),"../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.3SV7XLRR.js"),"../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.P6C656R7.js"),"../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.VOUHNCJ7.js"),"../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.AFL7G4NO.js"),"../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.TRKH4J6L.js"),"../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.TGTBYQYP.js"),"../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.HZTEA2Q2.js"),"../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.QEKTVYHX.js"),"../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.HRDZEYXV.js"),"../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.2R7WVAV3.js"),"../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.KHWKCZMK.js"),"../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.D6YHYKB6.js"),"../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.3NGFYB4U.js"),"../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.LYW2A6VH.js"),"../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.ILTDKZ2H.js"),"../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.KJZFKIJM.js"),"../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.5POYRJGA.js"),"../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.GN5UGR5G.js"),"../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.T3II5ZYL.js"),"../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.63HB4O5X.js"),"../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.AZ4SQZFW.js"),"../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.WDGRPXBK.js"),"../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.GYXXM7FX.js"),"../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.TBVAKNJJ.js"),"../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.GGWFQ3Y7.js"),"../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.NK7PKUS6.js"),"../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.SQG5YIVQ.js"),"../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.P2X3B7LC.js")});Oi(r=>bp(`../../localization/lit-localize/locales/${r}.ts`));var Ap={LOADER_DISABLED:"loader-disabled",CUSTOM_STYLES:"custom-styles",CLIENT_TOKEN:"client-token",JS_INIT:"js-initialized"},Pe=class extends v{constructor(){super();this.customStyles="";this.clientToken="";this.options={};this.disableLoader=!1;this._jsInitialized=!1;this.previousLoadingState=!0;this.hasAssignedContent=!1;this._loadingTimeoutId=null;this._eventListenerController=null;this.locale=Qt(vr());this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0,this.requestUpdate()};this.sdkContextController=new nr(this),this.sdkStateController=new ir(this),this.primerEventsController=new Zt(this),this.styleProcessingController=new or(this),this.vaultManagerController=new ga(this),this.cardNetworkController=new wa(this),this.achPaymentEventsController=new _r(this),this.headlessSdkController=new xr(this)}set jsInitialized(e){this.requestUpdate(),this._jsInitialized=e}get jsInitialized(){return this._jsInitialized}get primerJS(){return this.headlessSdkController?.primerJSInstance??void 0}connectedCallback(){super.connectedCallback(),this.sdkContextController.setEventsController(this.primerEventsController),this._eventListenerController=new AbortController,document.addEventListener("primer:card-submit",this.handleExternalCardSubmit.bind(this),{signal:this._eventListenerController.signal}),document.addEventListener("primer:vault-submit",this.handleExternalVaultSubmit.bind(this),{signal:this._eventListenerController.signal}),document.addEventListener("primer:show-other-payments-toggle",this.handleExternalShowOtherPaymentsToggle.bind(this),{signal:this._eventListenerController.signal})}attributeChangedCallback(e,a,i){e===Ap.CUSTOM_STYLES?this.styleProcessingController.processCustomStyles(i):super.attributeChangedCallback(e,a,i)}disconnectedCallback(){this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null),this.sdkStateController?.currentState.isLoading&&this.sdkStateController.forceCompleteLoading(),this._eventListenerController&&(this._eventListenerController.abort(),this._eventListenerController=null),super.disconnectedCallback()}willUpdate(e){e.has("options")&&(this.options?.locale&&(Fi(this.options?.locale)?this.locale=Qt(this.options?.locale):P.warn("\u{1F30E}\u2757 Unsupported locale provided:",this.options?.locale,"- Falling back to system locale")),Gi(this.locale))}updated(){let e=getComputedStyle(this);this.sdkContextController.setComputedStyles(e),this.checkLoadingStateChange()}handleExternalCardSubmit(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:card-submit",e.detail)}handleExternalVaultSubmit(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:vault-submit",e.detail)}handleExternalShowOtherPaymentsToggle(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:show-other-payments-toggle",e.detail)}checkLoadingStateChange(){let e=this.sdkStateController?.currentState.isLoading||!1;if(this.previousLoadingState&&!e){this.jsInitialized=!0,Q({eventName:"CHECKOUT_FLOW_STARTED"});let a=Ye.getSdkInitStartTime(),i=a?Date.now()-a:void 0;Eo(i)}this.previousLoadingState=e,e&&!this._loadingTimeoutId?this._loadingTimeoutId=window.setTimeout(()=>{this.sdkStateController?.currentState.isLoading&&(P.warn("Loading timeout in component, forcing completion"),this.sdkStateController.forceCompleteLoading(),this.jsInitialized=!0),this._loadingTimeoutId=null},1e4):!e&&this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null)}render(){let e=this.sdkStateController.currentState,a=e.isLoading,i=e.primerJsError,n=!a&&!i;return p` ${R(a,()=>y)} ${R(i,()=>p`<primer-checkout-error></primer-checkout-error>`)} ${R(n,()=>p`<slot name="main" @slotchange=${this.onSlotChange}></slot>${R(this.hasAssignedContent,()=>y,()=>p`<primer-main></primer-main>`)} `,()=>y)} `}addEventListener(e,a,i){super.addEventListener(e,a,i)}removeEventListener(e,a,i){super.removeEventListener(e,a,i)}};Pe.styles=[I,us],d([u({type:String,attribute:"custom-styles"})],Pe.prototype,"customStyles",2),d([u({type:String,attribute:"client-token"})],Pe.prototype,"clientToken",2),d([u({type:Object,attribute:!1,hasChanged:(e,a)=>!rr(e,a)})],Pe.prototype,"options",2),d([u({type:Boolean,attribute:"loader-disabled"})],Pe.prototype,"disableLoader",2),d([u({type:Boolean,reflect:!0,attribute:"js-initialized"})],Pe.prototype,"_jsInitialized",2),d([Le("slot")],Pe.prototype,"defaultSlot",2),d([N()],Pe.prototype,"previousLoadingState",2),Pe=d([D(),S("primer-checkout")],Pe);function Cp(r){return document.querySelector(`#${r}`)}function Mp(r,t){let e=document.createElement("style");return e.textContent=r,e.id=t,e}function La(r,t,e=!0){if(!kr||Cp(t))return;let i=Mp(r,t);e&&document.head.firstChild?document.head.insertBefore(i,document.head.firstChild):document.head.appendChild(i)}var bs=`
|
|
147
147
|
@keyframes primer-css-spinner-rotate {
|
|
148
148
|
0% {
|
|
149
149
|
transform: rotate(0deg);
|