@primer-io/primer-js 1.6.0 → 1.6.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/chunks/{ar.4ZFBST5B.js → ar.BIHRX5RF.js} +1 -1
- package/dist/chunks/{bg.A6DFGUKU.js → bg.FGU6YCAF.js} +1 -1
- package/dist/chunks/{ca.3MVWILFG.js → ca.IKG75KNP.js} +1 -1
- package/dist/chunks/{chunk.4VIC6WHG.js → chunk.B7X364D6.js} +1 -1
- package/dist/chunks/{cs.INYY7XZR.js → cs.MILBDWY6.js} +1 -1
- package/dist/chunks/{da.Y5IIDRC3.js → da.JTASZFYV.js} +1 -1
- package/dist/chunks/{de.JZT46DAB.js → de.DXQD6OEP.js} +1 -1
- package/dist/chunks/{el.FJQOSK4N.js → el.EFHFPB3R.js} +1 -1
- package/dist/chunks/en-GB.SXPN4WN6.js +1 -0
- package/dist/chunks/en.NNAZENAS.js +1 -0
- package/dist/chunks/{es-AR.GBZW2HPG.js → es-AR.PGD5Q57R.js} +1 -1
- package/dist/chunks/{es-MX.NFJ7HXSV.js → es-MX.PTII2RTJ.js} +1 -1
- package/dist/chunks/es.AKW6WGRC.js +1 -0
- package/dist/chunks/{et-EE.JZD334EI.js → et-EE.LHI2XOXI.js} +1 -1
- package/dist/chunks/{fi-FI.SHTM3UQK.js → fi-FI.IPGRD7WF.js} +1 -1
- package/dist/chunks/{fr.MZYBSJWU.js → fr.PDUWBPKF.js} +1 -1
- package/dist/chunks/{he.BQXGQQ4P.js → he.5SDFV353.js} +1 -1
- package/dist/chunks/{hr.EK5WNO4N.js → hr.LXFZTJMG.js} +1 -1
- package/dist/chunks/{hu.N2BVXVWY.js → hu.VXISLOF3.js} +1 -1
- package/dist/chunks/{id.IJ37WK5P.js → id.UCNPGRJA.js} +1 -1
- package/dist/chunks/{it.2ZUPJDRP.js → it.F7GBFWC2.js} +1 -1
- package/dist/chunks/{ja.BNLF6BZT.js → ja.BHTV4F5V.js} +1 -1
- package/dist/chunks/{ko.YJAZTBEF.js → ko.L4TUG67I.js} +1 -1
- package/dist/chunks/{lt-LT.GOVUI3KD.js → lt-LT.ULLOOI4H.js} +1 -1
- package/dist/chunks/{lt.IPLRYI7A.js → lt.WAZLYIAI.js} +1 -1
- package/dist/chunks/{lv-LV.EA76F4DL.js → lv-LV.TEXPN3ZR.js} +1 -1
- package/dist/chunks/{lv.I7E6LMWA.js → lv.TQJGMNOY.js} +1 -1
- package/dist/chunks/{ms.6I2BVK63.js → ms.Q2C5ZFHD.js} +1 -1
- package/dist/chunks/{nb.BYMLE7EQ.js → nb.KCZ6D34T.js} +1 -1
- package/dist/chunks/{nl.QOSIJQZE.js → nl.2CTHY5J7.js} +1 -1
- package/dist/chunks/{nl_NL.DVZWMQJN.js → nl_NL.SYW24NKO.js} +1 -1
- package/dist/chunks/{pl.VK5CNTV3.js → pl.AI5CECVT.js} +1 -1
- package/dist/chunks/{pt-BR.22GYWGY5.js → pt-BR.OWKVFNRL.js} +1 -1
- package/dist/chunks/{pt.L2PBSEBD.js → pt.LVBHJFXR.js} +1 -1
- package/dist/chunks/{ro.VFIM4IS3.js → ro.SJYNCSI5.js} +1 -1
- package/dist/chunks/{ru.VLLE4DKK.js → ru.3HE2B7ZT.js} +1 -1
- package/dist/chunks/{sk.JALTDVLO.js → sk.YAEVPIZD.js} +1 -1
- package/dist/chunks/{sl.PQOCETM2.js → sl.BA3GBVRO.js} +1 -1
- package/dist/chunks/{sr-RS.RGO57OCW.js → sr-RS.3C6VVYBB.js} +1 -1
- package/dist/chunks/{sv.FQJP73FF.js → sv.2VDFAELX.js} +1 -1
- package/dist/chunks/{th.QYA26J2E.js → th.J7ZUQIZS.js} +1 -1
- package/dist/chunks/{tr.5ZDAANBV.js → tr.E2CHOIPA.js} +1 -1
- package/dist/chunks/{uk-UA.FWQ7KVBB.js → uk-UA.QYJJIGTW.js} +1 -1
- package/dist/chunks/{vi.GB6QZAMD.js → vi.YGBNA3NJ.js} +1 -1
- package/dist/chunks/{zh-CN.OEA7I6ZA.js → zh-CN.SRN7TXMD.js} +1 -1
- package/dist/chunks/{zh-HK.OUXNL5ZM.js → zh-HK.3JAKYZ5N.js} +1 -1
- package/dist/chunks/{zh-TW.C5STTOCA.js → zh-TW.WTNQLAHV.js} +1 -1
- package/dist/custom-elements.json +95 -95
- package/dist/primer-loader.js +2 -2
- package/dist/web-types.json +1 -1
- package/package.json +1 -1
- package/dist/chunks/en-GB.TL522NMU.js +0 -1
- package/dist/chunks/en.JFPWSECQ.js +0 -1
- package/dist/chunks/es.FX4YBDVU.js +0 -1
package/dist/primer-loader.js
CHANGED
|
@@ -3,7 +3,7 @@ import{a as $r,b as q,c as mi,d,e as A}from"./chunks/chunk.QNO3CTH5.js";var ac=q
|
|
|
3
3
|
--apple-pay-button-width: 100%;
|
|
4
4
|
--apple-pay-button-height: ${r}px;
|
|
5
5
|
}
|
|
6
|
-
`,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(),Le({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:P.APPLE_PAY}),this.applePaySession=new ApplePaySession(to,pu(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){y.errorWithDatadog("Error initiating Apple Pay session",{error:e})}}async handleValidateMerchant(e){if(this.applePaySession)try{let{action:r}=await this.onStartPromise;if(r==="abort")return void this.abort(new N({message:"Payment creation aborted",code:L.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 N({message:"Failed to validate merchant",code:W.REQUEST_ERROR,paymentMethod:P.APPLE_PAY});this.applePaySession.completeMerchantValidation(i)}catch(r){y.warn("Apple Pay merchant validation failed:",r),this.abort()}}async handlePaymentMethodSelected(e){if(this.applePaySession)try{this.applePaySession.completePaymentMethodSelection(fi(this.context,this.config))}catch(r){y.errorWithDatadog("Error handling payment method selection",{error:r}),this.abort()}}async handlePaymentAuthorized(e){if(!this.applePaySession)return;let r=[new ApplePayError("unknown",void 0,this.context.translate(gr.UNKNOWN_ERROR,fr.UNKNOWN_ERROR))];try{if(this.clientOptions?.billingOptions?.requiredBillingContactFields?.includes("postalAddress")){let s=gi(e.payment.billingContact);if(s){if(!s.firstName||!s.lastName)throw r=[new ApplePayError("billingContactInvalid","name",this.context.translate(gr.MISSING_FIRST_OR_LAST_NAME,fr.MISSING_FIRST_OR_LAST_NAME))],new N({message:"Billing contact must include first and last name",code:xt.MISSING_PARAMETER,paymentMethod:P.APPLE_PAY,suggestion:"Ensure Apple Pay requiredBillingContactFields includes name fields"});let{error:l}=await this.context.clientSessionApi.setBillingAddress(s);l&&y.errorWithDatadog("Error setting billing address from Apple Pay",{error:l})}}let i=gi(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 r=[new ApplePayError("unknown",void 0,this.context.translate(gr.FAILED_TO_TOKENIZE,fr.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 N||i instanceof K?i:new N({message:"Error handling payment authorization",code:L.PAYMENT_FAILED,paymentMethod:P.APPLE_PAY,error:i instanceof Error?i:new Error(String(i))});y.errorWithDatadog("Apple Pay payment authorization failed",{error:n}),this.applePaySession&&(this.applePaySession.completePayment({status:ApplePaySession.STATUS_FAILURE,errors:r}),this.applePaySession=null),this.callbacks.onFinish(void 0,n)}}async handleShippingContactSelected(e){if(this.applePaySession)try{let{data:r,error:i}=await this.context.clientSessionApi.setShippingAddress(gi(e.shippingContact),e.shippingContact?.phoneNumber,e.shippingContact?.emailAddress);if(!this.applePaySession)return;if(!r||i)throw i??new N({message:"Failed to set shipping address",code:W.REQUEST_ERROR,paymentMethod:P.APPLE_PAY});this.applePaySession.completeShippingContactSelection(fi(this.context,this.config))}catch(r){y.errorWithDatadog("Error handling shipping contact selection",{error:r}),this.abort()}}async handleShippingMethodSelected(e){if(!this.applePaySession)return;let r=this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options;try{if(this.clientOptions?.shippingOptions?.requireShippingMethod&&r){let{data:i,error:n}=await this.context.clientSessionApi.selectShippingMethod(e.shippingMethod.identifier);if(!i||n)throw n??new N({message:"Failed to select shipping method",code:W.REQUEST_ERROR,paymentMethod:P.APPLE_PAY})}if(!this.applePaySession)return;this.applePaySession.completeShippingMethodSelection(fi(this.context,this.config))}catch(i){y.errorWithDatadog("Error handling shipping method selection",{error:i}),this.abort();return}}handleCancel(){this.applePaySession=null,this.context.clientSessionApi.unselectPaymentMethod(),y.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"))}},Oo="3.7.7",mu=Oo,qt=typeof Buffer=="function",ao=typeof TextDecoder=="function"?new TextDecoder:void 0,io=typeof TextEncoder=="function"?new TextEncoder:void 0,hu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",mr=Array.prototype.slice.call(hu),zr=(a=>{let t={};return a.forEach((e,r)=>t[e]=r),t})(mr),gu=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,ee=String.fromCharCode.bind(String),no=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):a=>new Uint8Array(Array.prototype.slice.call(a,0)),_o=a=>a.replace(/=/g,"").replace(/[+\/]/g,t=>t=="+"?"-":"_"),Go=a=>a.replace(/[^A-Za-z0-9\+\/]/g,""),Ko=a=>{let t,e,r,i,n="",o=a.length%3;for(let s=0;s<a.length;){if((e=a.charCodeAt(s++))>255||(r=a.charCodeAt(s++))>255||(i=a.charCodeAt(s++))>255)throw new TypeError("invalid character found");t=e<<16|r<<8|i,n+=mr[t>>18&63]+mr[t>>12&63]+mr[t>>6&63]+mr[63&t]}return o?n.slice(0,o-3)+"===".substring(o):n},Zi=typeof btoa=="function"?a=>btoa(a):qt?a=>Buffer.from(a,"binary").toString("base64"):Ko,Mi=qt?a=>Buffer.from(a).toString("base64"):a=>{let e=[];for(let r=0,i=a.length;r<i;r+=4096)e.push(ee.apply(null,a.subarray(r,r+4096)));return Zi(e.join(""))},qr=(a,t=!1)=>t?_o(Mi(a)):Mi(a),fu=a=>{if(a.length<2){var t=a.charCodeAt(0);return t<128?a:t<2048?ee(192|t>>>6)+ee(128|63&t):ee(224|t>>>12&15)+ee(128|t>>>6&63)+ee(128|63&t)}var t=65536+(a.charCodeAt(0)-55296)*1024+(a.charCodeAt(1)-56320);return ee(240|t>>>18&7)+ee(128|t>>>12&63)+ee(128|t>>>6&63)+ee(128|63&t)},yu=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,Fo=a=>a.replace(yu,fu),oo=qt?a=>Buffer.from(a,"utf8").toString("base64"):io?a=>Mi(io.encode(a)):a=>Zi(Fo(a)),zt=(a,t=!1)=>t?_o(oo(a)):oo(a),so=a=>zt(a,!0),vu=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,bu=a=>{switch(a.length){case 4:var t=(7&a.charCodeAt(0))<<18|(63&a.charCodeAt(1))<<12|(63&a.charCodeAt(2))<<6|63&a.charCodeAt(3),e=t-65536;return ee((e>>>10)+55296)+ee((1023&e)+56320);case 3:return ee((15&a.charCodeAt(0))<<12|(63&a.charCodeAt(1))<<6|63&a.charCodeAt(2));default:return ee((31&a.charCodeAt(0))<<6|63&a.charCodeAt(1))}},Uo=a=>a.replace(vu,bu),Vo=a=>{if(a=a.replace(/\s+/g,""),!gu.test(a))throw new TypeError("malformed base64.");a+="==".slice(2-(3&a.length));let t,e="",r,i;for(let n=0;n<a.length;)t=zr[a.charAt(n++)]<<18|zr[a.charAt(n++)]<<12|(r=zr[a.charAt(n++)])<<6|(i=zr[a.charAt(n++)]),e+=r===64?ee(t>>16&255):i===64?ee(t>>16&255,t>>8&255):ee(t>>16&255,t>>8&255,255&t);return e},Wi=typeof atob=="function"?a=>atob(Go(a)):qt?a=>Buffer.from(a,"base64").toString("binary"):Vo,Ho=qt?a=>no(Buffer.from(a,"base64")):a=>no(Wi(a).split("").map(t=>t.charCodeAt(0))),$o=a=>Ho(Yo(a)),Cu=qt?a=>Buffer.from(a,"base64").toString("utf8"):ao?a=>ao.decode(Ho(a)):a=>Uo(Wi(a)),Yo=a=>Go(a.replace(/[-_]/g,t=>t=="-"?"+":"/")),Ti=a=>Cu(Yo(a)),Su=a=>{if(typeof a!="string")return!1;let t=a.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(t)||!/[^\s0-9a-zA-Z\-_]/.test(t)},zo=a=>({value:a,enumerable:!1,writable:!0,configurable:!0}),jo=function(){let a=(t,e)=>Object.defineProperty(String.prototype,t,zo(e));a("fromBase64",function(){return Ti(this)}),a("toBase64",function(t){return zt(this,t)}),a("toBase64URI",function(){return zt(this,!0)}),a("toBase64URL",function(){return zt(this,!0)}),a("toUint8Array",function(){return $o(this)})},Zo=function(){let a=(t,e)=>Object.defineProperty(Uint8Array.prototype,t,zo(e));a("toBase64",function(t){return qr(this,t)}),a("toBase64URI",function(){return qr(this,!0)}),a("toBase64URL",function(){return qr(this,!0)})},Au=()=>{jo(),Zo()},Wo={version:Oo,VERSION:mu,atob:Wi,atobPolyfill:Vo,btoa:Zi,btoaPolyfill:Ko,fromBase64:Ti,toBase64:zt,encode:zt,encodeURI:so,encodeURL:so,utob:Fo,btou:Uo,decode:Ti,isValid:Su,fromUint8Array:qr,toUint8Array:$o,extendString:jo,extendUint8Array:Zo,extendBuiltins:Au},Wt={encode:Eu,decode:Wo.decode};function Eu(a,t={}){let{urlSafe:e=!1}=t;return Wo.encode(a,e)}function Jo(a,t){return!(a.intent!==`${t}_REDIRECTION`||!("statusUrl"in a)||!("redirectUrl"in a)||!a.redirectUrl||!a.statusUrl)}function We(a){let t=Pu(a),e=1e3*t.exp;if(Date.now()>e)throw new Error(`${Mu}. Expiration date: ${new Date(e).toISOString()}`);return t}var qo="The provided `clientToken`",Mu=`${qo} has expired`,Tu=`${qo} is malformed`;function Pu(a){try{let[t,e]=a.split("."),r=e||t;return JSON.parse(Wt.decode(r))}catch{throw new Error(Tu)}}var ta=class extends ge{constructor(){super(...arguments);A(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 N({message:"Payment creation aborted",code:L.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let r=await this.tokenize();this.callbacks.onFinish(r)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){if(!/^\d{6}$/.test(this.blikCode))throw new K({message:"BLIK code must be exactly 6 digits",code:L.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:Ze()?"MOBILE_WEB":"WEB",browserInfo:ht(),blikCode:this.blikCode}};try{let{error:r,data:i}=await this.context.pciApi.postBlikPaymentInstruments(e);if(this.clearBlikCode(),r||!i)throw r??new K({message:"Unable to tokenize BLIK payment method",code:L.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}catch(r){throw this.clearBlikCode(),r}}async handleRequiredAction(e){let r=e.requiredAction?.clientToken;if(!r)throw new le({message:"No client token provided for BLIK payment",code:Qr.MISSING_CLIENT_TOKEN,response:{id:e.id,data:e}});let i=We(r);if(!this.isValidBlikClientToken(i))throw new le({message:"Invalid BLIK client token: missing statusUrl or incorrect intent",code:Qr.INVALID_CLIENT_TOKEN,response:{id:e.id,data:e}});let n=await this.context.pciApi.pollResumeStatus(i.statusUrl,{timeout:864e5,isComplete:s=>!!s.error||s.data?.status==="COMPLETE"});if(n.error)throw n.error;let o=n.data?.id;if(!o){let s=await this.context.pciApi.getResumeStatus(i.statusUrl);if(s.error||!s.data?.id)throw s.error??new Error("Unable to get resume token");o=s.data.id}return await this.resumePayment(e.id,o)}isValidBlikClientToken(e){if(typeof e!="object"||e===null)return!1;let r=e;return!(r.intent!=="ADYEN_BLIK_REDIRECTION"||!("statusUrl"in r)||typeof r.statusUrl!="string"||!r.statusUrl)}},Ji="https://sdk.primer.io/web/hosted-pages/v0.0.36",Pi=!1,ku=`${Ji}/api-controller.html`,Iu=`${Ji}/hosted-input.html`,Nu=`${Ji}/3ds.html`,Qo="https://goat-assets.production.core.primer.io",wu="primer-js-1.6.0_sdk-core-0.14.0";function Xo(a,t,e){let r={checkoutSessionId:a,name:t};e!==void 0&&(r.defaultValue=e);try{return btoa(JSON.stringify(r))}catch{let{defaultValue:n,...o}=r;return btoa(JSON.stringify(o))}}Hi("../../node_modules/card-validator/dist/index.js");var ie={cardNumber:"cardNumber",cardSecurityCode:"cardSecurityCode",cardExpiryDate:"cardExpiryDate",cardholderName:"cardholderName"},lo="cardSecurityCodeRecapture";Object.values(ie);function Lu({networks:a,source:t},e){let r=e,i=new Set(r.map(u=>jt(u).backend)),n=a.map(u=>({...u,allowed:i.has(u.network)})).sort((u,m)=>u.allowed?r.indexOf(u.network)-r.indexOf(m.network):1),o=n.filter(u=>u.allowed),s=t==="REMOTE"&&o.length>1,[l,...c]=n;return{cardNetworkChangeEventData:{detectedCardNetworks:{items:n.map(jr),preferred:o.length?jr(o[0]):void 0},...s&&{selectableCardNetworks:{items:o.map(jr),preferred:o.length?jr(o[0]):void 0}},source:t},binDataAvailableEventData:{preferred:l,alternatives:c,status:t==="REMOTE"?"complete":"partial"}}}function jr({network:a,displayName:t,allowed:e}){return{network:a,displayName:t,allowed:e}}function Ru(a,t){return{cardNumber:hr(a,ie.cardNumber),cardSecurityCode:hr(a,ie.cardSecurityCode),cardExpiryDate:hr(a,ie.cardExpiryDate),cardholderName:hr(a,ie.cardholderName,t?.cardholderName)}}function hr(a,t,e){let r=document.createElement("iframe"),i=Xo(a,t,e);return r.src=`${Iu}#${i}`,r.setAttribute("tabindex","0"),r.setAttribute("frameBorder","0"),r.style.border="none",r.style.boxSizing="border-box",r.style.height="20px",r.style.width="100%",r.style.colorScheme="auto",r}var ra=class extends ge{constructor(e,r){super(e,r);A(this,"iframes");this.iframes=Ru(r.checkoutSessionId,{cardholderName:r.clientOptions.card?.cardholderName?.defaultValue})}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new N({message:"Payment creation aborted",code:L.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let r=await this.tokenize();this.callbacks.onFinish(r)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){let{error:e,data:r}=await this.context.pciApi.postCardPaymentInstruments();if(e||!r)throw e??new K({code:L.TOKENIZATION_ERROR,message:"Unable to tokenize payment method",paymentMethod:P.PAYMENT_CARD});return r}};function xu(a){if(!a)return{};let t=a.indexOf(" ");return t===-1?{firstName:a}:{firstName:a.substring(0,t),lastName:a.substring(t+1)}}function yi(a){let{firstName:t,lastName:e}=xu(a.name);return{firstName:t||null,lastName:e||null,addressLine1:a.address1||null,addressLine2:a.address2||null,city:a.locality||null,state:a.administrativeArea||null,postalCode:a.postalCode||null,countryCode:a.countryCode||null}}function co(a){return a.map(t=>({id:t.id,label:t.name,description:t.description||""}))}var uo=2,po=0,Bu="https://pay.google.com/gp/p/js/pay.js",Du={AMEX:"AMEX",DISCOVER:"DISCOVER",INTERAC:"INTERAC",JCB:"JCB",MASTERCARD:"MASTERCARD",VISA:"VISA"},mo=["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],Zr={FEE:"fee_label_fallback",ITEM:"item_label_fallback",SHIPPING:"shipping",SUBTOTAL:"subtotal"},Wr={FEE:"Fee",ITEM:"Item",SHIPPING:"Shipping",SUBTOTAL:"Subtotal"},Ou="buy",_u="black",Gu="fill",aa=class extends ge{constructor(){super(...arguments);A(this,"disabled",!1);A(this,"client",null)}async setDisabled(e){this.disabled=e}translate(e,r){return this.context.translate?.(e,r)??r}async tokenize(){throw new K({code:L.TOKENIZATION_ERROR,message:"Google Pay does not support direct tokenization",paymentMethod:P.GOOGLE_PAY})}async loadGooglePayScript(){if(typeof google<"u"&&google.payments?.api?.PaymentsClient)return!0;try{return await ji(Bu),!0}catch{return y.error("Failed to load Google Pay script"),!1}}async setup(){let{countryCode:e,currencyCode:r}=this.context.configuration.clientSession.order;if(!e)throw new N({code:xt.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing country code",paymentMethod:P.GOOGLE_PAY});if(!r)throw new N({code:xt.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing currency code",paymentMethod:P.GOOGLE_PAY});if(!await this.loadGooglePayScript())return y.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 y.info("Google Pay is not available in this browser/device"),!1;if(this.clientOptions?.existingPaymentMethodRequired&&l===!1)return y.info("Google Pay: existingPaymentMethodRequired is true but no existing payment method is available"),!1}catch(s){return y.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)&&y.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:uo,apiVersionMinor:po,allowedPaymentMethods:[this.allowedPaymentMethod],existingPaymentMethodRequired:this.clientOptions?.existingPaymentMethodRequired}}async render(e,{style:{shadowRoot:r}={}}={style:{}}){if(!this.client)return void y.error("Google Pay client not initialized. Call setup() first.");let i=this.client.createButton({buttonType:this.clientOptions?.buttonType??Ou,buttonColor:this.clientOptions?.buttonColor??_u,buttonSizeMode:this.clientOptions?.buttonSizeMode??Gu,buttonRadius:this.clientOptions?.buttonRadius,buttonLocale:this.clientOptions?.buttonLocale,buttonBorderType:this.clientOptions?.buttonBorderType,onClick:n=>this.handleClick(n),buttonRootNode:r??void 0});e.appendChild(i)}async handleClick(e){if(this.disabled)return;if(!this.client)return void y.error("Google Pay client not available");let r=this.callbacks.onStart();Le({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:P.GOOGLE_PAY});try{let i=await this.client.loadPaymentData(this.buildPaymentDataRequest()),{action:n}=await r;if(n==="abort")throw new N({message:"Payment creation aborted",code:L.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type});await this.processPaymentData(i)}catch(i){if(i.statusCode==="CANCELED")return void this.context.clientSessionApi.unselectPaymentMethod();y.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:r,error:i}=await this.context.pciApi.postGooglePayPaymentInstruments({flow:"GATEWAY",network:e.paymentMethodData.info?.cardNetwork??"OTHER",merchant_id:this.config.options.merchantId,encrypted_payload:Wt.encode(e.paymentMethodData.tokenizationData.token)});if(i||!r)throw this.callbacks.onFinish(void 0,i),i??new K({code:L.TOKENIZATION_ERROR,message:"Failed to tokenize payment data",paymentMethod:P.GOOGLE_PAY});this.callbacks.onFinish(r)}async updateBillingAddress(e){let r=e.paymentMethodData.info?.billingAddress;if(r){let i=yi(r);await this.context.clientSessionApi.setBillingAddress(i)}else y.warn("Google Pay: Could not retrieve billing address from payment data")}async updateShippingDetails(e){let r=e.shippingAddress,i=e.email,n=r?.phoneNumber;if(r||n||i){let o=r?yi(r):void 0;await this.context.clientSessionApi.setShippingAddress(o,n,i)}else y.warn("Google Pay: No shipping address, phone number, or email found in payment data")}async handlePaymentDataChanged(e){let r=e.callbackTrigger;try{if(r==="SHIPPING_OPTION"){let i=e.shippingOptionData?.id;return i&&await this.context.clientSessionApi.selectShippingMethod(i),{newTransactionInfo:this.getCurrentTransactionInfo()}}if(r==="SHIPPING_ADDRESS"||r==="INITIALIZE"){let i=e.shippingAddress;if(i){let s=yi(i);await this.context.clientSessionApi.setShippingAddress(s)}let n=this.getShippingModule(),o=n?.shippingMethods||[];return{...this.clientOptions?.requireShippingMethod&&o.length>0&&{newShippingOptionParameters:{shippingOptions:co(o),defaultSelectedOptionId:n?.selectedShippingMethod||o[0]?.id}},newTransactionInfo:this.getCurrentTransactionInfo()}}return{newTransactionInfo:this.getCurrentTransactionInfo()}}catch(i){return y.errorWithDatadog("Google Pay: Error handling payment data change",{error:i}),{error:{reason:"OTHER_ERROR",message:"An error occurred while processing your request",intent:r==="SHIPPING_OPTION"?"SHIPPING_OPTION":"SHIPPING_ADDRESS"}}}}getShippingModule(){return this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options}getCurrentTransactionInfo(){let{countryCode:e,currencyCode:r,merchantAmount:i,totalOrderAmount:n}=this.context.configuration.clientSession.order;return{countryCode:e,currencyCode:r,displayItems:this.getDisplayItems(),totalPriceStatus:"FINAL",totalPrice:pr(i??n,r),totalPriceLabel:"Total"}}getDisplayItems(){let e=this.context.configuration.clientSession.order,{currencyCode:r,merchantAmount:i,lineItems:n,fees:o,shipping:s}=e,l=this.clientOptions?.requireShippingMethod,c=[];return i?(c.push({label:this.translate(Zr.SUBTOTAL,Wr.SUBTOTAL),type:"SUBTOTAL",price:pr(i,r)}),c):(n&&n.length>0&&n.forEach(u=>{c.push({label:u.description||this.translate(Zr.ITEM,Wr.ITEM),type:"LINE_ITEM",price:pr(u.amount,r)})}),o&&o.length>0&&o.filter(u=>u.amount!==0).forEach(u=>{c.push({label:u.type||u.description||this.translate(Zr.FEE,Wr.FEE),type:"LINE_ITEM",price:pr(u.amount,r)})}),l&&s&&s.amount!==0&&c.push({label:s.methodName||this.translate(Zr.SHIPPING,Wr.SHIPPING),type:"LINE_ITEM",price:pr(s.amount,r)}),c)}get allowedCardNetworks(){let e=this.context.configuration.clientSession.paymentMethod?.orderedAllowedCardNetworks;if(!e||e.length===0)return mo;let r=e.map(i=>Du[i]).filter(i=>!!i);return r.length>0?r:mo}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,r=this.clientOptions?.emailRequired,i=this.clientOptions?.requireShippingMethod,n=this.getShippingModule(),o=n?.shippingMethods,s=n?.selectedShippingMethod;return{apiVersion:uo,apiVersionMinor:po,...r&&{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:co(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}}}]}}},Ku="https://x.klarnacdn.net/kp/lib/v1/api.js",ia=class extends Error{constructor(){super("Klarna authorization cancelled by user"),this.name="KlarnaUserCancelledError"}},na=class extends ge{constructor(){super(...arguments);A(this,"session",null);A(this,"selectedCategoryId",null)}getCategories(){let e=this.session?.categories??[],r=this.context.clientOptions.klarna?.allowedPaymentCategories;return r?r.map(i=>e.find(n=>n.identifier===i)).filter(i=>i!=null):e}setSelectedCategory(e){this.selectedCategoryId=e}async setup(){try{return await ji(Ku,{crossorigin:""}),window.Klarna?.Payments?(this.session=await this.createSession(),this.session?this.getCategories().length===0?(y.warn("No Klarna payment categories available"),!1):(window.Klarna.Payments.init({client_token:this.session.clientToken}),!0):!1):(y.error("Klarna SDK failed to load"),!1)}catch(e){return y.error("Klarna setup failed",e),!1}}get isRecurring(){return this.context.clientOptions.klarna?.paymentFlow==="PREFER_VAULT"}async createSession(){let{clientSession:e}=this.context.configuration,r=e.order,i={localeCode:this.context.locale,countryCode:r?.countryCode??"",currencyCode:r?.currencyCode??""},n;if(this.isRecurring)n={sessionType:"RECURRING_PAYMENT",paymentMethodConfigId:this.config.id,localeData:i,description:this.context.clientOptions.klarna?.recurringPaymentDescription};else{if(!r?.lineItems||r.lineItems.length===0)return y.error("Klarna requires order.lineItems to be provided"),null;let l=r.lineItems.map(u=>({name:u.name||u.description||"",unitAmount:u.amount,reference:u.itemId,quantity:u.quantity,discountAmount:u.discountAmount,taxCode:u.taxCode,taxAmount:u.taxAmount,productType:u.productType})),c=r.merchantAmount??r.totalOrderAmount??0;n={sessionType:"ONE_OFF_PAYMENT",paymentMethodConfigId:this.config.id,localeData:i,totalAmount:c,orderItems:l}}let{data:o,error:s}=await this.context.coreApi.createKlarnaSession(n);return s||!o?(y.error("Failed to create Klarna session",s),null):o}async renderCategory(e){if(!window.Klarna?.Payments)throw new K({message:"Klarna SDK not loaded",code:L.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{Payments:r}=window.Klarna,i=(typeof e.containerId=="string",e.containerId);return e.onHeightChange&&r.on("heightChanged",e.onHeightChange),new Promise((n,o)=>{r.load({container:i,payment_method_category:e.paymentMethodCategoryId},s=>{s.error?o(new K({message:`Klarna load failed: ${s.error.invalid_fields?.join(", ")}`,code:L.TOKENIZATION_ERROR,paymentMethod:this.config.type})):(this.selectedCategoryId=e.paymentMethodCategoryId,n())})})}async authorize(e){if(!window.Klarna?.Payments)throw new K({message:"Klarna SDK not loaded",code:L.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{Payments:r}=window.Klarna;return new Promise(i=>{r.authorize({payment_method_category:e},void 0,i)})}async finalizeSession(){if(!this.session)return null;let{data:e,error:r}=await this.context.coreApi.finalizeKlarnaSession({sessionId:this.session.sessionId,paymentMethodConfigId:this.config.id});return r||!e?(y.error("Failed to finalize Klarna session",r),null):e}async createCustomerToken(e){if(!this.session)return null;let r=this.context.clientOptions.klarna?.recurringPaymentDescription;if(!r)return y.error("klarna.recurringPaymentDescription must be provided for PREFER_VAULT flow"),null;let{clientSession:i}=this.context.configuration,n=i.order,{data:o,error:s}=await this.context.coreApi.createKlarnaCustomerToken({paymentMethodConfigId:this.config.id,sessionId:this.session.sessionId,authorizationToken:e,description:r,localeData:{localeCode:this.context.locale,countryCode:n?.countryCode??"",currencyCode:n?.currencyCode??""}});return s||!o?(y.error("Failed to create Klarna customer token",s),null):o}async tokenize(){if(!this.selectedCategoryId)throw new K({message:"No Klarna payment category selected",code:L.TOKENIZATION_ERROR,paymentMethod:this.config.type});let e=await this.authorize(this.selectedCategoryId);if(!e.approved&&!e.error)throw y.debug("Klarna authorization cancelled by user"),new ia;if(!e.approved||!e.authorization_token){let r=e.error?.invalid_fields?.join(", ")||"Authorization failed";throw new K({message:`Klarna authorization failed: ${r}`,code:L.TOKENIZATION_ERROR,paymentMethod:this.config.type})}return this.isRecurring?this.tokenizeWithCustomerToken(e.authorization_token):this.tokenizeWithAuthToken(e.authorization_token)}async tokenizeWithAuthToken(e){let r=await this.finalizeSession();if(!r)throw new K({message:"Failed to finalize Klarna session",code:L.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{data:i,error:n}=await this.context.pciApi.postKlarnaPaymentInstruments({klarnaAuthorizationToken:e,sessionData:r.sessionData});if(n||!i)throw n??new K({message:"Failed to tokenize Klarna payment",code:L.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}async tokenizeWithCustomerToken(e){let r=await this.createCustomerToken(e);if(!r)throw new K({message:"Failed to create Klarna customer token",code:L.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{data:i,error:n}=await this.context.pciApi.postKlarnaCustomerTokenInstruments({klarnaCustomerToken:r.customerTokenId,sessionData:r.sessionData});if(n||!i)throw n??new K({message:"Failed to tokenize Klarna payment",code:L.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new Error("Payment aborted"));let r=await this.tokenize();this.callbacks.onFinish(r)}catch(e){if(e instanceof ia)return void this.context.clientSessionApi.unselectPaymentMethod();this.callbacks.onFinish(void 0,e)}}async startWithCategory(e){return this.selectedCategoryId=e,this.start()}};function qi(a,t){return a?.redirect?.returnUrl?!0:(y.warn(`[Primer SDK] ${t} is enabled in your client session but \`options.redirect.returnUrl\` is missing. This payment method may redirect the customer to an external page; without a return URL the customer cannot be brought back. The payment method will not be available in this checkout. Set \`options.redirect.returnUrl\` to a page that re-initializes the SDK with the \`?clientToken=...\` query parameter Primer appends on return.`),!1)}function Fu(a,t){if(a?.redirect?.returnUrl)return;let e=typeof window<"u"&&window.location?window.location.href:"";y.warn(`[Primer SDK] Initiating ${t} which may redirect the customer to an external page, but no \`options.redirect.returnUrl\` is configured. The customer will be returned to the current page (${e}). Set \`options.redirect.returnUrl\` to control the return destination.`),Le({eventName:"REDIRECT_RETURN_URL_NOT_CONFIGURED",paymentMethod:t})}function Qi(a,t,e){let r="";try{r=new URL(a).origin}catch{r=""}y.info(`[Primer SDK] Redirecting to ${t} payment page at ${r} (${e})`),Le({eventName:"PAYMENT_REDIRECT_TO_THIRD_PARTY",paymentMethod:t,redirectDestinationUrl:r,redirectReason:e})}function ho(a,t={}){y.info(`[Primer SDK] Returned from third-party payment page (${a})`),Le({eventName:"PAYMENT_RETURNED_FROM_THIRD_PARTY",intent:a,...t})}function vr(a){return a?new Promise(t=>{setTimeout(t,a)}):Promise.resolve()}var Uu=100;function Vu({height:a,name:t,url:e="",width:r}){let i=new Set,n=window.open(e,t,$u({height:a,width:r}));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),Hu(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 Hu=a=>new Promise(t=>{let e=setInterval(()=>{a.closed&&(clearInterval(e),t())},Uu)});function $u(a){let t=Yu({parent:{left:window.screenLeft,top:window.screenTop,height:window.outerHeight,width:window.outerWidth},popup:a});return zu(t)}var Yu=({parent:a,popup:t})=>({left:a.left+(a.width-t.width)/2,top:a.top+(a.height-t.height)/2,height:t.height,width:t.width}),zu=a=>Object.entries(a).map(t=>t.join("=")).join(",");async function Xi(a){let t=Vu({name:a.name,height:a.displayMetadata.popup?.height??500,width:a.displayMetadata.popup?.width??1e3});return a.context.dialogProvider.show({htmlContent:ju({logoSrc:fo(a.displayMetadata),text:a.context.translate("paymentMethodPopupOverlayDescription","Having trouble viewing the {paymentMethodName} payment page? We'll help you find it!").replace("{paymentMethodName}",a.name),backgroundColor:go(a.displayMetadata)}),showCloseButton:!0,size:"flex",cta:{label:a.context.translate("paymentMethodPopupOverlayBringBackThePaymentPage","Bring back the payment page"),icon:"chevron-left",onClick:()=>{t?.focus()}}}).then(()=>{t?.isOpen&&t.close()}),t?.setContent(Zu({name:a.name,background:go(a.displayMetadata),logoSrc:fo(a.displayMetadata),logoAlt:a.name,message:`Loading ${a.name}...`})),t&&(await vr(300),!t.isOpen)?void a.context.dialogProvider.close():t}var ju=({logoSrc:a,text:t,backgroundColor:e})=>{let r=document.createElement("div");r.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: ${e};border-radius:var(--primer-radius-small);`);let n=document.createElement("img");n.src=a,i.appendChild(n),n.setAttribute("style","height:100%;"),r.appendChild(i);let o=document.createElement("p");return o.setAttribute("style","max-width: 300px;text-align: center;"),o.innerText=t,r.appendChild(o),r},Zu=({name:a,background:t,logoSrc:e,logoAlt:r,message:i})=>`<html>
|
|
6
|
+
`,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(),Le({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:P.APPLE_PAY}),this.applePaySession=new ApplePaySession(to,pu(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){y.errorWithDatadog("Error initiating Apple Pay session",{error:e})}}async handleValidateMerchant(e){if(this.applePaySession)try{let{action:r}=await this.onStartPromise;if(r==="abort")return void this.abort(new N({message:"Payment creation aborted",code:L.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 N({message:"Failed to validate merchant",code:W.REQUEST_ERROR,paymentMethod:P.APPLE_PAY});this.applePaySession.completeMerchantValidation(i)}catch(r){y.warn("Apple Pay merchant validation failed:",r),this.abort()}}async handlePaymentMethodSelected(e){if(this.applePaySession)try{this.applePaySession.completePaymentMethodSelection(fi(this.context,this.config))}catch(r){y.errorWithDatadog("Error handling payment method selection",{error:r}),this.abort()}}async handlePaymentAuthorized(e){if(!this.applePaySession)return;let r=[new ApplePayError("unknown",void 0,this.context.translate(gr.UNKNOWN_ERROR,fr.UNKNOWN_ERROR))];try{if(this.clientOptions?.billingOptions?.requiredBillingContactFields?.includes("postalAddress")){let s=gi(e.payment.billingContact);if(s){if(!s.firstName||!s.lastName)throw r=[new ApplePayError("billingContactInvalid","name",this.context.translate(gr.MISSING_FIRST_OR_LAST_NAME,fr.MISSING_FIRST_OR_LAST_NAME))],new N({message:"Billing contact must include first and last name",code:xt.MISSING_PARAMETER,paymentMethod:P.APPLE_PAY,suggestion:"Ensure Apple Pay requiredBillingContactFields includes name fields"});let{error:l}=await this.context.clientSessionApi.setBillingAddress(s);l&&y.errorWithDatadog("Error setting billing address from Apple Pay",{error:l})}}let i=gi(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 r=[new ApplePayError("unknown",void 0,this.context.translate(gr.FAILED_TO_TOKENIZE,fr.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 N||i instanceof K?i:new N({message:"Error handling payment authorization",code:L.PAYMENT_FAILED,paymentMethod:P.APPLE_PAY,error:i instanceof Error?i:new Error(String(i))});y.errorWithDatadog("Apple Pay payment authorization failed",{error:n}),this.applePaySession&&(this.applePaySession.completePayment({status:ApplePaySession.STATUS_FAILURE,errors:r}),this.applePaySession=null),this.callbacks.onFinish(void 0,n)}}async handleShippingContactSelected(e){if(this.applePaySession)try{let{data:r,error:i}=await this.context.clientSessionApi.setShippingAddress(gi(e.shippingContact),e.shippingContact?.phoneNumber,e.shippingContact?.emailAddress);if(!this.applePaySession)return;if(!r||i)throw i??new N({message:"Failed to set shipping address",code:W.REQUEST_ERROR,paymentMethod:P.APPLE_PAY});this.applePaySession.completeShippingContactSelection(fi(this.context,this.config))}catch(r){y.errorWithDatadog("Error handling shipping contact selection",{error:r}),this.abort()}}async handleShippingMethodSelected(e){if(!this.applePaySession)return;let r=this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options;try{if(this.clientOptions?.shippingOptions?.requireShippingMethod&&r){let{data:i,error:n}=await this.context.clientSessionApi.selectShippingMethod(e.shippingMethod.identifier);if(!i||n)throw n??new N({message:"Failed to select shipping method",code:W.REQUEST_ERROR,paymentMethod:P.APPLE_PAY})}if(!this.applePaySession)return;this.applePaySession.completeShippingMethodSelection(fi(this.context,this.config))}catch(i){y.errorWithDatadog("Error handling shipping method selection",{error:i}),this.abort();return}}handleCancel(){this.applePaySession=null,this.context.clientSessionApi.unselectPaymentMethod(),y.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"))}},Oo="3.7.7",mu=Oo,qt=typeof Buffer=="function",ao=typeof TextDecoder=="function"?new TextDecoder:void 0,io=typeof TextEncoder=="function"?new TextEncoder:void 0,hu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",mr=Array.prototype.slice.call(hu),zr=(a=>{let t={};return a.forEach((e,r)=>t[e]=r),t})(mr),gu=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,ee=String.fromCharCode.bind(String),no=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):a=>new Uint8Array(Array.prototype.slice.call(a,0)),_o=a=>a.replace(/=/g,"").replace(/[+\/]/g,t=>t=="+"?"-":"_"),Go=a=>a.replace(/[^A-Za-z0-9\+\/]/g,""),Ko=a=>{let t,e,r,i,n="",o=a.length%3;for(let s=0;s<a.length;){if((e=a.charCodeAt(s++))>255||(r=a.charCodeAt(s++))>255||(i=a.charCodeAt(s++))>255)throw new TypeError("invalid character found");t=e<<16|r<<8|i,n+=mr[t>>18&63]+mr[t>>12&63]+mr[t>>6&63]+mr[63&t]}return o?n.slice(0,o-3)+"===".substring(o):n},Zi=typeof btoa=="function"?a=>btoa(a):qt?a=>Buffer.from(a,"binary").toString("base64"):Ko,Mi=qt?a=>Buffer.from(a).toString("base64"):a=>{let e=[];for(let r=0,i=a.length;r<i;r+=4096)e.push(ee.apply(null,a.subarray(r,r+4096)));return Zi(e.join(""))},qr=(a,t=!1)=>t?_o(Mi(a)):Mi(a),fu=a=>{if(a.length<2){var t=a.charCodeAt(0);return t<128?a:t<2048?ee(192|t>>>6)+ee(128|63&t):ee(224|t>>>12&15)+ee(128|t>>>6&63)+ee(128|63&t)}var t=65536+(a.charCodeAt(0)-55296)*1024+(a.charCodeAt(1)-56320);return ee(240|t>>>18&7)+ee(128|t>>>12&63)+ee(128|t>>>6&63)+ee(128|63&t)},yu=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,Fo=a=>a.replace(yu,fu),oo=qt?a=>Buffer.from(a,"utf8").toString("base64"):io?a=>Mi(io.encode(a)):a=>Zi(Fo(a)),zt=(a,t=!1)=>t?_o(oo(a)):oo(a),so=a=>zt(a,!0),vu=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,bu=a=>{switch(a.length){case 4:var t=(7&a.charCodeAt(0))<<18|(63&a.charCodeAt(1))<<12|(63&a.charCodeAt(2))<<6|63&a.charCodeAt(3),e=t-65536;return ee((e>>>10)+55296)+ee((1023&e)+56320);case 3:return ee((15&a.charCodeAt(0))<<12|(63&a.charCodeAt(1))<<6|63&a.charCodeAt(2));default:return ee((31&a.charCodeAt(0))<<6|63&a.charCodeAt(1))}},Uo=a=>a.replace(vu,bu),Vo=a=>{if(a=a.replace(/\s+/g,""),!gu.test(a))throw new TypeError("malformed base64.");a+="==".slice(2-(3&a.length));let t,e="",r,i;for(let n=0;n<a.length;)t=zr[a.charAt(n++)]<<18|zr[a.charAt(n++)]<<12|(r=zr[a.charAt(n++)])<<6|(i=zr[a.charAt(n++)]),e+=r===64?ee(t>>16&255):i===64?ee(t>>16&255,t>>8&255):ee(t>>16&255,t>>8&255,255&t);return e},Wi=typeof atob=="function"?a=>atob(Go(a)):qt?a=>Buffer.from(a,"base64").toString("binary"):Vo,Ho=qt?a=>no(Buffer.from(a,"base64")):a=>no(Wi(a).split("").map(t=>t.charCodeAt(0))),$o=a=>Ho(Yo(a)),Cu=qt?a=>Buffer.from(a,"base64").toString("utf8"):ao?a=>ao.decode(Ho(a)):a=>Uo(Wi(a)),Yo=a=>Go(a.replace(/[-_]/g,t=>t=="-"?"+":"/")),Ti=a=>Cu(Yo(a)),Su=a=>{if(typeof a!="string")return!1;let t=a.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(t)||!/[^\s0-9a-zA-Z\-_]/.test(t)},zo=a=>({value:a,enumerable:!1,writable:!0,configurable:!0}),jo=function(){let a=(t,e)=>Object.defineProperty(String.prototype,t,zo(e));a("fromBase64",function(){return Ti(this)}),a("toBase64",function(t){return zt(this,t)}),a("toBase64URI",function(){return zt(this,!0)}),a("toBase64URL",function(){return zt(this,!0)}),a("toUint8Array",function(){return $o(this)})},Zo=function(){let a=(t,e)=>Object.defineProperty(Uint8Array.prototype,t,zo(e));a("toBase64",function(t){return qr(this,t)}),a("toBase64URI",function(){return qr(this,!0)}),a("toBase64URL",function(){return qr(this,!0)})},Au=()=>{jo(),Zo()},Wo={version:Oo,VERSION:mu,atob:Wi,atobPolyfill:Vo,btoa:Zi,btoaPolyfill:Ko,fromBase64:Ti,toBase64:zt,encode:zt,encodeURI:so,encodeURL:so,utob:Fo,btou:Uo,decode:Ti,isValid:Su,fromUint8Array:qr,toUint8Array:$o,extendString:jo,extendUint8Array:Zo,extendBuiltins:Au},Wt={encode:Eu,decode:Wo.decode};function Eu(a,t={}){let{urlSafe:e=!1}=t;return Wo.encode(a,e)}function Jo(a,t){return!(a.intent!==`${t}_REDIRECTION`||!("statusUrl"in a)||!("redirectUrl"in a)||!a.redirectUrl||!a.statusUrl)}function We(a){let t=Pu(a),e=1e3*t.exp;if(Date.now()>e)throw new Error(`${Mu}. Expiration date: ${new Date(e).toISOString()}`);return t}var qo="The provided `clientToken`",Mu=`${qo} has expired`,Tu=`${qo} is malformed`;function Pu(a){try{let[t,e]=a.split("."),r=e||t;return JSON.parse(Wt.decode(r))}catch{throw new Error(Tu)}}var ta=class extends ge{constructor(){super(...arguments);A(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 N({message:"Payment creation aborted",code:L.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let r=await this.tokenize();this.callbacks.onFinish(r)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){if(!/^\d{6}$/.test(this.blikCode))throw new K({message:"BLIK code must be exactly 6 digits",code:L.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:Ze()?"MOBILE_WEB":"WEB",browserInfo:ht(),blikCode:this.blikCode}};try{let{error:r,data:i}=await this.context.pciApi.postBlikPaymentInstruments(e);if(this.clearBlikCode(),r||!i)throw r??new K({message:"Unable to tokenize BLIK payment method",code:L.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}catch(r){throw this.clearBlikCode(),r}}async handleRequiredAction(e){let r=e.requiredAction?.clientToken;if(!r)throw new le({message:"No client token provided for BLIK payment",code:Qr.MISSING_CLIENT_TOKEN,response:{id:e.id,data:e}});let i=We(r);if(!this.isValidBlikClientToken(i))throw new le({message:"Invalid BLIK client token: missing statusUrl or incorrect intent",code:Qr.INVALID_CLIENT_TOKEN,response:{id:e.id,data:e}});let n=await this.context.pciApi.pollResumeStatus(i.statusUrl,{timeout:864e5,isComplete:s=>!!s.error||s.data?.status==="COMPLETE"});if(n.error)throw n.error;let o=n.data?.id;if(!o){let s=await this.context.pciApi.getResumeStatus(i.statusUrl);if(s.error||!s.data?.id)throw s.error??new Error("Unable to get resume token");o=s.data.id}return await this.resumePayment(e.id,o)}isValidBlikClientToken(e){if(typeof e!="object"||e===null)return!1;let r=e;return!(r.intent!=="ADYEN_BLIK_REDIRECTION"||!("statusUrl"in r)||typeof r.statusUrl!="string"||!r.statusUrl)}},Ji="https://sdk.primer.io/web/hosted-pages/v0.0.36",Pi=!1,ku=`${Ji}/api-controller.html`,Iu=`${Ji}/hosted-input.html`,Nu=`${Ji}/3ds.html`,Qo="https://goat-assets.production.core.primer.io",wu="primer-js-1.6.1_sdk-core-0.14.0";function Xo(a,t,e){let r={checkoutSessionId:a,name:t};e!==void 0&&(r.defaultValue=e);try{return btoa(JSON.stringify(r))}catch{let{defaultValue:n,...o}=r;return btoa(JSON.stringify(o))}}Hi("../../node_modules/card-validator/dist/index.js");var ie={cardNumber:"cardNumber",cardSecurityCode:"cardSecurityCode",cardExpiryDate:"cardExpiryDate",cardholderName:"cardholderName"},lo="cardSecurityCodeRecapture";Object.values(ie);function Lu({networks:a,source:t},e){let r=e,i=new Set(r.map(u=>jt(u).backend)),n=a.map(u=>({...u,allowed:i.has(u.network)})).sort((u,m)=>u.allowed?r.indexOf(u.network)-r.indexOf(m.network):1),o=n.filter(u=>u.allowed),s=t==="REMOTE"&&o.length>1,[l,...c]=n;return{cardNetworkChangeEventData:{detectedCardNetworks:{items:n.map(jr),preferred:o.length?jr(o[0]):void 0},...s&&{selectableCardNetworks:{items:o.map(jr),preferred:o.length?jr(o[0]):void 0}},source:t},binDataAvailableEventData:{preferred:l,alternatives:c,status:t==="REMOTE"?"complete":"partial"}}}function jr({network:a,displayName:t,allowed:e}){return{network:a,displayName:t,allowed:e}}function Ru(a,t){return{cardNumber:hr(a,ie.cardNumber),cardSecurityCode:hr(a,ie.cardSecurityCode),cardExpiryDate:hr(a,ie.cardExpiryDate),cardholderName:hr(a,ie.cardholderName,t?.cardholderName)}}function hr(a,t,e){let r=document.createElement("iframe"),i=Xo(a,t,e);return r.src=`${Iu}#${i}`,r.setAttribute("tabindex","0"),r.setAttribute("frameBorder","0"),r.style.border="none",r.style.boxSizing="border-box",r.style.height="20px",r.style.width="100%",r.style.colorScheme="auto",r}var ra=class extends ge{constructor(e,r){super(e,r);A(this,"iframes");this.iframes=Ru(r.checkoutSessionId,{cardholderName:r.clientOptions.card?.cardholderName?.defaultValue})}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new N({message:"Payment creation aborted",code:L.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let r=await this.tokenize();this.callbacks.onFinish(r)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){let{error:e,data:r}=await this.context.pciApi.postCardPaymentInstruments();if(e||!r)throw e??new K({code:L.TOKENIZATION_ERROR,message:"Unable to tokenize payment method",paymentMethod:P.PAYMENT_CARD});return r}};function xu(a){if(!a)return{};let t=a.indexOf(" ");return t===-1?{firstName:a}:{firstName:a.substring(0,t),lastName:a.substring(t+1)}}function yi(a){let{firstName:t,lastName:e}=xu(a.name);return{firstName:t||null,lastName:e||null,addressLine1:a.address1||null,addressLine2:a.address2||null,city:a.locality||null,state:a.administrativeArea||null,postalCode:a.postalCode||null,countryCode:a.countryCode||null}}function co(a){return a.map(t=>({id:t.id,label:t.name,description:t.description||""}))}var uo=2,po=0,Bu="https://pay.google.com/gp/p/js/pay.js",Du={AMEX:"AMEX",DISCOVER:"DISCOVER",INTERAC:"INTERAC",JCB:"JCB",MASTERCARD:"MASTERCARD",VISA:"VISA"},mo=["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],Zr={FEE:"fee_label_fallback",ITEM:"item_label_fallback",SHIPPING:"shipping",SUBTOTAL:"subtotal"},Wr={FEE:"Fee",ITEM:"Item",SHIPPING:"Shipping",SUBTOTAL:"Subtotal"},Ou="buy",_u="black",Gu="fill",aa=class extends ge{constructor(){super(...arguments);A(this,"disabled",!1);A(this,"client",null)}async setDisabled(e){this.disabled=e}translate(e,r){return this.context.translate?.(e,r)??r}async tokenize(){throw new K({code:L.TOKENIZATION_ERROR,message:"Google Pay does not support direct tokenization",paymentMethod:P.GOOGLE_PAY})}async loadGooglePayScript(){if(typeof google<"u"&&google.payments?.api?.PaymentsClient)return!0;try{return await ji(Bu),!0}catch{return y.error("Failed to load Google Pay script"),!1}}async setup(){let{countryCode:e,currencyCode:r}=this.context.configuration.clientSession.order;if(!e)throw new N({code:xt.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing country code",paymentMethod:P.GOOGLE_PAY});if(!r)throw new N({code:xt.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing currency code",paymentMethod:P.GOOGLE_PAY});if(!await this.loadGooglePayScript())return y.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 y.info("Google Pay is not available in this browser/device"),!1;if(this.clientOptions?.existingPaymentMethodRequired&&l===!1)return y.info("Google Pay: existingPaymentMethodRequired is true but no existing payment method is available"),!1}catch(s){return y.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)&&y.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:uo,apiVersionMinor:po,allowedPaymentMethods:[this.allowedPaymentMethod],existingPaymentMethodRequired:this.clientOptions?.existingPaymentMethodRequired}}async render(e,{style:{shadowRoot:r}={}}={style:{}}){if(!this.client)return void y.error("Google Pay client not initialized. Call setup() first.");let i=this.client.createButton({buttonType:this.clientOptions?.buttonType??Ou,buttonColor:this.clientOptions?.buttonColor??_u,buttonSizeMode:this.clientOptions?.buttonSizeMode??Gu,buttonRadius:this.clientOptions?.buttonRadius,buttonLocale:this.clientOptions?.buttonLocale,buttonBorderType:this.clientOptions?.buttonBorderType,onClick:n=>this.handleClick(n),buttonRootNode:r??void 0});e.appendChild(i)}async handleClick(e){if(this.disabled)return;if(!this.client)return void y.error("Google Pay client not available");let r=this.callbacks.onStart();Le({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:P.GOOGLE_PAY});try{let i=await this.client.loadPaymentData(this.buildPaymentDataRequest()),{action:n}=await r;if(n==="abort")throw new N({message:"Payment creation aborted",code:L.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type});await this.processPaymentData(i)}catch(i){if(i.statusCode==="CANCELED")return void this.context.clientSessionApi.unselectPaymentMethod();y.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:r,error:i}=await this.context.pciApi.postGooglePayPaymentInstruments({flow:"GATEWAY",network:e.paymentMethodData.info?.cardNetwork??"OTHER",merchant_id:this.config.options.merchantId,encrypted_payload:Wt.encode(e.paymentMethodData.tokenizationData.token)});if(i||!r)throw this.callbacks.onFinish(void 0,i),i??new K({code:L.TOKENIZATION_ERROR,message:"Failed to tokenize payment data",paymentMethod:P.GOOGLE_PAY});this.callbacks.onFinish(r)}async updateBillingAddress(e){let r=e.paymentMethodData.info?.billingAddress;if(r){let i=yi(r);await this.context.clientSessionApi.setBillingAddress(i)}else y.warn("Google Pay: Could not retrieve billing address from payment data")}async updateShippingDetails(e){let r=e.shippingAddress,i=e.email,n=r?.phoneNumber;if(r||n||i){let o=r?yi(r):void 0;await this.context.clientSessionApi.setShippingAddress(o,n,i)}else y.warn("Google Pay: No shipping address, phone number, or email found in payment data")}async handlePaymentDataChanged(e){let r=e.callbackTrigger;try{if(r==="SHIPPING_OPTION"){let i=e.shippingOptionData?.id;return i&&await this.context.clientSessionApi.selectShippingMethod(i),{newTransactionInfo:this.getCurrentTransactionInfo()}}if(r==="SHIPPING_ADDRESS"||r==="INITIALIZE"){let i=e.shippingAddress;if(i){let s=yi(i);await this.context.clientSessionApi.setShippingAddress(s)}let n=this.getShippingModule(),o=n?.shippingMethods||[];return{...this.clientOptions?.requireShippingMethod&&o.length>0&&{newShippingOptionParameters:{shippingOptions:co(o),defaultSelectedOptionId:n?.selectedShippingMethod||o[0]?.id}},newTransactionInfo:this.getCurrentTransactionInfo()}}return{newTransactionInfo:this.getCurrentTransactionInfo()}}catch(i){return y.errorWithDatadog("Google Pay: Error handling payment data change",{error:i}),{error:{reason:"OTHER_ERROR",message:"An error occurred while processing your request",intent:r==="SHIPPING_OPTION"?"SHIPPING_OPTION":"SHIPPING_ADDRESS"}}}}getShippingModule(){return this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options}getCurrentTransactionInfo(){let{countryCode:e,currencyCode:r,merchantAmount:i,totalOrderAmount:n}=this.context.configuration.clientSession.order;return{countryCode:e,currencyCode:r,displayItems:this.getDisplayItems(),totalPriceStatus:"FINAL",totalPrice:pr(i??n,r),totalPriceLabel:"Total"}}getDisplayItems(){let e=this.context.configuration.clientSession.order,{currencyCode:r,merchantAmount:i,lineItems:n,fees:o,shipping:s}=e,l=this.clientOptions?.requireShippingMethod,c=[];return i?(c.push({label:this.translate(Zr.SUBTOTAL,Wr.SUBTOTAL),type:"SUBTOTAL",price:pr(i,r)}),c):(n&&n.length>0&&n.forEach(u=>{c.push({label:u.description||this.translate(Zr.ITEM,Wr.ITEM),type:"LINE_ITEM",price:pr(u.amount,r)})}),o&&o.length>0&&o.filter(u=>u.amount!==0).forEach(u=>{c.push({label:u.type||u.description||this.translate(Zr.FEE,Wr.FEE),type:"LINE_ITEM",price:pr(u.amount,r)})}),l&&s&&s.amount!==0&&c.push({label:s.methodName||this.translate(Zr.SHIPPING,Wr.SHIPPING),type:"LINE_ITEM",price:pr(s.amount,r)}),c)}get allowedCardNetworks(){let e=this.context.configuration.clientSession.paymentMethod?.orderedAllowedCardNetworks;if(!e||e.length===0)return mo;let r=e.map(i=>Du[i]).filter(i=>!!i);return r.length>0?r:mo}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,r=this.clientOptions?.emailRequired,i=this.clientOptions?.requireShippingMethod,n=this.getShippingModule(),o=n?.shippingMethods,s=n?.selectedShippingMethod;return{apiVersion:uo,apiVersionMinor:po,...r&&{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:co(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}}}]}}},Ku="https://x.klarnacdn.net/kp/lib/v1/api.js",ia=class extends Error{constructor(){super("Klarna authorization cancelled by user"),this.name="KlarnaUserCancelledError"}},na=class extends ge{constructor(){super(...arguments);A(this,"session",null);A(this,"selectedCategoryId",null)}getCategories(){let e=this.session?.categories??[],r=this.context.clientOptions.klarna?.allowedPaymentCategories;return r?r.map(i=>e.find(n=>n.identifier===i)).filter(i=>i!=null):e}setSelectedCategory(e){this.selectedCategoryId=e}async setup(){try{return await ji(Ku,{crossorigin:""}),window.Klarna?.Payments?(this.session=await this.createSession(),this.session?this.getCategories().length===0?(y.warn("No Klarna payment categories available"),!1):(window.Klarna.Payments.init({client_token:this.session.clientToken}),!0):!1):(y.error("Klarna SDK failed to load"),!1)}catch(e){return y.error("Klarna setup failed",e),!1}}get isRecurring(){return this.context.clientOptions.klarna?.paymentFlow==="PREFER_VAULT"}async createSession(){let{clientSession:e}=this.context.configuration,r=e.order,i={localeCode:this.context.locale,countryCode:r?.countryCode??"",currencyCode:r?.currencyCode??""},n;if(this.isRecurring)n={sessionType:"RECURRING_PAYMENT",paymentMethodConfigId:this.config.id,localeData:i,description:this.context.clientOptions.klarna?.recurringPaymentDescription};else{if(!r?.lineItems||r.lineItems.length===0)return y.error("Klarna requires order.lineItems to be provided"),null;let l=r.lineItems.map(u=>({name:u.name||u.description||"",unitAmount:u.amount,reference:u.itemId,quantity:u.quantity,discountAmount:u.discountAmount,taxCode:u.taxCode,taxAmount:u.taxAmount,productType:u.productType})),c=r.merchantAmount??r.totalOrderAmount??0;n={sessionType:"ONE_OFF_PAYMENT",paymentMethodConfigId:this.config.id,localeData:i,totalAmount:c,orderItems:l}}let{data:o,error:s}=await this.context.coreApi.createKlarnaSession(n);return s||!o?(y.error("Failed to create Klarna session",s),null):o}async renderCategory(e){if(!window.Klarna?.Payments)throw new K({message:"Klarna SDK not loaded",code:L.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{Payments:r}=window.Klarna,i=(typeof e.containerId=="string",e.containerId);return e.onHeightChange&&r.on("heightChanged",e.onHeightChange),new Promise((n,o)=>{r.load({container:i,payment_method_category:e.paymentMethodCategoryId},s=>{s.error?o(new K({message:`Klarna load failed: ${s.error.invalid_fields?.join(", ")}`,code:L.TOKENIZATION_ERROR,paymentMethod:this.config.type})):(this.selectedCategoryId=e.paymentMethodCategoryId,n())})})}async authorize(e){if(!window.Klarna?.Payments)throw new K({message:"Klarna SDK not loaded",code:L.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{Payments:r}=window.Klarna;return new Promise(i=>{r.authorize({payment_method_category:e},void 0,i)})}async finalizeSession(){if(!this.session)return null;let{data:e,error:r}=await this.context.coreApi.finalizeKlarnaSession({sessionId:this.session.sessionId,paymentMethodConfigId:this.config.id});return r||!e?(y.error("Failed to finalize Klarna session",r),null):e}async createCustomerToken(e){if(!this.session)return null;let r=this.context.clientOptions.klarna?.recurringPaymentDescription;if(!r)return y.error("klarna.recurringPaymentDescription must be provided for PREFER_VAULT flow"),null;let{clientSession:i}=this.context.configuration,n=i.order,{data:o,error:s}=await this.context.coreApi.createKlarnaCustomerToken({paymentMethodConfigId:this.config.id,sessionId:this.session.sessionId,authorizationToken:e,description:r,localeData:{localeCode:this.context.locale,countryCode:n?.countryCode??"",currencyCode:n?.currencyCode??""}});return s||!o?(y.error("Failed to create Klarna customer token",s),null):o}async tokenize(){if(!this.selectedCategoryId)throw new K({message:"No Klarna payment category selected",code:L.TOKENIZATION_ERROR,paymentMethod:this.config.type});let e=await this.authorize(this.selectedCategoryId);if(!e.approved&&!e.error)throw y.debug("Klarna authorization cancelled by user"),new ia;if(!e.approved||!e.authorization_token){let r=e.error?.invalid_fields?.join(", ")||"Authorization failed";throw new K({message:`Klarna authorization failed: ${r}`,code:L.TOKENIZATION_ERROR,paymentMethod:this.config.type})}return this.isRecurring?this.tokenizeWithCustomerToken(e.authorization_token):this.tokenizeWithAuthToken(e.authorization_token)}async tokenizeWithAuthToken(e){let r=await this.finalizeSession();if(!r)throw new K({message:"Failed to finalize Klarna session",code:L.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{data:i,error:n}=await this.context.pciApi.postKlarnaPaymentInstruments({klarnaAuthorizationToken:e,sessionData:r.sessionData});if(n||!i)throw n??new K({message:"Failed to tokenize Klarna payment",code:L.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}async tokenizeWithCustomerToken(e){let r=await this.createCustomerToken(e);if(!r)throw new K({message:"Failed to create Klarna customer token",code:L.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{data:i,error:n}=await this.context.pciApi.postKlarnaCustomerTokenInstruments({klarnaCustomerToken:r.customerTokenId,sessionData:r.sessionData});if(n||!i)throw n??new K({message:"Failed to tokenize Klarna payment",code:L.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new Error("Payment aborted"));let r=await this.tokenize();this.callbacks.onFinish(r)}catch(e){if(e instanceof ia)return void this.context.clientSessionApi.unselectPaymentMethod();this.callbacks.onFinish(void 0,e)}}async startWithCategory(e){return this.selectedCategoryId=e,this.start()}};function qi(a,t){return a?.redirect?.returnUrl?!0:(y.warn(`[Primer SDK] ${t} is enabled in your client session but \`options.redirect.returnUrl\` is missing. This payment method may redirect the customer to an external page; without a return URL the customer cannot be brought back. The payment method will not be available in this checkout. Set \`options.redirect.returnUrl\` to a page that re-initializes the SDK with the \`?clientToken=...\` query parameter Primer appends on return.`),!1)}function Fu(a,t){if(a?.redirect?.returnUrl)return;let e=typeof window<"u"&&window.location?window.location.href:"";y.warn(`[Primer SDK] Initiating ${t} which may redirect the customer to an external page, but no \`options.redirect.returnUrl\` is configured. The customer will be returned to the current page (${e}). Set \`options.redirect.returnUrl\` to control the return destination.`),Le({eventName:"REDIRECT_RETURN_URL_NOT_CONFIGURED",paymentMethod:t})}function Qi(a,t,e){let r="";try{r=new URL(a).origin}catch{r=""}y.info(`[Primer SDK] Redirecting to ${t} payment page at ${r} (${e})`),Le({eventName:"PAYMENT_REDIRECT_TO_THIRD_PARTY",paymentMethod:t,redirectDestinationUrl:r,redirectReason:e})}function ho(a,t={}){y.info(`[Primer SDK] Returned from third-party payment page (${a})`),Le({eventName:"PAYMENT_RETURNED_FROM_THIRD_PARTY",intent:a,...t})}function vr(a){return a?new Promise(t=>{setTimeout(t,a)}):Promise.resolve()}var Uu=100;function Vu({height:a,name:t,url:e="",width:r}){let i=new Set,n=window.open(e,t,$u({height:a,width:r}));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),Hu(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 Hu=a=>new Promise(t=>{let e=setInterval(()=>{a.closed&&(clearInterval(e),t())},Uu)});function $u(a){let t=Yu({parent:{left:window.screenLeft,top:window.screenTop,height:window.outerHeight,width:window.outerWidth},popup:a});return zu(t)}var Yu=({parent:a,popup:t})=>({left:a.left+(a.width-t.width)/2,top:a.top+(a.height-t.height)/2,height:t.height,width:t.width}),zu=a=>Object.entries(a).map(t=>t.join("=")).join(",");async function Xi(a){let t=Vu({name:a.name,height:a.displayMetadata.popup?.height??500,width:a.displayMetadata.popup?.width??1e3});return a.context.dialogProvider.show({htmlContent:ju({logoSrc:fo(a.displayMetadata),text:a.context.translate("paymentMethodPopupOverlayDescription","Having trouble viewing the {paymentMethodName} payment page? We'll help you find it!").replace("{paymentMethodName}",a.name),backgroundColor:go(a.displayMetadata)}),showCloseButton:!0,size:"flex",cta:{label:a.context.translate("paymentMethodPopupOverlayBringBackThePaymentPage","Bring back the payment page"),icon:"chevron-left",onClick:()=>{t?.focus()}}}).then(()=>{t?.isOpen&&t.close()}),t?.setContent(Zu({name:a.name,background:go(a.displayMetadata),logoSrc:fo(a.displayMetadata),logoAlt:a.name,message:`Loading ${a.name}...`})),t&&(await vr(300),!t.isOpen)?void a.context.dialogProvider.close():t}var ju=({logoSrc:a,text:t,backgroundColor:e})=>{let r=document.createElement("div");r.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: ${e};border-radius:var(--primer-radius-small);`);let n=document.createElement("img");n.src=a,i.appendChild(n),n.setAttribute("style","height:100%;"),r.appendChild(i);let o=document.createElement("p");return o.setAttribute("style","max-width: 300px;text-align: center;"),o.innerText=t,r.appendChild(o),r},Zu=({name:a,background:t,logoSrc:e,logoAlt:r,message:i})=>`<html>
|
|
7
7
|
<head>
|
|
8
8
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
9
9
|
<style>
|
|
@@ -143,7 +143,7 @@ import{a as $r,b as q,c as mi,d,e as A}from"./chunks/chunk.QNO3CTH5.js";var ac=q
|
|
|
143
143
|
flex: 1;
|
|
144
144
|
`),e.appendChild(i),{container:e,setIframeSrc:()=>{i.src=t}}}};async function _p(a,t){if(!vi(t))return t;function e(r){r.requiredAction?.clientToken&&a.context.updateClientToken(r.requiredAction.clientToken)}try{e(t);let r=await a.handleRequiredAction(t);if(vi(r)&&r.requiredAction?.name==="3DS_AUTHENTICATION"){let i=new Ii(a.context);e(r),r=await i.handleRequiredAction(r)}if(vi(r)&&r.requiredAction?.name==="PROCESSOR_3DS"){let i=new Ni(a.context);e(r),r=await i.handleRequiredAction(r)}return{...r,id:t.id}}finally{a.context.restoreClientToken()}}function vi(a){return!a.cancelled&&a.status!=="FAILED"}async function wi(a,{paymentMethod:t,token:e,fetchPayment:r}){let i,n;try{if(i=await r(),t&&(i=await _p(t,i),i.cancelled))return}catch(o){n=o}Ke(a,i,n,e,t?.config.type)}async function Mo(a,t){let e=t.config.type,r=a.onBeforePaymentCreate?new Promise(i=>{let n=setTimeout(()=>{y.warn("onBeforePaymentCreate did not resolve within 10 seconds. Primer SDK will remain in a loading state until `continuePaymentCreation` or `abortPaymentCreation` is called.")},1e4);a.onBeforePaymentCreate?.({paymentMethodType:e},{continuePaymentCreation:o=>{clearTimeout(n),y.log(`Continuing payment creation for ${e}`),o?.idempotencyKey&&t.setIdempotencyKey(o.idempotencyKey),a.onPaymentCreationStart?.(),i({action:"continue"})},abortPaymentCreation:()=>{clearTimeout(n),y.log(`Aborting payment creation for ${e}`),i({action:"abort"})}})}):Promise.resolve({action:"continue"});return await t.context.clientSessionApi.selectPaymentMethod(e),Le({eventName:"PAYMENT_PROCESSING_STARTED",paymentMethod:e}),r}async function Fe(a,t,e){if(t.setCallbacks({onStart:()=>Mo(a,t),onFinish:(r,i)=>{To(a,t,r,i)}}),!e)return t.start();{let r,i;try{let{action:n}=await Mo(a,t);if(n==="abort")throw new N({message:"Payment creation aborted",code:L.PAYMENT_CREATION_ABORTED,paymentMethod:t.config.type});i=await t.tokenizeVaulted(e.id)}catch(n){r=n}return To(a,t,i,r)}}async function To(a,t,e,r){if(!e||r)return void Ke(a,void 0,r,e,t.config.type);let i=t.context.configuration?.clientSession;await wi(a,{paymentMethod:t,token:e,fetchPayment:()=>i?.approvalMode==="MANUAL"?Lp(a,t,e):t.createPayment(e)})}var Po=Symbol("PROXY_MARKER");function en({namespace:a,onMessage:t,sendMessage:e}){function r(i,n){return new Proxy(i,{get(o,s,l){if(s==="then")return null;if(o[Po])return Reflect.get(o,s,l);let c=()=>{};return c[Po]=!0,r(c,[...n,s])},apply(o,s,l){return new Promise((c,u)=>{try{let m=[],g=l.map(x=>{if(typeof x!="function")return x;{let w=he();return m.push(w),t(D=>{D.namespace===a&&D.sender===Ci.PROVIDER&&D.type===bi.CALLBACK&&D.id===w&&x(...D.data)}),w}}),v=he(),M=t(x=>{x.namespace===a&&x.sender===Ci.PROVIDER&&x.type===bi.APPLY&&x.id===v&&(x.error?u(new Error(x.error)):c(x.data),M?.())}),B={type:bi.APPLY,sender:Ci.INJECTOR,id:v,path:n,args:g,callbackIds:m,timeStamp:Date.now(),namespace:a};e(B)}catch(m){u(m)}})}})}return r({},[])}var bi={APPLY:"apply",CALLBACK:"callback"},Ci={PROVIDER:"provider",INJECTOR:"injector"};function Li(a,t){let e=t?.input?.base?.height;e&&(a.style.height=typeof e=="number"?`${e}px`:e)}function Gp(a,t,e,r={}){let i=[],n="LOCAL",o={[ie.cardNumber]:void 0,[ie.cardExpiryDate]:void 0,[ie.cardSecurityCode]:void 0,[ie.cardholderName]:void 0},s=!1,l=()=>{s=!0,e.iframes.cardNumber.remove(),e.iframes.cardSecurityCode.remove(),e.iframes.cardExpiryDate.remove(),e.iframes.cardholderName.remove()};t.subscribeToTeardown(()=>{l()});let c={createHostedInputs:()=>{let u=m=>{let g=new Map,v={};return{getOptions:()=>({placeholder:v.placeholder??"",ariaLabel:v.ariaLabel??"",style:v.style}),setOptions:M=>{v={...v,...M},Li(e.iframes[m],M.style),e.iframes[m].setAttribute("title",M.ariaLabel||""),o[m]?.setOptions(M)},render:(M,B)=>{v={...v,...B};let x=e.iframes[m];if(!x)return y.errorWithDatadog(`No iframe found for ${m}`),Promise.resolve();let w;return w=typeof M=="string"?document.getElementById(M):M,w?(Li(x,B.style),w.appendChild(x),new Promise(D=>{x.onload=()=>{if(s){y.warn(`Teardown was already called, aborting render for ${m}`),x.remove(),D();return}o[m]=en({namespace:`${t.checkoutSessionId}-${m}`,onMessage:V=>{let J=ur=>V(ur.data);return window.addEventListener("message",J),()=>window.removeEventListener("message",J)},sendMessage:V=>{x.contentWindow?.postMessage(V,"*")}}),e.iframes[m].setAttribute("title",B.ariaLabel||"");let U=a.cardholderName??a.card?.cardholderName,{defaultValue:F,...z}=U??{};o[m].setOptions({...B,orderedAllowedCardNetworks:t.configuration.clientSession.paymentMethod.orderedAllowedCardNetworks,cardholderName:z}),o[m].setBinDataLoadingChange(V=>{V&&r.onCardNetworksLoading?.(),r.onBinDataLoadingChange?.(V)}),o[m].setOnBlur(()=>{try{g.get("blur")?.()}catch(V){y.errorWithDatadog(`Blur listener error for ${m}`,{error:V})}}),o[m].setOnFocus(()=>{try{g.get("focus")?.()}catch(V){y.errorWithDatadog(`Focus listener error for ${m}`,{error:V})}}),o[m].setOnInput(V=>{let J={...V,errorCode:V.error,active:V.focused};try{g.get("input")?.(J),g.get("change")?.(J)}catch(ur){y.errorWithDatadog(`Input listener error for ${m}`,{error:ur})}}),o[m].setOnEnter(()=>{try{g.get("enter")?.()}catch(V){y.errorWithDatadog(`Enter listener error for ${m}`,{error:V})}}),m===ie.cardNumber&&(o[m].setBinDataApiConfig(t.configuration.binDataUrl,t.decodedClientToken.accessToken),o[m].setOnCardNetworksChange((V,J,ur)=>{if(J!==n||Kp(i,V)){i=V,n=J;let{cardNetworkChangeEventData:Rc,binDataAvailableEventData:xc}=Lu({networks:i,source:n},t.configuration.clientSession.paymentMethod.orderedAllowedCardNetworks);r.onCardNetworksChange?.(Rc),r.onBinDataAvailable?.({...xc,firstDigits:ur})}}))},D()})):(y.error(`Container not found for ${m}:`,M),Promise.resolve())},addEventListener:(M,B)=>{g.set(M,B)},focus:()=>{let M=e.iframes[m];if(M&&M.contentWindow)try{o[m]?.focus()}catch(B){y.errorWithDatadog(`Focus send error for ${m}`,{error:B})}else y.warn(`Focus failed for ${m} - iframe not available`)},blur:()=>{let M=e.iframes[m];if(M&&M.contentWindow)try{o[m]?.blur()}catch(B){y.errorWithDatadog(`Blur send error for ${m}`,{error:B})}},setDisabled:M=>{o[m]?.setDisabled(M)}}};return{cardNumberInput:u(ie.cardNumber),cardholderNameInput:u(ie.cardholderName),expiryInput:u(ie.cardExpiryDate),cvvInput:u(ie.cardSecurityCode)}},removeHostedInputs:l,submit:async u=>{if((await c.validate()).valid)return await t.apiController.setPreferredNetwork(u?.cardNetwork),Fe(a,e)},validate:async()=>{let u=(await Promise.all(Object.entries(o).filter(g=>g[1]!=null).map(([g,v])=>v.getFieldState().then(M=>[g,M]).catch(()=>{})))).filter(g=>g!==void 0),m=[];for(let[g,v]of u)!v.valid&&v.error&&m.push({field:g,name:g,error:v.error,message:v.error});return{valid:m.length===0,validationErrors:m}},reset:()=>{Object.values(o).forEach(u=>{u?.reset()}),t.apiController.setPreferredNetwork(void 0)},setCardholderName:u=>{try{o[ie.cardholderName]?.setCardholderName(u)}catch(m){y.errorWithDatadog("SetCardholderName error",{error:m})}}};return c}function Kp(a,t){if(a.length!==t.length)return!0;let e=t.map(({network:r})=>r);return!a.every(({network:r})=>e.includes(r))}function Fp(a,t,e){return{createButton:()=>({render:async(r,i)=>{await Fe(a,e);let n=typeof r=="string"?document.getElementById(r):r;if(!n)throw new N({code:Zc.CONTAINER_NOT_FOUND,message:`Container with id "${typeof r=="string"?r:"element"}" not found in the DOM.`});await e.render(n,i)},setDisabled:r=>e.setDisabled(r)})}}function Up(a,t,e){return{start:()=>Fe(a,e)}}function Vp(a,t,e){return{start:async r=>(r?.blikCode&&e.setBlikCode(r.blikCode),Fe(a,e))}}async function Hp(a,t,e,r){if(r?.onPaymentMethodCategoriesChange){let i=e.getCategories();i.length>0&&r.onPaymentMethodCategoriesChange(i.map(n=>({id:n.identifier,name:n.name,descriptiveAssetUrl:n.descriptiveAssetUrl,standardAssetUrl:n.standardAssetUrl})))}return{renderCategory:async i=>e.renderCategory(i),start:async i=>(e.setSelectedCategory(i.paymentMethodCategoryId),Fe(a,e))}}function $p(a,t,e,r){if(r?.onPaymentOptionsChange){let i=e.getOptions();i.length>0&&r.onPaymentOptionsChange(i)}return{getPaymentOptions:()=>e.getOptions(),selectOption:i=>{e.selectOption(i)},start:async()=>Fe(a,e)}}function Yp(a,t,e){return{start:async r=>(r?.phoneNumber&&e.setPhoneNumber(r.phoneNumber),Fe(a,e))}}function zp(a,t,e){return{start:r=>(e.setOnQRCodeReceived(r.onQRCodeReceived),Fe(a,e)),stop:()=>e.stop()}}var jp=new Set(["ADYEN_BANCONTACT_PAYCONIQ_REDIRECTION","XFERS_PAYNOW_REDIRECTION","OMISE_PROMPTPAY_REDIRECTION","RAPYD_PROMPTPAY_REDIRECTION"]);function Zp(a){return jp.has(a.intent)&&"statusUrl"in a&&("qrCode"in a||"qrCodeUrl"in a)}function Wp(a){return"qrCode"in a?a.qrCode:a.qrCodeUrl}var ca=class extends ge{constructor(){super(...arguments);A(this,"pollController",new AbortController);A(this,"onQRCodeReceived")}setOnQRCodeReceived(e){this.onQRCodeReceived=e}stop(){this.pollController.abort(),this.context.clientSessionApi.unselectPaymentMethod(),this.onQRCodeReceived=void 0}async start(){this.pollController=new AbortController;let e=this.pollController.signal;try{let{action:r}=await this.callbacks.onStart();if(e.aborted)return;if(r==="abort")return this.callbacks.onFinish(void 0,new N({message:"Payment creation aborted",code:L.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let i=await this.tokenize();if(e.aborted)return;this.callbacks.onFinish(i)}catch(r){if(e.aborted)return;this.callbacks.onFinish(void 0,r)}}async tokenize(){await this.context.clientSessionApi.selectPaymentMethod(this.config.type);let{error:e,data:r}=await this.context.pciApi.postRedirectPaymentInstruments({type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:this.context.locale,platform:Ze()?"MOBILE_WEB":"WEB",browserInfo:ht()}});if(e||!r)throw e??new K({code:L.TOKENIZATION_ERROR,message:"Unable to tokenize payment method",paymentMethod:this.config.type});return r}async handleRequiredAction(e){try{if(this.pollController.signal.aborted)return{...e,cancelled:!0};let r=e.requiredAction?.clientToken;if(!r)throw new K({message:"No client token provided"});let i=We(r);if(!Zp(i))throw new K({message:"Invalid QR code client token"});let n=Wp(i);this.onQRCodeReceived?.(n),y.debug(`QR code received for ${this.config.type}`);let o=await this.context.pciApi.pollResumeStatus(i.statusUrl,{signal:this.pollController.signal,timeout:864e5,isComplete:l=>l.data?.status==="COMPLETE"});if(o.error){if(this.pollController.signal.aborted)return{...e,cancelled:!0};throw o.error}let s=o.data?.id;if(!s){let l=await this.context.pciApi.getResumeStatus(i.statusUrl);if(l.error||!l.data?.id)throw l.error??new Error("Unable to get resume token");s=l.data.id}return await this.resumePayment(e.id,s)}catch(r){if(this.pollController.signal.aborted)return{...e,cancelled:!0};throw this.pollController.abort(),r}}};function Jp(a,t){return{"Content-Type":"application/json","primer-client-token":a,"primer-sdk-client":"WEB","primer-sdk-version":wu,"primer-sdk-checkout-session-id":t,"x-api-version":"2.4"}}var Ri=({backendErrorId:a,status:t})=>a==="TransactionRequestIdempotencyKeyAlreadyExists"?L.IDEMPOTENCY_KEY_ALREADY_EXISTS:t?t>=500?W.SERVER_ERROR:{400:W.BAD_REQUEST,401:W.UNAUTHORIZED,403:W.FORBIDDEN,404:W.NOT_FOUND,408:W.REQUEST_TIMEOUT,409:W.CONFLICT,422:W.VALIDATION_ERROR}[t]??W.REQUEST_ERROR:W.UNEXPECTED;function qp(a,t,e){if(e?.status&&e.status>=400&&e.status<500)return!1;if(e?.status&&e.status>=500)return!0;if(a instanceof Error){let r=a.message.toLowerCase();return r.includes("network")||r.includes("timeout")||r.includes("connection")}return!1}function Qp(a){let n=1e3*Math.pow(1.1,a),o=.1*n*(Math.random()-.5);return n=Math.max(0,n+o),Math.min(n,3e4)}var Xp={attempts:3,retryCondition:qp,delayCalculator:Qp,totalTimeout:3e5};async function em(a,t,e){let r={...Xp,...t.retry},i=[],n=Date.now(),o=t.id??he();for(let l=0;l<=r.attempts;l++)try{let c=await a();if(!c.error)return{...c,retryHistory:i.length>0?i:void 0};if(l===r.attempts||!r.retryCondition(c.error,l,c))return{...c,retryHistory:i};let u=r.delayCalculator(l);if(i.push({attempt:l+1,delay:u,error:c.error,timestamp:Date.now()}),Date.now()-n+u>r.totalTimeout)return{...c,error:new le({message:`Retry total timeout exceeded for ${t.method} ${e}`,code:Ri({status:408}),response:c}),retryHistory:i};await vr(u)}catch(c){i.push({attempt:l+1,delay:0,error:new le({message:`Request failed for ${t.method} ${e}`,code:W.UNEXPECTED,error:c,response:{id:o}}),timestamp:Date.now()})}let s=i[i.length-1]?.error;return{id:o,error:s,retryHistory:i}}var tm=1e3;async function rm(a,t){let e=he(),r=t.interval??tm,i=!1,n=t.timeout!=null?setTimeout(()=>{i=!0},t.timeout):void 0,o=!1,s=()=>{if(!t.continueAfterAbort&&t.signal?.aborted)return!0;let c=o||i;return t.signal?.aborted&&(o=!0),c},l;try{for(;!s();){let c=await a();if(t.isComplete(c))return c;if(s())break;await vr(r)}}catch(c){l=c}finally{n!=null&&clearTimeout(n)}return l?{id:e,error:new le({message:"Poll operation failed",code:W.UNEXPECTED,response:{id:e},error:l})}:i?{id:e,status:408,error:new le({message:"Poll operation timed out",code:W.REQUEST_TIMEOUT,response:{id:e}})}:{id:e,error:new le({message:"Poll operation aborted",code:W.POLLING_ABORTED,response:{id:e}})}}var Jt=class{constructor(t,e="",r={}){A(this,"fetch");A(this,"baseUrl");A(this,"defaultHeaders");this.fetch=t,this.baseUrl=e,this.defaultHeaders=Object.freeze({...r})}setDefaultHeader(t,e){this.defaultHeaders={...this.defaultHeaders,[t]:e}}async executeFetch(t,e){let r={...e,headers:{...this.defaultHeaders,...e?.headers},id:he()};return e?.retry?em(()=>this.fetch(t,{...r,retry:void 0}),r,t):this.fetch(t,r)}async get(t,e){return this.executeFetch(t,{...e,method:"GET"})}async post(t,e,r){return this.executeFetch(t,{...r,method:"POST",body:JSON.stringify(e)})}async delete(t,e){return this.executeFetch(t,{...e,method:"DELETE"})}async poll(t,e,r){return rm(()=>this.get(t,r),e)}};async function am(a,t){let e=t.id??he(),r={id:e};t.headers??(t.headers={}),t.headers["X-Request-Id"]=e;try{let i=await fetch(a,t);if(r.data=await i.json(),r.status=i.status,r.headers=Object.fromEntries(i.headers.entries()),!i.ok){let n=new le({message:`Request failed for ${t.method} ${a}`,code:Ri({backendErrorId:r.data?.error?.errorId,status:r.status}),response:{...r}});r.error=n}}catch(i){let n=new le({message:`Request failed for ${t.method} ${a}`,code:Ri({status:r.status}),response:{...r},error:i});r.error=n}return r}var im="https://goat-assets.production.core.primer.io/icon/gift/medium.svg",nm=["PAY_NL_KAARTDIRECT","MOLLIE_GIFTCARD"],om=["PAY_NL_PAYPAL"],sm="https://goat-assets.production.core.primer.io/brand/logo/paypal/inverted.svg";function lm(a){let e={PAY_NL_PAYPAL:sm}[a.type];return e?{...a,implementationType:"WEB_REDIRECT",displayMetadata:{...a.displayMetadata,button:{...a.displayMetadata.button,iconUrl:{...a.displayMetadata.button.iconUrl,colored:e}}}}:{...a,implementationType:"WEB_REDIRECT"}}function dm(a){return{...a,implementationType:"WEB_REDIRECT",displayMetadata:{...a.displayMetadata,button:{...a.displayMetadata.button,iconUrl:{...a.displayMetadata.button.iconUrl,colored:im},text:"Gift card"}}}}function cm(a){return{...a,paymentMethods:(a.paymentMethods??[]).map(t=>nm.includes(t.type)?dm(t):om.includes(t.type)?lm(t):t)}}var xi=class extends Jt{constructor(){super(...arguments);A(this,"configurationSubscribers",new Set);A(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=cm(e),this.configurationSubscribers.forEach(r=>r(this._configuration))}},Bi=class extends Jt{async getPaymentInstruments(){return this.get(`${this.baseUrl}/payment-instruments`)}async getPaymentInstrumentToken(t){return this.get(`${this.baseUrl}/payment-instruments/${t}`,{retry:{attempts:3}})}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 postMbwayPaymentInstruments(t){return this.postPaymentInstruments(t)}async postKlarnaPaymentInstruments(t){return this.postPaymentInstruments(t)}async postKlarnaCustomerTokenInstruments(t){return this.post(`${this.baseUrl}/payment-instruments`,{paymentInstrument:t,tokenType:"MULTI_USE",paymentFlow:"VAULT"})}async postAdyenKlarnaPaymentInstruments(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)}pollResumeStatus(t,e){return this.poll(t,e)}poll3dsAuth(t,e){return this.poll(t,e)}async postClientSessionPay(t,e){return this.post(`${this.baseUrl}/client-session/${t}:pay`,e)}async getClientSessionInstruction(t){return this.get(`${this.baseUrl}/client-session/${t}?expand=clientInstruction`,{retry:{attempts:3}})}async getClientSession(t){return this.get(`${this.baseUrl}/client-session/${t}`,{retry:{attempts:3}})}pollPayment(t,e){return this.poll(`${this.baseUrl}/payments/${t}?expand=requiredAction`,e,{retry:{attempts:3}})}};async function um(a){return new Promise((t,e)=>{let r=Xo(a,"api"),i=`${ku}#${r}`,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: ${typeof o=="string"?o:"load error"}`))},n.src=i,document.body.appendChild(n))})}var Rt=class Rt extends Jt{constructor(){super(...arguments);A(this,"onClientSessionUpdate");A(this,"onPaymentMethodAction");A(this,"selectedPaymentMethodType",null)}setOnClientSessionUpdate(e){this.onClientSessionUpdate=e}setOnPaymentMethodAction(e){this.onPaymentMethodAction=e}async postClientSessionActions(e){if(e.length===0)return Rt.noActionsResponse;let r=await this.post(`${this.baseUrl}/client-session/actions`,{actions:e}),{data:i}=r;return i&&this.onClientSessionUpdate?.(i),r}async selectPaymentMethod(e,r={}){return this.selectedPaymentMethodType===e||(this.selectedPaymentMethodType=e,this.onPaymentMethodAction?.("PAYMENT_METHOD_SELECTED",{paymentMethodType:e}),e==="PAYMENT_CARD"&&!r.binData)?Rt.noActionsResponse:this.postClientSessionActions([{type:"SELECT_PAYMENT_METHOD",params:{...r,paymentMethodType:e}}])}async unselectPaymentMethod(e,r){return this.onPaymentMethodAction?.("PAYMENT_METHOD_UNSELECTED",{paymentMethodType:this.selectedPaymentMethodType,payment:e,token:r}),this.selectedPaymentMethodType=null,this.postClientSessionActions([{type:"UNSELECT_PAYMENT_METHOD"}])}async selectCardNetwork(e){return this.selectPaymentMethod(P.PAYMENT_CARD,{binData:this.buildCardBinData(e)})}async setBillingAddress(e){let r=this.removeEmptyStringFromObject(e);return Object.values(r).length===0?Rt.noActionsResponse:this.postClientSessionActions([{type:"SET_BILLING_ADDRESS",params:{billingAddress:r}}])}async setShippingAddress(e,r,i){let n=[];return e&&Object.keys(e).some(s=>!!e[s])&&n.push({type:"SET_SHIPPING_ADDRESS",params:{shippingAddress:e}}),r&&n.push({type:"SET_MOBILE_NUMBER",params:{mobileNumber:r}}),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:r,lastName:i}){let n=[];return e&&n.push({type:"SET_EMAIL_ADDRESS",params:{emailAddress:e}}),r&&n.push({type:"SET_CUSTOMER_FIRST_NAME",params:{firstName:r}}),i&&n.push({type:"SET_CUSTOMER_LAST_NAME",params:{lastName:i}}),this.postClientSessionActions(n)}buildCardBinData(e){let{backend:r}=jt(e);return{network:r,issuer_name:null,product_code:r,product_name:r,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 r={...e};for(let i in r)r[i]===""?delete r[i]:typeof r[i]=="object"&&r[i]!==null&&!Array.isArray(r[i])&&(r[i]=this.removeEmptyStringFromObject(r[i]));return r}};A(Rt,"noActionsResponse",{data:{},error:void 0,headers:{},status:200,id:""});var Di=Rt,Oi=class extends Jt{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 createKlarnaSession(t){return this.post(`${this.baseUrl}/klarna/payment-sessions`,t)}async finalizeKlarnaSession(t){return this.post(`${this.baseUrl}/klarna/payment-sessions/finalize`,t)}async createKlarnaCustomerToken(t){return this.post(`${this.baseUrl}/klarna/customer-tokens`,t)}async getPaymentMethodOptions(t){return this.get(`${this.baseUrl}/payment-method-options/${t}/payment-types`)}};async function pm(a,{locale:t,dialogProvider:e,translate:r,clientOptions:i,integrationType:n="HEADLESS"}){let o=he(),s=We(a),l=await um(o),c=en({namespace:`api-controller-${o}`,onMessage:F=>{let z=V=>{if(V.data?.data?.error?.name==="RequestError"){let J=Object.assign(new le({...V.data.data.error}),V.data.data.error);typeof J.error=="object"&&"message"in J.error&&(J.error=Object.assign(new Error(J.error.message),{stack:J.error.stack})),V.data.data.error=J}return F(V.data)};return window.addEventListener("message",z),()=>window.removeEventListener("message",z)},sendMessage:F=>{l.contentWindow?.postMessage(F,"*")}}),u=Jp(s.accessToken,o),m=new xi(am,s.configurationUrl,u),g=Date.now(),{error:v}=await m.getConfiguration();if(v||!m.configuration)throw new Error(`Failed to fetch configuration: ${v}`);let M=c.fetch.bind(c),B=new Bi(M,m.configuration.pciUrl,u),x=new Oi(M,m.configuration.coreUrl,u),w=new Di(M,m.configuration.pciUrl,u);w.setOnClientSessionUpdate(F=>{m.configuration=F});let D=F=>{m.setDefaultHeader("primer-client-token",F),B.setDefaultHeader("primer-client-token",F),x.setDefaultHeader("primer-client-token",F),w.setDefaultHeader("primer-client-token",F)},U=new Set;return{get configuration(){return m.configuration},onClientConfigurationUpdate(F){return m.subscribe(F)},checkoutSessionId:o,integrationType:n,apiController:c,configurationApi:m,pciApi:B,coreApi:x,clientSessionApi:w,dialogProvider:e,decodedClientToken:s,locale:t||navigator.language||navigator.languages[0]||"en",configurationFetchStartTime:g,translate:r??((F,z)=>z),clientOptions:i,updateClientToken(F){try{D(We(F).accessToken)}catch{}},restoreClientToken(){D(s.accessToken)},async refreshClientConfiguration(){let{data:F,error:z}=await m.getConfiguration();return z||!F?(y.warn("Failed to refresh client configuration:",z),!1):(m.configuration=F,!0)},subscribeToTeardown(F){return U.add(F),()=>{U.delete(F)}},teardown(){l.remove(),U.forEach(F=>F())}}}var _i=class extends ge{constructor(){super(...arguments);A(this,"popup");A(this,"shouldRedirect",!1);A(this,"redirectReason","force_redirect")}async setup(){return qi(this.context.clientOptions,this.config.type)}async start(){try{let e=this.config.forceRedirect||!!this.context.clientOptions.redirect?.forceRedirect,r=!!this.context.clientOptions.redirect?.returnUrl;(e||Xr()||Ze()&&r)&&(this.shouldRedirect=!0,this.redirectReason=e?"force_redirect":Xr()?"in_app_browser":"mobile_device");let i=this.callbacks.onStart();this.shouldRedirect||(this.popup=await Xi({name:this.config.name,context:this.context,displayMetadata:this.config.displayMetadata}),this.popup?.isOpen||(this.shouldRedirect=!0,this.redirectReason="popup_blocked"));let{action:n}=await i;if(n==="abort")throw new N({message:"Payment creation aborted",code:L.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type});let o=await this.tokenize();this.callbacks.onFinish(o)}catch(e){this.cleanup(),this.callbacks.onFinish(void 0,e)}}async tokenize(){let{error:e,data:r}=await this.context.pciApi.postRedirectPaymentInstruments({type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:this.context.locale,platform:Ze()?"MOBILE_WEB":"WEB",browserInfo:ht(),merchantRedirectUrl:this.context.clientOptions.redirect?.returnUrl,redirectMode:this.shouldRedirect?"REDIRECT":"POPUP"}});if(e||!r)throw e??new K({message:"Unable to tokenize payment method",code:L.TOKENIZATION_ERROR});return r}async handleRequiredAction(e){try{let r=e.requiredAction?.clientToken;if(!r)throw new K({message:"No client token provided"});let i=We(r);if(!Jo(i,this.config.type))throw new K({message:"Invalid client token"});if(this.shouldRedirect&&(Qi(i.redirectUrl,this.config.type,this.redirectReason),window.location.assign(i.redirectUrl),await new Promise(()=>{})),!this.popup?.isOpen)return this.unselect(e),this.cleanup(),{...e,cancelled:!0};this.popup?.setUrl(i.redirectUrl);let n=new Promise(m=>{this.popup?.onClose(()=>{y.debug("Popup closed"),m({id:"",popupClosed:!0})})}),o=new AbortController,s=this.context.pciApi.pollResumeStatus(i.statusUrl,{continueAfterAbort:!0,signal:o.signal,isComplete:m=>!!m.error||m.data?.status==="COMPLETE"}).then(m=>m.error?{error:m.error,id:"",popupClosed:!1}:{id:m.data?.id??"",popupClosed:!1}),l=await Promise.race([n,s]);o.abort(),this.cleanup();let c=await s;if(c.id&&(l=c),"error"in l)throw l.error;if("popupClosed"in l&&l.popupClosed&&!this.context.clientOptions.redirect?.resumePaymentOnPopupClosure)return this.unselect(e),{...e,cancelled:!0};let u=l.id;if(!u){let m=await this.context.pciApi.getResumeStatus(i.statusUrl);if(m.error||!m.data?.id)throw m.error??new Error("Unable to get resume token");u=m.data.id}return await this.resumePayment(e.id,u)}catch(r){throw this.cleanup(),r}}cleanup(){this.popup?.close(),this.context.dialogProvider.close()}unselect(e){this.context.clientSessionApi.unselectPaymentMethod(e)}},Gi=class{constructor(t,e){A(this,"currentState");A(this,"stateProcessor");A(this,"handlerRegistry");this.stateProcessor=t,this.handlerRegistry=e}async run(t){let e=await this.stateProcessor.initialize(t??{});return this.handle(e)}async resume(t){let e=await this.stateProcessor.resume(t);return this.handle(e)}async handleEvent(t){if(!this.currentState)throw new Error("handleEvent() called before run()");y.debug("Orchestrator handling event",t);let e=await this.stateProcessor.applyEvent(this.currentState,t);return this.handle(e)}async handle(t){if(this.currentState=t.newState,t.error)throw new Error(t.error.message);if(t.terminal)return y.debug("Orchestrator reached terminal",t.terminal),t.terminal;if(!t.action)return y.debug("Orchestrator waiting for external event"),null;let e=t.action;y.debug(`Executing ${e.type}`,e.params);let r,i;try{let o=await this.handlerRegistry.execute(e.type,e);r=o.outcome,i=o.data??{}}catch(o){y.warn(`Handler failed for ${e.type}`,o),r="error",i={error:o instanceof Error?o.message:"Unknown error"}}let n=await this.stateProcessor.applyResult(this.currentState,e.id,r,i);return this.handle(n)}},Ki=class{constructor(){A(this,"handlers",new Map)}register(t,e){this.handlers.set(t,e)}get(t){return this.handlers.get(t)}async execute(t,e){let r=this.handlers.get(t);return r?r.execute(e):{outcome:"unsupported"}}finishAll(){this.handlers.forEach(t=>t.onFinish?.())}},mm=["https://sdk.primer.io/web/","https://sdk.dev.primer.io/web/","https://sdk.sandbox.primer.io/web/","https://sdk.production.primer.io/web/","https://sdk.primer.io/state-processor/","https://sdk.dev.primer.io/state-processor/","https://sdk.primer.io/cel-wrapper/","https://sdk.dev.primer.io/cel-wrapper/","https://assets.primer.io/","https://x.klarnacdn.net/kp/lib/v","https://www.paypal.com/sdk/js","https://www.paypalobjects.com/","https://js.stripe.com/","https://pay.google.com/gp/p/js/"];function hm(a){return mm.some(t=>a.startsWith(t))}async function ko(a,t){if(!hm(a))throw new Error(`Script source not authorized per PCI DSS 6.4.3: ${a}`);await new Promise((e,r)=>{let i=document.createElement("script");i.src=a,i.integrity=`sha256-${t}`,i.crossOrigin="anonymous",i.onload=()=>{i.remove(),e()},i.onerror=()=>{i.remove(),r(new Error(`SRI check or load failed for script: ${a}`))},document.head.appendChild(i)})}async function gm(a,t){let e=await fetch(a).then(n=>n.arrayBuffer()),r=await crypto.subtle.digest("SHA-256",e);if(btoa(String.fromCharCode(...new Uint8Array(r)))!==t)throw new Error(`Integrity check failed for ${a}`);return e}var ls=["MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEUM5exrePPsIdkWFL6IjKdYmEDoEHBZkoBvrApQpmDEhQ7IisLTCiP0byqN+5B5V60QjAj4I/Bw292h8gPGZyOg==","MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAERA0j68aAYtwMDagEx2FY+CBbm2+MAYviARSMxWHt1Qt8wGyVvLJ2FqIvg4m2pKfb7GqUwzuJRD/gaOrO2ZJulQ==","MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEp7v1KpNTWcI9yJSoZYGvRxsPtciT99P2YDpISVLyD6BDD8xqJ11A8v2/elOEPaSxx5hConszht1cOlPp9YdTsA=="];function fm(a){let t=2;a[1]===129&&(t=3),t++;let e=a[t++],r=a.slice(t,t+e);t+=e,t++;let i=a[t++],n=a.slice(t,t+i),o=new Uint8Array(new ArrayBuffer(64));return o.set(r.slice(-32),32-Math.min(r.length,32)),o.set(n.slice(-32),64-Math.min(n.length,32)),o}async function ym(a){let t=Uint8Array.from(atob(a),e=>e.charCodeAt(0));return crypto.subtle.importKey("spki",t,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}async function vm(a,t){let e=fm(Uint8Array.from(atob(t),i=>i.charCodeAt(0))),r=new TextEncoder().encode(a);for(let i of ls)try{let n=await ym(i);if(await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},n,e,r))return!0}catch{}return!1}async function bm(a){let e;for(let r=0;r<3;r++){r>0&&await vr(300*r);try{let i=await fetch(a.manifestUrl);if(!i.ok)throw new Error(`Failed to fetch state processor manifest: ${i.status}`);let n=await i.json(),{signature:o,manifest:s}=n;if(typeof o!="string"||typeof s!="string")throw new Error("Invalid manifest response format");let l=Wt.decode(s);if(!await vm(l,o))throw new Error("Manifest signature verification failed");return JSON.parse(l)}catch(i){e=i}}throw e}async function Cm(){return Promise.all(ls.map(async a=>{let t=Uint8Array.from(atob(a),r=>r.charCodeAt(0)),e=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(e)).map(r=>r.toString(16).padStart(2,"0")).join("")}))}async function Sm(a,t,e){let r=await bm(a),i=r.cel.noModules,n=await gm(i.wasm.br,i.wasm.sha256),o="primer_wasm_bindgen";typeof window[o]!="function"&&await ko(i.js.url,i.js.sha256);let s=window[o];if(typeof s!="function")throw new Error(`Invalid CEL wrapper: window.${o} not set after script load`);let l=Object.getOwnPropertyDescriptor(window,o);if(!l||l.configurable!==!1||l.writable!==!1)throw new Error(`Invalid CEL wrapper: window.${o} global is not hardened`);await s(n),window.StateProcessor?.createStateProcessor||await ko(r.stateProcessor.umd.url,r.stateProcessor.umd.sha256);let c=window.StateProcessor;if(!c?.createStateProcessor)throw new Error("createStateProcessor not found after loading state processor module");return c.createStateProcessor(t,e)}function Am(a,t){return new Promise((e,r)=>{if(t.aborted)return void r(new DOMException("Aborted","AbortError"));let i=setTimeout(e,a);t.addEventListener("abort",()=>{clearTimeout(i),r(new DOMException("Aborted","AbortError"))},{once:!0})})}var Fi=class{constructor(t,e,r){A(this,"popup");A(this,"shouldRedirect",!1);A(this,"resolveOutcome");A(this,"context");A(this,"config");A(this,"onBeforeRedirect");this.context=t,this.config=e,this.onBeforeRedirect=r}async execute(t){let{url:e}=t.params,r=!!this.config.forceRedirect||!!this.context.clientOptions.redirect?.forceRedirect,i=!!this.context.clientOptions.redirect?.returnUrl,n=null;return r?(this.shouldRedirect=!0,n="force_redirect"):Xr()?(this.shouldRedirect=!0,n="in_app_browser"):Ze()&&i&&(this.shouldRedirect=!0,n="mobile_device"),this.shouldRedirect||(this.popup=await Xi({name:this.config.name,context:this.context,displayMetadata:this.config.displayMetadata}),this.popup?.isOpen||(this.shouldRedirect=!0,n="popup_blocked")),this.shouldRedirect&&n?(Qi(e,this.config.type,n),this.onBeforeRedirect(),window.location.assign(e),new Promise(()=>{})):(this.popup?.setUrl(e),new Promise(o=>{this.resolveOutcome=o,this.popup?.onClose(()=>{this.context.dialogProvider.close(),o({outcome:"cancelled"})})}))}onFinish(){this.resolveOutcome?.({outcome:"success"}),this.context.dialogProvider.close(),this.popup?.close()}get isOpen(){return this.popup?.isOpen??!1}focus(){this.popup?.focus()}},Ui=class{async execute(t){let{message:e,severity:r,context:i}=t.params.properties;return wo(e,{status:r,metadata:i}),{outcome:"success"}}},Vi=class{async execute(t){return Le({...t.params,eventName:t.params.eventName}),{outcome:"success"}}},yr=class extends ge{constructor(e,r){super(e,r);A(this,"onFinishCallback");A(this,"stepHandlerRegistry");A(this,"abortController");A(this,"stateProcessorConfig");this.stepHandlerRegistry=new Ki;let i=r.decodedClientToken.env,n=null;i!=="PRODUCTION"&&(n=new URLSearchParams(window.location.search).get("manifestUrl")),this.stateProcessorConfig={manifestUrl:n??`https://sdk.primer.io/state-processor/v0/manifests/${i.toLowerCase()}.json`},r.subscribeToTeardown(()=>{this.abortController?.abort(),this.stepHandlerRegistry?.finishAll()})}async setup(){return qi(this.context.clientOptions,this.config.type)?super.setup():!1}setOnFinishCallback(e){this.onFinishCallback=e}async tokenize(){throw new N({message:"Tokenize is not supported for backend-driven payment methods"})}async start(){let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new N({message:"Payment creation aborted",code:L.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));this.abortController=new AbortController;let r=this.abortController.signal;try{let i=this.context.configuration.clientSession.clientSessionId,n=await this.initiatePayment(i),o=await this.runInstructionLoop(n,i,r);if(r.aborted)return this.finishCancel();if(o.type!=="END")throw new N({message:"Unexpected final instruction type"});this.handleEndInstruction(o)}catch(i){if(r.aborted)return this.finishCancel();this.stepHandlerRegistry?.finishAll(),this.onFinishCallback?.({result:"complete",error:this.normalizeError(i)})}}async resume(e){this.abortController=new AbortController;let r=this.abortController.signal;try{let i=await this.fetchNextInstruction(e),n=await this.runInstructionLoop(i,e,r);if(r.aborted)return this.finishCancel();if(n.type!=="END")throw new N({message:"Unexpected final instruction type"});this.handleEndInstruction(n)}catch(i){if(r.aborted)return this.finishCancel();this.stepHandlerRegistry?.finishAll(),this.onFinishCallback?.({result:"complete",error:this.normalizeError(i)})}}async runInstructionLoop(e,r,i){let n=e,o=null;for(;!i.aborted&&n.type!=="END";){n.type==="EXECUTE"&&!o&&(o=this.processExecute(n)),await Am(n.pollDelayMilliseconds,i);let s=this.fetchNextInstruction(r);if(o){let l=await Promise.race([s.then(c=>({kind:"poll",value:c})),o.then(c=>({kind:"orch",value:c}))]);if(l.kind==="orch"){if(l.value?.outcome==="cancelled"){this.abortController?.abort();break}if(l.value?.outcome==="error")throw s.catch(()=>{}),new Error("Step handler failed");n=await s,o=null;continue}n=l.value;continue}n=await s}return n}async initiatePayment(e){Fu(this.context.clientOptions,this.config.type);let{data:r,error:i}=await this.context.pciApi.postClientSessionPay(e,this.buildInlinePayRequest());if(i||!r?.clientInstruction)throw i??new N({message:"Failed to initiate backend-driven payment"});return r.clientInstruction}async fetchNextInstruction(e){let{data:r,error:i}=await this.context.pciApi.getClientSessionInstruction(e);if(i||!r)throw i??new N({message:"Failed to fetch payment instruction"});return r.clientInstruction}async processExecute(e){let{schema:r,parameters:i}=e.payload;Cm().then(s=>{Le({eventName:"BDC_FLOW_START",trustedKeyFingerprints:s})}).catch(()=>{});let n=await Sm(this.stateProcessorConfig,JSON.stringify(r),this.buildSdkContext()),o=new Gi(n,this.stepHandlerRegistry);return this.stepHandlerRegistry.register("url.open",new Fi(this.context,this.config,()=>this.abortController?.abort())),this.stepHandlerRegistry.register("platform.log",new Ui),this.stepHandlerRegistry.register("analytics.event",new Vi),o.run(i)}buildSdkContext(){let e=ht();return{sdk:{type:"WEB",version:ua.getContext()?.sdkVersion??"",integrationType:this.context.integrationType},device:{locale:e.language,userAgent:e.userAgent},session:{checkoutSessionId:this.context.checkoutSessionId,clientSessionId:this.context.configuration.clientSession.clientSessionId,customerId:this.context.configuration.clientSession.customer?.customerId},merchant:{primerAccountId:this.context.configuration.primerAccountId},payment:{paymentMethodType:this.config.type}}}handleEndInstruction(e){this.stepHandlerRegistry?.finishAll();let{checkoutOutcome:r,payment:i}=e.payload;if(i){let{paymentInstrumentToken:n,...o}=i;this.onFinishCallback?.({result:"complete",payment:{...o,checkoutOutcome:r},token:n})}else this.onFinishCallback?.({result:"complete"})}finishCancel(){this.stepHandlerRegistry?.finishAll(),this.onFinishCallback?.({result:"cancel"})}normalizeError(e){return e instanceof N?e:e instanceof Error?new N({message:e.message}):new N({message:String(e)})}},Em=[P.ADYEN_AFFIRM,P.ADYEN_BANCONTACT_CARD,P.ADYEN_EPS,P.ADYEN_MULTIBANCO,P.GO_CARDLESS,P.RAPYD_FAST,P.STRIPE_ACH,P.NETS];function Mm(a,t){return Em.includes(a.type)?(y.warn(`Payment method ${a.type} is not supported in sdk core.`),null):(y.debug("Initializing payment method:",a.type),a.implementationType==="BACKEND_DRIVEN"||a.implementationType==="WEB_REDIRECT"&&a.capabilities?.includes("BACKEND_DRIVEN")?new yr(a,t):a.type===P.ADYEN_BANCONTACT_PAYCONIQ||a.type===P.XFERS_PAYNOW||a.type===P.RAPYD_PROMPTPAY||a.type===P.OMISE_PROMPTPAY?new ca(a,t):a.type===P.PAYMENT_CARD?new ra(a,t):a.type===P.PAYPAL?new la(a,t):a.type===P.APPLE_PAY?new ea(a,t):a.type===P.GOOGLE_PAY?new aa(a,t):a.type===P.ADYEN_BLIK?new ta(a,t):a.type===P.KLARNA?new na(a,t):a.type===P.ADYEN_KLARNA?new oa(a,t):a.type===P.ADYEN_MBWAY?new sa(a,t):a.implementationType==="WEB_REDIRECT"?new _i(a,t):null)}async function Tm(a){if(!a)return null;try{return await a.setup()?a:null}catch(t){return y.warn(`Failed to initialize payment method ${a.config.type}:`,t),null}}async function ds(a,t,e){let r=new Map((e??[]).map(n=>[n.config.type,n]));return(await Promise.all(a.configuration.paymentMethods.filter(({type:n})=>t?t.includes(n):!0).map(async n=>{let o=r.get(n.type);return o||Tm(Mm(n,a))}))).filter(n=>!!n)}function Pm(a,t,e){if(!t.configuration.clientSession.customer?.customerId)throw new N({message:"You must provide a `customerId` in the client session to use the Vault Manager."});let r=[];return{async fetchVaultedPaymentMethods(){let{data:i,error:n}=await t.pciApi.getPaymentInstruments();if(n)throw n;if(!i)throw new N({code:Yr.VAULT_ERROR,message:"Missing vaulted payment methods data"});return r=km(i.data,t.configuration?.clientSession?.paymentMethod?.orderedAllowedCardNetworks),r},async deleteVaultedPaymentMethod(i){if(!r.find(s=>s.id===i))throw new N({code:Yr.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;r=r.filter(s=>s.id!==i)},async startPaymentFlow(i){let n=r.find(s=>s.id===i);if(!n)throw new N({code:Yr.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 K({code:Yr.TOKENIZATION_ERROR,message:`Payment instrument type ${n.paymentInstrumentType} is not recognized or not supported.`});await Fe(a,o,n)},async createCvvInput(i){let n={blur:new Set,change:new Set,focus:new Set},o,s=hr(t.checkoutSessionId,lo);await new Promise(g=>{s.onload=()=>{g()},(typeof i.container=="string"?document.querySelector(i.container):i.container)?.appendChild(s)}),Li(s,i.style),s.setAttribute("title",i.ariaLabel||"");let l=en({namespace:`${t.checkoutSessionId}-${lo}`,onMessage:g=>{let v=M=>g(M.data);return window.addEventListener("message",v),()=>window.removeEventListener("message",v)},sendMessage:g=>{s.contentWindow?.postMessage(g,"*")}});function c(g,v){g!=="metadata"&&n[g].add(v)}l.setOnFocus(()=>{n.focus.forEach(g=>g())}),l.setOnBlur(()=>{n.blur.forEach(g=>g())}),l.setOnInput(g=>{o=g,n.change.forEach(v=>v())}),l.setCardNetwork(i.cardNetwork??""),l.setOptions({placeholder:i.placeholder??"123",ariaLabel:i.ariaLabel??"CVV",style:i.style});function u(){s.parentNode&&s.remove()}let m=t.subscribeToTeardown(u);return{frame:s,remove:()=>{m(),u()},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(g,v){g!=="metadata"&&n[g].delete(v)},blur(){l.blur()},focus(){l.focus()},validate(){l.getFieldState().then(g=>{o=g,n.change.forEach(v=>v(o))})}}}}}function km(a,t){if(!t||t.length===0)return a;let e=new Set(t.map(r=>jt(r).backend));return a.filter(r=>{if(r.paymentInstrumentType!==mt.CARD)return!0;let i=r.paymentInstrumentData?.network;return typeof i!="string"||!i?!0:e.has(jt(i).backend)})}function Im(a,t,e){return e.setOnFinishCallback(r=>{r.result==="cancel"?t.clientSessionApi.unselectPaymentMethod():Ke(a,r.payment,r.error,r.token,e.config.type)}),{start:()=>Fe(a,e)}}function Nm(a,t,e){let r=null,i=async()=>{if(!await a.refreshClientConfiguration())return!1;let o=await ds(a,e.enabledPaymentMethods,t);return o.length===t.length&&o.every((l,c)=>l===t[c])||(t.length=0,t.push(...o),e.onAvailablePaymentMethodsRefresh?.(o.map(l=>({type:l.config.type,managerType:us(l)})))),!0};return()=>r||(r=i().finally(()=>{r=null}),r)}async function wm(a,t,e=[]){let{currentAttempt:r}=t.configuration.clientSession;r&&(a.onCheckoutResume?.(),Lm(a,t,r,e))}async function Lm(a,t,e,r){let{clientSessionId:i}=t.configuration.clientSession,n=e.approvalStatus;if(n==="ABORTED"||n==="EXPIRED")return void Ke(a,void 0,xm(n),null);if(!e.paymentInstrumentTokenId)return void Ke(a,void 0,new N({code:L.PAYMENT_FAILED,message:"The payment approval attempt has no payment instrument token."}),null);let o;try{o=await Rm(t,e.paymentInstrumentTokenId)}catch(c){Ke(a,void 0,c,null);return}let s=r.find(c=>c.config.type===o.paymentInstrumentType);if(n==="APPROVED")return void await wi(a,{paymentMethod:s,token:o,fetchPayment:()=>os(t,e,s?.config.type)});let{onPaymentApprovalRequired:l}=a;if(l)try{await ss(l,{clientSessionId:i,paymentAttemptId:e.id,paymentMethodToken:o}),await wi(a,{paymentMethod:s,token:o,fetchPayment:()=>ns(t,s?.config.type)})}catch(c){Ke(a,void 0,c,o,s?.config.type)}}async function Rm(a,t){let{data:e,error:r}=await a.pciApi.getPaymentInstrumentToken(t);if(r||!e)throw r??new N({code:L.PAYMENT_FAILED,message:"Unable to fetch the token to restore the approval request."});return e}function xm(a){return new N({code:L.PAYMENT_FAILED,message:a==="EXPIRED"?"The payment approval attempt expired before it was approved.":"The payment approval attempt was aborted."})}async function cs(a,t){y.debug("createHeadless",t);let e=await pm(a,{locale:t.locale,dialogProvider:t.dialogProvider,translate:t.translate,integrationType:t.integrationType,clientOptions:{paypal:t.paypal,applePay:t.applePay,googlePay:t.googlePay,klarna:t.klarna,merchantDomain:t.merchantDomain,redirect:t.redirect,card:t.card}}),r=await ds(e,t.enabledPaymentMethods);t.onClientSessionUpdate?.(e.configuration.clientSession),e.onClientConfigurationUpdate(async n=>{t.onClientSessionUpdate?.(n.clientSession)}),t.onPaymentMethodAction&&e.clientSessionApi.setOnPaymentMethodAction((n,o)=>t.onPaymentMethodAction?.(n,{...o,payment:ki(o.payment,o.token)??void 0}));let i={environment:Pi?"LOCAL":e.decodedClientToken.env,primerAccountId:e.configuration.primerAccountId,checkoutSessionId:e.checkoutSessionId,clientSessionId:e.configuration.clientSession?.clientSessionId,clientSessionToken:a,sdkVersion:t.sdkVersion,configurationFetchStartTime:e.configurationFetchStartTime};return $c({environment:Pi?"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?.(r.map(n=>({type:n.config.type,managerType:us(n)}))),{start:async()=>{if(e.decodedClientToken.intent==="REDIRECTION_END"){ho(e.decodedClientToken.intent,{paymentId:e.decodedClientToken.paymentId});let{data:n,error:o}=await e.pciApi.postResumePayment(e.decodedClientToken.paymentId,e.decodedClientToken.resumeToken);Ke(t,n,o);return}if(e.decodedClientToken.intent==="AWAIT_CLIENT_INSTRUCTION"){let{clientSessionId:n,paymentMethodType:o,intent:s}=e.decodedClientToken;ho(s,{paymentMethod:o});let l=r.find(c=>c instanceof yr&&c.config.type===o);if(!l)return void Ke(t,void 0,new N({message:"No backend-driven payment method found for resume"}));l.setOnFinishCallback(({result:c,payment:u,error:m,token:g})=>{c!=="cancel"&&Ke(t,u,m,g,l.config.type)}),await l.resume(n);return}if(e.configuration.clientSession.approvalMode==="MANUAL")return void await wm(t,e,r)},createPaymentMethodManager:async(n,o)=>{let s=r.find(({config:l})=>l.type===n);return s?s instanceof ra?Gp(t,e,s,o):s instanceof la||s instanceof ea||s instanceof aa?Fp(t,e,s):s instanceof ta?Vp(t,e,s):s instanceof yr?Im(t,e,s):s instanceof na?Hp(t,e,s,o):s instanceof oa?$p(t,e,s,o):s instanceof sa?Yp(t,e,s):s instanceof ca?zp(t,e,s):Up(t,e,s):(y.warn(`Payment method ${n} not found`),null)},getSDKUtilities:()=>({getCardNetworkAsset:Io,getUIOrderAmount:()=>{let{merchantAmount:n,totalOrderAmount:o,currencyCode:s}=e.configuration.clientSession.order;return Ro(e.locale,n??o,s)},getCDNAssets:async n=>{let o=r.find(({config:c})=>c.type===n);if(!o)return;let{backgroundColor:s}=o.config.displayMetadata?.button||{};return{assets:{icon:n?`brand/icon/${n.toLowerCase().replace(/_/g,"-")}.svg`:""},colors:{background:s?.colored||"",main:s?.colored||""},description:o.config.name||null,is_primer_app:!1,name:o.config.name,website:null,goatCdnUrl:Qo}},getPaymentMethodConfiguration:n=>r.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 N({message:"Failed to set billing address"})}}),getAnalyticsUtils:()=>i,createVaultManager(){return Pm(t,e,r)},getAssetsManager:()=>({getCardNetworkAsset:Io,getPaymentMethodAsset:async n=>{let o=r.find(({config:u})=>u.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:Nm(e,r,{enabledPaymentMethods:t.enabledPaymentMethods,onAvailablePaymentMethodsRefresh:t.onAvailablePaymentMethodsRefresh}),getConfiguration:()=>e.configuration,teardown:()=>e.teardown()}}function us(a){switch(a.config.type){case P.PAYMENT_CARD:return pt.CARD;case P.KLARNA:return pt.KLARNA;case P.ADYEN_KLARNA:return pt.ADYEN_KLARNA;case P.ADYEN_MBWAY:return pt.MBWAY;case P.ADYEN_BLIK:return pt.BLIK;case P.ADYEN_BANCONTACT_PAYCONIQ:case P.OMISE_PROMPTPAY:case P.RAPYD_PROMPTPAY:case P.XFERS_PAYNOW:return pt.QRCODE;default:return a.config.implementationType==="NATIVE_SDK"?pt.NATIVE:pt.REDIRECT}}var Io=a=>{let{asset:t,display:e}=jt(a);return{cardUrl:`${Qo}/brand/card/${t}.svg`,displayName:e}},Bm=new Set(["paymentMethodType","last4Digits","network","accountNumberLastFourDigits","bankName"]);function Qt(a){let{id:t,orderId:e,paymentMethodData:r}=a,i={id:t,orderId:e};if(!r||typeof r!="object")return i;let n={};for(let[o,s]of Object.entries(r))Bm.has(o)&&(n[o]=s);return i.paymentMethodData=n,i}var Dm={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 Om(a,t){let e=a;for(let r of t.split(".")){if(!e||typeof e!="object")return;e=e[r]}return e&&typeof e=="object"?e:void 0}function _m(a,t){if(!a)return;let e={};for(let r of t)a[r]!==void 0&&(e[r]=a[r]);return Object.keys(e).length>0?e:void 0}function ps(a){let{id:t,analyticsId:e,paymentMethodType:r,paymentInstrumentType:i,paymentInstrumentData:n,userDescription:o}=a,s=Dm[i],l;if(s&&n&&typeof n=="object"){let c=s.path?Om(n,s.path):n;l=_m(c,s.fields)}return{id:t,analyticsId:e,paymentMethodType:r,paymentInstrumentType:i,...o&&{userDescription:o},...l&&{paymentInstrumentData:l}}}var Xt=class{constructor(t){this.host=t}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 r=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:r},bubbles:!0,composed:!0,cancelable:!0});return this.host.dispatchEvent(n),n.defaultPrevented?!0:i}dispatchPaymentSuccess(t,e){let r=Qt(t),i=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:payment-success",{payment:r,paymentMethodType:e,timestamp:i})}dispatchPaymentFailure(t,e,r){let i=Math.floor(Date.now()/1e3),n=r?Qt(r):void 0;this.dispatchEvent("primer:payment-failure",{error:t,payment:n,paymentMethodType:e,timestamp:i})}dispatchPaymentApprovalRequired(t){let e=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:payment-approval-required",{...t,timestamp:e})}dispatchVaultMethodsUpdate(t,e){let r=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:vault-methods-update",{vaultedPayments:t,cvvRecapture:e,timestamp:r})}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 gt=class extends Event{constructor(t,e,r,i){super("context-request",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=e,this.callback=r,this.subscribe=i??!1}};var er=class{constructor(t,e,r,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=r,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 gt(this.context,this.host,this.t,this.subscribe))}};var ma=class{get value(){return this.o}set value(t){this.setValue(t)}setValue(t,e=!1){let r=e||!Object.is(t,this.o);this.o=t,r&&this.updateObservers()}constructor(t){this.subscriptions=new Map,this.updateObservers=()=>{for(let[e,{disposer:r}]of this.subscriptions)e(this.o,r)},t!==void 0&&(this.value=t)}addCallback(t,e,r){if(!r)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 tn=class extends Event{constructor(t,e){super("context-provider",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=e}},ft=class extends ma{constructor(t,e,r){super(e.context!==void 0?e.initialValue:r),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 gt(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 tn(this.context,this.host))}};function _({context:a,subscribe:t}){return(e,r)=>{typeof r=="object"?r.addInitializer((function(){new er(this,{context:a,callback:i=>{e.set.call(this,i)},subscribe:t})})):e.constructor.addInitializer((i=>{new er(i,{context:a,callback:n=>{i[r]=n},subscribe:t})}))}}var yt=a=>!!a&&a.isProcessing,G=Symbol("primer-context");function vt(a,t,e=0,r=10){if(e>r)return a===t;if(a===t)return!0;if(a==null||t==null||typeof a!="object"||typeof t!="object")return!1;let i=Object.keys(a);if(i.length!==Object.keys(t).length)return!1;for(let n of i){if(!(n in t))return!1;let o=a[n],s=t[n];if(typeof o=="object"&&o!==null&&(typeof s=="object"&&s!==null)){if(!vt(o,s,e+1,r))return!1}else if(o!==s)return!1}return!0}var hs={klarnaCategories:{categories:[],isLoading:!0},sdkState:{isSuccessful:!1,isProcessing:!1,isLoading:!1,primerJsError:null,paymentFailure:null},paymentMethods:[]},ha=class{constructor(t){(this.host=t).addController(this),this.contextProvider=new ft(t,{context:G,initialValue:structuredClone(hs)})}hostConnected(){}setContext(t){this.contextProvider?.setValue({...this.contextProvider.value,...t})}setSdkState(t){let e=this.contextProvider.value.sdkState,r={...e,...t};vt(e,r)||(this.host.primerEventsController.dispatchSdkState(r),this.setContext({sdkState:r}))}resetSdkState(){this.setContext(structuredClone(hs))}setCardNetworks(t){this.setContext({cardNetworks:t})}setCardNetworksLoadingFalse(){this.setContext({cardNetworks:{detectedCardNetwork:this.contextProvider.value.cardNetworks?.detectedCardNetwork??null,selectableCardNetworks:this.contextProvider.value.cardNetworks?.selectableCardNetworks??[],isLoading:!1}})}setVaultManager(t){this.setContext({vaultManager:t})}setKlarnaCategories(t){this.setContext({klarnaCategories:t})}setAdyenKlarnaOptions(t){this.setContext({adyenKlarnaOptions:t})}setComputedStyles(t){this.setContext({computedStyles:t})}setVaultManagerCvv(t){this.setContext({vaultItem:t})}setEventsController(t){this.setContext({events:t})}};var Bt=class Bt{constructor(t){(this.host=t).addController(this)}processCustomStyles(t){try{let e=JSON.parse(t);this.applyStyles(e)}catch(e){T.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 r=/^[\w\s#.,%()\-+/!]+$/.test(t);return r||T.warn(`Rejected potentially unsafe CSS value: ${t}`),r}getCssVarName(t){let e=Bt.cssVarCache.get(t);return e||(e=`--${t.replace(/([A-Z])/g,(r,i)=>`-${i.toLowerCase()}`)}`,Bt.cssVarCache.set(t,e)),e}applyStyles(t){let e=[];for(let r of Object.keys(t)){let i=t[r];if(!i)continue;if(!this.isValidCssProperty(r)){T.warn(`Skipping invalid CSS property name: ${r}`);continue}if(!this.isValidCssValue(i))continue;let n=this.getCssVarName(r);e.push([n,i])}if(e.length>0)for(let[r,i]of e)this.host.style.setProperty(r,i)}removeStyle(t){let e=this.getCssVarName(t);this.host.style.removeProperty(e)}clearAllStyles(){for(let t of Bt.cssVarCache.keys()){let e=Bt.cssVarCache.get(t);e&&this.host.style.removeProperty(e)}}hostDisconnected(){}};Bt.cssVarCache=new Map;var ga=Bt;var fa=globalThis,va=fa.ShadowRoot&&(fa.ShadyCSS===void 0||fa.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,fs=Symbol(),gs=new WeakMap,ya=class{constructor(t,e,r){if(this._$cssResult$=!0,r!==fs)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(va&&t===void 0){let r=e!==void 0&&e.length===1;r&&(t=gs.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),r&&gs.set(e,t))}return t}toString(){return this.cssText}},ys=a=>new ya(typeof a=="string"?a:a+"",void 0,fs);var rn=(a,t)=>{if(va)a.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let r=document.createElement("style"),i=fa.litNonce;i!==void 0&&r.setAttribute("nonce",i),r.textContent=e.cssText,a.appendChild(r)}},ba=va?a=>a:a=>a instanceof CSSStyleSheet?(t=>{let e="";for(let r of t.cssRules)e+=r.cssText;return ys(e)})(a):a;var{is:Gm,defineProperty:Km,getOwnPropertyDescriptor:Fm,getOwnPropertyNames:Um,getOwnPropertySymbols:Vm,getPrototypeOf:Hm}=Object,bt=globalThis,vs=bt.trustedTypes,$m=vs?vs.emptyScript:"",Ym=bt.reactiveElementPolyfillSupport,br=(a,t)=>a,an={toAttribute(a,t){switch(t){case Boolean:a=a?$m:null;break;case Object:case Array:a=a==null?a:JSON.stringify(a)}return a},fromAttribute(a,t){let e=a;switch(t){case Boolean:e=a!==null;break;case Number:e=a===null?null:Number(a);break;case Object:case Array:try{e=JSON.parse(a)}catch{e=null}}return e}},Ca=(a,t)=>!Gm(a,t),bs={attribute:!0,type:String,converter:an,reflect:!1,hasChanged:Ca};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),bt.litPropertyMetadata??(bt.litPropertyMetadata=new WeakMap);var Dt=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=bs){if(e.state&&(e.attribute=!1),this._$Ei(),this.elementProperties.set(t,e),!e.noAccessor){let r=Symbol(),i=this.getPropertyDescriptor(t,r,e);i!==void 0&&Km(this.prototype,t,i)}}static getPropertyDescriptor(t,e,r){let{get:i,set:n}=Fm(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,r)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??bs}static _$Ei(){if(this.hasOwnProperty(br("elementProperties")))return;let t=Hm(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(br("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(br("properties"))){let e=this.properties,r=[...Um(e),...Vm(e)];for(let i of r)this.createProperty(i,e[i])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[r,i]of e)this.elementProperties.set(r,i)}this._$Eh=new Map;for(let[e,r]of this.elementProperties){let i=this._$Eu(e,r);i!==void 0&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let e=[];if(Array.isArray(t)){let r=new Set(t.flat(1/0).reverse());for(let i of r)e.unshift(ba(i))}else t!==void 0&&e.push(ba(t));return e}static _$Eu(t,e){let r=e.attribute;return r===!1?void 0:typeof r=="string"?r: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 r of e.keys())this.hasOwnProperty(r)&&(t.set(r,this[r]),delete this[r]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return rn(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,r){this._$AK(t,r)}_$EC(t,e){let r=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,r);if(i!==void 0&&r.reflect===!0){let n=(r.converter?.toAttribute!==void 0?r.converter:an).toAttribute(e,r.type);this._$Em=t,n==null?this.removeAttribute(i):this.setAttribute(i,n),this._$Em=null}}_$AK(t,e){let r=this.constructor,i=r._$Eh.get(t);if(i!==void 0&&this._$Em!==i){let n=r.getPropertyOptions(i),o=typeof n.converter=="function"?{fromAttribute:n.converter}:n.converter?.fromAttribute!==void 0?n.converter:an;this._$Em=i,this[i]=o.fromAttribute(e,n.type),this._$Em=null}}requestUpdate(t,e,r){if(t!==void 0){if(r??(r=this.constructor.getPropertyOptions(t)),!(r.hasChanged??Ca)(this[t],e))return;this.P(t,e,r)}this.isUpdatePending===!1&&(this._$ES=this._$ET())}P(t,e,r){this._$AL.has(t)||this._$AL.set(t,e),r.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 r=this.constructor.elementProperties;if(r.size>0)for(let[i,n]of r)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((r=>r.hostUpdate?.())),this.update(e)):this._$EU()}catch(r){throw t=!1,this._$EU(),r}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){}};Dt.elementStyles=[],Dt.shadowRootOptions={mode:"open"},Dt[br("elementProperties")]=new Map,Dt[br("finalized")]=new Map,Ym?.({ReactiveElement:Dt}),(bt.reactiveElementVersions??(bt.reactiveElementVersions=[])).push("2.0.4");var Ct={INITIAL:0,PENDING:1,COMPLETE:2,ERROR:3},Y=Symbol(),j=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,r){this.p=0,this.i=0,(this._=t).addController(this);let i=typeof e=="object"?e:{task:e,args:r};this.v=i.task,this.j=i.args,this.m=i.argsEqual??Cs,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,r;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,r=o}if(this.p===i){if(e===Y)this.i=0;else{if(n===!1){try{this.k?.(e)}catch{}this.i=2,this.o?.(e)}else{try{this.A?.(r)}catch{}this.i=3,this.h?.(r)}this.u=e,this.l=r}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)}}},Cs=(a,t)=>a===t||a.length===t.length&&a.every(((e,r)=>!Ca(e,t[r])));var Sa={enabled:!1,isLoading:!1,isUpdating:!1,cvvRecapture:!1,showEmptyState:!1,headless:!1,vaultedPaymentMethods:[],createCvvInput:null,deleteVaultedPaymentMethod:()=>Promise.resolve(),startVaultedPaymentFlow:()=>Promise.resolve()},Ss={cvvInput:null,formIsDirty:!1,setCvvInput:()=>{},selectedVaultedPaymentMethod:null,setSelectedVaultedPaymentMethod:()=>{}},Cr=class{constructor(t){this.host=t;this._coreState={...Sa};this._itemState={...Ss};this._vaultManager=null;this._options=null;this.createVaultManagerFn=null;this.createCvvInput=t=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");return this._vaultManager.createCvvInput(t)};this.deleteVaultedPaymentMethod=async t=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");try{this.updateCoreState({vaultedPaymentMethods:this._coreState.vaultedPaymentMethods}),await this._vaultManager.deleteVaultedPaymentMethod(t),await this.fetchVaultedPaymentMethods()}catch(e){let r=e instanceof Error?e:new Error("Failed to delete payment method");throw this.updateCoreState({isLoading:!1,isUpdating:!1}),this.host.sdkContextController.setSdkState({primerJsError:r}),e}};this.setCvvInput=t=>{this.updateItemState({cvvInput:t})};this.startVaultedPaymentFlow=async()=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");let t=this._itemState.selectedVaultedPaymentMethod,e=this._coreState.cvvRecapture,r=this._itemState.cvvInput;if(!t||e&&(!r||r.metadata.error)){this.updateItemState({formIsDirty:!0});return}this.host.sdkContextController.setSdkState({isProcessing:!0,paymentFailure:null,primerJsError:null});try{await this._vaultManager.startPaymentFlow(t.id)}catch(i){T.errorWithDatadog("VaultManagerController: Error starting vaulted payment flow",{error:i});let n=i instanceof Error?i:new Error("Failed to start vaulted payment flow");this.updateCoreState({isLoading:!1,isUpdating:!1}),this.host.sdkContextController.setSdkState({isProcessing:!1,primerJsError:n})}};this.setSelectedVaultedPaymentMethod=t=>{this.updateItemState({selectedVaultedPaymentMethod:t,formIsDirty:!1}),this.host.primerEventsController.dispatchVaultSelectionChange(t?.id??null)};this.startVaultPaymentById=async(t,e)=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");let r=this._coreState.vaultedPaymentMethods.find(i=>i.id===t);if(!r)throw new Error(`Payment method not found: ${t}`);this.setSelectedVaultedPaymentMethod(r),this.host.sdkContextController.setSdkState({isProcessing:!0,paymentFailure:null,primerJsError:null});try{await this._vaultManager.startPaymentFlow(t,e?.cvv?{cvv:e.cvv}:void 0)}catch(i){T.errorWithDatadog("VaultManagerController: Error starting vaulted payment flow",{error:i});let n=i instanceof Error?i:new Error("Failed to start vaulted payment flow");throw this.updateCoreState({isLoading:!1,isUpdating:!1}),this.host.sdkContextController.setSdkState({isProcessing:!1,primerJsError:n}),i}};this.host.addController(this),this._coreState={...this._coreState,deleteVaultedPaymentMethod:this.deleteVaultedPaymentMethod.bind(this),startVaultedPaymentFlow:this.startVaultedPaymentFlow.bind(this),createCvvInput:this.createCvvInput},this._itemState={...this._itemState,setCvvInput:this.setCvvInput.bind(this),setSelectedVaultedPaymentMethod:this.setSelectedVaultedPaymentMethod.bind(this)},new j(this.host,{task:async([e,r])=>{if(!e||!r?.vaultEnabled)return this.updateCoreState({...Sa,enabled:!1}),Y;this.updateCoreState({isLoading:!0});try{let i=e();this._vaultManager=i,this.updateCoreState({enabled:r.vaultEnabled,cvvRecapture:!!r.captureVaultedCardCvv,showEmptyState:r.showEmptyState??!1,headless:r.headless??!1,deleteVaultedPaymentMethod:this.deleteVaultedPaymentMethod.bind(this),startVaultedPaymentFlow:this.startVaultedPaymentFlow.bind(this),createCvvInput:this.createCvvInput}),this.host.sdkContextController.setVaultManagerCvv(this._itemState),await this.fetchVaultedPaymentMethods(!0),T.log("VaultManagerController: Vault initialized successfully",{coreState:this.vaultManagerState,cvvState:this.vaultItemState})}catch(i){T.errorWithDatadog("VaultManagerController: Failed to initialize vault",{error:i});let n=i instanceof Error?i:new Error("Unknown error");this.updateCoreState({isLoading:!1,isUpdating:!1}),this.host.sdkContextController.setSdkState({primerJsError:n})}return this._vaultManager},args:()=>[this.createVaultManagerFn,this.options]})}updateCoreState(t){let e={...this._coreState,...t};vt(this._coreState,e)?this._coreState=e:(this._coreState=e,this.host.sdkContextController.setVaultManager(e))}updateItemState(t){let e={...this._itemState,...t};vt(this._itemState,e)?this._itemState=e:(this._itemState=e,this.host.sdkContextController.setVaultManagerCvv(e))}initializeVaultManager(t,e){this.createVaultManagerFn=t,this.options=e??null}get vaultManager(){return this._vaultManager}set vaultManager(t){this._vaultManager=t,this.host.requestUpdate()}get options(){return this._options}set options(t){this._options=t,this.host.requestUpdate()}get vaultManagerState(){return Object.freeze({...this._coreState})}get vaultItemState(){return Object.freeze({...this._itemState})}hostConnected(){}hostDisconnected(){this.vaultManager=null,this.updateCoreState({...Sa})}createVaultedPaymentsArray(t){return t.map(e=>ps(e))}updatePaymentMethodsWithEvents(t){this.updateCoreState({vaultedPaymentMethods:t,isLoading:!1,isUpdating:!1});let e=this.createVaultedPaymentsArray(t);this.host.primerEventsController.dispatchVaultMethodsUpdate(e,this.vaultManagerState.cvvRecapture),this.host.primerJS?.handleVaultedMethodsUpdate(e,this.vaultManagerState.cvvRecapture),T.log("VaultManagerController: Dispatched vault methods update",{methodCount:t.length,filteredMethodCount:e.length})}async fetchVaultedPaymentMethods(t){if(!this._vaultManager)throw new Error("Vault manager not initialized");try{t||this.updateCoreState({isUpdating:!0});let e=await this._vaultManager.fetchVaultedPaymentMethods();return T.log("VaultManagerController: Fetched payment methods",e),this.updatePaymentMethodsWithEvents(e),e}catch(e){let r=e instanceof Error?e:new Error("Failed to fetch payment methods");throw this.updateCoreState({isLoading:!1,isUpdating:!1}),this.host.sdkContextController.setSdkState({primerJsError:r}),e}}};var As=()=>Es.randomUUID?.()||zm(),zm=()=>("10000000-1000-4000-8000"+-1e11).replace(/[018]/g,a=>(a^jm()>>a/4).toString(16)),jm=()=>(Es.getRandomValues?.(new Uint8Array(1))[0]??Math.random()*16)&15,Es=typeof crypto<"u"?crypto:{};var Zm={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"},nn=class{sendEvent(t){let e=Ge.getContext();if(!e)return;let r={...t,id:As(),timestamp:Date.now(),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};Jm(r,e)}},Wm=new nn;function Ms(a){let t={...a,userAgent:a.userAgent||(typeof navigator<"u"?navigator.userAgent:"")};Ge.initialize(t)}function Q(a){Wm.sendEvent(a)}function Ts(){Ge.clear()}async function Jm(a,{environment:t,clientSessionToken:e}){if(t==="LOCAL"){T.debug(`Analytics event ${a.eventName}:`,a);return}let r=Zm[t];return fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...e&&{Authorization:`Bearer ${e}`}},body:JSON.stringify(a),keepalive:!0,priority:"low"}).catch(i=>{T.error("Failed to send analytics event:",i)})}var Sr="lit-localize-status";var Ps=a=>typeof a!="string"&&"strTag"in a,Aa=(a,t,e)=>{let r=a[0];for(let i=1;i<a.length;i++)r+=t[e?e[i-1]:i-1],r+=a[i];return r};var Ar=(a=>Ps(a)?Aa(a.strings,a.values):a);var E=Ar,ks=!1;function on(a){if(ks)throw new Error("lit-localize can only be configured once");E=a,ks=!0}var sn=class{constructor(t){this.__litLocalizeEventHandler=e=>{e.detail.status==="ready"&&this.host.requestUpdate()},this.host=t}hostConnected(){window.addEventListener(Sr,this.__litLocalizeEventHandler)}hostDisconnected(){window.removeEventListener(Sr,this.__litLocalizeEventHandler)}},qm=a=>a.addController(new sn(a)),Is=qm;var O=()=>(a,t)=>(a.addInitializer(Is),a);var Er=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 Je=[];for(let a=0;a<256;a++)Je[a]=(a>>4&15).toString(16)+(a&15).toString(16);function Ns(a){let t=0,e=8997,r=0,i=33826,n=0,o=40164,s=0,l=52210;for(let c=0;c<a.length;c++)e^=a.charCodeAt(c),t=e*435,r=i*435,n=o*435,s=l*435,n+=e<<8,s+=i<<8,r+=t>>>16,e=t&65535,n+=r>>>16,i=r&65535,l=s+(n>>>16)&65535,o=n&65535;return Je[l>>8]+Je[l&255]+Je[o>>8]+Je[o&255]+Je[i>>8]+Je[i&255]+Je[e>>8]+Je[e&255]}var Qm="",Xm="h",eh="s";function ws(a,t){return(t?Xm:eh)+Ns(typeof a=="string"?a:a.join(Qm))}var Ls=new WeakMap,Rs=new Map;function xs(a,t,e){if(a){let r=e?.id??th(t),i=a[r];if(i){if(typeof i=="string")return i;if("strTag"in i)return Aa(i.strings,t.values,i.values);{let n=Ls.get(i);return n===void 0&&(n=i.values,Ls.set(i,n)),{...i,values:n.map(o=>t.values[o])}}}}return Ar(t)}function th(a){let t=typeof a=="string"?a:a.strings,e=Rs.get(t);return e===void 0&&(e=ws(t,typeof a!="string"&&!("strTag"in a)),Rs.set(t,e)),e}function ln(a){window.dispatchEvent(new CustomEvent(Sr,{detail:a}))}var Ma="",dn,Bs,Ta,cn,Ds,Ot=new Er;Ot.resolve();var Ea=0,Os=a=>(on(((t,e)=>xs(Ds,t,e))),Ma=Bs=a.sourceLocale,Ta=new Set(a.targetLocales),Ta.add(a.sourceLocale),cn=a.loadLocale,{getLocale:rh,setLocale:ah}),rh=()=>Ma,ah=a=>{if(a===(dn??Ma))return Ot.promise;if(!Ta||!cn)throw new Error("Internal error");if(!Ta.has(a))throw new Error("Invalid locale code");Ea++;let t=Ea;return dn=a,Ot.settled&&(Ot=new Er),ln({status:"loading",loadingLocale:a}),(a===Bs?Promise.resolve({templates:void 0}):cn(a)).then(r=>{Ea===t&&(Ma=a,dn=void 0,Ds=r.templates,ln({status:"ready",readyLocale:a}),Ot.resolve())},r=>{Ea===t&&(ln({status:"error",errorLocale:a,errorMessage:r.toString()}),Ot.reject(r))}),Ot.promise};var un="en",pn=["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"],mn="You must call `loadLocale` first to set up the localized template.",Pa,ka,_s=a=>{let t=Os({sourceLocale:un,targetLocales:pn,loadLocale:a});Pa=t.getLocale,ka=t.setLocale};var hn=a=>{_s(a)},gn=a=>{if(!ka)throw new Error(mn);return ka(a)},fn=()=>{if(!Pa)throw new Error(mn);return Pa()};var Mr=new Set(pn);Mr.add(un);var yn=a=>{if(typeof a!="string")return!1;if(a==="en")return!0;let t=a.replace("_","-");if(Mr.has(t))return!0;let e=t.split("-")[0];return!!Mr.has(e)},Ia=()=>navigator.language||navigator.languages[0]||"en",tr=a=>{let t=a.replace("_","-"),e=t.split("-")[0];return e==="en"?"en-GB":Mr.has(t)?t:Mr.has(e)?e:"en-GB"};var Na=globalThis,wa=Na.ShadowRoot&&(Na.ShadyCSS===void 0||Na.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,vn=Symbol(),Gs=new WeakMap,Tr=class{constructor(t,e,r){if(this._$cssResult$=!0,r!==vn)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(wa&&t===void 0){let r=e!==void 0&&e.length===1;r&&(t=Gs.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),r&&Gs.set(e,t))}return t}toString(){return this.cssText}},St=a=>new Tr(typeof a=="string"?a:a+"",void 0,vn),b=(a,...t)=>{let e=a.length===1?a[0]:t.reduce(((r,i,n)=>r+(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)+a[n+1]),a[0]);return new Tr(e,a,vn)},Ks=(a,t)=>{if(wa)a.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let r=document.createElement("style"),i=Na.litNonce;i!==void 0&&r.setAttribute("nonce",i),r.textContent=e.cssText,a.appendChild(r)}},bn=wa?a=>a:a=>a instanceof CSSStyleSheet?(t=>{let e="";for(let r of t.cssRules)e+=r.cssText;return St(e)})(a):a;var{is:ih,defineProperty:nh,getOwnPropertyDescriptor:oh,getOwnPropertyNames:sh,getOwnPropertySymbols:lh,getPrototypeOf:dh}=Object,At=globalThis,Fs=At.trustedTypes,ch=Fs?Fs.emptyScript:"",uh=At.reactiveElementPolyfillSupport,Pr=(a,t)=>a,kr={toAttribute(a,t){switch(t){case Boolean:a=a?ch:null;break;case Object:case Array:a=a==null?a:JSON.stringify(a)}return a},fromAttribute(a,t){let e=a;switch(t){case Boolean:e=a!==null;break;case Number:e=a===null?null:Number(a);break;case Object:case Array:try{e=JSON.parse(a)}catch{e=null}}return e}},La=(a,t)=>!ih(a,t),Us={attribute:!0,type:String,converter:kr,reflect:!1,useDefault:!1,hasChanged:La};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),At.litPropertyMetadata??(At.litPropertyMetadata=new WeakMap);var qe=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=Us){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 r=Symbol(),i=this.getPropertyDescriptor(t,r,e);i!==void 0&&nh(this.prototype,t,i)}}static getPropertyDescriptor(t,e,r){let{get:i,set:n}=oh(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,r)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Us}static _$Ei(){if(this.hasOwnProperty(Pr("elementProperties")))return;let t=dh(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Pr("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Pr("properties"))){let e=this.properties,r=[...sh(e),...lh(e)];for(let i of r)this.createProperty(i,e[i])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[r,i]of e)this.elementProperties.set(r,i)}this._$Eh=new Map;for(let[e,r]of this.elementProperties){let i=this._$Eu(e,r);i!==void 0&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let e=[];if(Array.isArray(t)){let r=new Set(t.flat(1/0).reverse());for(let i of r)e.unshift(bn(i))}else t!==void 0&&e.push(bn(t));return e}static _$Eu(t,e){let r=e.attribute;return r===!1?void 0:typeof r=="string"?r: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 r of e.keys())this.hasOwnProperty(r)&&(t.set(r,this[r]),delete this[r]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Ks(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,r){this._$AK(t,r)}_$ET(t,e){let r=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,r);if(i!==void 0&&r.reflect===!0){let n=(r.converter?.toAttribute!==void 0?r.converter:kr).toAttribute(e,r.type);this._$Em=t,n==null?this.removeAttribute(i):this.setAttribute(i,n),this._$Em=null}}_$AK(t,e){let r=this.constructor,i=r._$Eh.get(t);if(i!==void 0&&this._$Em!==i){let n=r.getPropertyOptions(i),o=typeof n.converter=="function"?{fromAttribute:n.converter}:n.converter?.fromAttribute!==void 0?n.converter:kr;this._$Em=i,this[i]=o.fromAttribute(e,n.type)??this._$Ej?.get(i)??null,this._$Em=null}}requestUpdate(t,e,r){if(t!==void 0){let i=this.constructor,n=this[t];if(r??(r=i.getPropertyOptions(t)),!((r.hasChanged??La)(n,e)||r.useDefault&&r.reflect&&n===this._$Ej?.get(t)&&!this.hasAttribute(i._$Eu(t,r))))return;this.C(t,e,r)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,e,{useDefault:r,reflect:i,wrapped:n},o){r&&!(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||r||(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 r=this.constructor.elementProperties;if(r.size>0)for(let[i,n]of r){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((r=>r.hostUpdate?.())),this.update(e)):this._$EM()}catch(r){throw t=!1,this._$EM(),r}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){}};qe.elementStyles=[],qe.shadowRootOptions={mode:"open"},qe[Pr("elementProperties")]=new Map,qe[Pr("finalized")]=new Map,uh?.({ReactiveElement:qe}),(At.reactiveElementVersions??(At.reactiveElementVersions=[])).push("2.1.0");var Nr=globalThis,Ra=Nr.trustedTypes,Vs=Ra?Ra.createPolicy("lit-html",{createHTML:a=>a}):void 0,Sn="$lit$",Qe=`lit$${Math.random().toFixed(9).slice(2)}$`,An="?"+Qe,ph=`<${An}>`,Kt=document,wr=()=>Kt.createComment(""),Lr=a=>a===null||typeof a!="object"&&typeof a!="function",En=Array.isArray,Zs=a=>En(a)||typeof a?.[Symbol.iterator]=="function",Cn=`[
|
|
145
145
|
\f\r]`,Ir=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Hs=/-->/g,$s=/>/g,_t=RegExp(`>|${Cn}(?:([^\\s"'>=/]+)(${Cn}*=${Cn}*(?:[^
|
|
146
|
-
\f\r"'\`<>=]|("|')|))|$)`,"g"),Ys=/'/g,zs=/"/g,Ws=/^(?:script|style|textarea|title)$/i,Mn=a=>(t,...e)=>({_$litType$:a,strings:t,values:e}),p=Mn(1),fe=Mn(2),ob=Mn(3),Xe=Symbol.for("lit-noChange"),f=Symbol.for("lit-nothing"),js=new WeakMap,Gt=Kt.createTreeWalker(Kt,129);function Js(a,t){if(!En(a)||!a.hasOwnProperty("raw"))throw Error("invalid template strings array");return Vs!==void 0?Vs.createHTML(t):t}var qs=(a,t)=>{let e=a.length-1,r=[],i,n=t===2?"<svg>":t===3?"<math>":"",o=Ir;for(let s=0;s<e;s++){let l=a[s],c,u,m=-1,g=0;for(;g<l.length&&(o.lastIndex=g,u=o.exec(l),u!==null);)g=o.lastIndex,o===Ir?u[1]==="!--"?o=Hs:u[1]!==void 0?o=$s:u[2]!==void 0?(Ws.test(u[2])&&(i=RegExp("</"+u[2],"g")),o=_t):u[3]!==void 0&&(o=_t):o===_t?u[0]===">"?(o=i??Ir,m=-1):u[1]===void 0?m=-2:(m=o.lastIndex-u[2].length,c=u[1],o=u[3]===void 0?_t:u[3]==='"'?zs:Ys):o===zs||o===Ys?o=_t:o===Hs||o===$s?o=Ir:(o=_t,i=void 0);let v=o===_t&&a[s+1].startsWith("/>")?" ":"";n+=o===Ir?l+ph:m>=0?(r.push(c),l.slice(0,m)+Sn+l.slice(m)+Qe+v):l+Qe+(m===-2?s:v)}return[Js(a,n+(a[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),r]},Rr=class a{constructor({strings:t,_$litType$:e},r){let i;this.parts=[];let n=0,o=0,s=t.length-1,l=this.parts,[c,u]=qs(t,e);if(this.el=a.createElement(c,r),Gt.currentNode=this.el.content,e===2||e===3){let m=this.el.content.firstChild;m.replaceWith(...m.childNodes)}for(;(i=Gt.nextNode())!==null&&l.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let m of i.getAttributeNames())if(m.endsWith(Sn)){let g=u[o++],v=i.getAttribute(m).split(Qe),M=/([.?@])?(.*)/.exec(g);l.push({type:1,index:n,name:M[2],strings:v,ctor:M[1]==="."?Ba:M[1]==="?"?Da:M[1]==="@"?Oa:Ut}),i.removeAttribute(m)}else m.startsWith(Qe)&&(l.push({type:6,index:n}),i.removeAttribute(m));if(Ws.test(i.tagName)){let m=i.textContent.split(Qe),g=m.length-1;if(g>0){i.textContent=Ra?Ra.emptyScript:"";for(let v=0;v<g;v++)i.append(m[v],wr()),Gt.nextNode(),l.push({type:2,index:++n});i.append(m[g],wr())}}}else if(i.nodeType===8)if(i.data===An)l.push({type:2,index:n});else{let m=-1;for(;(m=i.data.indexOf(Qe,m+1))!==-1;)l.push({type:7,index:n}),m+=Qe.length-1}n++}}static createElement(t,e){let r=Kt.createElement("template");return r.innerHTML=t,r}};function Ft(a,t,e=a,r){if(t===Xe)return t;let i=r!==void 0?e._$Co?.[r]:e._$Cl,n=Lr(t)?void 0:t._$litDirective$;return i?.constructor!==n&&(i?._$AO?.(!1),n===void 0?i=void 0:(i=new n(a),i._$AT(a,e,r)),r!==void 0?(e._$Co??(e._$Co=[]))[r]=i:e._$Cl=i),i!==void 0&&(t=Ft(a,i._$AS(a,t.values),i,r)),t}var xa=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:r}=this._$AD,i=(t?.creationScope??Kt).importNode(e,!0);Gt.currentNode=i;let n=Gt.nextNode(),o=0,s=0,l=r[0];for(;l!==void 0;){if(o===l.index){let c;l.type===2?c=new rr(n,n.nextSibling,this,t):l.type===1?c=new l.ctor(n,l.name,l.strings,this,t):l.type===6&&(c=new _a(n,this,t)),this._$AV.push(c),l=r[++s]}o!==l?.index&&(n=Gt.nextNode(),o++)}return Gt.currentNode=Kt,i}p(t){let e=0;for(let r of this._$AV)r!==void 0&&(r.strings!==void 0?(r._$AI(t,r,e),e+=r.strings.length-2):r._$AI(t[e])),e++}},rr=class a{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,e,r,i){this.type=2,this._$AH=f,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=r,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=Ft(this,t,e),Lr(t)?t===f||t==null||t===""?(this._$AH!==f&&this._$AR(),this._$AH=f):t!==this._$AH&&t!==Xe&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Zs(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!==f&&Lr(this._$AH)?this._$AA.nextSibling.data=t:this.T(Kt.createTextNode(t)),this._$AH=t}$(t){let{values:e,_$litType$:r}=t,i=typeof r=="number"?this._$AC(t):(r.el===void 0&&(r.el=Rr.createElement(Js(r.h,r.h[0]),this.options)),r);if(this._$AH?._$AD===i)this._$AH.p(e);else{let n=new xa(i,this),o=n.u(this.options);n.p(e),this.T(o),this._$AH=n}}_$AC(t){let e=js.get(t.strings);return e===void 0&&js.set(t.strings,e=new Rr(t)),e}k(t){En(this._$AH)||(this._$AH=[],this._$AR());let e=this._$AH,r,i=0;for(let n of t)i===e.length?e.push(r=new a(this.O(wr()),this.O(wr()),this,this.options)):r=e[i],r._$AI(n),i++;i<e.length&&(this._$AR(r&&r._$AB.nextSibling,i),e.length=i)}_$AR(t=this._$AA.nextSibling,e){for(this._$AP?.(!1,!0,e);t&&t!==this._$AB;){let r=t.nextSibling;t.remove(),t=r}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},Ut=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,r,i,n){this.type=1,this._$AH=f,this._$AN=void 0,this.element=t,this.name=e,this._$AM=i,this.options=n,r.length>2||r[0]!==""||r[1]!==""?(this._$AH=Array(r.length-1).fill(new String),this.strings=r):this._$AH=f}_$AI(t,e=this,r,i){let n=this.strings,o=!1;if(n===void 0)t=Ft(this,t,e,0),o=!Lr(t)||t!==this._$AH&&t!==Xe,o&&(this._$AH=t);else{let s=t,l,c;for(t=n[0],l=0;l<n.length-1;l++)c=Ft(this,s[r+l],e,l),c===Xe&&(c=this._$AH[l]),o||(o=!Lr(c)||c!==this._$AH[l]),c===f?t=f:t!==f&&(t+=(c??"")+n[l+1]),this._$AH[l]=c}o&&!i&&this.j(t)}j(t){t===f?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Ba=class extends Ut{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===f?void 0:t}},Da=class extends Ut{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==f)}},Oa=class extends Ut{constructor(t,e,r,i,n){super(t,e,r,i,n),this.type=5}_$AI(t,e=this){if((t=Ft(this,t,e,0)??f)===Xe)return;let r=this._$AH,i=t===f&&r!==f||t.capture!==r.capture||t.once!==r.once||t.passive!==r.passive,n=t!==f&&(r===f||i);i&&this.element.removeEventListener(this.name,this,r),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)}},_a=class{constructor(t,e,r){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=r}get _$AU(){return this._$AM._$AU}_$AI(t){Ft(this,t)}},Qs={M:Sn,P:Qe,A:An,C:1,L:qs,R:xa,D:Zs,V:Ft,I:rr,H:Ut,N:Da,U:Oa,B:Ba,F:_a},mh=Nr.litHtmlPolyfillSupport;mh?.(Rr,rr),(Nr.litHtmlVersions??(Nr.litHtmlVersions=[])).push("3.3.0");var Xs=(a,t,e)=>{let r=e?.renderBefore??t,i=r._$litPart$;if(i===void 0){let n=e?.renderBefore??null;r._$litPart$=i=new rr(t.insertBefore(wr(),n),n,void 0,e??{})}return i._$AI(a),i};var xr=globalThis,C=class extends qe{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=Xs(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Xe}};C._$litElement$=!0,C.finalized=!0,xr.litElementHydrateSupport?.({LitElement:C});var hh=xr.litElementPolyfillSupport;hh?.({LitElement:C});(xr.litElementVersions??(xr.litElementVersions=[])).push("4.2.0");var S=a=>(t,e)=>{e!==void 0?e.addInitializer((()=>{customElements.define(a,t)})):customElements.define(a,t)};var gh={attribute:!0,type:String,converter:kr,reflect:!1,hasChanged:La},fh=(a=gh,t,e)=>{let{kind:r,metadata:i}=e,n=globalThis.litPropertyMetadata.get(i);if(n===void 0&&globalThis.litPropertyMetadata.set(i,n=new Map),r==="setter"&&((a=Object.create(a)).wrapped=!0),n.set(e.name,a),r==="accessor"){let{name:o}=e;return{set(s){let l=t.get.call(this);t.set.call(this,s),this.requestUpdate(o,l,a)},init(s){return s!==void 0&&this.C(o,void 0,a,s),s}}}if(r==="setter"){let{name:o}=e;return function(s){let l=this[o];t.call(this,s),this.requestUpdate(o,l,a)}}throw Error("Unsupported decorator location: "+r)};function h(a){return(t,e)=>typeof e=="object"?fh(a,t,e):((r,i,n)=>{let o=i.hasOwnProperty(n);return i.constructor.createProperty(n,r),o?Object.getOwnPropertyDescriptor(i,n):void 0})(a,t,e)}function k(a){return h({...a,state:!0,attribute:!1})}var Vt=(a,t,e)=>(e.configurable=!0,e.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(a,t,e),e);function de(a,t){return(e,r,i)=>{let n=o=>o.renderRoot?.querySelector(a)??null;if(t){let{get:o,set:s}=typeof r=="object"?e:i??(()=>{let l=Symbol();return{get(){return this[l]},set(c){this[l]=c}}})();return Vt(e,r,{get(){let l=o.call(this);return l===void 0&&(l=n(this),(l!==null||this.hasUpdated)&&s.call(this,l)),l}})}return Vt(e,r,{get(){return n(this)}})}}function R(a,t,e){return a?t(a):e?.(a)}var I=b` * { box-sizing: border-box; } `,el=b` :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 Ga=class{constructor(t){this.paymentMethods=null;this.vaultController=null;this.isPaymentInProgress=null;this.headlessInstance=t,this.vault={createCvvInput:e=>this.createCvvInputInternal(e),startPayment:(e,r)=>this.startVaultPaymentInternal(e,r),delete:e=>this.deleteVaultPaymentMethod(e)}}setPaymentMethods(t){this.paymentMethods=t}setVaultController(t){this.vaultController=t}setPaymentInProgressCheck(t){this.isPaymentInProgress=t}async createCvvInputInternal(t){return this.vaultController?this.vaultController.createCvvInput(t):(T.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){T.errorWithDatadog("PrimerJS: Cannot refresh session: Headless instance not available");return}if(this.isPaymentInProgress?.()){T.warn("PrimerJS: refreshSession() skipped \u2014 a payment is in progress.");return}try{await this.headlessInstance.refreshClientSession()}catch(t){throw T.errorWithDatadog("PrimerJS: Error refreshing client session",{error:t}),t}}getPaymentMethods(){return this.paymentMethods?this.paymentMethods:(T.warn("PrimerJS: Payment methods not available"),[])}getInitializedPaymentMethods(){return this.paymentMethods??[]}handlePaymentStart(){this.onPaymentStart&&this.onPaymentStart()}handleVaultedMethodsUpdate(t,e){if(this.onVaultedMethodsUpdate){let r=Math.floor(Date.now()/1e3);this.onVaultedMethodsUpdate({vaultedPayments:t,cvvRecapture:e,timestamp:r})}}setCardholderName(t){let e=this.paymentMethods?.find(r=>r.type===P.PAYMENT_CARD)?.manager;if(!e){T.warn("PrimerJS: Card payment manager not available - setCardholderName cannot be called yet");return}try{e.setCardholderName(t)}catch(r){T.errorWithDatadog("PrimerJS: Error setting cardholder name",{error:r})}}};var tl=b` :host { display: contents; } .cta-button { display: block; margin: auto; } `;var te=class extends C{constructor(){super(...arguments);this.size="large";this.showCloseButton=!1;this.darkMode=!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.darkMode&&this.classList.add("primer-dark-theme"),this.open||this.openDialog()}updated(e){super.updated(e),e.has("darkMode")&&(this.darkMode?this.classList.add("primer-dark-theme"):this.classList.remove("primer-dark-theme")),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 class="${this.darkMode?"primer-dark-theme":""}" .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>`:f} ${this.cta.label}</primer-button>`:f}</primer-dialog>`:f}};te.styles=[I,tl],d([h({type:String})],te.prototype,"size",2),d([h({type:Boolean})],te.prototype,"showCloseButton",2),d([h({type:Boolean})],te.prototype,"darkMode",2),d([h({type:Object})],te.prototype,"onOpen",2),d([h({type:Object})],te.prototype,"onContentRendered",2),d([h({type:Object})],te.prototype,"cta",2),d([k()],te.prototype,"open",2),d([de("primer-dialog")],te.prototype,"dialog",2),te=d([S("primer-portal-dialog"),O()],te);var Ka=class{constructor(t){this.currentDialog=null;this.currentResolver=null;this.currentThreeDsResolver=null;this.host=t}async show(t){return new Promise(e=>{let r=new te;r.size=t.size??"large",r.showCloseButton=t.showCloseButton??!1;let i=document.querySelector("primer-checkout");r.darkMode=i?.classList.contains("primer-dark-theme")??!1,r.onContentRendered=t.onContentReady,r.cta=t.cta;let n=()=>{r.remove(),this.currentDialog=null,this.currentResolver=null,e({success:!1})};r.addEventListener("primer:dialog-close",n),this.currentDialog=r,this.currentResolver=e,document.body.appendChild(r),r.appendChild(t.htmlContent)})}close(){this.currentDialog&&this.currentResolver&&(this.currentDialog.closeDialog(),this.currentResolver({success:!0}),this.currentDialog.remove(),this.currentDialog=null,this.currentResolver=null)}async show3dsChallenge(t){let e=new CustomEvent("primer:3ds-challenge",{detail:{url:t.url,width:t.width,height:t.height},bubbles:!0,composed:!0,cancelable:!0});return this.host.dispatchEvent(e)?this.show({htmlContent:t.htmlContent,onContentReady:t.onContentReady}):new Promise(i=>{this.currentThreeDsResolver=i})}close3dsChallenge(){if(this.host.dispatchEvent(new CustomEvent("primer:3ds-challenge-completed",{detail:{},bubbles:!0,composed:!0})),this.currentThreeDsResolver){this.currentThreeDsResolver({success:!0}),this.currentThreeDsResolver=null;return}this.close()}};var yh=$r({"../../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.4ZFBST5B.js"),"../../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.A6DFGUKU.js"),"../../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.3MVWILFG.js"),"../../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.INYY7XZR.js"),"../../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.Y5IIDRC3.js"),"../../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.JZT46DAB.js"),"../../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.FJQOSK4N.js"),"../../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.TL522NMU.js"),"../../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.JFPWSECQ.js"),"../../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.GBZW2HPG.js"),"../../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.NFJ7HXSV.js"),"../../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.FX4YBDVU.js"),"../../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.JZD334EI.js"),"../../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.SHTM3UQK.js"),"../../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.MZYBSJWU.js"),"../../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.BQXGQQ4P.js"),"../../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.EK5WNO4N.js"),"../../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.N2BVXVWY.js"),"../../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.IJ37WK5P.js"),"../../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.2ZUPJDRP.js"),"../../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.BNLF6BZT.js"),"../../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.YJAZTBEF.js"),"../../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.GOVUI3KD.js"),"../../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.IPLRYI7A.js"),"../../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.EA76F4DL.js"),"../../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.I7E6LMWA.js"),"../../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.6I2BVK63.js"),"../../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.BYMLE7EQ.js"),"../../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.QOSIJQZE.js"),"../../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.DVZWMQJN.js"),"../../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.VK5CNTV3.js"),"../../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.22GYWGY5.js"),"../../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.L2PBSEBD.js"),"../../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.VFIM4IS3.js"),"../../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.VLLE4DKK.js"),"../../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.JALTDVLO.js"),"../../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.PQOCETM2.js"),"../../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.RGO57OCW.js"),"../../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.FQJP73FF.js"),"../../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.QYA26J2E.js"),"../../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.5ZDAANBV.js"),"../../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.FWQ7KVBB.js"),"../../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.GB6QZAMD.js"),"../../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.LNP32XVM.js"),"../../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.OEA7I6ZA.js"),"../../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.OUXNL5ZM.js"),"../../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.C5STTOCA.js")});var ar=null,Tn=null;async function rl(a){if(Tn===a&&ar)return ar;try{return ar=(await yh(`../../../localization/lit-localize/locales/${a}.ts`)).templates,Tn=a,ar}catch{return a!=="en-GB"?rl("en-GB"):(ar={},Tn=a,ar)}}async function al(a){let t=await rl(a);return(e,r)=>t[e]??r}function il(a,t,e){return a.isDisconnected?!1:(a.host.sdkContextController.contextProvider.value.sdkState.paymentFailure!==null&&Q({eventName:"PAYMENT_REATTEMPTED",paymentMethod:t}),a.host.sdkContextController.setSdkState({isProcessing:!0,paymentFailure:null,primerJsError:null}),a.host.primerEventsController.dispatchPaymentStart(t,e))}function nl(a,t,e){if(!a.isDisconnected&&(T.info("Payment completed:",t),a.host.sdkContextController.setSdkState({isProcessing:!1,isSuccessful:!0}),a.host.primerEventsController.dispatchPaymentSuccess(t,e),Q({eventName:"PAYMENT_SUCCESS",paymentId:t?.id,paymentMethod:e}),a.primerJS?.onPaymentSuccess)){let r=Math.floor(Date.now()/1e3);a.primerJS.onPaymentSuccess({payment:Qt(t),paymentMethodType:e,timestamp:r})}}function ol(a,t,e,r){if(a.isDisconnected)return;(l=>typeof l=="object"&&l!==null&&"response"in l&&typeof l.response=="object"&&l.response!==null&&"status"in l.response&&typeof l.response.status=="number")(t)&&t.response.status>=500?T.errorWithDatadog("Payment failed with server error",{error:t}):T.error("Payment failed:",t);let o=l=>{if(typeof l!="object"||l===null||!("response"in l))return;let c=l.response;return typeof c?.id=="string"?c.id:void 0},s=(()=>{let l=t,c=l instanceof Error||typeof l=="object"&&l!==null&&typeof l.message=="string",u=c&&"code"in l&&typeof l.code=="string"?l.code:"UNKNOWN_ERROR",m=c?l.message:"Unknown error occurred";return{code:u,message:m,diagnosticsId:o(l),data:{error:t}}})();if(a.host.sdkContextController.setSdkState({isProcessing:!1,paymentFailure:s}),a.host.primerEventsController.dispatchPaymentFailure({code:s.code,message:s.message,diagnosticsId:"diagnosticsId"in s?s.diagnosticsId??void 0:void 0,data:s.data},e,r),Q({eventName:"PAYMENT_FAILURE",paymentId:r?.id,paymentMethod:e}),a.primerJS?.onPaymentFailure){let l=Math.floor(Date.now()/1e3);a.primerJS.onPaymentFailure({error:{code:s.code,message:s.message,diagnosticsId:"diagnosticsId"in s?s.diagnosticsId??void 0:void 0,data:s.data},payment:r?Qt(r):void 0,paymentMethodType:e,timestamp:l})}}var sl="1.6.0",Fa=class{constructor(t){this.currentSdkInstance=null;this.primerJS=null;this.loadingTimeout=null;this.isDisconnected=!1;(this.host=t).addController(this),this.isDisconnected=!1,new j(t,{args:()=>[this.host.clientToken,this.host.options],task:this.initializeHeadless()})}get primerJSInstance(){return this.primerJS}hostConnected(){this.isDisconnected=!1,this.host.sdkContextController.setSdkState({isLoading:!0}),this.setupLoadingTimeout()}hostDisconnected(){if(this.isDisconnected=!0,this.host.sdkContextController.contextProvider?.value?.analytics){let e=this.host.sdkContextController.contextProvider.value.sdkState;(e.isProcessing||e.isLoading||this.currentSdkInstance)&&Q({eventName:"PAYMENT_FLOW_EXITED"})}this.cleanupResources()}setupLoadingTimeout(){this.clearLoadingTimeout(),this.loadingTimeout=setTimeout(()=>{this.host.sdkContextController.contextProvider.value.sdkState.isLoading&&(T.warn("Loading timeout reached, resetting SDK state"),Q({eventName:"PAYMENT_FLOW_EXITED",eventType:"timeout"}),this.cleanupResources(),this.host.sdkContextController.setSdkState({isLoading:!1}))},1e4)}clearLoadingTimeout(){this.loadingTimeout!==null&&(clearTimeout(this.loadingTimeout),this.loadingTimeout=null)}cleanupResources(){if(this.clearLoadingTimeout(),this.currentSdkInstance)try{this.host.sdkContextController.resetSdkState(),this.currentSdkInstance.teardown?.(),T.info("SDK instance cleaned up")}catch(t){T.errorWithDatadog("Error cleaning up SDK instance",{error:t})}Ts(),T.setClientToken(void 0),T.setSdkOptions(void 0),this.currentSdkInstance=null,this.primerJS=null}handlePaymentApprovalRequired(t){this.isDisconnected||(this.host.sdkContextController.setSdkState({isProcessing:!0,paymentFailure:null,primerJsError:null}),this.host.primerEventsController.dispatchPaymentApprovalRequired(t))}initializeHeadless(){return async([t,e])=>{if(this.isDisconnected)return T.warn("Component disconnected, aborting SDK initialization"),Y;if(!t||!e)return Y;this.cleanupResources();let r;try{let i=new Ka(this.host),n=tr(e.locale||Ia()),o=await al(n);this.primerJS=new Ga(null),this.primerJS.setVaultController(this.host.vaultManagerController),this.primerJS.setPaymentInProgressCheck(()=>this.isProcessing),T.setClientToken(t),T.setSdkOptions(e);let s=[],l=await cs(t,{...e,dialogProvider:i,translate:o,sdkVersion:sl,locale:n,onAvailablePaymentMethodsLoad:g=>{this.isDisconnected||(T.info("Configuration payment methods:",g),s=g)},onAvailablePaymentMethodsRefresh:g=>{this.onMethodsRefreshed(g)},onCheckoutComplete:({payment:g})=>{let v=g?.paymentMethodData?.paymentMethodType;nl({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},g,v)},onCheckoutFail:(g,v)=>{let M=v.payment?.paymentMethodData?.paymentMethodType;ol({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},g,M,v.payment)},onBeforePaymentCreate:(g,v)=>{if(!g.paymentMethodType){T.error("Payment creation started without payment method type"),v?.abortPaymentCreation();return}if(!(il({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},g.paymentMethodType,v)||this.isDisconnected)){if(this.primerJS?.onPaymentPrepare){this.primerJS.onPaymentPrepare({paymentMethodType:g.paymentMethodType},v);return}v?.continuePaymentCreation()}},onPaymentMethodAction:(g,v)=>{this.isDisconnected||g==="PAYMENT_METHOD_UNSELECTED"&&(this.host.primerEventsController.dispatchPaymentCancel(v),this.host.sdkContextController.setSdkState({isProcessing:!1}))},onPaymentCreationStart:()=>{this.isDisconnected||this.primerJS&&this.primerJS.handlePaymentStart()},onPaymentApprovalRequired:g=>this.handlePaymentApprovalRequired(g),onCheckoutResume:()=>{this.isDisconnected||this.host.sdkContextController.setSdkState({isProcessing:!0,paymentFailure:null,primerJsError:null})}});if(this.currentSdkInstance=l,this.primerJS&&Object.defineProperty(this.primerJS,"headlessInstance",{value:l,writable:!1}),await l.start(),this.isDisconnected)return this.cleanupResources(),Y;let c=l.getSDKUtilities();r=l.getAnalyticsUtils?.(),r&&(Ms({environment:r.environment,checkoutSessionId:r.checkoutSessionId,clientSessionId:r.clientSessionId||"",primerAccountId:r.primerAccountId||"",sdkVersion:sl,clientSessionToken:r.clientSessionToken,userAgent:typeof navigator<"u"?navigator.userAgent:""}),r.configurationFetchStartTime&&Ge.setSdkInitStartTime(r.configurationFetchStartTime),Q({eventName:"SDK_INIT_START"})),this.host.vaultManagerController.initializeVaultManager(l.createVaultManager.bind(l),{vaultEnabled:e.vault?.enabled,captureVaultedCardCvv:!!c.getPaymentMethodConfiguration("PAYMENT_CARD")?.options?.captureVaultedCardCvv,showEmptyState:e.vault?.showEmptyState,headless:e.vault?.headless??!1});let u=(await Promise.all(s.map(async g=>{let v=await this.createManager(g,l);return v?{...g,manager:v}:null}))).filter(g=>!!g),m={clientOptions:e,analytics:r,headlessUtils:c,configuration:l.getConfiguration?.(),paymentMethods:u};return this.host.sdkContextController.setContext(m),this.primerJS&&(this.host.primerEventsController.dispatchCheckoutInitialized(this.primerJS),this.primerJS.setPaymentMethods(u)),this.host.primerEventsController.dispatchPaymentMethods(u),T.info("Initialized payment methods:",u),this.host.sdkContextController.setSdkState({isLoading:!1}),Q({eventName:"SDK_INIT_END"}),l}catch(i){throw i instanceof Error&&(T.errorWithDatadog("SDK initialization error",{error:i,status:"error"}),this.host.sdkContextController.setSdkState({primerJsError:i})),this.cleanupResources(),i}}}async createManager(t,e){try{if(t.managerType==="KLARNA")return await e.createPaymentMethodManager("KLARNA",{onPaymentMethodCategoriesChange:r=>{this.isDisconnected||this.host.sdkContextController.setKlarnaCategories({categories:r,isLoading:!1})}});if(t.managerType==="ADYEN_KLARNA"){let r=await e.createPaymentMethodManager("ADYEN_KLARNA",{onPaymentOptionsChange:i=>{this.isDisconnected||this.host.sdkContextController.setAdyenKlarnaOptions({options:i,isLoading:!1})}});if(r&&"getPaymentOptions"in r){let i=r.getPaymentOptions();i.length>0&&this.host.sdkContextController.setAdyenKlarnaOptions({options:i,isLoading:!1})}return r}return t.managerType==="CARD"?await e.createPaymentMethodManager("PAYMENT_CARD",{onBinDataAvailable:r=>{this.isDisconnected||this.host.primerEventsController.dispatchBinDataAvailable(r)},onCardNetworksChange:r=>{if(this.isDisconnected)return;let{detectedCardNetworks:i,selectableCardNetworks:n}=r;this.updateCardNetworksState({detectedCardNetwork:i.preferred??i.items[0],selectableCardNetworks:n?.items??[],isLoading:!1})},onBinDataLoadingChange:r=>{this.isDisconnected||(r?this.updateCardNetworksState({detectedCardNetwork:null,selectableCardNetworks:[],isLoading:!0}):this.host.sdkContextController.setCardNetworksLoadingFalse(),this.host.primerEventsController.dispatchBinDataLoadingChange(r))}}):await e.createPaymentMethodManager(t.type)}catch(r){T.errorWithDatadog(`Failed to initialize manager for ${t.type}`,{error:r})}}updateCardNetworksState(t){this.host.primerEventsController.dispatchCardNetworkChange(t),this.host.sdkContextController.setCardNetworks(t)}get isProcessing(){return!!this.host.sdkContextController.contextProvider?.value?.sdkState?.isProcessing}async onMethodsRefreshed(t){if(this.isDisconnected||!this.currentSdkInstance||!this.primerJS)return;let e=this.primerJS.getInitializedPaymentMethods(),r=new Map(e.map(l=>[l.type,l])),i=new Set(t.map(l=>l.type)),n=this.currentSdkInstance,o=await Promise.all(t.map(async l=>{let c=r.get(l.type);if(c)return c;let u=await this.createManager(l,n);return u?{...l,manager:u}:null}));if(this.isDisconnected||this.currentSdkInstance!==n||!this.primerJS)return;let s=o.filter(l=>l!==null);e.some(l=>l.type===P.KLARNA)&&!i.has(P.KLARNA)&&this.host.sdkContextController.setKlarnaCategories({categories:[],isLoading:!1}),e.some(l=>l.type===P.ADYEN_KLARNA)&&!i.has(P.ADYEN_KLARNA)&&this.host.sdkContextController.setAdyenKlarnaOptions({options:[],isLoading:!1}),this.primerJS.setPaymentMethods(s),this.host.sdkContextController.setContext({paymentMethods:s,configuration:n.getConfiguration?.()}),this.host.primerEventsController.dispatchPaymentMethods(s)}};var vh=$r({"../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.4ZFBST5B.js"),"../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.A6DFGUKU.js"),"../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.3MVWILFG.js"),"../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.INYY7XZR.js"),"../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.Y5IIDRC3.js"),"../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.JZT46DAB.js"),"../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.FJQOSK4N.js"),"../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.TL522NMU.js"),"../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.JFPWSECQ.js"),"../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.GBZW2HPG.js"),"../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.NFJ7HXSV.js"),"../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.FX4YBDVU.js"),"../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.JZD334EI.js"),"../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.SHTM3UQK.js"),"../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.MZYBSJWU.js"),"../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.BQXGQQ4P.js"),"../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.EK5WNO4N.js"),"../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.N2BVXVWY.js"),"../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.IJ37WK5P.js"),"../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.2ZUPJDRP.js"),"../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.BNLF6BZT.js"),"../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.YJAZTBEF.js"),"../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.GOVUI3KD.js"),"../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.IPLRYI7A.js"),"../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.EA76F4DL.js"),"../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.I7E6LMWA.js"),"../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.6I2BVK63.js"),"../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.BYMLE7EQ.js"),"../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.QOSIJQZE.js"),"../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.DVZWMQJN.js"),"../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.VK5CNTV3.js"),"../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.22GYWGY5.js"),"../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.L2PBSEBD.js"),"../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.VFIM4IS3.js"),"../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.VLLE4DKK.js"),"../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.JALTDVLO.js"),"../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.PQOCETM2.js"),"../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.RGO57OCW.js"),"../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.FQJP73FF.js"),"../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.QYA26J2E.js"),"../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.5ZDAANBV.js"),"../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.FWQ7KVBB.js"),"../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.GB6QZAMD.js"),"../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.LNP32XVM.js"),"../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.OEA7I6ZA.js"),"../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.OUXNL5ZM.js"),"../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.C5STTOCA.js")});hn(a=>vh(`../../localization/lit-localize/locales/${a}.ts`));var bh={LOADER_DISABLED:"loader-disabled",CUSTOM_STYLES:"custom-styles",CLIENT_TOKEN:"client-token",JS_INIT:"js-initialized"},ye=class extends C{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._classObserver=null;this.locale=tr(Ia());this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0,this.requestUpdate()};this.sdkContextController=new ha(this),this.primerEventsController=new Xt(this),this.styleProcessingController=new ga(this),this.vaultManagerController=new Cr(this),this.headlessSdkController=new Fa(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}),this._classObserver=new MutationObserver(()=>{this.requestUpdate()}),this._classObserver.observe(this,{attributes:!0,attributeFilter:["class"]})}attributeChangedCallback(e,r,i){e===bh.CUSTOM_STYLES?this.styleProcessingController.processCustomStyles(i):super.attributeChangedCallback(e,r,i)}disconnectedCallback(){this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null),this.sdkContextController.contextProvider.value.sdkState?.isLoading&&this.sdkContextController.setSdkState({isLoading:!1}),this._eventListenerController&&(this._eventListenerController.abort(),this._eventListenerController=null),this._classObserver&&(this._classObserver.disconnect(),this._classObserver=null),super.disconnectedCallback()}willUpdate(e){e.has("options")&&(this.options?.locale&&(yn(this.options?.locale)?this.locale=tr(this.options?.locale):T.warn("\u{1F30E}\u2757 Unsupported locale provided:",this.options?.locale,"- Falling back to system locale")),gn(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.sdkContextController.contextProvider.value.sdkState.isLoading||!1;if(this.previousLoadingState&&!e){this.jsInitialized=!0,Q({eventName:"CHECKOUT_FLOW_STARTED"});let r=Ge.getSdkInitStartTime(),i=r?Date.now()-r:void 0;Wn(i)}this.previousLoadingState=e,e&&!this._loadingTimeoutId?this._loadingTimeoutId=window.setTimeout(()=>{this.sdkContextController.contextProvider.value.sdkState.isLoading&&(T.warn("Loading timeout in component, forcing completion"),this.sdkContextController.setSdkState({isLoading:!1}),this.jsInitialized=!0),this._loadingTimeoutId=null},1e4):!e&&this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null)}render(){let e=this.sdkContextController.contextProvider.value.sdkState,r=e.isLoading,i=e.primerJsError,n=!r&&!i;return p` ${R(i,()=>p`<primer-checkout-error></primer-checkout-error>`)}<slot name="main" @slotchange=${this.onSlotChange}></slot>${R(this.hasAssignedContent||!n,()=>f,()=>p`<primer-main></primer-main>`)} `}addEventListener(e,r,i){super.addEventListener(e,r,i)}removeEventListener(e,r,i){super.removeEventListener(e,r,i)}};ye.styles=[I,el],d([h({type:String,attribute:"custom-styles"})],ye.prototype,"customStyles",2),d([h({type:String,attribute:"client-token"})],ye.prototype,"clientToken",2),d([h({type:Object,attribute:!1,hasChanged:(e,r)=>!vt(e,r)})],ye.prototype,"options",2),d([h({type:Boolean,attribute:"loader-disabled"})],ye.prototype,"disableLoader",2),d([h({type:Boolean,reflect:!0,attribute:"js-initialized"})],ye.prototype,"_jsInitialized",2),d([de("slot")],ye.prototype,"defaultSlot",2),d([k()],ye.prototype,"previousLoadingState",2),ye=d([O(),S("primer-checkout")],ye);var ll=typeof window<"u"&&typeof window.document<"u";function Ch(a){return document.querySelector(`#${a}`)}function Sh(a,t){let e=document.createElement("style");return e.textContent=a,e.id=t,e}function Br(a,t,e=!0){if(!ll||Ch(t))return;let i=Sh(a,t);e&&document.head.firstChild?document.head.insertBefore(i,document.head.firstChild):document.head.appendChild(i)}var dl=`
|
|
146
|
+
\f\r"'\`<>=]|("|')|))|$)`,"g"),Ys=/'/g,zs=/"/g,Ws=/^(?:script|style|textarea|title)$/i,Mn=a=>(t,...e)=>({_$litType$:a,strings:t,values:e}),p=Mn(1),fe=Mn(2),ob=Mn(3),Xe=Symbol.for("lit-noChange"),f=Symbol.for("lit-nothing"),js=new WeakMap,Gt=Kt.createTreeWalker(Kt,129);function Js(a,t){if(!En(a)||!a.hasOwnProperty("raw"))throw Error("invalid template strings array");return Vs!==void 0?Vs.createHTML(t):t}var qs=(a,t)=>{let e=a.length-1,r=[],i,n=t===2?"<svg>":t===3?"<math>":"",o=Ir;for(let s=0;s<e;s++){let l=a[s],c,u,m=-1,g=0;for(;g<l.length&&(o.lastIndex=g,u=o.exec(l),u!==null);)g=o.lastIndex,o===Ir?u[1]==="!--"?o=Hs:u[1]!==void 0?o=$s:u[2]!==void 0?(Ws.test(u[2])&&(i=RegExp("</"+u[2],"g")),o=_t):u[3]!==void 0&&(o=_t):o===_t?u[0]===">"?(o=i??Ir,m=-1):u[1]===void 0?m=-2:(m=o.lastIndex-u[2].length,c=u[1],o=u[3]===void 0?_t:u[3]==='"'?zs:Ys):o===zs||o===Ys?o=_t:o===Hs||o===$s?o=Ir:(o=_t,i=void 0);let v=o===_t&&a[s+1].startsWith("/>")?" ":"";n+=o===Ir?l+ph:m>=0?(r.push(c),l.slice(0,m)+Sn+l.slice(m)+Qe+v):l+Qe+(m===-2?s:v)}return[Js(a,n+(a[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),r]},Rr=class a{constructor({strings:t,_$litType$:e},r){let i;this.parts=[];let n=0,o=0,s=t.length-1,l=this.parts,[c,u]=qs(t,e);if(this.el=a.createElement(c,r),Gt.currentNode=this.el.content,e===2||e===3){let m=this.el.content.firstChild;m.replaceWith(...m.childNodes)}for(;(i=Gt.nextNode())!==null&&l.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let m of i.getAttributeNames())if(m.endsWith(Sn)){let g=u[o++],v=i.getAttribute(m).split(Qe),M=/([.?@])?(.*)/.exec(g);l.push({type:1,index:n,name:M[2],strings:v,ctor:M[1]==="."?Ba:M[1]==="?"?Da:M[1]==="@"?Oa:Ut}),i.removeAttribute(m)}else m.startsWith(Qe)&&(l.push({type:6,index:n}),i.removeAttribute(m));if(Ws.test(i.tagName)){let m=i.textContent.split(Qe),g=m.length-1;if(g>0){i.textContent=Ra?Ra.emptyScript:"";for(let v=0;v<g;v++)i.append(m[v],wr()),Gt.nextNode(),l.push({type:2,index:++n});i.append(m[g],wr())}}}else if(i.nodeType===8)if(i.data===An)l.push({type:2,index:n});else{let m=-1;for(;(m=i.data.indexOf(Qe,m+1))!==-1;)l.push({type:7,index:n}),m+=Qe.length-1}n++}}static createElement(t,e){let r=Kt.createElement("template");return r.innerHTML=t,r}};function Ft(a,t,e=a,r){if(t===Xe)return t;let i=r!==void 0?e._$Co?.[r]:e._$Cl,n=Lr(t)?void 0:t._$litDirective$;return i?.constructor!==n&&(i?._$AO?.(!1),n===void 0?i=void 0:(i=new n(a),i._$AT(a,e,r)),r!==void 0?(e._$Co??(e._$Co=[]))[r]=i:e._$Cl=i),i!==void 0&&(t=Ft(a,i._$AS(a,t.values),i,r)),t}var xa=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:r}=this._$AD,i=(t?.creationScope??Kt).importNode(e,!0);Gt.currentNode=i;let n=Gt.nextNode(),o=0,s=0,l=r[0];for(;l!==void 0;){if(o===l.index){let c;l.type===2?c=new rr(n,n.nextSibling,this,t):l.type===1?c=new l.ctor(n,l.name,l.strings,this,t):l.type===6&&(c=new _a(n,this,t)),this._$AV.push(c),l=r[++s]}o!==l?.index&&(n=Gt.nextNode(),o++)}return Gt.currentNode=Kt,i}p(t){let e=0;for(let r of this._$AV)r!==void 0&&(r.strings!==void 0?(r._$AI(t,r,e),e+=r.strings.length-2):r._$AI(t[e])),e++}},rr=class a{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,e,r,i){this.type=2,this._$AH=f,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=r,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=Ft(this,t,e),Lr(t)?t===f||t==null||t===""?(this._$AH!==f&&this._$AR(),this._$AH=f):t!==this._$AH&&t!==Xe&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Zs(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!==f&&Lr(this._$AH)?this._$AA.nextSibling.data=t:this.T(Kt.createTextNode(t)),this._$AH=t}$(t){let{values:e,_$litType$:r}=t,i=typeof r=="number"?this._$AC(t):(r.el===void 0&&(r.el=Rr.createElement(Js(r.h,r.h[0]),this.options)),r);if(this._$AH?._$AD===i)this._$AH.p(e);else{let n=new xa(i,this),o=n.u(this.options);n.p(e),this.T(o),this._$AH=n}}_$AC(t){let e=js.get(t.strings);return e===void 0&&js.set(t.strings,e=new Rr(t)),e}k(t){En(this._$AH)||(this._$AH=[],this._$AR());let e=this._$AH,r,i=0;for(let n of t)i===e.length?e.push(r=new a(this.O(wr()),this.O(wr()),this,this.options)):r=e[i],r._$AI(n),i++;i<e.length&&(this._$AR(r&&r._$AB.nextSibling,i),e.length=i)}_$AR(t=this._$AA.nextSibling,e){for(this._$AP?.(!1,!0,e);t&&t!==this._$AB;){let r=t.nextSibling;t.remove(),t=r}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},Ut=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,r,i,n){this.type=1,this._$AH=f,this._$AN=void 0,this.element=t,this.name=e,this._$AM=i,this.options=n,r.length>2||r[0]!==""||r[1]!==""?(this._$AH=Array(r.length-1).fill(new String),this.strings=r):this._$AH=f}_$AI(t,e=this,r,i){let n=this.strings,o=!1;if(n===void 0)t=Ft(this,t,e,0),o=!Lr(t)||t!==this._$AH&&t!==Xe,o&&(this._$AH=t);else{let s=t,l,c;for(t=n[0],l=0;l<n.length-1;l++)c=Ft(this,s[r+l],e,l),c===Xe&&(c=this._$AH[l]),o||(o=!Lr(c)||c!==this._$AH[l]),c===f?t=f:t!==f&&(t+=(c??"")+n[l+1]),this._$AH[l]=c}o&&!i&&this.j(t)}j(t){t===f?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Ba=class extends Ut{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===f?void 0:t}},Da=class extends Ut{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==f)}},Oa=class extends Ut{constructor(t,e,r,i,n){super(t,e,r,i,n),this.type=5}_$AI(t,e=this){if((t=Ft(this,t,e,0)??f)===Xe)return;let r=this._$AH,i=t===f&&r!==f||t.capture!==r.capture||t.once!==r.once||t.passive!==r.passive,n=t!==f&&(r===f||i);i&&this.element.removeEventListener(this.name,this,r),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)}},_a=class{constructor(t,e,r){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=r}get _$AU(){return this._$AM._$AU}_$AI(t){Ft(this,t)}},Qs={M:Sn,P:Qe,A:An,C:1,L:qs,R:xa,D:Zs,V:Ft,I:rr,H:Ut,N:Da,U:Oa,B:Ba,F:_a},mh=Nr.litHtmlPolyfillSupport;mh?.(Rr,rr),(Nr.litHtmlVersions??(Nr.litHtmlVersions=[])).push("3.3.0");var Xs=(a,t,e)=>{let r=e?.renderBefore??t,i=r._$litPart$;if(i===void 0){let n=e?.renderBefore??null;r._$litPart$=i=new rr(t.insertBefore(wr(),n),n,void 0,e??{})}return i._$AI(a),i};var xr=globalThis,C=class extends qe{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=Xs(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Xe}};C._$litElement$=!0,C.finalized=!0,xr.litElementHydrateSupport?.({LitElement:C});var hh=xr.litElementPolyfillSupport;hh?.({LitElement:C});(xr.litElementVersions??(xr.litElementVersions=[])).push("4.2.0");var S=a=>(t,e)=>{e!==void 0?e.addInitializer((()=>{customElements.define(a,t)})):customElements.define(a,t)};var gh={attribute:!0,type:String,converter:kr,reflect:!1,hasChanged:La},fh=(a=gh,t,e)=>{let{kind:r,metadata:i}=e,n=globalThis.litPropertyMetadata.get(i);if(n===void 0&&globalThis.litPropertyMetadata.set(i,n=new Map),r==="setter"&&((a=Object.create(a)).wrapped=!0),n.set(e.name,a),r==="accessor"){let{name:o}=e;return{set(s){let l=t.get.call(this);t.set.call(this,s),this.requestUpdate(o,l,a)},init(s){return s!==void 0&&this.C(o,void 0,a,s),s}}}if(r==="setter"){let{name:o}=e;return function(s){let l=this[o];t.call(this,s),this.requestUpdate(o,l,a)}}throw Error("Unsupported decorator location: "+r)};function h(a){return(t,e)=>typeof e=="object"?fh(a,t,e):((r,i,n)=>{let o=i.hasOwnProperty(n);return i.constructor.createProperty(n,r),o?Object.getOwnPropertyDescriptor(i,n):void 0})(a,t,e)}function k(a){return h({...a,state:!0,attribute:!1})}var Vt=(a,t,e)=>(e.configurable=!0,e.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(a,t,e),e);function de(a,t){return(e,r,i)=>{let n=o=>o.renderRoot?.querySelector(a)??null;if(t){let{get:o,set:s}=typeof r=="object"?e:i??(()=>{let l=Symbol();return{get(){return this[l]},set(c){this[l]=c}}})();return Vt(e,r,{get(){let l=o.call(this);return l===void 0&&(l=n(this),(l!==null||this.hasUpdated)&&s.call(this,l)),l}})}return Vt(e,r,{get(){return n(this)}})}}function R(a,t,e){return a?t(a):e?.(a)}var I=b` * { box-sizing: border-box; } `,el=b` :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 Ga=class{constructor(t){this.paymentMethods=null;this.vaultController=null;this.isPaymentInProgress=null;this.headlessInstance=t,this.vault={createCvvInput:e=>this.createCvvInputInternal(e),startPayment:(e,r)=>this.startVaultPaymentInternal(e,r),delete:e=>this.deleteVaultPaymentMethod(e)}}setPaymentMethods(t){this.paymentMethods=t}setVaultController(t){this.vaultController=t}setPaymentInProgressCheck(t){this.isPaymentInProgress=t}async createCvvInputInternal(t){return this.vaultController?this.vaultController.createCvvInput(t):(T.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){T.errorWithDatadog("PrimerJS: Cannot refresh session: Headless instance not available");return}if(this.isPaymentInProgress?.()){T.warn("PrimerJS: refreshSession() skipped \u2014 a payment is in progress.");return}try{await this.headlessInstance.refreshClientSession()}catch(t){throw T.errorWithDatadog("PrimerJS: Error refreshing client session",{error:t}),t}}getPaymentMethods(){return this.paymentMethods?this.paymentMethods:(T.warn("PrimerJS: Payment methods not available"),[])}getInitializedPaymentMethods(){return this.paymentMethods??[]}handlePaymentStart(){this.onPaymentStart&&this.onPaymentStart()}handleVaultedMethodsUpdate(t,e){if(this.onVaultedMethodsUpdate){let r=Math.floor(Date.now()/1e3);this.onVaultedMethodsUpdate({vaultedPayments:t,cvvRecapture:e,timestamp:r})}}setCardholderName(t){let e=this.paymentMethods?.find(r=>r.type===P.PAYMENT_CARD)?.manager;if(!e){T.warn("PrimerJS: Card payment manager not available - setCardholderName cannot be called yet");return}try{e.setCardholderName(t)}catch(r){T.errorWithDatadog("PrimerJS: Error setting cardholder name",{error:r})}}};var tl=b` :host { display: contents; } .cta-button { display: block; margin: auto; } `;var te=class extends C{constructor(){super(...arguments);this.size="large";this.showCloseButton=!1;this.darkMode=!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.darkMode&&this.classList.add("primer-dark-theme"),this.open||this.openDialog()}updated(e){super.updated(e),e.has("darkMode")&&(this.darkMode?this.classList.add("primer-dark-theme"):this.classList.remove("primer-dark-theme")),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 class="${this.darkMode?"primer-dark-theme":""}" .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>`:f} ${this.cta.label}</primer-button>`:f}</primer-dialog>`:f}};te.styles=[I,tl],d([h({type:String})],te.prototype,"size",2),d([h({type:Boolean})],te.prototype,"showCloseButton",2),d([h({type:Boolean})],te.prototype,"darkMode",2),d([h({type:Object})],te.prototype,"onOpen",2),d([h({type:Object})],te.prototype,"onContentRendered",2),d([h({type:Object})],te.prototype,"cta",2),d([k()],te.prototype,"open",2),d([de("primer-dialog")],te.prototype,"dialog",2),te=d([S("primer-portal-dialog"),O()],te);var Ka=class{constructor(t){this.currentDialog=null;this.currentResolver=null;this.currentThreeDsResolver=null;this.host=t}async show(t){return new Promise(e=>{let r=new te;r.size=t.size??"large",r.showCloseButton=t.showCloseButton??!1;let i=document.querySelector("primer-checkout");r.darkMode=i?.classList.contains("primer-dark-theme")??!1,r.onContentRendered=t.onContentReady,r.cta=t.cta;let n=()=>{r.remove(),this.currentDialog=null,this.currentResolver=null,e({success:!1})};r.addEventListener("primer:dialog-close",n),this.currentDialog=r,this.currentResolver=e,document.body.appendChild(r),r.appendChild(t.htmlContent)})}close(){this.currentDialog&&this.currentResolver&&(this.currentDialog.closeDialog(),this.currentResolver({success:!0}),this.currentDialog.remove(),this.currentDialog=null,this.currentResolver=null)}async show3dsChallenge(t){let e=new CustomEvent("primer:3ds-challenge",{detail:{url:t.url,width:t.width,height:t.height},bubbles:!0,composed:!0,cancelable:!0});return this.host.dispatchEvent(e)?this.show({htmlContent:t.htmlContent,onContentReady:t.onContentReady}):new Promise(i=>{this.currentThreeDsResolver=i})}close3dsChallenge(){if(this.host.dispatchEvent(new CustomEvent("primer:3ds-challenge-completed",{detail:{},bubbles:!0,composed:!0})),this.currentThreeDsResolver){this.currentThreeDsResolver({success:!0}),this.currentThreeDsResolver=null;return}this.close()}};var yh=$r({"../../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.BIHRX5RF.js"),"../../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.FGU6YCAF.js"),"../../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.IKG75KNP.js"),"../../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.MILBDWY6.js"),"../../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.JTASZFYV.js"),"../../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.DXQD6OEP.js"),"../../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.EFHFPB3R.js"),"../../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.SXPN4WN6.js"),"../../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.NNAZENAS.js"),"../../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.PGD5Q57R.js"),"../../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.PTII2RTJ.js"),"../../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.AKW6WGRC.js"),"../../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.LHI2XOXI.js"),"../../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.IPGRD7WF.js"),"../../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.PDUWBPKF.js"),"../../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.5SDFV353.js"),"../../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.LXFZTJMG.js"),"../../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.VXISLOF3.js"),"../../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.UCNPGRJA.js"),"../../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.F7GBFWC2.js"),"../../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.BHTV4F5V.js"),"../../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.L4TUG67I.js"),"../../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.ULLOOI4H.js"),"../../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.WAZLYIAI.js"),"../../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.TEXPN3ZR.js"),"../../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.TQJGMNOY.js"),"../../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.Q2C5ZFHD.js"),"../../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.KCZ6D34T.js"),"../../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.2CTHY5J7.js"),"../../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.SYW24NKO.js"),"../../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.AI5CECVT.js"),"../../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.OWKVFNRL.js"),"../../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.LVBHJFXR.js"),"../../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.SJYNCSI5.js"),"../../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.3HE2B7ZT.js"),"../../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.YAEVPIZD.js"),"../../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.BA3GBVRO.js"),"../../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.3C6VVYBB.js"),"../../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.2VDFAELX.js"),"../../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.J7ZUQIZS.js"),"../../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.E2CHOIPA.js"),"../../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.QYJJIGTW.js"),"../../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.YGBNA3NJ.js"),"../../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.LNP32XVM.js"),"../../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.SRN7TXMD.js"),"../../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.3JAKYZ5N.js"),"../../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.WTNQLAHV.js")});var ar=null,Tn=null;async function rl(a){if(Tn===a&&ar)return ar;try{return ar=(await yh(`../../../localization/lit-localize/locales/${a}.ts`)).templates,Tn=a,ar}catch{return a!=="en-GB"?rl("en-GB"):(ar={},Tn=a,ar)}}async function al(a){let t=await rl(a);return(e,r)=>t[e]??r}function il(a,t,e){return a.isDisconnected?!1:(a.host.sdkContextController.contextProvider.value.sdkState.paymentFailure!==null&&Q({eventName:"PAYMENT_REATTEMPTED",paymentMethod:t}),a.host.sdkContextController.setSdkState({isProcessing:!0,paymentFailure:null,primerJsError:null}),a.host.primerEventsController.dispatchPaymentStart(t,e))}function nl(a,t,e){if(!a.isDisconnected&&(T.info("Payment completed:",t),a.host.sdkContextController.setSdkState({isProcessing:!1,isSuccessful:!0}),a.host.primerEventsController.dispatchPaymentSuccess(t,e),Q({eventName:"PAYMENT_SUCCESS",paymentId:t?.id,paymentMethod:e}),a.primerJS?.onPaymentSuccess)){let r=Math.floor(Date.now()/1e3);a.primerJS.onPaymentSuccess({payment:Qt(t),paymentMethodType:e,timestamp:r})}}function ol(a,t,e,r){if(a.isDisconnected)return;(l=>typeof l=="object"&&l!==null&&"response"in l&&typeof l.response=="object"&&l.response!==null&&"status"in l.response&&typeof l.response.status=="number")(t)&&t.response.status>=500?T.errorWithDatadog("Payment failed with server error",{error:t}):T.error("Payment failed:",t);let o=l=>{if(typeof l!="object"||l===null||!("response"in l))return;let c=l.response;return typeof c?.id=="string"?c.id:void 0},s=(()=>{let l=t,c=l instanceof Error||typeof l=="object"&&l!==null&&typeof l.message=="string",u=c&&"code"in l&&typeof l.code=="string"?l.code:"UNKNOWN_ERROR",m=c?l.message:"Unknown error occurred";return{code:u,message:m,diagnosticsId:o(l),data:{error:t}}})();if(a.host.sdkContextController.setSdkState({isProcessing:!1,paymentFailure:s}),a.host.primerEventsController.dispatchPaymentFailure({code:s.code,message:s.message,diagnosticsId:"diagnosticsId"in s?s.diagnosticsId??void 0:void 0,data:s.data},e,r),Q({eventName:"PAYMENT_FAILURE",paymentId:r?.id,paymentMethod:e}),a.primerJS?.onPaymentFailure){let l=Math.floor(Date.now()/1e3);a.primerJS.onPaymentFailure({error:{code:s.code,message:s.message,diagnosticsId:"diagnosticsId"in s?s.diagnosticsId??void 0:void 0,data:s.data},payment:r?Qt(r):void 0,paymentMethodType:e,timestamp:l})}}var sl="1.6.1",Fa=class{constructor(t){this.currentSdkInstance=null;this.primerJS=null;this.loadingTimeout=null;this.isDisconnected=!1;(this.host=t).addController(this),this.isDisconnected=!1,new j(t,{args:()=>[this.host.clientToken,this.host.options],task:this.initializeHeadless()})}get primerJSInstance(){return this.primerJS}hostConnected(){this.isDisconnected=!1,this.host.sdkContextController.setSdkState({isLoading:!0}),this.setupLoadingTimeout()}hostDisconnected(){if(this.isDisconnected=!0,this.host.sdkContextController.contextProvider?.value?.analytics){let e=this.host.sdkContextController.contextProvider.value.sdkState;(e.isProcessing||e.isLoading||this.currentSdkInstance)&&Q({eventName:"PAYMENT_FLOW_EXITED"})}this.cleanupResources()}setupLoadingTimeout(){this.clearLoadingTimeout(),this.loadingTimeout=setTimeout(()=>{this.host.sdkContextController.contextProvider.value.sdkState.isLoading&&(T.warn("Loading timeout reached, resetting SDK state"),Q({eventName:"PAYMENT_FLOW_EXITED",eventType:"timeout"}),this.cleanupResources(),this.host.sdkContextController.setSdkState({isLoading:!1}))},1e4)}clearLoadingTimeout(){this.loadingTimeout!==null&&(clearTimeout(this.loadingTimeout),this.loadingTimeout=null)}cleanupResources(){if(this.clearLoadingTimeout(),this.currentSdkInstance)try{this.host.sdkContextController.resetSdkState(),this.currentSdkInstance.teardown?.(),T.info("SDK instance cleaned up")}catch(t){T.errorWithDatadog("Error cleaning up SDK instance",{error:t})}Ts(),T.setClientToken(void 0),T.setSdkOptions(void 0),this.currentSdkInstance=null,this.primerJS=null}handlePaymentApprovalRequired(t){this.isDisconnected||(this.host.sdkContextController.setSdkState({isProcessing:!0,paymentFailure:null,primerJsError:null}),this.host.primerEventsController.dispatchPaymentApprovalRequired(t))}initializeHeadless(){return async([t,e])=>{if(this.isDisconnected)return T.warn("Component disconnected, aborting SDK initialization"),Y;if(!t||!e)return Y;this.cleanupResources();let r;try{let i=new Ka(this.host),n=tr(e.locale||Ia()),o=await al(n);this.primerJS=new Ga(null),this.primerJS.setVaultController(this.host.vaultManagerController),this.primerJS.setPaymentInProgressCheck(()=>this.isProcessing),T.setClientToken(t),T.setSdkOptions(e);let s=[],l=await cs(t,{...e,dialogProvider:i,translate:o,sdkVersion:sl,locale:n,onAvailablePaymentMethodsLoad:g=>{this.isDisconnected||(T.info("Configuration payment methods:",g),s=g)},onAvailablePaymentMethodsRefresh:g=>{this.onMethodsRefreshed(g)},onCheckoutComplete:({payment:g})=>{let v=g?.paymentMethodData?.paymentMethodType;nl({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},g,v)},onCheckoutFail:(g,v)=>{let M=v.payment?.paymentMethodData?.paymentMethodType;ol({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},g,M,v.payment)},onBeforePaymentCreate:(g,v)=>{if(!g.paymentMethodType){T.error("Payment creation started without payment method type"),v?.abortPaymentCreation();return}if(!(il({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},g.paymentMethodType,v)||this.isDisconnected)){if(this.primerJS?.onPaymentPrepare){this.primerJS.onPaymentPrepare({paymentMethodType:g.paymentMethodType},v);return}v?.continuePaymentCreation()}},onPaymentMethodAction:(g,v)=>{this.isDisconnected||g==="PAYMENT_METHOD_UNSELECTED"&&(this.host.primerEventsController.dispatchPaymentCancel(v),this.host.sdkContextController.setSdkState({isProcessing:!1}))},onPaymentCreationStart:()=>{this.isDisconnected||this.primerJS&&this.primerJS.handlePaymentStart()},onPaymentApprovalRequired:g=>this.handlePaymentApprovalRequired(g),onCheckoutResume:()=>{this.isDisconnected||this.host.sdkContextController.setSdkState({isProcessing:!0,paymentFailure:null,primerJsError:null})}});if(this.currentSdkInstance=l,this.primerJS&&Object.defineProperty(this.primerJS,"headlessInstance",{value:l,writable:!1}),await l.start(),this.isDisconnected)return this.cleanupResources(),Y;let c=l.getSDKUtilities();r=l.getAnalyticsUtils?.(),r&&(Ms({environment:r.environment,checkoutSessionId:r.checkoutSessionId,clientSessionId:r.clientSessionId||"",primerAccountId:r.primerAccountId||"",sdkVersion:sl,clientSessionToken:r.clientSessionToken,userAgent:typeof navigator<"u"?navigator.userAgent:""}),r.configurationFetchStartTime&&Ge.setSdkInitStartTime(r.configurationFetchStartTime),Q({eventName:"SDK_INIT_START"})),this.host.vaultManagerController.initializeVaultManager(l.createVaultManager.bind(l),{vaultEnabled:e.vault?.enabled,captureVaultedCardCvv:!!c.getPaymentMethodConfiguration("PAYMENT_CARD")?.options?.captureVaultedCardCvv,showEmptyState:e.vault?.showEmptyState,headless:e.vault?.headless??!1});let u=(await Promise.all(s.map(async g=>{let v=await this.createManager(g,l);return v?{...g,manager:v}:null}))).filter(g=>!!g),m={clientOptions:e,analytics:r,headlessUtils:c,configuration:l.getConfiguration?.(),paymentMethods:u};return this.host.sdkContextController.setContext(m),this.primerJS&&(this.host.primerEventsController.dispatchCheckoutInitialized(this.primerJS),this.primerJS.setPaymentMethods(u)),this.host.primerEventsController.dispatchPaymentMethods(u),T.info("Initialized payment methods:",u),this.host.sdkContextController.setSdkState({isLoading:!1}),Q({eventName:"SDK_INIT_END"}),l}catch(i){throw i instanceof Error&&(T.errorWithDatadog("SDK initialization error",{error:i,status:"error"}),this.host.sdkContextController.setSdkState({primerJsError:i})),this.cleanupResources(),i}}}async createManager(t,e){try{if(t.managerType==="KLARNA")return await e.createPaymentMethodManager("KLARNA",{onPaymentMethodCategoriesChange:r=>{this.isDisconnected||this.host.sdkContextController.setKlarnaCategories({categories:r,isLoading:!1})}});if(t.managerType==="ADYEN_KLARNA"){let r=await e.createPaymentMethodManager("ADYEN_KLARNA",{onPaymentOptionsChange:i=>{this.isDisconnected||this.host.sdkContextController.setAdyenKlarnaOptions({options:i,isLoading:!1})}});if(r&&"getPaymentOptions"in r){let i=r.getPaymentOptions();i.length>0&&this.host.sdkContextController.setAdyenKlarnaOptions({options:i,isLoading:!1})}return r}return t.managerType==="CARD"?await e.createPaymentMethodManager("PAYMENT_CARD",{onBinDataAvailable:r=>{this.isDisconnected||this.host.primerEventsController.dispatchBinDataAvailable(r)},onCardNetworksChange:r=>{if(this.isDisconnected)return;let{detectedCardNetworks:i,selectableCardNetworks:n}=r;this.updateCardNetworksState({detectedCardNetwork:i.preferred??i.items[0],selectableCardNetworks:n?.items??[],isLoading:!1})},onBinDataLoadingChange:r=>{this.isDisconnected||(r?this.updateCardNetworksState({detectedCardNetwork:null,selectableCardNetworks:[],isLoading:!0}):this.host.sdkContextController.setCardNetworksLoadingFalse(),this.host.primerEventsController.dispatchBinDataLoadingChange(r))}}):await e.createPaymentMethodManager(t.type)}catch(r){T.errorWithDatadog(`Failed to initialize manager for ${t.type}`,{error:r})}}updateCardNetworksState(t){this.host.primerEventsController.dispatchCardNetworkChange(t),this.host.sdkContextController.setCardNetworks(t)}get isProcessing(){return!!this.host.sdkContextController.contextProvider?.value?.sdkState?.isProcessing}async onMethodsRefreshed(t){if(this.isDisconnected||!this.currentSdkInstance||!this.primerJS)return;let e=this.primerJS.getInitializedPaymentMethods(),r=new Map(e.map(l=>[l.type,l])),i=new Set(t.map(l=>l.type)),n=this.currentSdkInstance,o=await Promise.all(t.map(async l=>{let c=r.get(l.type);if(c)return c;let u=await this.createManager(l,n);return u?{...l,manager:u}:null}));if(this.isDisconnected||this.currentSdkInstance!==n||!this.primerJS)return;let s=o.filter(l=>l!==null);e.some(l=>l.type===P.KLARNA)&&!i.has(P.KLARNA)&&this.host.sdkContextController.setKlarnaCategories({categories:[],isLoading:!1}),e.some(l=>l.type===P.ADYEN_KLARNA)&&!i.has(P.ADYEN_KLARNA)&&this.host.sdkContextController.setAdyenKlarnaOptions({options:[],isLoading:!1}),this.primerJS.setPaymentMethods(s),this.host.sdkContextController.setContext({paymentMethods:s,configuration:n.getConfiguration?.()}),this.host.primerEventsController.dispatchPaymentMethods(s)}};var vh=$r({"../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.BIHRX5RF.js"),"../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.FGU6YCAF.js"),"../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.IKG75KNP.js"),"../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.MILBDWY6.js"),"../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.JTASZFYV.js"),"../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.DXQD6OEP.js"),"../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.EFHFPB3R.js"),"../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.SXPN4WN6.js"),"../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.NNAZENAS.js"),"../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.PGD5Q57R.js"),"../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.PTII2RTJ.js"),"../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.AKW6WGRC.js"),"../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.LHI2XOXI.js"),"../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.IPGRD7WF.js"),"../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.PDUWBPKF.js"),"../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.5SDFV353.js"),"../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.LXFZTJMG.js"),"../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.VXISLOF3.js"),"../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.UCNPGRJA.js"),"../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.F7GBFWC2.js"),"../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.BHTV4F5V.js"),"../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.L4TUG67I.js"),"../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.ULLOOI4H.js"),"../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.WAZLYIAI.js"),"../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.TEXPN3ZR.js"),"../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.TQJGMNOY.js"),"../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.Q2C5ZFHD.js"),"../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.KCZ6D34T.js"),"../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.2CTHY5J7.js"),"../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.SYW24NKO.js"),"../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.AI5CECVT.js"),"../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.OWKVFNRL.js"),"../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.LVBHJFXR.js"),"../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.SJYNCSI5.js"),"../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.3HE2B7ZT.js"),"../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.YAEVPIZD.js"),"../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.BA3GBVRO.js"),"../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.3C6VVYBB.js"),"../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.2VDFAELX.js"),"../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.J7ZUQIZS.js"),"../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.E2CHOIPA.js"),"../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.QYJJIGTW.js"),"../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.YGBNA3NJ.js"),"../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.LNP32XVM.js"),"../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.SRN7TXMD.js"),"../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.3JAKYZ5N.js"),"../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.WTNQLAHV.js")});hn(a=>vh(`../../localization/lit-localize/locales/${a}.ts`));var bh={LOADER_DISABLED:"loader-disabled",CUSTOM_STYLES:"custom-styles",CLIENT_TOKEN:"client-token",JS_INIT:"js-initialized"},ye=class extends C{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._classObserver=null;this.locale=tr(Ia());this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0,this.requestUpdate()};this.sdkContextController=new ha(this),this.primerEventsController=new Xt(this),this.styleProcessingController=new ga(this),this.vaultManagerController=new Cr(this),this.headlessSdkController=new Fa(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}),this._classObserver=new MutationObserver(()=>{this.requestUpdate()}),this._classObserver.observe(this,{attributes:!0,attributeFilter:["class"]})}attributeChangedCallback(e,r,i){e===bh.CUSTOM_STYLES?this.styleProcessingController.processCustomStyles(i):super.attributeChangedCallback(e,r,i)}disconnectedCallback(){this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null),this.sdkContextController.contextProvider.value.sdkState?.isLoading&&this.sdkContextController.setSdkState({isLoading:!1}),this._eventListenerController&&(this._eventListenerController.abort(),this._eventListenerController=null),this._classObserver&&(this._classObserver.disconnect(),this._classObserver=null),super.disconnectedCallback()}willUpdate(e){e.has("options")&&(this.options?.locale&&(yn(this.options?.locale)?this.locale=tr(this.options?.locale):T.warn("\u{1F30E}\u2757 Unsupported locale provided:",this.options?.locale,"- Falling back to system locale")),gn(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.sdkContextController.contextProvider.value.sdkState.isLoading||!1;if(this.previousLoadingState&&!e){this.jsInitialized=!0,Q({eventName:"CHECKOUT_FLOW_STARTED"});let r=Ge.getSdkInitStartTime(),i=r?Date.now()-r:void 0;Wn(i)}this.previousLoadingState=e,e&&!this._loadingTimeoutId?this._loadingTimeoutId=window.setTimeout(()=>{this.sdkContextController.contextProvider.value.sdkState.isLoading&&(T.warn("Loading timeout in component, forcing completion"),this.sdkContextController.setSdkState({isLoading:!1}),this.jsInitialized=!0),this._loadingTimeoutId=null},1e4):!e&&this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null)}render(){let e=this.sdkContextController.contextProvider.value.sdkState,r=e.isLoading,i=e.primerJsError,n=!r&&!i;return p` ${R(i,()=>p`<primer-checkout-error></primer-checkout-error>`)}<slot name="main" @slotchange=${this.onSlotChange}></slot>${R(this.hasAssignedContent||!n,()=>f,()=>p`<primer-main></primer-main>`)} `}addEventListener(e,r,i){super.addEventListener(e,r,i)}removeEventListener(e,r,i){super.removeEventListener(e,r,i)}};ye.styles=[I,el],d([h({type:String,attribute:"custom-styles"})],ye.prototype,"customStyles",2),d([h({type:String,attribute:"client-token"})],ye.prototype,"clientToken",2),d([h({type:Object,attribute:!1,hasChanged:(e,r)=>!vt(e,r)})],ye.prototype,"options",2),d([h({type:Boolean,attribute:"loader-disabled"})],ye.prototype,"disableLoader",2),d([h({type:Boolean,reflect:!0,attribute:"js-initialized"})],ye.prototype,"_jsInitialized",2),d([de("slot")],ye.prototype,"defaultSlot",2),d([k()],ye.prototype,"previousLoadingState",2),ye=d([O(),S("primer-checkout")],ye);var ll=typeof window<"u"&&typeof window.document<"u";function Ch(a){return document.querySelector(`#${a}`)}function Sh(a,t){let e=document.createElement("style");return e.textContent=a,e.id=t,e}function Br(a,t,e=!0){if(!ll||Ch(t))return;let i=Sh(a,t);e&&document.head.firstChild?document.head.insertBefore(i,document.head.firstChild):document.head.appendChild(i)}var dl=`
|
|
147
147
|
@keyframes primer-css-spinner-rotate {
|
|
148
148
|
0% {
|
|
149
149
|
transform: rotate(0deg);
|