@primer-io/primer-js 0.3.2 → 0.3.3
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 +111 -0
- package/dist/custom-elements.json +14 -5
- package/dist/primer-loader.d.ts +5 -4
- package/dist/primer-loader.js +2 -2
- package/dist/primer-react-wrappers.js +2 -2
- package/dist/web-types.json +1 -1
- package/package.json +2 -2
- package/src/controllers/reactive-state/README.md +210 -0
package/dist/primer-loader.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Ui,b as s,c as R}from"./chunks/chunk.DV3REKZU.js";var qt=class{constructor(t){(this.host=t).addController(this)}hostConnected(){}setCardNetworksLoading(){let t={detectedCardNetwork:null,selectableCardNetworks:[],isLoading:!0};this.updateCardNetworksState(t)}updateCardNetworksState(t){this.host.primerEventsController.dispatchCardNetworkChange(t),this.host.sdkContextController.setCardNetworks(t)}processCardNetworkChangeEvent(t){let{detectedCardNetworks:e,selectableCardNetworks:r}=t,o=e.preferred??e.items[0],a=r?.items??[];this.updateCardNetworksState({detectedCardNetwork:o,selectableCardNetworks:a,isLoading:!1})}};var ht=class{constructor(t){(this.host=t).addController(this)}hostConnected(){}dispatchEvent(t,e){this.host.dispatchEvent(new CustomEvent(t,{detail:e,bubbles:!0,composed:!0}))}dispatchSdkState(t){this.dispatchEvent("primer:state-change",t)}dispatchPaymentMethods(t){this.dispatchEvent("primer:methods-update",t)}dispatchCheckoutInitialized(t){this.dispatchEvent("primer:ready",t)}dispatchCardNetworkChange(t){this.dispatchEvent("primer:card-network-change",t)}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})}};var He=class extends Event{constructor(t,e,r,o){super("context-request",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=e,this.callback=r,this.subscribe=o??!1}};var ft=class{constructor(t,e,r,o){if(this.subscribe=!1,this.provided=!1,this.value=void 0,this.t=(a,n)=>{this.unsubscribe&&(this.unsubscribe!==n&&(this.provided=!1,this.unsubscribe()),this.subscribe||this.unsubscribe()),this.value=a,this.host.requestUpdate(),this.provided&&!this.subscribe||(this.provided=!0,this.callback&&this.callback(a,n)),this.unsubscribe=n},this.host=t,e.context!==void 0){let a=e;this.context=a.context,this.callback=a.callback,this.subscribe=a.subscribe??!1}else this.context=e,this.callback=r,this.subscribe=o??!1;this.host.addController(this)}hostConnected(){this.dispatchRequest()}hostDisconnected(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=void 0)}dispatchRequest(){this.host.dispatchEvent(new He(this.context,this.host,this.t,this.subscribe))}};var Wt=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:o}=this.subscriptions.get(t);t(this.value,o)}clearCallbacks(){this.subscriptions.clear()}};var Wr=class extends Event{constructor(t,e){super("context-provider",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=e}},z=class extends Wt{constructor(t,e,r){super(e.context!==void 0?e.initialValue:r),this.onContextRequest=o=>{if(o.context!==this.context)return;let a=o.contextTarget??o.composedPath()[0];a!==this.host&&(o.stopPropagation(),this.addCallback(o.callback,a,o.subscribe))},this.onProviderRequest=o=>{if(o.context!==this.context||(o.contextTarget??o.composedPath()[0])===this.host)return;let a=new Set;for(let[n,{consumerHost:l}]of this.subscriptions)a.has(n)||(a.add(n),l.dispatchEvent(new He(this.context,l,n,!0)));o.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 Wr(this.context,this.host))}};function C({context:i,subscribe:t}){return(e,r)=>{typeof r=="object"?r.addInitializer(function(){new ft(this,{context:i,callback:o=>{e.set.call(this,o)},subscribe:t})}):e.constructor.addInitializer(o=>{new ft(o,{context:i,callback:a=>{o[r]=a},subscribe:t})})}}var Jt="cardNetworksContext";var ae="clientOptionsContext";var ze="computedStylesContext";var U="headlessInstanceContext";var Zt="klarnaCategoriesContext";var Z="managerContext";var Be="paymentMethodsContext";var Y="sdkStateContext";var X="vaultManagerContext";var ue="vaultManagerCvvContext";var V=class V{static log(t,...e){V.enabled}static info(t,...e){V.enabled}static warn(t,...e){V.enabled}static error(t,...e){V.enabled}static debug(t,...e){V.enabled}static table(t,e){V.enabled}static time(t){V.enabled}static timeEnd(t){V.enabled}};V.enabled=!0,V.defaultFont="font-family: Consolas, monospace; font-size: 12px;",V.brandTag="[PRIMER]",V.brandStyle=`background: #24292e; color: #ffffff; padding: 2px 6px; border-radius: 3px; font-weight: bold; margin-right: 4px; ${V.defaultFont}`,V.styles={log:`color: #4CAF50; ${V.defaultFont}`,info:`color: #2196F3; ${V.defaultFont}`,warn:`color: #FF9800; ${V.defaultFont}`,error:`color: #F44336; ${V.defaultFont}`,debug:`color: #9C27B0; ${V.defaultFont}`};var S=V;function An(i,t,e,r){let o=i,a=e;return{dispatch:n=>{let l=t(o,n,a);o=l,r(l)},getState:()=>Object.freeze({...o}),setCallbacks:n=>{a={...a,...n}}}}function wt(i){return(t,e,r)=>{let o=i[e.type];if(!o)throw new Error(`No handler for action type: ${e.type}`);return o(t,e,r)}}var et=class{constructor(t,e,r,o,a=()=>{this.host.requestUpdate()}){this.host=t;this.stateHandler=a;this.host.addController(this),this._dispatcher=An(e,r,o,n=>{this.stateHandler(n)})}get currentState(){return this._dispatcher.getState()}dispatch(t){this._dispatcher.dispatch(t)}setCallbacks(t){this._dispatcher.setCallbacks(t)}hostConnected(){}hostDisconnected(){}},Xt=class{constructor(t){this.host=t;this._controllers=[];"addController"in this.host&&this.host.addController(this)}addController(t){this._controllers.push(t)}hostConnected(){this._controllers.forEach(t=>{t.hostConnected&&t.hostConnected()})}hostDisconnected(){this._controllers.forEach(t=>{t.hostDisconnected&&t.hostDisconnected()})}};var er={isSuccessful:!1,isProcessing:!1,isLoading:!1,error:null,failure:null},Sn={START_LOADING:i=>({...i,isLoading:!0}),START_PROCESSING:i=>({...i,failure:null,isProcessing:!0}),STOP_PROCESSING:i=>({...i,isProcessing:!1}),COMPLETE_PROCESSING:i=>({...i,isProcessing:!1,isSuccessful:!0}),SET_ERROR:(i,t)=>(S.error(t.payload.message),{...i,isProcessing:!1,error:t.payload}),SET_FAILURE:(i,t)=>({...i,isProcessing:!1,failure:t.payload}),COMPLETE_LOADING:i=>({...i,isLoading:!1}),RESET:()=>er,RESET_ERROR:i=>({...i,error:null,failure:null})},_n=wt(Sn),Qt=class extends et{constructor(t){super(t,er,_n,null,e=>{t.sdkContextController.setSdkState(e),t.primerEventsController.dispatchSdkState(e)})}startLoading(){this.dispatch({type:"START_LOADING"})}startProcessing(){this.dispatch({type:"START_PROCESSING"})}stopProcessing(){this.dispatch({type:"STOP_PROCESSING"})}completeProcessing(){this.dispatch({type:"COMPLETE_PROCESSING"})}completeLoading(){this.dispatch({type:"COMPLETE_LOADING"})}setError(t){this.dispatch({type:"SET_ERROR",payload:t})}setFailure(t,e,r){this.dispatch({type:"SET_FAILURE",payload:{code:t,message:e,details:r}})}reset(){this.dispatch({type:"RESET"})}resetError(){this.dispatch({type:"RESET_ERROR"})}forceCompleteLoading(){this.currentState.isLoading&&(S.warn("Force completing loading state"),this.completeLoading())}};var tr=class{constructor(t){this.sdkStateProvider=null;this.paymentMethodsProvider=null;this.paymentManagerProvider=null;this.cardNetworksContext=null;this.vaultManagerCvvProvider=null;this.clientOptionsContext=null;this.headlessUtilsProvider=null;this.klarnaCategoriesProvider=null;this.computedStylesProvider=null;(this.host=t).addController(this),this.sdkStateProvider=new z(t,{context:Y,initialValue:er}),this.paymentMethodsProvider=new z(t,{context:Be,initialValue:null}),this.paymentManagerProvider=new z(t,{context:Z,initialValue:new Map}),this.cardNetworksContext=new z(t,{context:Jt,initialValue:null}),this.vaultManagerProvider=new z(t,{context:X,initialValue:null}),this.vaultManagerCvvProvider=new z(t,{context:ue,initialValue:null}),this.clientOptionsContext=new z(t,{context:ae,initialValue:null}),this.klarnaCategoriesProvider=new z(t,{context:Zt,initialValue:{categories:[],isLoading:!0}}),this.headlessUtilsProvider=new z(t,{context:U,initialValue:null}),this.computedStylesProvider=new z(t,{context:ze,initialValue:null})}hostConnected(){}setSdkState(t){this.sdkStateProvider?.setValue(t)}setPaymentMethods(t){this.paymentMethodsProvider?.setValue(t)}setPaymentManagers(t){this.paymentManagerProvider?.setValue(t)}setCardNetworks(t){this.cardNetworksContext?.setValue(t)}setVaultManager(t){this.vaultManagerProvider?.setValue(t)}setKlarnaCategories(t){this.klarnaCategoriesProvider?.setValue(t)}setClientOptions(t){this.clientOptionsContext?.setValue(t)}setHeadlessUtils(t){this.headlessUtilsProvider?.setValue(t)}setComputedStyles(t){this.computedStylesProvider?.setValue(t)}setVaultManagerCvv(t){this.vaultManagerCvvProvider?.setValue(t)}};var tt=class tt{constructor(t){(this.host=t).addController(this)}processCustomStyles(t){try{let e=JSON.parse(t);this.applyStyles(e)}catch(e){S.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||S.warn(`Rejected potentially unsafe CSS value: ${t}`),r}getCssVarName(t){let e=tt.cssVarCache.get(t);return e||(e=`--${t.replace(/([A-Z])/g,(r,o)=>`-${o.toLowerCase()}`)}`,tt.cssVarCache.set(t,e)),e}applyStyles(t){let e=[];for(let r of Object.keys(t)){let o=t[r];if(!o)continue;if(!this.isValidCssProperty(r)){S.warn(`Skipping invalid CSS property name: ${r}`);continue}if(!this.isValidCssValue(o))continue;let a=this.getCssVarName(r);e.push([a,o])}if(e.length>0)for(let[r,o]of e)this.host.style.setProperty(r,o)}removeStyle(t){let e=this.getCssVarName(t);this.host.style.removeProperty(e)}clearAllStyles(){for(let t of tt.cssVarCache.keys()){let e=tt.cssVarCache.get(t);e&&this.host.style.removeProperty(e)}}hostDisconnected(){}};tt.cssVarCache=new Map;var rr=tt;var ir=globalThis,ar=ir.ShadowRoot&&(ir.ShadyCSS===void 0||ir.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,zi=Symbol(),Hi=new WeakMap,or=class{constructor(t,e,r){if(this._$cssResult$=!0,r!==zi)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(ar&&t===void 0){let r=e!==void 0&&e.length===1;r&&(t=Hi.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),r&&Hi.set(e,t))}return t}toString(){return this.cssText}},Bi=i=>new or(typeof i=="string"?i:i+"",void 0,zi);var Jr=(i,t)=>{if(ar)i.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let e of t){let r=document.createElement("style"),o=ir.litNonce;o!==void 0&&r.setAttribute("nonce",o),r.textContent=e.cssText,i.appendChild(r)}},nr=ar?i=>i:i=>i instanceof CSSStyleSheet?(t=>{let e="";for(let r of t.cssRules)e+=r.cssText;return Bi(e)})(i):i;var{is:Pn,defineProperty:wn,getOwnPropertyDescriptor:Mn,getOwnPropertyNames:Tn,getOwnPropertySymbols:kn,getPrototypeOf:In}=Object,Fe=globalThis,Fi=Fe.trustedTypes,Ln=Fi?Fi.emptyScript:"",Nn=Fe.reactiveElementPolyfillSupport,Mt=(i,t)=>i,Zr={toAttribute(i,t){switch(t){case Boolean:i=i?Ln:null;break;case Object:case Array:i=i==null?i:JSON.stringify(i)}return i},fromAttribute(i,t){let e=i;switch(t){case Boolean:e=i!==null;break;case Number:e=i===null?null:Number(i);break;case Object:case Array:try{e=JSON.parse(i)}catch{e=null}}return e}},sr=(i,t)=>!Pn(i,t),ji={attribute:!0,type:String,converter:Zr,reflect:!1,hasChanged:sr};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Fe.litPropertyMetadata??(Fe.litPropertyMetadata=new WeakMap);var rt=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=ji){if(e.state&&(e.attribute=!1),this._$Ei(),this.elementProperties.set(t,e),!e.noAccessor){let r=Symbol(),o=this.getPropertyDescriptor(t,r,e);o!==void 0&&wn(this.prototype,t,o)}}static getPropertyDescriptor(t,e,r){let{get:o,set:a}=Mn(this.prototype,t)??{get(){return this[e]},set(n){this[e]=n}};return{get(){return o?.call(this)},set(n){let l=o?.call(this);a.call(this,n),this.requestUpdate(t,l,r)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??ji}static _$Ei(){if(this.hasOwnProperty(Mt("elementProperties")))return;let t=In(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Mt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Mt("properties"))){let e=this.properties,r=[...Tn(e),...kn(e)];for(let o of r)this.createProperty(o,e[o])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[r,o]of e)this.elementProperties.set(r,o)}this._$Eh=new Map;for(let[e,r]of this.elementProperties){let o=this._$Eu(e,r);o!==void 0&&this._$Eh.set(o,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 o of r)e.unshift(nr(o))}else t!==void 0&&e.push(nr(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 Jr(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),o=this.constructor._$Eu(t,r);if(o!==void 0&&r.reflect===!0){let a=(r.converter?.toAttribute!==void 0?r.converter:Zr).toAttribute(e,r.type);this._$Em=t,a==null?this.removeAttribute(o):this.setAttribute(o,a),this._$Em=null}}_$AK(t,e){let r=this.constructor,o=r._$Eh.get(t);if(o!==void 0&&this._$Em!==o){let a=r.getPropertyOptions(o),n=typeof a.converter=="function"?{fromAttribute:a.converter}:a.converter?.fromAttribute!==void 0?a.converter:Zr;this._$Em=o,this[o]=n.fromAttribute(e,a.type),this._$Em=null}}requestUpdate(t,e,r){if(t!==void 0){if(r??(r=this.constructor.getPropertyOptions(t)),!(r.hasChanged??sr)(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[o,a]of this._$Ep)this[o]=a;this._$Ep=void 0}let r=this.constructor.elementProperties;if(r.size>0)for(let[o,a]of r)a.wrapped!==!0||this._$AL.has(o)||this[o]===void 0||this.P(o,this[o],a)}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){}};rt.elementStyles=[],rt.shadowRootOptions={mode:"open"},rt[Mt("elementProperties")]=new Map,rt[Mt("finalized")]=new Map,Nn?.({ReactiveElement:rt}),(Fe.reactiveElementVersions??(Fe.reactiveElementVersions=[])).push("2.0.4");var je={INITIAL:0,PENDING:1,COMPLETE:2,ERROR:3},T=Symbol(),L=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 o=typeof e=="object"?e:{task:e,args:r};this.v=o.task,this.j=o.args,this.m=o.argsEqual??Ki,this.k=o.onComplete,this.A=o.onError,this.autoRun=o.autoRun??!0,"initialValue"in o&&(this.u=o.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 o=++this.p;this.q=new AbortController;let a=!1;try{e=await this.v(t,{signal:this.q.signal})}catch(n){a=!0,r=n}if(this.p===o){if(e===T)this.i=0;else{if(a===!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)}}},Ki=(i,t)=>i===t||i.length===t.length&&i.every((e,r)=>!sr(e,t[r]));var On={SET_LOADING:(i,t)=>({...i,isLoading:t.payload}),SET_UPDATING:(i,t)=>({...i,isUpdating:t.payload}),INITIALIZE_VAULT_MANAGER:(i,t,e)=>({...i,enabled:t.vaultEnabled,cvvRecapture:t.cvvRecapture,showEmptyState:t.showEmptyState,deleteVaultedPaymentMethod:e.deleteVaultedPaymentMethod,startVaultedPaymentFlow:e.startVaultedPaymentFlow,createCvvInput:e.createCvvInput}),UPDATE_PAYMENT_METHODS:(i,t)=>({...i,vaultedPaymentMethods:t.payload,isLoading:!1,isUpdating:!1}),SET_ERROR:i=>({...i,isLoading:!1,isUpdating:!1}),DISABLE:i=>({...i,enabled:!1}),RESET:()=>Gi},Rn={INITIALIZE_CVV:(i,t,e)=>({...i,setCvvInput:e.setCvvInput,setSelectedVaultedPaymentMethod:e.setSelectedVaultedPaymentMethod}),SET_FORM_DIRTY:(i,t)=>({...i,formIsDirty:t.payload}),SET_CVV_INPUT:(i,t)=>({...i,cvvInput:t.payload}),SET_SELECTED_VAULTED_PAYMENT_METHOD:(i,t)=>({...i,selectedVaultedPaymentMethod:t.payload}),RESET_CVV:()=>qi},Dn=wt(On),$n=wt(Rn),Gi={enabled:!1,isLoading:!1,isUpdating:!1,cvvRecapture:!1,showEmptyState:!0,vaultedPaymentMethods:[],createCvvInput:null,deleteVaultedPaymentMethod:()=>Promise.resolve(),startVaultedPaymentFlow:()=>Promise.resolve()},qi={cvvInput:null,formIsDirty:!1,setCvvInput:()=>{},selectedVaultedPaymentMethod:null,setSelectedVaultedPaymentMethod:()=>{}},Xr=class extends et{constructor(t,e){super(t,Gi,Dn,e,r=>{t.sdkContextController.setVaultManager(r)})}setLoading(t){this.dispatch({type:"SET_LOADING",payload:t})}setUpdating(t){this.dispatch({type:"SET_UPDATING",payload:t})}initializeVaultManager(t,e,r,o){this.dispatch({type:"INITIALIZE_VAULT_MANAGER",payload:t,vaultEnabled:e,cvvRecapture:r,showEmptyState:o})}updatePaymentMethods(t){this.dispatch({type:"UPDATE_PAYMENT_METHODS",payload:t})}setError(t){this.dispatch({type:"SET_ERROR",payload:t})}disable(){this.dispatch({type:"DISABLE"})}reset(){this.dispatch({type:"RESET"})}},Qr=class extends et{constructor(t,e){super(t,qi,$n,e,r=>{t.sdkContextController.setVaultManagerCvv(r)})}initializeCvv(t){this.dispatch({type:"INITIALIZE_CVV",createCvvInput:t})}setFormDirty(t){this.dispatch({type:"SET_FORM_DIRTY",payload:t})}setCvvInputState(t){this.dispatch({type:"SET_CVV_INPUT",payload:t})}setSelectedPaymentMethod(t){this.dispatch({type:"SET_SELECTED_VAULTED_PAYMENT_METHOD",payload:t})}resetCvv(){this.dispatch({type:"RESET_CVV"})}},Tt=class extends Xt{constructor(e){super(e);this._vaultManager=null;this._options=null;this.createCvvInput=e=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");return this._vaultManager.createCvvInput(e)};this.deleteVaultedPaymentMethod=async e=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");try{this.coreController.updatePaymentMethods(this.vaultManagerState.vaultedPaymentMethods),await this._vaultManager.deleteVaultedPaymentMethod(e),await this.fetchVaultedPaymentMethods()}catch(r){throw this.coreController.setError(r instanceof Error?r:new Error("Failed to delete payment method")),r}};this.setCvvInput=e=>{this.itemController.setCvvInputState(e)};this.startVaultedPaymentFlow=async()=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");let e=this.vaultItemState.selectedVaultedPaymentMethod,r=this.vaultManagerState.cvvRecapture,o=this.vaultItemState.cvvInput;if(!e||r&&(!o||o.metadata.error)){this.itemController.setFormDirty(!0);return}this.host.sdkStateController.startProcessing();try{await this._vaultManager.startPaymentFlow(e.id,r?{cvv:o.valueToken}:void 0)}catch(a){S.error("VaultManagerController: Error starting vaulted payment flow",a),this.coreController.setError(a instanceof Error?a:new Error("Failed to start vaulted payment flow")),this.host.sdkStateController.stopProcessing()}};this.setSelectedVaultedPaymentMethod=e=>{this.itemController.setSelectedPaymentMethod(e),this.itemController.setFormDirty(!1)};this.coreController=new Xr(e,{deleteVaultedPaymentMethod:this.deleteVaultedPaymentMethod.bind(this),startVaultedPaymentFlow:this.startVaultedPaymentFlow.bind(this),createCvvInput:this.createCvvInput}),this.itemController=new Qr(e,{setCvvInput:this.setCvvInput.bind(this),setSelectedVaultedPaymentMethod:this.setSelectedVaultedPaymentMethod.bind(this)}),this.addController(this.coreController),this.addController(this.itemController),new L(this.host,{task:async([r,o])=>{if(!r||!o?.vaultEnabled)return this.coreController.disable(),T;this.coreController.setLoading(!0);try{this.coreController.initializeVaultManager(r,o.vaultEnabled,!!o.captureVaultedCardCvv,o.showEmptyState??!0),this.itemController.initializeCvv(r.createCvvInput),await this.fetchVaultedPaymentMethods(!0),S.log("VaultManagerController: Vault initialized successfully",{coreState:this.coreController.currentState,cvvState:this.itemController.currentState})}catch(a){S.error("VaultManagerController: Failed to initialize vault",a),this.coreController.setError(a instanceof Error?a:new Error("Unknown error"))}return this._vaultManager},args:()=>[this.vaultManager,this.options]})}initializeVaultManager(e,r){this.vaultManager=e,this.options=r??null}get vaultManager(){return this._vaultManager}set vaultManager(e){this._vaultManager=e,this.host.requestUpdate()}get options(){return this._options}set options(e){this._options=e,this.host.requestUpdate()}get vaultManagerState(){return this.coreController.currentState}get vaultItemState(){return this.itemController.currentState}hostDisconnected(){super.hostDisconnected(),this.vaultManager=null,this.coreController.reset()}async fetchVaultedPaymentMethods(e){if(!this._vaultManager)throw new Error("Vault manager not initialized");try{e||this.coreController.setUpdating(!0);let r=await this._vaultManager.fetchVaultedPaymentMethods();return S.log("VaultManagerController: Fetched payment methods",r),this.coreController.updatePaymentMethods(r),r}catch(r){throw this.coreController.setError(r instanceof Error?r:new Error("Failed to fetch payment methods")),r}}};var kt="lit-localize-status";var Wi=i=>typeof i!="string"&&"strTag"in i,lr=(i,t,e)=>{let r=i[0];for(let o=1;o<i.length;o++)r+=t[e?e[o-1]:o-1],r+=i[o];return r};var It=i=>Wi(i)?lr(i.strings,i.values):i;var x=It,Ji=!1;function ei(i){if(Ji)throw new Error("lit-localize can only be configured once");x=i,Ji=!0}var ti=class{constructor(t){this.__litLocalizeEventHandler=e=>{e.detail.status==="ready"&&this.host.requestUpdate()},this.host=t}hostConnected(){window.addEventListener(kt,this.__litLocalizeEventHandler)}hostDisconnected(){window.removeEventListener(kt,this.__litLocalizeEventHandler)}},Vn=i=>i.addController(new ti(i)),Zi=Vn;var M=()=>(i,t)=>(i.addInitializer(Zi),i);var Lt=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 Pe=[];for(let i=0;i<256;i++)Pe[i]=(i>>4&15).toString(16)+(i&15).toString(16);function Xi(i){let t=0,e=8997,r=0,o=33826,a=0,n=40164,l=0,d=52210;for(let m=0;m<i.length;m++)e^=i.charCodeAt(m),t=e*435,r=o*435,a=n*435,l=d*435,a+=e<<8,l+=o<<8,r+=t>>>16,e=t&65535,a+=r>>>16,o=r&65535,d=l+(a>>>16)&65535,n=a&65535;return Pe[d>>8]+Pe[d&255]+Pe[n>>8]+Pe[n&255]+Pe[o>>8]+Pe[o&255]+Pe[e>>8]+Pe[e&255]}var Yn="",Un="h",Hn="s";function Qi(i,t){return(t?Un:Hn)+Xi(typeof i=="string"?i:i.join(Yn))}var eo=new WeakMap,to=new Map;function ro(i,t,e){if(i){let r=e?.id??zn(t),o=i[r];if(o){if(typeof o=="string")return o;if("strTag"in o)return lr(o.strings,t.values,o.values);{let a=eo.get(o);return a===void 0&&(a=o.values,eo.set(o,a)),{...o,values:a.map(n=>t.values[n])}}}}return It(t)}function zn(i){let t=typeof i=="string"?i:i.strings,e=to.get(t);return e===void 0&&(e=Qi(t,typeof i!="string"&&!("strTag"in i)),to.set(t,e)),e}function ri(i){window.dispatchEvent(new CustomEvent(kt,{detail:i}))}var cr="",ii,io,pr,oi,oo,it=new Lt;it.resolve();var dr=0,ao=i=>(ei((t,e)=>ro(oo,t,e)),cr=io=i.sourceLocale,pr=new Set(i.targetLocales),pr.add(i.sourceLocale),oi=i.loadLocale,{getLocale:Bn,setLocale:Fn}),Bn=()=>cr,Fn=i=>{if(i===(ii??cr))return it.promise;if(!pr||!oi)throw new Error("Internal error");if(!pr.has(i))throw new Error("Invalid locale code");dr++;let t=dr;return ii=i,it.settled&&(it=new Lt),ri({status:"loading",loadingLocale:i}),(i===io?Promise.resolve({templates:void 0}):oi(i)).then(r=>{dr===t&&(cr=i,ii=void 0,oo=r.templates,ri({status:"ready",readyLocale:i}),it.resolve())},r=>{dr===t&&(ri({status:"error",errorLocale:i,errorMessage:r.toString()}),it.reject(r))}),it.promise};var ai="en",ni=["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"],no="You must call `loadLocale` first to set up the localized template.",so,mr,lo=i=>{let t=ao({sourceLocale:ai,targetLocales:ni,loadLocale:i});so=t.getLocale,mr=t.setLocale};var si=i=>{lo(i)},li=i=>{if(!mr)throw new Error(no);return mr(i)};var Nt=new Set(ni);Nt.add(ai);var di=i=>{if(typeof i!="string")return!1;if(i==="en")return!0;let t=i.replace("_","-");if(Nt.has(t))return!0;let e=t.split("-")[0];return!!Nt.has(e)},ci=i=>{if(i==="en")return"en-GB";let t=i.replace("_","-");if(Nt.has(t))return t;let e=t.split("-")[0];return Nt.has(e)?e:"en-GB"};var ur=globalThis,hr=ur.ShadowRoot&&(ur.ShadyCSS===void 0||ur.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,pi=Symbol(),co=new WeakMap,Ot=class{constructor(t,e,r){if(this._$cssResult$=!0,r!==pi)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(hr&&t===void 0){let r=e!==void 0&&e.length===1;r&&(t=co.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),r&&co.set(e,t))}return t}toString(){return this.cssText}},he=i=>new Ot(typeof i=="string"?i:i+"",void 0,pi),y=(i,...t)=>{let e=i.length===1?i[0]:t.reduce((r,o,a)=>r+(n=>{if(n._$cssResult$===!0)return n.cssText;if(typeof n=="number")return n;throw Error("Value passed to 'css' function must be a 'css' function result: "+n+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(o)+i[a+1],i[0]);return new Ot(e,i,pi)},po=(i,t)=>{if(hr)i.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let e of t){let r=document.createElement("style"),o=ur.litNonce;o!==void 0&&r.setAttribute("nonce",o),r.textContent=e.cssText,i.appendChild(r)}},mi=hr?i=>i:i=>i instanceof CSSStyleSheet?(t=>{let e="";for(let r of t.cssRules)e+=r.cssText;return he(e)})(i):i;var{is:jn,defineProperty:Kn,getOwnPropertyDescriptor:Gn,getOwnPropertyNames:qn,getOwnPropertySymbols:Wn,getPrototypeOf:Jn}=Object,Ke=globalThis,mo=Ke.trustedTypes,Zn=mo?mo.emptyScript:"",Xn=Ke.reactiveElementPolyfillSupport,Rt=(i,t)=>i,Dt={toAttribute(i,t){switch(t){case Boolean:i=i?Zn:null;break;case Object:case Array:i=i==null?i:JSON.stringify(i)}return i},fromAttribute(i,t){let e=i;switch(t){case Boolean:e=i!==null;break;case Number:e=i===null?null:Number(i);break;case Object:case Array:try{e=JSON.parse(i)}catch{e=null}}return e}},fr=(i,t)=>!jn(i,t),uo={attribute:!0,type:String,converter:Dt,reflect:!1,useDefault:!1,hasChanged:fr};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Ke.litPropertyMetadata??(Ke.litPropertyMetadata=new WeakMap);var we=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=uo){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(),o=this.getPropertyDescriptor(t,r,e);o!==void 0&&Kn(this.prototype,t,o)}}static getPropertyDescriptor(t,e,r){let{get:o,set:a}=Gn(this.prototype,t)??{get(){return this[e]},set(n){this[e]=n}};return{get:o,set(n){let l=o?.call(this);a?.call(this,n),this.requestUpdate(t,l,r)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??uo}static _$Ei(){if(this.hasOwnProperty(Rt("elementProperties")))return;let t=Jn(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Rt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Rt("properties"))){let e=this.properties,r=[...qn(e),...Wn(e)];for(let o of r)this.createProperty(o,e[o])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[r,o]of e)this.elementProperties.set(r,o)}this._$Eh=new Map;for(let[e,r]of this.elementProperties){let o=this._$Eu(e,r);o!==void 0&&this._$Eh.set(o,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 o of r)e.unshift(mi(o))}else t!==void 0&&e.push(mi(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 po(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),o=this.constructor._$Eu(t,r);if(o!==void 0&&r.reflect===!0){let a=(r.converter?.toAttribute!==void 0?r.converter:Dt).toAttribute(e,r.type);this._$Em=t,a==null?this.removeAttribute(o):this.setAttribute(o,a),this._$Em=null}}_$AK(t,e){let r=this.constructor,o=r._$Eh.get(t);if(o!==void 0&&this._$Em!==o){let a=r.getPropertyOptions(o),n=typeof a.converter=="function"?{fromAttribute:a.converter}:a.converter?.fromAttribute!==void 0?a.converter:Dt;this._$Em=o,this[o]=n.fromAttribute(e,a.type)??this._$Ej?.get(o)??null,this._$Em=null}}requestUpdate(t,e,r){if(t!==void 0){let o=this.constructor,a=this[t];if(r??(r=o.getPropertyOptions(t)),!((r.hasChanged??fr)(a,e)||r.useDefault&&r.reflect&&a===this._$Ej?.get(t)&&!this.hasAttribute(o._$Eu(t,r))))return;this.C(t,e,r)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,e,{useDefault:r,reflect:o,wrapped:a},n){r&&!(this._$Ej??(this._$Ej=new Map)).has(t)&&(this._$Ej.set(t,n??e??this[t]),a!==!0||n!==void 0)||(this._$AL.has(t)||(this.hasUpdated||r||(e=void 0),this._$AL.set(t,e)),o===!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[o,a]of this._$Ep)this[o]=a;this._$Ep=void 0}let r=this.constructor.elementProperties;if(r.size>0)for(let[o,a]of r){let{wrapped:n}=a,l=this[o];n!==!0||this._$AL.has(o)||l===void 0||this.C(o,void 0,a,l)}}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){}};we.elementStyles=[],we.shadowRootOptions={mode:"open"},we[Rt("elementProperties")]=new Map,we[Rt("finalized")]=new Map,Xn?.({ReactiveElement:we}),(Ke.reactiveElementVersions??(Ke.reactiveElementVersions=[])).push("2.1.0");var Vt=globalThis,yr=Vt.trustedTypes,ho=yr?yr.createPolicy("lit-html",{createHTML:i=>i}):void 0,hi="$lit$",Me=`lit$${Math.random().toFixed(9).slice(2)}$`,fi="?"+Me,Qn=`<${fi}>`,nt=document,Yt=()=>nt.createComment(""),Ut=i=>i===null||typeof i!="object"&&typeof i!="function",yi=Array.isArray,Co=i=>yi(i)||typeof i?.[Symbol.iterator]=="function",ui=`[
|
|
1
|
+
import{a as Ui,b as s,c as R}from"./chunks/chunk.DV3REKZU.js";var qt=class{constructor(t){(this.host=t).addController(this)}hostConnected(){}setCardNetworksLoading(){let t={detectedCardNetwork:null,selectableCardNetworks:[],isLoading:!0};this.updateCardNetworksState(t)}updateCardNetworksState(t){this.host.primerEventsController.dispatchCardNetworkChange(t),this.host.sdkContextController.setCardNetworks(t)}processCardNetworkChangeEvent(t){let{detectedCardNetworks:e,selectableCardNetworks:r}=t,o=e.preferred??e.items[0],a=r?.items??[];this.updateCardNetworksState({detectedCardNetwork:o,selectableCardNetworks:a,isLoading:!1})}};var ht=class{constructor(t){(this.host=t).addController(this)}hostConnected(){}dispatchEvent(t,e){this.host.dispatchEvent(new CustomEvent(t,{detail:e,bubbles:!0,composed:!0}))}dispatchSdkState(t){this.dispatchEvent("primer:state-change",t)}dispatchPaymentMethods(t){this.dispatchEvent("primer:methods-update",t)}dispatchCheckoutInitialized(t){this.dispatchEvent("primer:ready",t)}dispatchCardNetworkChange(t){this.dispatchEvent("primer:card-network-change",t)}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})}};var He=class extends Event{constructor(t,e,r,o){super("context-request",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=e,this.callback=r,this.subscribe=o??!1}};var ft=class{constructor(t,e,r,o){if(this.subscribe=!1,this.provided=!1,this.value=void 0,this.t=(a,n)=>{this.unsubscribe&&(this.unsubscribe!==n&&(this.provided=!1,this.unsubscribe()),this.subscribe||this.unsubscribe()),this.value=a,this.host.requestUpdate(),this.provided&&!this.subscribe||(this.provided=!0,this.callback&&this.callback(a,n)),this.unsubscribe=n},this.host=t,e.context!==void 0){let a=e;this.context=a.context,this.callback=a.callback,this.subscribe=a.subscribe??!1}else this.context=e,this.callback=r,this.subscribe=o??!1;this.host.addController(this)}hostConnected(){this.dispatchRequest()}hostDisconnected(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=void 0)}dispatchRequest(){this.host.dispatchEvent(new He(this.context,this.host,this.t,this.subscribe))}};var Wt=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:o}=this.subscriptions.get(t);t(this.value,o)}clearCallbacks(){this.subscriptions.clear()}};var Wr=class extends Event{constructor(t,e){super("context-provider",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=e}},z=class extends Wt{constructor(t,e,r){super(e.context!==void 0?e.initialValue:r),this.onContextRequest=o=>{if(o.context!==this.context)return;let a=o.contextTarget??o.composedPath()[0];a!==this.host&&(o.stopPropagation(),this.addCallback(o.callback,a,o.subscribe))},this.onProviderRequest=o=>{if(o.context!==this.context||(o.contextTarget??o.composedPath()[0])===this.host)return;let a=new Set;for(let[n,{consumerHost:l}]of this.subscriptions)a.has(n)||(a.add(n),l.dispatchEvent(new He(this.context,l,n,!0)));o.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 Wr(this.context,this.host))}};function C({context:i,subscribe:t}){return(e,r)=>{typeof r=="object"?r.addInitializer(function(){new ft(this,{context:i,callback:o=>{e.set.call(this,o)},subscribe:t})}):e.constructor.addInitializer(o=>{new ft(o,{context:i,callback:a=>{o[r]=a},subscribe:t})})}}var Jt="cardNetworksContext";var ae="clientOptionsContext";var ze="computedStylesContext";var U="headlessInstanceContext";var Zt="klarnaCategoriesContext";var Z="managerContext";var Be="paymentMethodsContext";var Y="sdkStateContext";var X="vaultManagerContext";var ue="vaultManagerCvvContext";var V=class V{static log(t,...e){V.enabled}static info(t,...e){V.enabled}static warn(t,...e){V.enabled}static error(t,...e){V.enabled}static debug(t,...e){V.enabled}static table(t,e){V.enabled}static time(t){V.enabled}static timeEnd(t){V.enabled}};V.enabled=!0,V.defaultFont="font-family: Consolas, monospace; font-size: 12px;",V.brandTag="[PRIMER]",V.brandStyle=`background: #24292e; color: #ffffff; padding: 2px 6px; border-radius: 3px; font-weight: bold; margin-right: 4px; ${V.defaultFont}`,V.styles={log:`color: #4CAF50; ${V.defaultFont}`,info:`color: #2196F3; ${V.defaultFont}`,warn:`color: #FF9800; ${V.defaultFont}`,error:`color: #F44336; ${V.defaultFont}`,debug:`color: #9C27B0; ${V.defaultFont}`};var S=V;function An(i,t,e,r){let o=i,a=e;return{dispatch:n=>{let l=t(o,n,a);o=l,r(l)},getState:()=>Object.freeze({...o}),setCallbacks:n=>{a={...a,...n}}}}function wt(i){return(t,e,r)=>{let o=i[e.type];if(!o)throw new Error(`No handler for action type: ${e.type}`);return o(t,e,r)}}var et=class{constructor(t,e,r,o,a=()=>{this.host.requestUpdate()}){this.host=t;this.stateHandler=a;this.host.addController(this),this._dispatcher=An(e,r,o,n=>{this.stateHandler(n)})}get currentState(){return this._dispatcher.getState()}dispatch(t){this._dispatcher.dispatch(t)}setCallbacks(t){this._dispatcher.setCallbacks(t)}hostConnected(){}hostDisconnected(){}},Xt=class{constructor(t){this.host=t;this._controllers=[];"addController"in this.host&&this.host.addController(this)}addController(t){this._controllers.push(t)}hostConnected(){this._controllers.forEach(t=>{t.hostConnected&&t.hostConnected()})}hostDisconnected(){this._controllers.forEach(t=>{t.hostDisconnected&&t.hostDisconnected()})}};var er={isSuccessful:!1,isProcessing:!1,isLoading:!1,error:null,failure:null},Sn={START_LOADING:i=>({...i,isLoading:!0}),START_PROCESSING:i=>({...i,failure:null,isProcessing:!0}),STOP_PROCESSING:i=>({...i,isProcessing:!1}),COMPLETE_PROCESSING:i=>({...i,isProcessing:!1,isSuccessful:!0}),SET_ERROR:(i,t)=>(S.error(t.payload.message),{...i,isProcessing:!1,error:t.payload}),SET_FAILURE:(i,t)=>({...i,isProcessing:!1,failure:t.payload}),COMPLETE_LOADING:i=>({...i,isLoading:!1}),RESET:()=>er,RESET_ERROR:i=>({...i,error:null,failure:null})},_n=wt(Sn),Qt=class extends et{constructor(t){super(t,er,_n,null,e=>{t.sdkContextController.setSdkState(e),t.primerEventsController.dispatchSdkState(e)})}startLoading(){this.dispatch({type:"START_LOADING"})}startProcessing(){this.dispatch({type:"START_PROCESSING"})}stopProcessing(){this.dispatch({type:"STOP_PROCESSING"})}completeProcessing(){this.dispatch({type:"COMPLETE_PROCESSING"})}completeLoading(){this.dispatch({type:"COMPLETE_LOADING"})}setError(t){this.dispatch({type:"SET_ERROR",payload:t})}setFailure(t,e,r){this.dispatch({type:"SET_FAILURE",payload:{code:t,message:e,details:r}})}reset(){this.dispatch({type:"RESET"})}resetError(){this.dispatch({type:"RESET_ERROR"})}forceCompleteLoading(){this.currentState.isLoading&&(S.warn("Force completing loading state"),this.completeLoading())}};var tr=class{constructor(t){this.sdkStateProvider=null;this.paymentMethodsProvider=null;this.paymentManagerProvider=null;this.cardNetworksContext=null;this.vaultManagerCvvProvider=null;this.clientOptionsContext=null;this.headlessUtilsProvider=null;this.klarnaCategoriesProvider=null;this.computedStylesProvider=null;(this.host=t).addController(this),this.sdkStateProvider=new z(t,{context:Y,initialValue:er}),this.paymentMethodsProvider=new z(t,{context:Be,initialValue:null}),this.paymentManagerProvider=new z(t,{context:Z,initialValue:new Map}),this.cardNetworksContext=new z(t,{context:Jt,initialValue:null}),this.vaultManagerProvider=new z(t,{context:X,initialValue:null}),this.vaultManagerCvvProvider=new z(t,{context:ue,initialValue:null}),this.clientOptionsContext=new z(t,{context:ae,initialValue:null}),this.klarnaCategoriesProvider=new z(t,{context:Zt,initialValue:{categories:[],isLoading:!0}}),this.headlessUtilsProvider=new z(t,{context:U,initialValue:null}),this.computedStylesProvider=new z(t,{context:ze,initialValue:null})}hostConnected(){}setSdkState(t){this.sdkStateProvider?.setValue(t)}setPaymentMethods(t){this.paymentMethodsProvider?.setValue(t)}setPaymentManagers(t){this.paymentManagerProvider?.setValue(t)}setCardNetworks(t){this.cardNetworksContext?.setValue(t)}setVaultManager(t){this.vaultManagerProvider?.setValue(t)}setKlarnaCategories(t){this.klarnaCategoriesProvider?.setValue(t)}setClientOptions(t){this.clientOptionsContext?.setValue(t)}setHeadlessUtils(t){this.headlessUtilsProvider?.setValue(t)}setComputedStyles(t){this.computedStylesProvider?.setValue(t)}setVaultManagerCvv(t){this.vaultManagerCvvProvider?.setValue(t)}};var tt=class tt{constructor(t){(this.host=t).addController(this)}processCustomStyles(t){try{let e=JSON.parse(t);this.applyStyles(e)}catch(e){S.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||S.warn(`Rejected potentially unsafe CSS value: ${t}`),r}getCssVarName(t){let e=tt.cssVarCache.get(t);return e||(e=`--${t.replace(/([A-Z])/g,(r,o)=>`-${o.toLowerCase()}`)}`,tt.cssVarCache.set(t,e)),e}applyStyles(t){let e=[];for(let r of Object.keys(t)){let o=t[r];if(!o)continue;if(!this.isValidCssProperty(r)){S.warn(`Skipping invalid CSS property name: ${r}`);continue}if(!this.isValidCssValue(o))continue;let a=this.getCssVarName(r);e.push([a,o])}if(e.length>0)for(let[r,o]of e)this.host.style.setProperty(r,o)}removeStyle(t){let e=this.getCssVarName(t);this.host.style.removeProperty(e)}clearAllStyles(){for(let t of tt.cssVarCache.keys()){let e=tt.cssVarCache.get(t);e&&this.host.style.removeProperty(e)}}hostDisconnected(){}};tt.cssVarCache=new Map;var rr=tt;var ir=globalThis,ar=ir.ShadowRoot&&(ir.ShadyCSS===void 0||ir.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,zi=Symbol(),Hi=new WeakMap,or=class{constructor(t,e,r){if(this._$cssResult$=!0,r!==zi)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(ar&&t===void 0){let r=e!==void 0&&e.length===1;r&&(t=Hi.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),r&&Hi.set(e,t))}return t}toString(){return this.cssText}},Bi=i=>new or(typeof i=="string"?i:i+"",void 0,zi);var Jr=(i,t)=>{if(ar)i.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let e of t){let r=document.createElement("style"),o=ir.litNonce;o!==void 0&&r.setAttribute("nonce",o),r.textContent=e.cssText,i.appendChild(r)}},nr=ar?i=>i:i=>i instanceof CSSStyleSheet?(t=>{let e="";for(let r of t.cssRules)e+=r.cssText;return Bi(e)})(i):i;var{is:Pn,defineProperty:wn,getOwnPropertyDescriptor:Mn,getOwnPropertyNames:Tn,getOwnPropertySymbols:kn,getPrototypeOf:In}=Object,Fe=globalThis,Fi=Fe.trustedTypes,Ln=Fi?Fi.emptyScript:"",Nn=Fe.reactiveElementPolyfillSupport,Mt=(i,t)=>i,Zr={toAttribute(i,t){switch(t){case Boolean:i=i?Ln:null;break;case Object:case Array:i=i==null?i:JSON.stringify(i)}return i},fromAttribute(i,t){let e=i;switch(t){case Boolean:e=i!==null;break;case Number:e=i===null?null:Number(i);break;case Object:case Array:try{e=JSON.parse(i)}catch{e=null}}return e}},sr=(i,t)=>!Pn(i,t),ji={attribute:!0,type:String,converter:Zr,reflect:!1,hasChanged:sr};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Fe.litPropertyMetadata??(Fe.litPropertyMetadata=new WeakMap);var rt=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=ji){if(e.state&&(e.attribute=!1),this._$Ei(),this.elementProperties.set(t,e),!e.noAccessor){let r=Symbol(),o=this.getPropertyDescriptor(t,r,e);o!==void 0&&wn(this.prototype,t,o)}}static getPropertyDescriptor(t,e,r){let{get:o,set:a}=Mn(this.prototype,t)??{get(){return this[e]},set(n){this[e]=n}};return{get(){return o?.call(this)},set(n){let l=o?.call(this);a.call(this,n),this.requestUpdate(t,l,r)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??ji}static _$Ei(){if(this.hasOwnProperty(Mt("elementProperties")))return;let t=In(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Mt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Mt("properties"))){let e=this.properties,r=[...Tn(e),...kn(e)];for(let o of r)this.createProperty(o,e[o])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[r,o]of e)this.elementProperties.set(r,o)}this._$Eh=new Map;for(let[e,r]of this.elementProperties){let o=this._$Eu(e,r);o!==void 0&&this._$Eh.set(o,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 o of r)e.unshift(nr(o))}else t!==void 0&&e.push(nr(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 Jr(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),o=this.constructor._$Eu(t,r);if(o!==void 0&&r.reflect===!0){let a=(r.converter?.toAttribute!==void 0?r.converter:Zr).toAttribute(e,r.type);this._$Em=t,a==null?this.removeAttribute(o):this.setAttribute(o,a),this._$Em=null}}_$AK(t,e){let r=this.constructor,o=r._$Eh.get(t);if(o!==void 0&&this._$Em!==o){let a=r.getPropertyOptions(o),n=typeof a.converter=="function"?{fromAttribute:a.converter}:a.converter?.fromAttribute!==void 0?a.converter:Zr;this._$Em=o,this[o]=n.fromAttribute(e,a.type),this._$Em=null}}requestUpdate(t,e,r){if(t!==void 0){if(r??(r=this.constructor.getPropertyOptions(t)),!(r.hasChanged??sr)(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[o,a]of this._$Ep)this[o]=a;this._$Ep=void 0}let r=this.constructor.elementProperties;if(r.size>0)for(let[o,a]of r)a.wrapped!==!0||this._$AL.has(o)||this[o]===void 0||this.P(o,this[o],a)}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){}};rt.elementStyles=[],rt.shadowRootOptions={mode:"open"},rt[Mt("elementProperties")]=new Map,rt[Mt("finalized")]=new Map,Nn?.({ReactiveElement:rt}),(Fe.reactiveElementVersions??(Fe.reactiveElementVersions=[])).push("2.0.4");var je={INITIAL:0,PENDING:1,COMPLETE:2,ERROR:3},T=Symbol(),L=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 o=typeof e=="object"?e:{task:e,args:r};this.v=o.task,this.j=o.args,this.m=o.argsEqual??Ki,this.k=o.onComplete,this.A=o.onError,this.autoRun=o.autoRun??!0,"initialValue"in o&&(this.u=o.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 o=++this.p;this.q=new AbortController;let a=!1;try{e=await this.v(t,{signal:this.q.signal})}catch(n){a=!0,r=n}if(this.p===o){if(e===T)this.i=0;else{if(a===!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)}}},Ki=(i,t)=>i===t||i.length===t.length&&i.every((e,r)=>!sr(e,t[r]));var On={SET_LOADING:(i,t)=>({...i,isLoading:t.payload}),SET_UPDATING:(i,t)=>({...i,isUpdating:t.payload}),INITIALIZE_VAULT_MANAGER:(i,t,e)=>({...i,enabled:t.vaultEnabled,cvvRecapture:t.cvvRecapture,showEmptyState:t.showEmptyState,deleteVaultedPaymentMethod:e.deleteVaultedPaymentMethod,startVaultedPaymentFlow:e.startVaultedPaymentFlow,createCvvInput:e.createCvvInput}),UPDATE_PAYMENT_METHODS:(i,t)=>({...i,vaultedPaymentMethods:t.payload,isLoading:!1,isUpdating:!1}),SET_ERROR:i=>({...i,isLoading:!1,isUpdating:!1}),DISABLE:i=>({...i,enabled:!1}),RESET:()=>Gi},Rn={INITIALIZE_CVV:(i,t,e)=>({...i,setCvvInput:e.setCvvInput,setSelectedVaultedPaymentMethod:e.setSelectedVaultedPaymentMethod}),SET_FORM_DIRTY:(i,t)=>({...i,formIsDirty:t.payload}),SET_CVV_INPUT:(i,t)=>({...i,cvvInput:t.payload}),SET_SELECTED_VAULTED_PAYMENT_METHOD:(i,t)=>({...i,selectedVaultedPaymentMethod:t.payload}),RESET_CVV:()=>qi},Dn=wt(On),$n=wt(Rn),Gi={enabled:!1,isLoading:!1,isUpdating:!1,cvvRecapture:!1,showEmptyState:!0,vaultedPaymentMethods:[],createCvvInput:null,deleteVaultedPaymentMethod:()=>Promise.resolve(),startVaultedPaymentFlow:()=>Promise.resolve()},qi={cvvInput:null,formIsDirty:!1,setCvvInput:()=>{},selectedVaultedPaymentMethod:null,setSelectedVaultedPaymentMethod:()=>{}},Xr=class extends et{constructor(t,e){super(t,Gi,Dn,e,r=>{t.sdkContextController.setVaultManager(r)})}setLoading(t){this.dispatch({type:"SET_LOADING",payload:t})}setUpdating(t){this.dispatch({type:"SET_UPDATING",payload:t})}initializeVaultManager(t,e,r,o){this.dispatch({type:"INITIALIZE_VAULT_MANAGER",payload:t,vaultEnabled:e,cvvRecapture:r,showEmptyState:o})}updatePaymentMethods(t){this.dispatch({type:"UPDATE_PAYMENT_METHODS",payload:t})}setError(t){this.dispatch({type:"SET_ERROR",payload:t})}disable(){this.dispatch({type:"DISABLE"})}reset(){this.dispatch({type:"RESET"})}},Qr=class extends et{constructor(t,e){super(t,qi,$n,e,r=>{t.sdkContextController.setVaultManagerCvv(r)})}initializeCvv(t){this.dispatch({type:"INITIALIZE_CVV",createCvvInput:t})}setFormDirty(t){this.dispatch({type:"SET_FORM_DIRTY",payload:t})}setCvvInputState(t){this.dispatch({type:"SET_CVV_INPUT",payload:t})}setSelectedPaymentMethod(t){this.dispatch({type:"SET_SELECTED_VAULTED_PAYMENT_METHOD",payload:t})}resetCvv(){this.dispatch({type:"RESET_CVV"})}},Tt=class extends Xt{constructor(e){super(e);this._vaultManager=null;this._options=null;this.createVaultManagerFn=null;this.createCvvInput=e=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");return this._vaultManager.createCvvInput(e)};this.deleteVaultedPaymentMethod=async e=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");try{this.coreController.updatePaymentMethods(this.vaultManagerState.vaultedPaymentMethods),await this._vaultManager.deleteVaultedPaymentMethod(e),await this.fetchVaultedPaymentMethods()}catch(r){throw this.coreController.setError(r instanceof Error?r:new Error("Failed to delete payment method")),r}};this.setCvvInput=e=>{this.itemController.setCvvInputState(e)};this.startVaultedPaymentFlow=async()=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");let e=this.vaultItemState.selectedVaultedPaymentMethod,r=this.vaultManagerState.cvvRecapture,o=this.vaultItemState.cvvInput;if(!e||r&&(!o||o.metadata.error)){this.itemController.setFormDirty(!0);return}this.host.sdkStateController.startProcessing();try{await this._vaultManager.startPaymentFlow(e.id,r?{cvv:o.valueToken}:void 0)}catch(a){S.error("VaultManagerController: Error starting vaulted payment flow",a),this.coreController.setError(a instanceof Error?a:new Error("Failed to start vaulted payment flow")),this.host.sdkStateController.stopProcessing()}};this.setSelectedVaultedPaymentMethod=e=>{this.itemController.setSelectedPaymentMethod(e),this.itemController.setFormDirty(!1)};this.coreController=new Xr(e,{deleteVaultedPaymentMethod:this.deleteVaultedPaymentMethod.bind(this),startVaultedPaymentFlow:this.startVaultedPaymentFlow.bind(this),createCvvInput:this.createCvvInput}),this.itemController=new Qr(e,{setCvvInput:this.setCvvInput.bind(this),setSelectedVaultedPaymentMethod:this.setSelectedVaultedPaymentMethod.bind(this)}),this.addController(this.coreController),this.addController(this.itemController),new L(this.host,{task:async([r,o])=>{if(!r||!o?.vaultEnabled)return this.coreController.disable(),T;this.coreController.setLoading(!0);try{let a=r();this._vaultManager=a,this.coreController.initializeVaultManager(a,o.vaultEnabled,!!o.captureVaultedCardCvv,o.showEmptyState??!0),this.itemController.initializeCvv(a.createCvvInput),await this.fetchVaultedPaymentMethods(!0),S.log("VaultManagerController: Vault initialized successfully",{coreState:this.coreController.currentState,cvvState:this.itemController.currentState})}catch(a){S.error("VaultManagerController: Failed to initialize vault",a),this.coreController.setError(a instanceof Error?a:new Error("Unknown error"))}return this._vaultManager},args:()=>[this.createVaultManagerFn,this.options]})}initializeVaultManager(e,r){this.createVaultManagerFn=e,this.options=r??null}get vaultManager(){return this._vaultManager}set vaultManager(e){this._vaultManager=e,this.host.requestUpdate()}get options(){return this._options}set options(e){this._options=e,this.host.requestUpdate()}get vaultManagerState(){return this.coreController.currentState}get vaultItemState(){return this.itemController.currentState}hostDisconnected(){super.hostDisconnected(),this.vaultManager=null,this.coreController.reset()}async fetchVaultedPaymentMethods(e){if(!this._vaultManager)throw new Error("Vault manager not initialized");try{e||this.coreController.setUpdating(!0);let r=await this._vaultManager.fetchVaultedPaymentMethods();return S.log("VaultManagerController: Fetched payment methods",r),this.coreController.updatePaymentMethods(r),r}catch(r){throw this.coreController.setError(r instanceof Error?r:new Error("Failed to fetch payment methods")),r}}};var kt="lit-localize-status";var Wi=i=>typeof i!="string"&&"strTag"in i,lr=(i,t,e)=>{let r=i[0];for(let o=1;o<i.length;o++)r+=t[e?e[o-1]:o-1],r+=i[o];return r};var It=i=>Wi(i)?lr(i.strings,i.values):i;var x=It,Ji=!1;function ei(i){if(Ji)throw new Error("lit-localize can only be configured once");x=i,Ji=!0}var ti=class{constructor(t){this.__litLocalizeEventHandler=e=>{e.detail.status==="ready"&&this.host.requestUpdate()},this.host=t}hostConnected(){window.addEventListener(kt,this.__litLocalizeEventHandler)}hostDisconnected(){window.removeEventListener(kt,this.__litLocalizeEventHandler)}},Vn=i=>i.addController(new ti(i)),Zi=Vn;var M=()=>(i,t)=>(i.addInitializer(Zi),i);var Lt=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 Pe=[];for(let i=0;i<256;i++)Pe[i]=(i>>4&15).toString(16)+(i&15).toString(16);function Xi(i){let t=0,e=8997,r=0,o=33826,a=0,n=40164,l=0,d=52210;for(let m=0;m<i.length;m++)e^=i.charCodeAt(m),t=e*435,r=o*435,a=n*435,l=d*435,a+=e<<8,l+=o<<8,r+=t>>>16,e=t&65535,a+=r>>>16,o=r&65535,d=l+(a>>>16)&65535,n=a&65535;return Pe[d>>8]+Pe[d&255]+Pe[n>>8]+Pe[n&255]+Pe[o>>8]+Pe[o&255]+Pe[e>>8]+Pe[e&255]}var Yn="",Un="h",Hn="s";function Qi(i,t){return(t?Un:Hn)+Xi(typeof i=="string"?i:i.join(Yn))}var eo=new WeakMap,to=new Map;function ro(i,t,e){if(i){let r=e?.id??zn(t),o=i[r];if(o){if(typeof o=="string")return o;if("strTag"in o)return lr(o.strings,t.values,o.values);{let a=eo.get(o);return a===void 0&&(a=o.values,eo.set(o,a)),{...o,values:a.map(n=>t.values[n])}}}}return It(t)}function zn(i){let t=typeof i=="string"?i:i.strings,e=to.get(t);return e===void 0&&(e=Qi(t,typeof i!="string"&&!("strTag"in i)),to.set(t,e)),e}function ri(i){window.dispatchEvent(new CustomEvent(kt,{detail:i}))}var cr="",ii,io,pr,oi,oo,it=new Lt;it.resolve();var dr=0,ao=i=>(ei((t,e)=>ro(oo,t,e)),cr=io=i.sourceLocale,pr=new Set(i.targetLocales),pr.add(i.sourceLocale),oi=i.loadLocale,{getLocale:Bn,setLocale:Fn}),Bn=()=>cr,Fn=i=>{if(i===(ii??cr))return it.promise;if(!pr||!oi)throw new Error("Internal error");if(!pr.has(i))throw new Error("Invalid locale code");dr++;let t=dr;return ii=i,it.settled&&(it=new Lt),ri({status:"loading",loadingLocale:i}),(i===io?Promise.resolve({templates:void 0}):oi(i)).then(r=>{dr===t&&(cr=i,ii=void 0,oo=r.templates,ri({status:"ready",readyLocale:i}),it.resolve())},r=>{dr===t&&(ri({status:"error",errorLocale:i,errorMessage:r.toString()}),it.reject(r))}),it.promise};var ai="en",ni=["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"],no="You must call `loadLocale` first to set up the localized template.",so,mr,lo=i=>{let t=ao({sourceLocale:ai,targetLocales:ni,loadLocale:i});so=t.getLocale,mr=t.setLocale};var si=i=>{lo(i)},li=i=>{if(!mr)throw new Error(no);return mr(i)};var Nt=new Set(ni);Nt.add(ai);var di=i=>{if(typeof i!="string")return!1;if(i==="en")return!0;let t=i.replace("_","-");if(Nt.has(t))return!0;let e=t.split("-")[0];return!!Nt.has(e)},ci=i=>{if(i==="en")return"en-GB";let t=i.replace("_","-");if(Nt.has(t))return t;let e=t.split("-")[0];return Nt.has(e)?e:"en-GB"};var ur=globalThis,hr=ur.ShadowRoot&&(ur.ShadyCSS===void 0||ur.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,pi=Symbol(),co=new WeakMap,Ot=class{constructor(t,e,r){if(this._$cssResult$=!0,r!==pi)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(hr&&t===void 0){let r=e!==void 0&&e.length===1;r&&(t=co.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),r&&co.set(e,t))}return t}toString(){return this.cssText}},he=i=>new Ot(typeof i=="string"?i:i+"",void 0,pi),y=(i,...t)=>{let e=i.length===1?i[0]:t.reduce((r,o,a)=>r+(n=>{if(n._$cssResult$===!0)return n.cssText;if(typeof n=="number")return n;throw Error("Value passed to 'css' function must be a 'css' function result: "+n+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(o)+i[a+1],i[0]);return new Ot(e,i,pi)},po=(i,t)=>{if(hr)i.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let e of t){let r=document.createElement("style"),o=ur.litNonce;o!==void 0&&r.setAttribute("nonce",o),r.textContent=e.cssText,i.appendChild(r)}},mi=hr?i=>i:i=>i instanceof CSSStyleSheet?(t=>{let e="";for(let r of t.cssRules)e+=r.cssText;return he(e)})(i):i;var{is:jn,defineProperty:Kn,getOwnPropertyDescriptor:Gn,getOwnPropertyNames:qn,getOwnPropertySymbols:Wn,getPrototypeOf:Jn}=Object,Ke=globalThis,mo=Ke.trustedTypes,Zn=mo?mo.emptyScript:"",Xn=Ke.reactiveElementPolyfillSupport,Rt=(i,t)=>i,Dt={toAttribute(i,t){switch(t){case Boolean:i=i?Zn:null;break;case Object:case Array:i=i==null?i:JSON.stringify(i)}return i},fromAttribute(i,t){let e=i;switch(t){case Boolean:e=i!==null;break;case Number:e=i===null?null:Number(i);break;case Object:case Array:try{e=JSON.parse(i)}catch{e=null}}return e}},fr=(i,t)=>!jn(i,t),uo={attribute:!0,type:String,converter:Dt,reflect:!1,useDefault:!1,hasChanged:fr};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Ke.litPropertyMetadata??(Ke.litPropertyMetadata=new WeakMap);var we=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=uo){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(),o=this.getPropertyDescriptor(t,r,e);o!==void 0&&Kn(this.prototype,t,o)}}static getPropertyDescriptor(t,e,r){let{get:o,set:a}=Gn(this.prototype,t)??{get(){return this[e]},set(n){this[e]=n}};return{get:o,set(n){let l=o?.call(this);a?.call(this,n),this.requestUpdate(t,l,r)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??uo}static _$Ei(){if(this.hasOwnProperty(Rt("elementProperties")))return;let t=Jn(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Rt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Rt("properties"))){let e=this.properties,r=[...qn(e),...Wn(e)];for(let o of r)this.createProperty(o,e[o])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[r,o]of e)this.elementProperties.set(r,o)}this._$Eh=new Map;for(let[e,r]of this.elementProperties){let o=this._$Eu(e,r);o!==void 0&&this._$Eh.set(o,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 o of r)e.unshift(mi(o))}else t!==void 0&&e.push(mi(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 po(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),o=this.constructor._$Eu(t,r);if(o!==void 0&&r.reflect===!0){let a=(r.converter?.toAttribute!==void 0?r.converter:Dt).toAttribute(e,r.type);this._$Em=t,a==null?this.removeAttribute(o):this.setAttribute(o,a),this._$Em=null}}_$AK(t,e){let r=this.constructor,o=r._$Eh.get(t);if(o!==void 0&&this._$Em!==o){let a=r.getPropertyOptions(o),n=typeof a.converter=="function"?{fromAttribute:a.converter}:a.converter?.fromAttribute!==void 0?a.converter:Dt;this._$Em=o,this[o]=n.fromAttribute(e,a.type)??this._$Ej?.get(o)??null,this._$Em=null}}requestUpdate(t,e,r){if(t!==void 0){let o=this.constructor,a=this[t];if(r??(r=o.getPropertyOptions(t)),!((r.hasChanged??fr)(a,e)||r.useDefault&&r.reflect&&a===this._$Ej?.get(t)&&!this.hasAttribute(o._$Eu(t,r))))return;this.C(t,e,r)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,e,{useDefault:r,reflect:o,wrapped:a},n){r&&!(this._$Ej??(this._$Ej=new Map)).has(t)&&(this._$Ej.set(t,n??e??this[t]),a!==!0||n!==void 0)||(this._$AL.has(t)||(this.hasUpdated||r||(e=void 0),this._$AL.set(t,e)),o===!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[o,a]of this._$Ep)this[o]=a;this._$Ep=void 0}let r=this.constructor.elementProperties;if(r.size>0)for(let[o,a]of r){let{wrapped:n}=a,l=this[o];n!==!0||this._$AL.has(o)||l===void 0||this.C(o,void 0,a,l)}}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){}};we.elementStyles=[],we.shadowRootOptions={mode:"open"},we[Rt("elementProperties")]=new Map,we[Rt("finalized")]=new Map,Xn?.({ReactiveElement:we}),(Ke.reactiveElementVersions??(Ke.reactiveElementVersions=[])).push("2.1.0");var Vt=globalThis,yr=Vt.trustedTypes,ho=yr?yr.createPolicy("lit-html",{createHTML:i=>i}):void 0,hi="$lit$",Me=`lit$${Math.random().toFixed(9).slice(2)}$`,fi="?"+Me,Qn=`<${fi}>`,nt=document,Yt=()=>nt.createComment(""),Ut=i=>i===null||typeof i!="object"&&typeof i!="function",yi=Array.isArray,Co=i=>yi(i)||typeof i?.[Symbol.iterator]=="function",ui=`[
|
|
2
2
|
\f\r]`,$t=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,fo=/-->/g,yo=/>/g,ot=RegExp(`>|${ui}(?:([^\\s"'>=/]+)(${ui}*=${ui}*(?:[^
|
|
3
3
|
\f\r"'\`<>=]|("|')|))|$)`,"g"),go=/'/g,vo=/"/g,xo=/^(?:script|style|textarea|title)$/i,gi=i=>(t,...e)=>({_$litType$:i,strings:t,values:e}),p=gi(1),fe=gi(2),mp=gi(3),Te=Symbol.for("lit-noChange"),h=Symbol.for("lit-nothing"),bo=new WeakMap,at=nt.createTreeWalker(nt,129);function Eo(i,t){if(!yi(i)||!i.hasOwnProperty("raw"))throw Error("invalid template strings array");return ho!==void 0?ho.createHTML(t):t}var Ao=(i,t)=>{let e=i.length-1,r=[],o,a=t===2?"<svg>":t===3?"<math>":"",n=$t;for(let l=0;l<e;l++){let d=i[l],m,f,u=-1,b=0;for(;b<d.length&&(n.lastIndex=b,f=n.exec(d),f!==null);)b=n.lastIndex,n===$t?f[1]==="!--"?n=fo:f[1]!==void 0?n=yo:f[2]!==void 0?(xo.test(f[2])&&(o=RegExp("</"+f[2],"g")),n=ot):f[3]!==void 0&&(n=ot):n===ot?f[0]===">"?(n=o??$t,u=-1):f[1]===void 0?u=-2:(u=n.lastIndex-f[2].length,m=f[1],n=f[3]===void 0?ot:f[3]==='"'?vo:go):n===vo||n===go?n=ot:n===fo||n===yo?n=$t:(n=ot,o=void 0);let P=n===ot&&i[l+1].startsWith("/>")?" ":"";a+=n===$t?d+Qn:u>=0?(r.push(m),d.slice(0,u)+hi+d.slice(u)+Me+P):d+Me+(u===-2?l:P)}return[Eo(i,a+(i[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),r]},Ht=class i{constructor({strings:t,_$litType$:e},r){let o;this.parts=[];let a=0,n=0,l=t.length-1,d=this.parts,[m,f]=Ao(t,e);if(this.el=i.createElement(m,r),at.currentNode=this.el.content,e===2||e===3){let u=this.el.content.firstChild;u.replaceWith(...u.childNodes)}for(;(o=at.nextNode())!==null&&d.length<l;){if(o.nodeType===1){if(o.hasAttributes())for(let u of o.getAttributeNames())if(u.endsWith(hi)){let b=f[n++],P=o.getAttribute(u).split(Me),A=/([.?@])?(.*)/.exec(b);d.push({type:1,index:a,name:A[2],strings:P,ctor:A[1]==="."?vr:A[1]==="?"?br:A[1]==="@"?Cr:lt}),o.removeAttribute(u)}else u.startsWith(Me)&&(d.push({type:6,index:a}),o.removeAttribute(u));if(xo.test(o.tagName)){let u=o.textContent.split(Me),b=u.length-1;if(b>0){o.textContent=yr?yr.emptyScript:"";for(let P=0;P<b;P++)o.append(u[P],Yt()),at.nextNode(),d.push({type:2,index:++a});o.append(u[b],Yt())}}}else if(o.nodeType===8)if(o.data===fi)d.push({type:2,index:a});else{let u=-1;for(;(u=o.data.indexOf(Me,u+1))!==-1;)d.push({type:7,index:a}),u+=Me.length-1}a++}}static createElement(t,e){let r=nt.createElement("template");return r.innerHTML=t,r}};function st(i,t,e=i,r){if(t===Te)return t;let o=r!==void 0?e._$Co?.[r]:e._$Cl,a=Ut(t)?void 0:t._$litDirective$;return o?.constructor!==a&&(o?._$AO?.(!1),a===void 0?o=void 0:(o=new a(i),o._$AT(i,e,r)),r!==void 0?(e._$Co??(e._$Co=[]))[r]=o:e._$Cl=o),o!==void 0&&(t=st(i,o._$AS(i,t.values),o,r)),t}var gr=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,o=(t?.creationScope??nt).importNode(e,!0);at.currentNode=o;let a=at.nextNode(),n=0,l=0,d=r[0];for(;d!==void 0;){if(n===d.index){let m;d.type===2?m=new yt(a,a.nextSibling,this,t):d.type===1?m=new d.ctor(a,d.name,d.strings,this,t):d.type===6&&(m=new xr(a,this,t)),this._$AV.push(m),d=r[++l]}n!==d?.index&&(a=at.nextNode(),n++)}return at.currentNode=nt,o}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++}},yt=class i{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,e,r,o){this.type=2,this._$AH=h,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=r,this.options=o,this._$Cv=o?.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=st(this,t,e),Ut(t)?t===h||t==null||t===""?(this._$AH!==h&&this._$AR(),this._$AH=h):t!==this._$AH&&t!==Te&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Co(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!==h&&Ut(this._$AH)?this._$AA.nextSibling.data=t:this.T(nt.createTextNode(t)),this._$AH=t}$(t){let{values:e,_$litType$:r}=t,o=typeof r=="number"?this._$AC(t):(r.el===void 0&&(r.el=Ht.createElement(Eo(r.h,r.h[0]),this.options)),r);if(this._$AH?._$AD===o)this._$AH.p(e);else{let a=new gr(o,this),n=a.u(this.options);a.p(e),this.T(n),this._$AH=a}}_$AC(t){let e=bo.get(t.strings);return e===void 0&&bo.set(t.strings,e=new Ht(t)),e}k(t){yi(this._$AH)||(this._$AH=[],this._$AR());let e=this._$AH,r,o=0;for(let a of t)o===e.length?e.push(r=new i(this.O(Yt()),this.O(Yt()),this,this.options)):r=e[o],r._$AI(a),o++;o<e.length&&(this._$AR(r&&r._$AB.nextSibling,o),e.length=o)}_$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))}},lt=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,r,o,a){this.type=1,this._$AH=h,this._$AN=void 0,this.element=t,this.name=e,this._$AM=o,this.options=a,r.length>2||r[0]!==""||r[1]!==""?(this._$AH=Array(r.length-1).fill(new String),this.strings=r):this._$AH=h}_$AI(t,e=this,r,o){let a=this.strings,n=!1;if(a===void 0)t=st(this,t,e,0),n=!Ut(t)||t!==this._$AH&&t!==Te,n&&(this._$AH=t);else{let l=t,d,m;for(t=a[0],d=0;d<a.length-1;d++)m=st(this,l[r+d],e,d),m===Te&&(m=this._$AH[d]),n||(n=!Ut(m)||m!==this._$AH[d]),m===h?t=h:t!==h&&(t+=(m??"")+a[d+1]),this._$AH[d]=m}n&&!o&&this.j(t)}j(t){t===h?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},vr=class extends lt{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===h?void 0:t}},br=class extends lt{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==h)}},Cr=class extends lt{constructor(t,e,r,o,a){super(t,e,r,o,a),this.type=5}_$AI(t,e=this){if((t=st(this,t,e,0)??h)===Te)return;let r=this._$AH,o=t===h&&r!==h||t.capture!==r.capture||t.once!==r.once||t.passive!==r.passive,a=t!==h&&(r===h||o);o&&this.element.removeEventListener(this.name,this,r),a&&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)}},xr=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){st(this,t)}},So={M:hi,P:Me,A:fi,C:1,L:Ao,R:gr,D:Co,V:st,I:yt,H:lt,N:br,U:Cr,B:vr,F:xr},es=Vt.litHtmlPolyfillSupport;es?.(Ht,yt),(Vt.litHtmlVersions??(Vt.litHtmlVersions=[])).push("3.3.0");var _o=(i,t,e)=>{let r=e?.renderBefore??t,o=r._$litPart$;if(o===void 0){let a=e?.renderBefore??null;r._$litPart$=o=new yt(t.insertBefore(Yt(),a),a,void 0,e??{})}return o._$AI(i),o};var zt=globalThis,g=class extends we{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=_o(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Te}};g._$litElement$=!0,g.finalized=!0,zt.litElementHydrateSupport?.({LitElement:g});var ts=zt.litElementPolyfillSupport;ts?.({LitElement:g});(zt.litElementVersions??(zt.litElementVersions=[])).push("4.2.0");var v=i=>(t,e)=>{e!==void 0?e.addInitializer(()=>{customElements.define(i,t)}):customElements.define(i,t)};var rs={attribute:!0,type:String,converter:Dt,reflect:!1,hasChanged:fr},is=(i=rs,t,e)=>{let{kind:r,metadata:o}=e,a=globalThis.litPropertyMetadata.get(o);if(a===void 0&&globalThis.litPropertyMetadata.set(o,a=new Map),r==="setter"&&((i=Object.create(i)).wrapped=!0),a.set(e.name,i),r==="accessor"){let{name:n}=e;return{set(l){let d=t.get.call(this);t.set.call(this,l),this.requestUpdate(n,d,i)},init(l){return l!==void 0&&this.C(n,void 0,i,l),l}}}if(r==="setter"){let{name:n}=e;return function(l){let d=this[n];t.call(this,l),this.requestUpdate(n,d,i)}}throw Error("Unsupported decorator location: "+r)};function c(i){return(t,e)=>typeof e=="object"?is(i,t,e):((r,o,a)=>{let n=o.hasOwnProperty(a);return o.constructor.createProperty(a,r),n?Object.getOwnPropertyDescriptor(o,a):void 0})(i,t,e)}function _(i){return c({...i,state:!0,attribute:!1})}var dt=(i,t,e)=>(e.configurable=!0,e.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(i,t,e),e);function Ge(i,t){return(e,r,o)=>{let a=n=>n.renderRoot?.querySelector(i)??null;if(t){let{get:n,set:l}=typeof r=="object"?e:o??(()=>{let d=Symbol();return{get(){return this[d]},set(m){this[d]=m}}})();return dt(e,r,{get(){let d=n.call(this);return d===void 0&&(d=a(this),(d!==null||this.hasUpdated)&&l.call(this,d)),d}})}return dt(e,r,{get(){return a(this)}})}}function I(i,t,e){return i?t(i):e?.(i)}var E=y` * { box-sizing: border-box; } `,Po=y` :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 wo="https://sdk.primer.io/web/v2-latest/Primer.min.js",ye="20px";var Er=class{constructor(t){this._methods=t}get(t){return this._methods.get(t)}toArray(){return Array.from(this._methods.values())}size(){return this._methods.size}};var Ar=class{constructor(t){this.paymentMethods=null;this.headlessInstance=t}setPaymentMethods(t){this.paymentMethods=t}async refreshSession(){if(!this.headlessInstance){S.error("PrimerJS: Cannot refresh session: Headless instance not available");return}try{await this.headlessInstance.refreshClientSession()}catch(t){throw S.error("PrimerJS: Error refreshing client session:",t),t}}getPaymentMethods(){return this.paymentMethods?this.paymentMethods.toArray():(S.warn("PrimerJS: Payment methods not available"),[])}handlePaymentStart(){this.onPaymentStart&&this.onPaymentStart()}handleBeforePaymentCreate(t,e){if(this.onPaymentPrepare){let r={continuePaymentCreation:()=>{S.info("PrimerJS: Payment creation continuing"),e.continuePaymentCreation()},abortPaymentCreation:()=>{S.info("PrimerJS: Payment creation aborted"),e.abortPaymentCreation()}};this.onPaymentPrepare(t,r)}else S.info("PrimerJS: No payment prepare handler, continuing by default"),e.continuePaymentCreation()}handlePaymentComplete(t){this.onPaymentComplete&&this.onPaymentComplete({payment:t,status:"success"})}handlePaymentFailure(t,e){this.onPaymentComplete&&this.onPaymentComplete({payment:e||null,status:"error",error:t})}};var Sr=typeof window<"u"&&typeof window.document<"u";function os(i){return document.querySelector(`script[src^="${i}"]`)}function as(i,t){let e=document.createElement("script");return e.setAttribute("src",i),e.setAttribute("async",""),e.setAttribute("crossorigin","anonymous"),t&&e.setAttribute("type","module"),e}function Mo(i,t=!1){if(!Sr)throw new Error("Cannot load script in server environment");let e=os(i)??as(i,t);return new Promise((r,o)=>{e.onload=()=>{r()},e.onerror=()=>{o(new Error(`Failed to load script: ${i}`))},e.parentNode||document.head.appendChild(e)})}var ns={"../../node_modules/card-validator/dist/card-number.js":function(i,t,e){Object.defineProperty(t,"__esModule",{value:!0}),t.cardNumber=void 0;var r=e("../../node_modules/card-validator/dist/luhn-10.js"),o=e("../../node_modules/credit-card-type/dist/index.js");function a(l,d,m){return{card:l,isPotentiallyValid:d,isValid:m}}function n(l,d){d===void 0&&(d={});var m,f,u;if(typeof l!="string"&&typeof l!="number")return a(null,!1,!1);var b=String(l).replace(/-|\s/g,"");if(!/^\d*$/.test(b))return a(null,!1,!1);var P=o(b);if(P.length===0)return a(null,!1,!1);if(P.length!==1)return a(null,!0,!1);var A=P[0];if(d.maxLength&&b.length>d.maxLength)return a(A,!1,!1);f=d.skipLuhnValidation===!0||A.type===o.types.UNIONPAY&&d.luhnValidateUnionPay!==!0?!0:r(b),u=Math.max.apply(null,A.lengths),d.maxLength&&(u=Math.min(d.maxLength,u));for(var k=0;k<A.lengths.length;k++)if(A.lengths[k]===b.length)return m=b.length<u||f,a(A,m,f);return a(A,b.length<u,!1)}t.cardNumber=n},"../../node_modules/card-validator/dist/cardholder-name.js":function(i,t){Object.defineProperty(t,"__esModule",{value:!0}),t.cardholderName=void 0;var e=/^[\d\s-]*$/,r=255;function o(n,l){return{isValid:n,isPotentiallyValid:l}}function a(n){return typeof n!="string"?o(!1,!1):n.length===0?o(!1,!0):n.length>r?o(!1,!1):e.test(n)?o(!1,!0):o(!0,!0)}t.cardholderName=a},"../../node_modules/card-validator/dist/cvv.js":function(i,t){Object.defineProperty(t,"__esModule",{value:!0}),t.cvv=void 0;var e=3;function r(l,d){for(var m=0;m<l.length;m++)if(d===l[m])return!0;return!1}function o(l){for(var d=e,m=0;m<l.length;m++)d=l[m]>d?l[m]:d;return d}function a(l,d){return{isValid:l,isPotentiallyValid:d}}function n(l,d){return d===void 0&&(d=e),d=d instanceof Array?d:[d],typeof l!="string"||!/^\d*$/.test(l)?a(!1,!1):r(d,l.length)?a(!0,!0):l.length<Math.min.apply(null,d)?a(!1,!0):l.length>o(d)?a(!1,!1):a(!0,!0)}t.cvv=n},"../../node_modules/card-validator/dist/expiration-date.js":function(i,t,e){var r=this&&this.__assign||function(){return r=Object.assign||function(m){for(var f,u=1,b=arguments.length;u<b;u++){f=arguments[u];for(var P in f)Object.prototype.hasOwnProperty.call(f,P)&&(m[P]=f[P])}return m},r.apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0}),t.expirationDate=void 0;var o=e("../../node_modules/card-validator/dist/lib/parse-date.js"),a=e("../../node_modules/card-validator/dist/expiration-month.js"),n=e("../../node_modules/card-validator/dist/expiration-year.js");function l(m,f,u,b){return{isValid:m,isPotentiallyValid:f,month:u,year:b}}function d(m,f){var u;if(typeof m=="string")m=m.replace(/^(\d\d) (\d\d(\d\d)?)$/,"$1/$2"),u=(0,o.parseDate)(String(m));else{if(m===null||typeof m!="object")return l(!1,!1,null,null);var b=r({},m);u={month:String(b.month),year:String(b.year)}}var P=(0,a.expirationMonth)(u.month),A=(0,n.expirationYear)(u.year,f);if(P.isValid){if(A.isCurrentYear){var k=P.isValidForThisYear;return l(k,k,u.month,u.year)}if(A.isValid)return l(!0,!0,u.month,u.year)}return P.isPotentiallyValid&&A.isPotentiallyValid?l(!1,!0,null,null):l(!1,!1,null,null)}t.expirationDate=d},"../../node_modules/card-validator/dist/expiration-month.js":function(i,t){Object.defineProperty(t,"__esModule",{value:!0}),t.expirationMonth=void 0;function e(o,a,n){return{isValid:o,isPotentiallyValid:a,isValidForThisYear:n||!1}}function r(o){var a=new Date().getMonth()+1;if(typeof o!="string")return e(!1,!1);if(o.replace(/\s/g,"")===""||o==="0")return e(!1,!0);if(!/^\d*$/.test(o))return e(!1,!1);var n=parseInt(o,10);if(isNaN(Number(o)))return e(!1,!1);var l=n>0&&n<13;return e(l,l,l&&n>=a)}t.expirationMonth=r},"../../node_modules/card-validator/dist/expiration-year.js":function(i,t){Object.defineProperty(t,"__esModule",{value:!0}),t.expirationYear=void 0;var e=19;function r(a,n,l){return{isValid:a,isPotentiallyValid:n,isCurrentYear:l||!1}}function o(a,n){n===void 0&&(n=e);var l;if(typeof a!="string")return r(!1,!1);if(a.replace(/\s/g,"")==="")return r(!1,!0);if(!/^\d*$/.test(a))return r(!1,!1);var d=a.length;if(d<2)return r(!1,!0);var m=new Date().getFullYear();if(d===3){var f=a.slice(0,2),u=String(m).slice(0,2);return r(!1,f===u)}if(d>4)return r(!1,!1);var b=parseInt(a,10),P=Number(String(m).substr(2,2)),A=!1;if(d===2){if(String(m).substr(0,2)===a)return r(!1,!0);l=P===b,A=b>=P&&b<=P+n}else d===4&&(l=m===b,A=b>=m&&b<=m+n);return r(A,A,l)}t.expirationYear=o},"../../node_modules/card-validator/dist/index.js":function(i,t,e){var r=this&&this.__createBinding||(Object.create?function(k,O,w,N){N===void 0&&(N=w);var $=Object.getOwnPropertyDescriptor(O,w);(!$||("get"in $?!O.__esModule:$.writable||$.configurable))&&($={enumerable:!0,get:function(){return O[w]}}),Object.defineProperty(k,N,$)}:function(k,O,w,N){N===void 0&&(N=w),k[N]=O[w]}),o=this&&this.__setModuleDefault||(Object.create?function(k,O){Object.defineProperty(k,"default",{enumerable:!0,value:O})}:function(k,O){k.default=O}),a=this&&this.__importStar||function(k){if(k&&k.__esModule)return k;var O={};if(k!=null)for(var w in k)w!=="default"&&Object.prototype.hasOwnProperty.call(k,w)&&r(O,k,w);return o(O,k),O},n=a(e("../../node_modules/credit-card-type/dist/index.js")),l=e("../../node_modules/card-validator/dist/cardholder-name.js"),d=e("../../node_modules/card-validator/dist/card-number.js"),m=e("../../node_modules/card-validator/dist/expiration-date.js"),f=e("../../node_modules/card-validator/dist/expiration-month.js"),u=e("../../node_modules/card-validator/dist/expiration-year.js"),b=e("../../node_modules/card-validator/dist/cvv.js"),P=e("../../node_modules/card-validator/dist/postal-code.js"),A={creditCardType:n,cardholderName:l.cardholderName,number:d.cardNumber,expirationDate:m.expirationDate,expirationMonth:f.expirationMonth,expirationYear:u.expirationYear,cvv:b.cvv,postalCode:P.postalCode};i.exports=A},"../../node_modules/card-validator/dist/lib/is-array.js":function(i,t){Object.defineProperty(t,"__esModule",{value:!0}),t.isArray=void 0,t.isArray=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"}},"../../node_modules/card-validator/dist/lib/parse-date.js":function(i,t,e){Object.defineProperty(t,"__esModule",{value:!0}),t.parseDate=void 0;var r=e("../../node_modules/card-validator/dist/expiration-year.js"),o=e("../../node_modules/card-validator/dist/lib/is-array.js");function a(l){var d=Number(l[0]),m;return d===0?2:d>1||d===1&&Number(l[1])>2?1:d===1?(m=l.substr(1),(0,r.expirationYear)(m).isPotentiallyValid?1:2):l.length===5?1:l.length>5?2:1}function n(l){var d;if(/^\d{4}-\d{1,2}$/.test(l)?d=l.split("-").reverse():/\//.test(l)?d=l.split(/\s*\/\s*/g):/\s/.test(l)&&(d=l.split(/ +/g)),(0,o.isArray)(d))return{month:d[0]||"",year:d.slice(1).join()};var m=a(l),f=l.substr(0,m);return{month:f,year:l.substr(f.length)}}t.parseDate=n},"../../node_modules/card-validator/dist/luhn-10.js":function(i){function t(e){for(var r=0,o=!1,a=e.length-1,n;a>=0;)n=parseInt(e.charAt(a),10),o&&(n*=2,n>9&&(n=n%10+1)),o=!o,r+=n,a--;return r%10===0}i.exports=t},"../../node_modules/card-validator/dist/postal-code.js":function(i,t){Object.defineProperty(t,"__esModule",{value:!0}),t.postalCode=void 0;var e=3,r=new RegExp(/^[a-z0-9]+$/i);function o(n,l){return{isValid:n,isPotentiallyValid:l}}function a(n,l){l===void 0&&(l={});var d=l.minLength||e;return typeof n!="string"?o(!1,!1):n.length<d||!r.test(n.trim().slice(0,d))?o(!1,!0):o(!0,!0)}t.postalCode=a},"../../node_modules/credit-card-type/dist/index.js":function(i,t,e){var r=this&&this.__assign||function(){return r=Object.assign||function(w){for(var N,$=1,Ue=arguments.length;$<Ue;$++){N=arguments[$];for(var Pt in N)Object.prototype.hasOwnProperty.call(N,Pt)&&(w[Pt]=N[Pt])}return w},r.apply(this,arguments)},o=e("../../node_modules/credit-card-type/dist/lib/card-types.js"),a=e("../../node_modules/credit-card-type/dist/lib/add-matching-cards-to-results.js"),n=e("../../node_modules/credit-card-type/dist/lib/is-valid-input-type.js"),l=e("../../node_modules/credit-card-type/dist/lib/find-best-match.js"),d=e("../../node_modules/credit-card-type/dist/lib/clone.js"),m={},f={VISA:"visa",MASTERCARD:"mastercard",AMERICAN_EXPRESS:"american-express",DINERS_CLUB:"diners-club",DISCOVER:"discover",JCB:"jcb",UNIONPAY:"unionpay",MAESTRO:"maestro",ELO:"elo",MIR:"mir",HIPER:"hiper",HIPERCARD:"hipercard"},u=[f.VISA,f.MASTERCARD,f.AMERICAN_EXPRESS,f.DINERS_CLUB,f.DISCOVER,f.JCB,f.UNIONPAY,f.MAESTRO,f.ELO,f.MIR,f.HIPER,f.HIPERCARD],b=(0,d.clone)(u);function P(w){return m[w]||o[w]}function A(){return b.map(function(w){return(0,d.clone)(P(w))})}function k(w,N){N===void 0&&(N=!1);var $=b.indexOf(w);if(!N&&$===-1)throw new Error('"'+w+'" is not a supported card type.');return $}function O(w){var N=[];if(!(0,n.isValidInputType)(w))return N;if(w.length===0)return A();b.forEach(function(Ue){var Pt=P(Ue);(0,a.addMatchingCardsToResults)(w,Pt,N)});var $=(0,l.findBestMatch)(N);return $?[$]:N}O.getTypeInfo=function(w){return(0,d.clone)(P(w))},O.removeCard=function(w){var N=k(w);b.splice(N,1)},O.addCard=function(w){var N=k(w.type,!0);m[w.type]=w,N===-1&&b.push(w.type)},O.updateCard=function(w,N){var $=m[w]||o[w];if(!$)throw new Error('"'.concat(w,"\" is not a recognized type. Use `addCard` instead.'"));if(N.type&&$.type!==N.type)throw new Error("Cannot overwrite type parameter.");var Ue=(0,d.clone)($);Ue=r(r({},Ue),N),m[Ue.type]=Ue},O.changeOrder=function(w,N){var $=k(w);b.splice($,1),b.splice(N,0,w)},O.resetModifications=function(){b=(0,d.clone)(u),m={}},O.types=f,i.exports=O},"../../node_modules/credit-card-type/dist/lib/add-matching-cards-to-results.js":function(i,t,e){Object.defineProperty(t,"__esModule",{value:!0}),t.addMatchingCardsToResults=void 0;var r=e("../../node_modules/credit-card-type/dist/lib/clone.js"),o=e("../../node_modules/credit-card-type/dist/lib/matches.js");function a(n,l,d){var m,f;for(m=0;m<l.patterns.length;m++){var u=l.patterns[m];if((0,o.matches)(n,u)){var b=(0,r.clone)(l);f=Array.isArray(u)?String(u[0]).length:String(u).length,n.length>=f&&(b.matchStrength=f),d.push(b);break}}}t.addMatchingCardsToResults=a},"../../node_modules/credit-card-type/dist/lib/card-types.js":function(i){var t={visa:{niceType:"Visa",type:"visa",patterns:[4],gaps:[4,8,12],lengths:[16,18,19],code:{name:"CVV",size:3}},mastercard:{niceType:"Mastercard",type:"mastercard",patterns:[[51,55],[2221,2229],[223,229],[23,26],[270,271],2720],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},"american-express":{niceType:"American Express",type:"american-express",patterns:[34,37],gaps:[4,10],lengths:[15],code:{name:"CID",size:4}},"diners-club":{niceType:"Diners Club",type:"diners-club",patterns:[[300,305],36,38,39],gaps:[4,10],lengths:[14,16,19],code:{name:"CVV",size:3}},discover:{niceType:"Discover",type:"discover",patterns:[6011,[644,649],65],gaps:[4,8,12],lengths:[16,19],code:{name:"CID",size:3}},jcb:{niceType:"JCB",type:"jcb",patterns:[2131,1800,[3528,3589]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVV",size:3}},unionpay:{niceType:"UnionPay",type:"unionpay",patterns:[620,[62100,62182],[62184,62187],[62185,62197],[62200,62205],[622010,622999],622018,[62207,62209],[623,626],6270,6272,6276,[627700,627779],[627781,627799],[6282,6289],6291,6292,810,[8110,8131],[8132,8151],[8152,8163],[8164,8171]],gaps:[4,8,12],lengths:[14,15,16,17,18,19],code:{name:"CVN",size:3}},maestro:{niceType:"Maestro",type:"maestro",patterns:[493698,[5e5,504174],[504176,506698],[506779,508999],[56,59],63,67,6],gaps:[4,8,12],lengths:[12,13,14,15,16,17,18,19],code:{name:"CVC",size:3}},elo:{niceType:"Elo",type:"elo",patterns:[401178,401179,438935,457631,457632,431274,451416,457393,504175,[506699,506778],[509e3,509999],627780,636297,636368,[650031,650033],[650035,650051],[650405,650439],[650485,650538],[650541,650598],[650700,650718],[650720,650727],[650901,650978],[651652,651679],[655e3,655019],[655021,655058]],gaps:[4,8,12],lengths:[16],code:{name:"CVE",size:3}},mir:{niceType:"Mir",type:"mir",patterns:[[2200,2204]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVP2",size:3}},hiper:{niceType:"Hiper",type:"hiper",patterns:[637095,63737423,63743358,637568,637599,637609,637612],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},hipercard:{niceType:"Hipercard",type:"hipercard",patterns:[606282],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}}};i.exports=t},"../../node_modules/credit-card-type/dist/lib/clone.js":function(i,t){Object.defineProperty(t,"__esModule",{value:!0}),t.clone=void 0;function e(r){return r?JSON.parse(JSON.stringify(r)):null}t.clone=e},"../../node_modules/credit-card-type/dist/lib/find-best-match.js":function(i,t){Object.defineProperty(t,"__esModule",{value:!0}),t.findBestMatch=void 0;function e(o){var a=o.filter(function(n){return n.matchStrength}).length;return a>0&&a===o.length}function r(o){return e(o)?o.reduce(function(a,n){return!a||Number(a.matchStrength)<Number(n.matchStrength)?n:a}):null}t.findBestMatch=r},"../../node_modules/credit-card-type/dist/lib/is-valid-input-type.js":function(i,t){Object.defineProperty(t,"__esModule",{value:!0}),t.isValidInputType=void 0;function e(r){return typeof r=="string"||r instanceof String}t.isValidInputType=e},"../../node_modules/credit-card-type/dist/lib/matches.js":function(i,t){Object.defineProperty(t,"__esModule",{value:!0}),t.matches=void 0;function e(a,n,l){var d=String(n).length,m=a.substr(0,d),f=parseInt(m,10);return n=parseInt(String(n).substr(0,m.length),10),l=parseInt(String(l).substr(0,m.length),10),f>=n&&f<=l}function r(a,n){return n=String(n),n.substring(0,a.length)===a.substring(0,n.length)}function o(a,n){return Array.isArray(n)?e(a,n[0],n[1]):r(a,n)}t.matches=o}},To={};function ge(i){var t=To[i];if(t!==void 0)return t.exports;var e=To[i]={exports:{}};return ns[i].call(e.exports,e,e.exports,ge),e.exports}ge.n=i=>{var t=i&&i.__esModule?()=>i.default:()=>i;return ge.d(t,{a:t}),t};ge.d=(i,t)=>{for(var e in t)ge.o(t,e)&&!ge.o(i,e)&&Object.defineProperty(i,e,{enumerable:!0,get:t[e]})};ge.o=(i,t)=>Object.prototype.hasOwnProperty.call(i,t);var ko=ge("../../node_modules/credit-card-type/dist/index.js");function Mi(i){return i.replace(/[-_]/g," ").replace(/[^\s\w]/g,"").replace(/([A-Z][a-z]+|[0-9]+)/g," $1").replace(/([A-Z]{2,})/g," $1").trim().split(/\s+/g)}function ss(i){return Mi(i).filter(Boolean).map(t=>t[0].toUpperCase()+t.slice(1).toLowerCase()).join(" ")}function Io(i){return Mi(i).join("-").toLowerCase()}function Lo(i){return Mi(i).join("_").toUpperCase()}var Bo=[["AMEX","american-express"],["CARTES_BANCAIRES"],["DANKORT"],["DINERS_CLUB","diners-club"],["DISCOVER","discover"],["ENROUTE"],["ELO","elo"],["HIPER","hiper","hiper-pay"],["HIPERCARD","hipercard"],["INTERAC"],["JCB","jcb"],["MAESTRO","maestro"],["MASTERCARD","mastercard"],["MIR","mir","mir-pay"],["OTHER",void 0,"payment-card"],["UNIONPAY","unionpay"],["VISA","visa"]],No=new Map(Bo.map(i=>[i[0],i])),ls=new Map(Bo.filter(i=>i[1]).map(i=>[i[1],i]));function Fo(i){let{niceType:t,type:e}=(0,ko.getTypeInfo)(Io(i))||(0,ko.getTypeInfo)(No.get(Lo(i))?.[1]||"")||{},[r,o,a]=ls.get(e)||No.get(Lo(i))||[];return{asset:a||Io(o||i),backend:r,display:t||ss(i),library:o}}var gt={WORLDPAY_IDEAL:"WORLDPAY_IDEAL",STRIPE_ACH:"STRIPE_ACH",STRIPE_IDEAL:"STRIPE_IDEAL",ADYEN_KLARNA:"ADYEN_KLARNA",ADYEN_BANCONTACT_CARD:"ADYEN_BANCONTACT_CARD",PAY_NL_KAARTDIRECT:"PAY_NL_KAARTDIRECT",ADYEN_EPS:"ADYEN_EPS",ADYEN_BANCONTACT_PAYCONIQ:"ADYEN_BANCONTACT_PAYCONIQ",OMISE_PROMPTPAY:"OMISE_PROMPTPAY",OMISE_TRUEMONEY:"OMISE_TRUEMONEY",ADYEN_MULTIBANCO:"ADYEN_MULTIBANCO",PACYPAY_WECHAT:"PACYPAY_WECHAT",PACYPAY_ALIPAY:"PACYPAY_ALIPAY",ADYEN_MBWAY:"ADYEN_MBWAY",XENDIT_DANA:"XENDIT_DANA",XENDIT_SHOPEEPAY:"XENDIT_SHOPEEPAY",ADYEN_PAYSHOP:"ADYEN_PAYSHOP",ADYEN_PAYTRAIL:"ADYEN_PAYTRAIL",CLEARPAY:"CLEARPAY",RAPYD_FAST:"RAPYD_FAST",RAPYD_PROMPTPAY:"RAPYD_PROMPTPAY",RAPYD_GCASH:"RAPYD_GCASH",RAPYD_POLI:"RAPYD_POLI",RAPYD_GRABPAY:"RAPYD_GRABPAY",PRIMER_PAYPAL:"PRIMER_PAYPAL",TWOC2P:"TWOC2P",NETS:"NETS",STRIPE_GIROPAY:"STRIPE_GIROPAY",MOLLIE_GIROPAY:"MOLLIE_GIROPAY",MOLLIE_EPS:"MOLLIE_EPS",PAY_NL_EPS:"PAY_NL_EPS",PAY_NL_P24:"PAY_NL_P24",MOLLIE_P24:"MOLLIE_P24",MOLLIE_SOFORT:"MOLLIE_SOFORT",COINBASE:"COINBASE",OPENNODE:"OPENNODE",MOLLIE_GIFT_CARD:"MOLLIE_GIFTCARD",XFERS_PAYNOW:"XFERS_PAYNOW",PAYMENT_CARD:"PAYMENT_CARD",APPLE_PAY:"APPLE_PAY",GOOGLE_PAY:"GOOGLE_PAY",PAYPAL:"PAYPAL",GO_CARDLESS:"GOCARDLESS",KLARNA:"KLARNA",PAY_NL_IDEAL:"PAY_NL_IDEAL",PAY_NL_SOFORT_BANKING:"PAY_NL_SOFORT_BANKING",PAY_NL_BANCONTACT:"PAY_NL_BANCONTACT",PAY_NL_PAYPAL:"PAY_NL_PAYPAL",PAY_NL_CREDIT_TRANSFER:"PAY_NL_CREDIT_TRANSFER",PAY_NL_DIRECT_DEBIT:"PAY_NL_DIRECT_DEBIT",PAY_NL_GIROPAY:"PAY_NL_GIROPAY",PAY_NL_PAYCONIQ:"PAY_NL_PAYCONIQ",PAY_NL_RIVERTY:"PAY_NL_RIVERTY",HOOLAH:"HOOLAH",ADYEN_BLIK:"ADYEN_BLIK",ADYEN_MOBILEPAY:"ADYEN_MOBILEPAY",ADYEN_VIPPS:"ADYEN_VIPPS",ADYEN_GIROPAY:"ADYEN_GIROPAY",ADYEN_SOFORT:"ADYEN_SOFORT",ADYEN_IDEAL:"ADYEN_IDEAL",ADYEN_TRUSTLY:"ADYEN_TRUSTLY",ADYEN_ALIPAY:"ADYEN_ALIPAY",ADYEN_TWINT:"ADYEN_TWINT",ADYEN_BANK_TRANSFER:"ADYEN_BANK_TRANSFER",MOLLIE_BANCONTACT:"MOLLIE_BANCONTACT",MOLLIE_IDEAL:"MOLLIE_IDEAL",BUCKAROO_GIROPAY:"BUCKAROO_GIROPAY",BUCKAROO_EPS:"BUCKAROO_EPS",BUCKAROO_SOFORT:"BUCKAROO_SOFORT",BUCKAROO_BANCONTACT:"BUCKAROO_BANCONTACT",BUCKAROO_IDEAL:"BUCKAROO_IDEAL",ATOME:"ATOME",DLOCAL_PIX:"DLOCAL_PIX",ALMA:"ALMA"};function ds(i,t){return{"Content-Type":"application/json","primer-client-token":i,"primer-sdk-client":"WEB","primer-sdk-version":"0.0.0-local","primer-sdk-checkout-session-id":t,"x-api-version":"2.4"}}var Ft=()=>jo.randomUUID?.()||cs(),cs=()=>"10000000-1000-4000-8000-100000000000".replace(/[018]/g,i=>(i^ps()>>i/4).toString(16)),ps=()=>(jo.getRandomValues?.(new Uint8Array(1))[0]??16*Math.random())&15,jo=typeof crypto<"u"?crypto:{};function ms(i,t){return async(e,r)=>new Promise(o=>{let a=Ft(),n={id:t,type:"http-request",url:e,init:r,requestId:a};i.contentWindow?.postMessage(n,"*");let l=d=>{d.data.type==="http-response"&&d.data.requestId===a&&(window.removeEventListener("message",l),o(d.data))};window.addEventListener("message",l)})}var Ct=class{constructor(t,e="",r={}){R(this,"fetch");R(this,"baseUrl");R(this,"defaultHeaders");this.fetch=t,this.baseUrl=e,this.defaultHeaders=Object.freeze({...r})}setDefaultHeader(t,e){this.defaultHeaders={...this.defaultHeaders,[t]:e}}async get(t,e){return this.fetch(t,{...e,method:"GET",headers:{...this.defaultHeaders,...e?.headers}})}async post(t,e,r){return this.fetch(t,{...r,method:"POST",body:JSON.stringify(e),headers:{...this.defaultHeaders,...r?.headers}})}async delete(t,e){return this.fetch(t,{...e,method:"DELETE",headers:{...this.defaultHeaders,...e?.headers}})}},vi=class extends Ct{async getConfiguration(){return this.get(this.baseUrl)}},bi=class extends Ct{async getPaymentInstruments(){return this.get(`${this.baseUrl}/payment-instruments`)}async postPaymentInstruments(t){return this.post(`${this.baseUrl}/payment-instruments`,t==="pci-card-form-data"?t:{paymentInstrument:t})}async postCreatePayment(t){return this.post(`${this.baseUrl}/payments`,{paymentMethodToken:t})}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)}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)}},Ko="3.7.7",us=Ko,xt=typeof Buffer=="function",Oo=typeof TextDecoder=="function"?new TextDecoder:void 0,Ro=typeof TextEncoder=="function"?new TextEncoder:void 0,hs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Bt=Array.prototype.slice.call(hs),_r=(i=>{let t={};return i.forEach((e,r)=>t[e]=r),t})(Bt),fs=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,B=String.fromCharCode.bind(String),Do=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):i=>new Uint8Array(Array.prototype.slice.call(i,0)),Go=i=>i.replace(/=/g,"").replace(/[+\/]/g,t=>t=="+"?"-":"_"),qo=i=>i.replace(/[^A-Za-z0-9\+\/]/g,""),Wo=i=>{let t,e,r,o,a="",n=i.length%3;for(let l=0;l<i.length;){if((e=i.charCodeAt(l++))>255||(r=i.charCodeAt(l++))>255||(o=i.charCodeAt(l++))>255)throw new TypeError("invalid character found");t=e<<16|r<<8|o,a+=Bt[t>>18&63]+Bt[t>>12&63]+Bt[t>>6&63]+Bt[63&t]}return n?a.slice(0,n-3)+"===".substring(n):a},Ti=typeof btoa=="function"?i=>btoa(i):xt?i=>Buffer.from(i,"binary").toString("base64"):Wo,Ci=xt?i=>Buffer.from(i).toString("base64"):i=>{let e=[];for(let r=0,o=i.length;r<o;r+=4096)e.push(B.apply(null,i.subarray(r,r+4096)));return Ti(e.join(""))},Mr=(i,t=!1)=>t?Go(Ci(i)):Ci(i),ys=i=>{if(i.length<2){var t=i.charCodeAt(0);return t<128?i:t<2048?B(192|t>>>6)+B(128|63&t):B(224|t>>>12&15)+B(128|t>>>6&63)+B(128|63&t)}var t=65536+(i.charCodeAt(0)-55296)*1024+(i.charCodeAt(1)-56320);return B(240|t>>>18&7)+B(128|t>>>12&63)+B(128|t>>>6&63)+B(128|63&t)},gs=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,Jo=i=>i.replace(gs,ys),$o=xt?i=>Buffer.from(i,"utf8").toString("base64"):Ro?i=>Ci(Ro.encode(i)):i=>Ti(Jo(i)),vt=(i,t=!1)=>t?Go($o(i)):$o(i),Vo=i=>vt(i,!0),vs=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,bs=i=>{switch(i.length){case 4:var t=(7&i.charCodeAt(0))<<18|(63&i.charCodeAt(1))<<12|(63&i.charCodeAt(2))<<6|63&i.charCodeAt(3),e=t-65536;return B((e>>>10)+55296)+B((1023&e)+56320);case 3:return B((15&i.charCodeAt(0))<<12|(63&i.charCodeAt(1))<<6|63&i.charCodeAt(2));default:return B((31&i.charCodeAt(0))<<6|63&i.charCodeAt(1))}},Zo=i=>i.replace(vs,bs),Xo=i=>{if(i=i.replace(/\s+/g,""),!fs.test(i))throw new TypeError("malformed base64.");i+="==".slice(2-(3&i.length));let t,e="",r,o;for(let a=0;a<i.length;)t=_r[i.charAt(a++)]<<18|_r[i.charAt(a++)]<<12|(r=_r[i.charAt(a++)])<<6|(o=_r[i.charAt(a++)]),e+=r===64?B(t>>16&255):o===64?B(t>>16&255,t>>8&255):B(t>>16&255,t>>8&255,255&t);return e},ki=typeof atob=="function"?i=>atob(qo(i)):xt?i=>Buffer.from(i,"base64").toString("binary"):Xo,Qo=xt?i=>Do(Buffer.from(i,"base64")):i=>Do(ki(i).split("").map(t=>t.charCodeAt(0))),ea=i=>Qo(ta(i)),Cs=xt?i=>Buffer.from(i,"base64").toString("utf8"):Oo?i=>Oo.decode(Qo(i)):i=>Zo(ki(i)),ta=i=>qo(i.replace(/[-_]/g,t=>t=="-"?"+":"/")),xi=i=>Cs(ta(i)),xs=i=>{if(typeof i!="string")return!1;let t=i.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(t)||!/[^\s0-9a-zA-Z\-_]/.test(t)},ra=i=>({value:i,enumerable:!1,writable:!0,configurable:!0}),ia=function(){let i=(t,e)=>Object.defineProperty(String.prototype,t,ra(e));i("fromBase64",function(){return xi(this)}),i("toBase64",function(t){return vt(this,t)}),i("toBase64URI",function(){return vt(this,!0)}),i("toBase64URL",function(){return vt(this,!0)}),i("toUint8Array",function(){return ea(this)})},oa=function(){let i=(t,e)=>Object.defineProperty(Uint8Array.prototype,t,ra(e));i("toBase64",function(t){return Mr(this,t)}),i("toBase64URI",function(){return Mr(this,!0)}),i("toBase64URL",function(){return Mr(this,!0)})},Es=()=>{ia(),oa()},aa={version:Ko,VERSION:us,atob:ki,atobPolyfill:Xo,btoa:Ti,btoaPolyfill:Wo,fromBase64:xi,toBase64:vt,encode:vt,encodeURI:Vo,encodeURL:Vo,utob:Jo,btou:Zo,decode:xi,isValid:xs,fromUint8Array:Mr,toUint8Array:ea,extendString:ia,extendUint8Array:oa,extendBuiltins:Es},Tr={encode:As,decode:aa.decode};function As(i,t={}){let{urlSafe:e=!1}=t;return aa.encode(i,e)}function Ss(i,t){return!(i.intent!==`${t}_REDIRECTION`||!("statusUrl"in i)||!("redirectUrl"in i)||!i.redirectUrl||!i.statusUrl)}function kr(i){let t=ws(i),e=1e3*t.exp;if(Date.now()>e)throw new Error(`${_s}. Expiration date: ${new Date(e).toISOString()}`);return t}var na="The provided `clientToken`",_s=`${na} has expired`,Ps=`${na} is malformed`;function ws(i){try{let[t,e]=i.split("."),r=e||t;return JSON.parse(Tr.decode(r))}catch{throw new Error(Ps)}}var sa="https://sdk.primer.io/web/hosted-pages/v0-latest",Ms=`${sa}/api-controller.html`,Ts=`${sa}/hosted-input.html`,ks="https://goat-assets.production.core.primer.io";function la(i,t){return btoa(JSON.stringify({checkoutSessionId:i,name:t}))}async function Is(i){return new Promise((t,e)=>{let r=la(i,"api"),o=`${Ms}#${r}`,a=document.querySelector(`iframe[src="${o}"]`)??document.createElement("iframe");a.parentElement?t(a):(a.style.display="none",a.onload=()=>t(a),a.onerror=n=>{e(new Error(`Failed to initialize Primer SDK: ${n}`))},a.src=o,document.body.appendChild(a))})}var Ei=class extends Ct{async postClientSessionActions(t){return t.length===0?Promise.resolve({data:void 0,headers:{},status:200,id:"",requestId:"",type:"http-response"}):this.post(`${this.baseUrl}/client-session/actions`,{actions:t})}async selectPaymentMethod(t,e={}){return this.postClientSessionActions([{type:"SELECT_PAYMENT_METHOD",params:{...e,paymentMethodType:t}}])}async unselectPaymentMethod(){return this.postClientSessionActions([{type:"UNSELECT_PAYMENT_METHOD"}])}async selectCardNetwork(t){return this.selectPaymentMethod(gt.PAYMENT_CARD,{binData:this.buildCardBinData(t)})}async setBillingAddress(t){let e=this.removeEmptyStringFromObject(t);return this.postClientSessionActions([{type:"SET_BILLING_ADDRESS",params:{billingAddress:e}}])}async setShippingAddress(t,e,r){let o=[];return t&&Object.keys(t).some(n=>!!t[n])&&o.push({type:"SET_SHIPPING_ADDRESS",params:{shippingAddress:t}}),e&&o.push({type:"SET_MOBILE_NUMBER",params:{mobileNumber:e}}),r&&o.push({type:"SET_EMAIL_ADDRESS",params:{emailAddress:r}}),this.postClientSessionActions(o)}async selectShippingMethod(t){return this.postClientSessionActions([{type:"SELECT_SHIPPING_METHOD",params:{shippingMethodId:t}}])}async setCustomerDetails({emailAddress:t,firstName:e,lastName:r}){let o=[];return t&&o.push({type:"SET_EMAIL_ADDRESS",params:{emailAddress:t}}),e&&o.push({type:"SET_CUSTOMER_FIRST_NAME",params:{firstName:e}}),r&&o.push({type:"SET_CUSTOMER_LAST_NAME",params:{lastName:r}}),this.postClientSessionActions(o)}buildCardBinData(t){let e=this.getCardNetworkName(t);return{network:e,issuer_name:null,product_code:e,product_name:e,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"}}getCardNetworkName(t){return{visa:"VISA",mastercard:"MASTERCARD",amex:"AMERICAN_EXPRESS",discover:"DISCOVER"}[t.toLowerCase()]||t}removeEmptyStringFromObject(t){let e={...t};for(let r in e)e[r]===""?delete e[r]:typeof e[r]=="object"&&e[r]!==null&&!Array.isArray(e[r])&&(e[r]=this.removeEmptyStringFromObject(e[r]));return e}},Ai=class extends Ct{async createPaypalOrder(t){return this.post(`${this.baseUrl}/paypal/orders/create`,t)}async createApplePaySession(t){return this.post(`${this.baseUrl}/apple-pay/sessions`,t)}},Si=class{constructor(t){R(this,"listeners",new Set);R(this,"state");R(this,"initialState");this.initialState=t,this.state=Object.freeze(structuredClone(t))}reset(){this.setState(structuredClone(this.initialState))}getState(){return this.state}setState(t){this.state=Object.freeze({...this.state,...t}),this.notify()}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}notify(){this.listeners.forEach(t=>t(this.state))}},bt=class extends Si{constructor(e,r){super(e);R(this,"options");R(this,"channel");R(this,"key");this.key=r.id+r.name,this.options=r,this.channel=new BroadcastChannel(this.key),this.channel.addEventListener("message",this.onMessage.bind(this)),this.options.crossOriginTarget&&window.addEventListener("message",this.onMessage.bind(this)),this.requestInitialState()}requestInitialState(){this.options.main||this.postMessage({key:this.key,type:"request-initial-state"})}sendInitialState(){this.options.main&&this.postMessage({type:"post-state",key:this.key,state:super.getState()})}setState(e){this.internalSetState(e)}onMessage(e){if(e.data.key===this.key){if(e.data.type==="request-initial-state")return void this.sendInitialState();this.internalSetState(e.data.state,e.data.type)}}internalSetState(e,r){this.options.main?this.setMainState(e):this.setNonMainState(e,r)}setMainState(e){super.setState(e),this.postMessage({type:"post-state",key:this.key,state:super.getState()})}setNonMainState(e,r){if(r!=="patch-state"){if(r==="post-state")return void super.setState(e);this.postMessage({type:"patch-state",key:this.key,state:e})}}postMessage(e){this.channel.postMessage(e),this.options.crossOriginTarget?.postMessage(e,"*")}};function Ls(i,t,e=!1){return new bt({accessToken:"",binDataUrl:"",orderedAllowedCardNetworks:[]},{main:e,id:i,name:"checkout-config-store",crossOriginTarget:t})}var Ns=ge("../../node_modules/card-validator/dist/index.js"),Os=ge.n(Ns);function Rs(i){let t=Os().number(i);return{isValid:t.isValid||!1,card:{type:t.card?.type||null,code:t.card?.code||{name:"CVV",size:4},lengths:t.card?.lengths||[16],gaps:t.card?.gaps||[4,8,12]}}}var Pr={placeholder:"",ariaLabel:"",style:{}};function Ds(i,t,e=!1){return{pciStore:new bt({cardNumber:"",cardSecurityCode:"",cardExpiryDate:"",cardHolderName:""},{main:e,id:i,name:"card-form-pci"}),publicStore:new bt({cardNumber:{valid:!1,dirty:!1,touched:!1,focused:!1,disabled:!1,error:""},cardSecurityCode:{valid:!1,dirty:!1,touched:!1,focused:!1,disabled:!1,error:""},cardExpiryDate:{valid:!1,dirty:!1,touched:!1,focused:!1,disabled:!1,error:""},cardHolderName:{valid:!1,dirty:!1,touched:!1,focused:!1,disabled:!1,error:""},type:Rs(""),networks:[],networksSource:"LOCAL",preferredNetwork:void 0},{main:e,id:i,name:"card-form-public",crossOriginTarget:t}),optionsStore:new bt({cardNumber:structuredClone(Pr),cardSecurityCode:structuredClone(Pr),cardExpiryDate:structuredClone(Pr),cardHolderName:structuredClone(Pr)},{main:e,id:i,name:"card-form-options",crossOriginTarget:t})}}async function $s(i){let t=Ft(),e=kr(i),r=await Is(t),o=ms(r,t),a=ds(e.accessToken,t),n=Ls(t,r.contentWindow);n.setState({accessToken:e.accessToken});let l=new vi(o,e.configurationUrl,a),{data:d,error:m}=await l.getConfiguration();if(m||!d)throw new Error(`Failed to fetch configuration: ${m}`);n.setState({binDataUrl:d.binDataUrl,orderedAllowedCardNetworks:d.clientSession.paymentMethod.orderedAllowedCardNetworks});let f=new bi(o,d.pciUrl,a),u=new Ai(o,d.coreUrl,a),b=new Ei(o,d.pciUrl,a);return{apiControllerIframe:r,configuration:d,checkoutSessionId:t,configurationApi:l,pciApi:f,coreApi:u,clientSessionApi:b,updateClientToken:P=>{try{let A=kr(P);l.setDefaultHeader("primer-client-token",A.accessToken),f.setDefaultHeader("primer-client-token",A.accessToken),u.setDefaultHeader("primer-client-token",A.accessToken),b.setDefaultHeader("primer-client-token",A.accessToken),n.setState({accessToken:A.accessToken})}catch{}}}}var _i=class{constructor(t){R(this,"context");this.context=t}};function da(){return{javaEnabled:typeof window.navigator.javaEnabled=="function"?window.navigator.javaEnabled():!1,language:window.navigator.language,colorDepth:window.screen.colorDepth,screenHeight:window.screen.height,screenWidth:window.screen.width,timezoneOffset:new Date().getTimezoneOffset(),userAgent:window.navigator.userAgent}}function ca(i){return i?new Promise(t=>{setTimeout(t,i)}):Promise.resolve()}var Pi=class extends _i{async handleRequiredAction(t){let e=t.requiredAction?.clientToken;if(!e)throw new Error("No client token provided");let r=kr(e);if(!("intent"in r)||r.intent!=="3DS_AUTHENTICATION")throw new Error("Invalid client token");let{error:o,data:a}=await this.context.pciApi.post3dsAuth(r.tokenId,{device:da()});if(o||!a||!a.authentication)throw o??new Error("Unable to authenticate");let n=a;a.authentication.responseCode==="METHOD"?n=await this.handleMethod(r.tokenId,a.authentication):a.authentication.responseCode==="CHALLENGE"&&(n=await this.handleChallenge(r.tokenId,a.authentication));let l=await this.context.pciApi.postResumePayment(t.id,n.resumeToken);if(l.error||!l.data)throw l.error??new Error("Unable to resume payment");return l.data}async handleMethod(t,e){let r="primer-3ds-method-box",o="primer-3ds-method-iframe",a="primer-3ds-method-form",n="threeDSMethodData",l=document.createElement("div");l.id=r,l.style.position="absolute",l.style.width="2px",l.style.height="2px",l.style.left="-10000px";let d=document.createElement("iframe");d.style.display="none",d.id=o,d.name=o,l.appendChild(d);let m=document.createElement("form"),f=document.createElement("input");f.type="hidden",f.id=n,f.name=n,f.value=Tr.encode(JSON.stringify({threeDSServerTransID:e.transactionId,threeDSMethodNotificationURL:e.notificationUrl}),{urlSafe:!0}).replace(/=+$/g,""),m.appendChild(f),m.id=a,m.name=a,m.action=e.acsMethodUrl,m.target=o,m.method="post",l.appendChild(m),document.body.appendChild(l),m.submit();let{data:u,error:b}=await this.pollStatus(e.statusUrl,"METHOD",1e3).promise;return l.remove(),b||!u?this.continueAuth(t):u}pollStatus(t,e="METHOD",r=1e3,o=66e4){let a=!0;return{promise:new Promise(async n=>{let l=setTimeout(()=>{a=!1,n({error:new Error("Operation timed out"),data:null})},o);try{for(;a;){let d=await this.context.pciApi.get3dsResumeStatus(t);if(d.error){clearTimeout(l),n(d);return}if(await ca(r),d.data&&d.data.authentication.responseCode!==e){clearTimeout(l),n(d);return}}}catch(d){clearTimeout(l),n({error:d,data:null})}}),abort:()=>{a=!1}}}async continueAuth(t){let{data:e,error:r}=await this.context.pciApi.post3dsContinue(t);return r||!e?{resumeToken:Ft(),authentication:{responseCode:"SKIPPED",skippedReasonCode:"NEGOTIATION_ERROR",skippedReasonText:"Failed to negotiate with 3DS server"}}:e}async handleChallenge(t,e){let r=`3ds-challenge-iframe-${Ft()}`,o=document.createElement("div");o.style.position="fixed",o.style.top="0",o.style.left="0",o.style.width="100%",o.style.height="100%",o.style.backgroundColor="rgba(0, 0, 0, 0.5)";let a=document.createElement("div");a.style.height="min(calc(100vh - 16px), 600px)",a.style.width="min(calc(100vw - 16px), 500px)",a.style.display="grid",a.style.placeContent="center",a.style.backgroundColor="#ffffff",a.style.borderRadius="3px",a.style.position="relative",a.style.boxShadow="1px 1px 5px 3px rgba(0, 0, 0, 0.05)",a.style.overflow="hidden",o.appendChild(a);let n=document.createElement("iframe");n.id=r,n.name=r,n.width="100%",n.height="100%",n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.setAttribute("frameBorder","0"),n.setAttribute("border","0"),n.style.position="absolute",n.style.top="0",n.style.left="0";let l=document.createElement("form");if(l.style.width="1px",l.style.height="1px",l.style.position="absolute",l.style.left="-10000px",l.action=e.acsChallengeUrl,l.target=r,l.method="post",/^1/.test(e.protocolVersion)){let u=document.createElement("input"),b=document.createElement("input");u.type="hidden",u.name="PaReq",u.id="PaReq",u.value=e.acsChallengeData??"",b.type="hidden",b.name="TermUrl",b.id="TermUrl",b.value=e.notificationUrl??"",l.appendChild(u),l.appendChild(b)}else{let u=document.createElement("input"),b=document.createElement("input");u.type="hidden",u.name="creq",u.id="creq",u.value=Tr.encode(JSON.stringify({threeDSServerTransID:e.transactionId,acsTransID:e.acsTransactionId,messageVersion:e.protocolVersion,messageType:"CReq",challengeWindowSize:"05"}),{urlSafe:!0}),b.type="hidden",b.name="threeDSSessionData",b.id="threeDSSessionData",l.appendChild(u),l.appendChild(b)}a.appendChild(l),a.appendChild(n),document.body.appendChild(o),l.submit();let f=await this.pollStatus(e.statusUrl,"CHALLENGE",2500,66e4).promise;return o.remove(),f.error||!f.data?this.continueAuth(t):f.data}},ct=class{constructor(t,e){R(this,"config");R(this,"context");this.config=Object.freeze(t),this.context=e}async setup(){return!0}async start(){}async render(t){}async handleRequiredAction(t){return t.requiredAction?.name==="3DS_AUTHENTICATION"?new Pi(this.context).handleRequiredAction(t):t}async createPayment(t){let{error:e,data:r}=await this.context.pciApi.postCreatePayment(t);if(e||!r)throw e??new Error("Unable to create payment");return r.requiredAction?.clientToken&&this.context.updateClientToken(r.requiredAction.clientToken),r}async resumePayment(t,e){let{error:r,data:o}=await this.context.pciApi.postResumePayment(t,e);if(r||!o)throw r??new Error("Unable to resume payment");return o}};function Vs(i){return{cardNumber:wr(i,"cardNumber"),cardSecurityCode:wr(i,"cardSecurityCode"),cardExpiryDate:wr(i,"cardExpiryDate"),cardHolderName:wr(i,"cardHolderName")}}function wr(i,t){let e=document.createElement("iframe"),r=la(i,t);return e.src=`${Ts}#${r}`,e.setAttribute("tabindex","0"),e.setAttribute("frameBorder","0"),e.style.border="none",e.style.boxSizing="border-box",e.style.height="20px",e.style.width="100%",e.style.colorScheme="auto",e}var Ir=class extends ct{constructor(e,r){super(e,r);R(this,"iframes");R(this,"store");this.store=Ds(r.checkoutSessionId,r.apiControllerIframe.contentWindow),this.iframes=Vs(r.checkoutSessionId)}async tokenize(){let{error:e,data:r}=await this.context.pciApi.postPaymentInstruments("pci-card-form-data");if(e||!r)throw e??new Error("Unable to tokenize payment method");return r}},Ys=100;function Us({height:i,name:t,url:e="",width:r}){let o=new Set,a=window.open(e,t,zs({height:i,width:r}));if(!a)return;function n(){a?.close(),l()}function l(){o.forEach(d=>d()),o.clear(),window.removeEventListener("beforeunload",n)}return window.addEventListener("beforeunload",n),Hs(a).then(l),{close:n,focus(){a.focus()},get isOpen(){return a?.closed===!1},onClose(d){return o.add(d),()=>{o.delete(d)}},setContent(d){a.document.write(d)},setUrl(d){a.location.replace(d)}}}var Hs=i=>new Promise(t=>{let e=setInterval(()=>{i.closed&&(clearInterval(e),t())},Ys)});function zs(i){let t=Bs({parent:{left:window.screenLeft,top:window.screenTop,height:window.outerHeight,width:window.outerWidth},popup:i});return Fs(t)}var Bs=({parent:i,popup:t})=>({left:i.left+(i.width-t.width)/2,top:i.top+(i.height-t.height)/2,height:t.height,width:t.width}),Fs=i=>Object.entries(i).map(t=>t.join("=")).join(","),wi=class extends ct{constructor(){super(...arguments);R(this,"popup")}async start(){this.openPopup()}async tokenize(){let{error:e,data:r}=await this.context.pciApi.postPaymentInstruments({type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:"en",platform:"WEB",browserInfo:da()}});if(e||!r)throw e??new Error("Unable to tokenize payment method");return r}async handleRequiredAction(e){let r=e.requiredAction?.clientToken;if(!r)throw new Error("No client token provided");let o=kr(r);if(!Ss(o,this.config.type))throw new Error("Invalid client token");this.popup?.setUrl(o.redirectUrl);let a=new Promise(f=>{this.popup?.onClose(()=>f({id:""}))}),{promise:n,abort:l}=this.pollStatus(o.statusUrl),d=await Promise.race([a,n]);if(l(),this.popup?.close(),"error"in d)throw d.error;let m=d.id;if(!m){let f=await this.context.pciApi.getResumeStatus(o.statusUrl);if(f.error||!f.data?.id)throw f.error??new Error("Unable to get resume token");m=f.data.id}return await this.resumePayment(e.id,m)}pollStatus(e){let r=!0;return{promise:new Promise(async o=>{for(;r;){let{data:a,error:n}=await this.context.pciApi.getResumeStatus(e);if(n)return void o({error:n});if(await ca(1e3),a?.status==="COMPLETE")return void o({id:a.id})}}),abort:()=>{r=!1}}}openPopup(){let{name:e,displayMetadata:{button:r,overlay:o,popup:a}}=this.config;this.popup=Us({name:e,height:a?.height??500,width:a?.width??1e3});let n=o?.logo.colored||r?.iconUrl.colored||o?.logo.light||r?.iconUrl.light||o?.logo.dark||r?.iconUrl.dark;this.popup?.setContent(js({name:e,logoSrc:n,logoAlt:e,message:`Loading ${e}...`}))}},js=({name:i,logoSrc:t,logoAlt:e,message:r})=>`<html>
|
|
4
4
|
<head>
|
|
@@ -109,7 +109,7 @@ import{a as Ui,b as s,c as R}from"./chunks/chunk.DV3REKZU.js";var qt=class{const
|
|
|
109
109
|
</div>
|
|
110
110
|
</body>
|
|
111
111
|
</html>
|
|
112
|
-
`;function Ks(i,t){var e={};for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&t.indexOf(r)<0&&(e[r]=i[r]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(i);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(i,r[o])&&(e[r[o]]=i[r[o]]);return e}function Gs(i,t){var e=document.querySelector('script[src="'.concat(i,'"]'));if(e===null)return null;var r=pa(i,t),o=e.cloneNode();if(delete o.dataset.uidAuto,Object.keys(o.dataset).length!==Object.keys(r.dataset).length)return null;var a=!0;return Object.keys(o.dataset).forEach(function(n){o.dataset[n]!==r.dataset[n]&&(a=!1)}),a?e:null}function qs(i){var t=i.url,e=i.attributes,r=i.onSuccess,o=i.onError,a=pa(t,e);a.onerror=o,a.onload=r,document.head.insertBefore(a,document.head.firstElementChild)}function Ws(i){var t=i.sdkBaseUrl,e=i.environment,r=Ks(i,["sdkBaseUrl","environment"]),o=t||Xs(e),a=r,n=Object.keys(a).filter(function(m){return a[m]!==void 0&&a[m]!==null&&a[m]!==""}).reduce(function(m,f){var u=a[f].toString();return f=Js(f),f.substring(0,4)==="data"||f==="crossorigin"?m.attributes[f]=u:m.queryParams[f]=u,m},{queryParams:{},attributes:{}}),l=n.queryParams,d=n.attributes;return l["merchant-id"]&&l["merchant-id"].indexOf(",")!==-1&&(d["data-merchant-id"]=l["merchant-id"],l["merchant-id"]="*"),{url:"".concat(o,"?").concat(Zs(l)),attributes:d}}function Js(i){var t=function(e,r){return(r?"-":"")+e.toLowerCase()};return i.replace(/[A-Z]+(?![a-z])|[A-Z]/g,t)}function Zs(i){var t="";return Object.keys(i).forEach(function(e){t.length!==0&&(t+="&"),t+=e+"="+i[e]}),t}function Xs(i){return i==="sandbox"?"https://www.sandbox.paypal.com/sdk/js":"https://www.paypal.com/sdk/js"}function pa(i,t){t===void 0&&(t={});var e=document.createElement("script");return e.src=i,Object.keys(t).forEach(function(r){e.setAttribute(r,t[r]),r==="data-csp-nonce"&&e.setAttribute("nonce",t["data-csp-nonce"])}),e}function Qs(i,t){if(t===void 0&&(t=Promise),ma(i,t),typeof document>"u")return t.resolve(null);var e=Ws(i),r=e.url,o=e.attributes,a=o["data-namespace"]||"paypal",n=Yo(a);return o["data-js-sdk-library"]||(o["data-js-sdk-library"]="paypal-js"),Gs(r,o)&&n?t.resolve(n):el({url:r,attributes:o},t).then(function(){var l=Yo(a);if(l)return l;throw new Error("The window.".concat(a," global variable is not available."))})}function el(i,t){t===void 0&&(t=Promise),ma(i,t);var e=i.url,r=i.attributes;if(typeof e!="string"||e.length===0)throw new Error("Invalid url.");if(r!==void 0&&typeof r!="object")throw new Error("Expected attributes to be an object.");return new t(function(o,a){if(typeof document>"u")return o();qs({url:e,attributes:r,onSuccess:function(){return o()},onError:function(){var n=new Error('The script "'.concat(e,'" failed to load. Check the HTTP status code and response body in DevTools to learn more.'));return a(n)}})})}function Yo(i){return window[i]}function ma(i,t){if(typeof i!="object"||i===null)throw new Error("Expected an options object.");var e=i.environment;if(e&&e!=="production"&&e!=="sandbox")throw new Error('The `environment` option must be either "production" or "sandbox".');if(t!==void 0&&typeof t!="function")throw new Error("Expected PromisePonyfill to be a function.")}var Lr=class extends ct{constructor(){super(...arguments);R(this,"paypalInstance");R(this,"dataNamespace",Ft());R(this,"callbacks",{onStart:()=>{},onError:()=>{},onSuccess:()=>{}})}setCallbacks(e){this.callbacks=e}async tokenize(){throw new Error("PayPal does not support direct tokenization")}async setup(){let{clientId:e,intent:r}=this.config.options;if(!e||!r)return!1;try{let o=await Qs({dataNamespace:this.dataNamespace,clientId:e,currency:this.context.configuration.clientSession.order.currencyCode,components:["buttons","funding-eligibility"],disableFunding:["bancontact","card","credit"],intent:r??"authorize"});return o?(this.paypalInstance=o,!0):!1}catch{return!1}}async render(e){if(!this.paypalInstance.Buttons)return;let r=this.paypalInstance.Buttons({style:{color:"gold",shape:"rect",label:"paypal",tagline:!1},createOrder:this.handleCreateOrder.bind(this),onInit:this.handleInit.bind(this),onClick:this.handleClick.bind(this),onApprove:this.handleApprove.bind(this),onCancel:this.handleCancel.bind(this),onError:this.handleError.bind(this)});if(!r.isEligible())throw new Error("PayPal Buttons are not eligible for rendering");await r.render(e)}handleInit(e,r){}handleClick(e,r){return r.resolve()}async handleCreateOrder(){this.callbacks.onStart(),await this.context.clientSessionApi.selectPaymentMethod(this.config.type);let{data:e,error:r}=await this.context.coreApi.createPaypalOrder(this.buildCreateOrderRequestBody());if(r||!e)throw r??new Error("Unable to create PayPal order");return e.orderId}async handleApprove(e,r){let o=null;try{o=await r?.order?.get()??null}catch{}let{error:a,data:n}=await this.context.pciApi.postPaymentInstruments({external_payer_info:{email:o?.payment_source?.paypal?.email_address,external_payer_id:e.payerID??void 0},paypal_order_id:e.orderID,paypal_status:o?.status});if(a||!n)throw a??new Error("Unable to create payment instrument");let l=await this.createPayment(n.token);this.callbacks.onSuccess(l)}handleCancel(){this.context.clientSessionApi.unselectPaymentMethod()}handleError(e){}buildCreateOrderRequestBody(){let{order:{currencyCode:e,merchantAmount:r,totalOrderAmount:o,shipping:a,lineItems:n=[],fees:l=[]}}=this.context.configuration.clientSession;if(!e)throw new Error("Currency code is not provided");let d={amount:r??o,currencyCode:e,paymentMethodConfigId:this.config.id,amountBreakdown:{}},m=!n.some(({description:f})=>!f);if(m&&(d.items=n.map(({description:f,taxAmount:u,amount:b,quantity:P})=>{let A=u?Math.floor(u/P):0;return{name:f,unit_amount:{value:b,currency_code:e},quantity:P.toString(),tax:{value:A,currency_code:e}}})),m&&n.length){let f=n.reduce((A,{amount:k,quantity:O})=>A+k*O,0),u=l?.reduce?.((A,{amount:k})=>A+(k??0),0),b=n?.reduce((A,{discountAmount:k})=>A+(k??0),0),P=n?.reduce((A,{taxAmount:k,quantity:O})=>A+(k??0*O),0);d.amountBreakdown={item_total:{value:f,currency_code:e},tax_total:{value:P,currency_code:e},handling:{value:u??0,currency_code:e},shipping:{value:a?.amount??0,currency_code:e},discount:{value:b,currency_code:e}}}return d}};function Nr(i,t){return(i/100).toFixed(2)}var Uo=5,Or=class extends ct{constructor(){super(...arguments);R(this,"applePaySession",null);R(this,"callbacks",{onStart:()=>{},onError:()=>{},onSuccess:()=>{}})}setCallbacks(e){this.callbacks=e}async tokenize(){throw new Error("ApplePay does not support direct tokenization")}async setup(){try{if(!ApplePaySession||!ApplePaySession.supportsVersion(Uo)||!ApplePaySession.canMakePayments())return!1;let e=window.location.hostname;if(!(this.config.options.merchantDomains||[]).includes(e))return!1}catch{return!1}return!0}async render(e){let r=document.createElement("button");r.setAttribute("style","display: inline-block;width: 100%;cursor: pointer;height: 40px;-webkit-appearance: -apple-pay-button;-apple-pay-button-type: plain;-apple-pay-button-style: black"),r.setAttribute("type","button"),r.classList.add("primer-apple-pay-button"),r.addEventListener("click",this.handleButtonClick.bind(this)),e.appendChild(r)}async handleButtonClick(){try{this.callbacks.onStart(),this.applePaySession=new ApplePaySession(Uo,this.createPaymentRequest()),this.applePaySession.onvalidatemerchant=this.handleValidateMerchant.bind(this),this.applePaySession.onpaymentauthorized=this.handlePaymentAuthorized.bind(this),this.applePaySession.onpaymentmethodselected=this.handlePaymentMethodSelected.bind(this),this.applePaySession.oncancel=this.handleCancel.bind(this),this.applePaySession.begin()}catch{}}async handleValidateMerchant({validationURL:e}){if(this.applePaySession)try{let{data:r,error:o}=await this.context.coreApi.createApplePaySession({validationUrl:e,paymentMethodConfigId:this.config.id,merchantDomain:window.location.hostname});if(o||!r||!this.applePaySession)throw o??new Error("Failed to validate merchant");this.applePaySession.completeMerchantValidation(r)}catch{this.abort()}}async handlePaymentMethodSelected(){if(this.applePaySession)try{let{merchantAmount:e,totalOrderAmount:r,currencyCode:o}=this.context.configuration.clientSession.order;this.applePaySession.completePaymentMethodSelection({newTotal:{label:this.config.options.merchantName,amount:Nr(e??r,o),type:"final"}})}catch{this.abort()}}async handlePaymentAuthorized({payment:e}){if(this.applePaySession)try{let r={paymentMethodConfigId:this.config.id,token:e.token},o=await this.context.pciApi.postPaymentInstruments(r),a=await this.createPayment(o.data.token),n=await this.handleRequiredAction(a);n.status==="SUCCESS"?(this.applePaySession.completePayment(ApplePaySession.STATUS_SUCCESS),this.callbacks.onSuccess(n)):(this.applePaySession.completePayment(ApplePaySession.STATUS_FAILURE),this.callbacks.onError()),this.applePaySession=null}catch{this.applePaySession&&(this.applePaySession.completePayment(ApplePaySession.STATUS_FAILURE),this.applePaySession=null),this.callbacks.onError()}}handleCancel(){this.applePaySession=null,this.callbacks.onError()}abort(){this.applePaySession?.abort(),this.applePaySession=null,this.callbacks.onError()}createPaymentRequest(){let{countryCode:e,currencyCode:r,merchantAmount:o,totalOrderAmount:a}=this.context.configuration.clientSession.order;if(!e||!r)throw new Error("Country code and currency code are required");let n=["visa","masterCard","amex"],l=Nr(o??a,r);return{countryCode:e,currencyCode:r,merchantCapabilities:["supports3DS"],supportedNetworks:n,total:{amount:l,label:this.config.options.merchantName,type:"pending"}}}};function tl(i,t={}){return new Promise((e,r)=>{if(document.querySelector(`script[src="${i}"]`))return void e();let o=document.createElement("script");o.src=i,Object.entries(t).forEach(([a,n])=>{o.setAttribute(a,n)}),o.onload=()=>{e()},o.onerror=()=>{r(new Error(`Failed to load script: ${i}`))},document.head.appendChild(o)})}var Ho=2,zo=0,Rr=class extends ct{constructor(){super(...arguments);R(this,"client");R(this,"callbacks",{onStart:()=>{},onError:()=>{},onSuccess:()=>{}});R(this,"allowedPaymentMethod",{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY"],allowedCardNetworks:["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"]}})}setCallbacks(e){this.callbacks=e}async tokenize(){throw new Error("Google Pay does not support direct tokenization")}async setup(){try{await tl("https://pay.google.com/gp/p/js/pay.js")}catch{return!1}if(!window.google||!window.google.payments||(this.client=new google.payments.api.PaymentsClient({environment:"TEST"}),!this.client.isReadyToPay(this.buildIsReadyToPayRequest())))return!1;let{countryCode:e,currencyCode:r}=this.context.configuration.clientSession.order;return!(!e||!r)}async render(e){let r=this.client.createButton({buttonType:"buy",buttonColor:"black",buttonSizeMode:"fill",buttonRootNode:e instanceof ShadowRoot?e:void 0,onClick:this.handleButtonClick.bind(this)});e.appendChild(r)}async handleButtonClick(){this.callbacks.onStart();try{let e=this.buildPaymentDataRequest(),r=await this.client.loadPaymentData(e),{data:o,error:a}=await this.context.pciApi.postPaymentInstruments({flow:"GATEWAY",network:r.paymentMethodData.info?.cardNetwork??"OTHER",merchant_id:this.config.options.merchantId,encrypted_payload:Tr.encode(r.paymentMethodData.tokenizationData.token)});if(a||!o)throw a??new Error("Failed to tokenize payment data");let n=await this.createPayment(o.token);n.status==="SUCCESS"?this.callbacks.onSuccess(n):this.callbacks.onError()}catch(e){throw this.callbacks.onError(),e}}async handlePaymentDataChanged(e){return{}}buildIsReadyToPayRequest(){return{apiVersion:Ho,apiVersionMinor:zo,allowedPaymentMethods:[this.allowedPaymentMethod]}}buildPaymentDataRequest(){let{countryCode:e,currencyCode:r,merchantAmount:o,totalOrderAmount:a}=this.context.configuration.clientSession.order;return{apiVersion:Ho,apiVersionMinor:zo,transactionInfo:{countryCode:e,currencyCode:r,displayItems:[],totalPriceStatus:"FINAL",totalPrice:Nr(o??a,r),totalPriceLabel:"Total"},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}}}]}}};async function rl(i){let t=i.configuration.paymentMethods.map(r=>{if(r.implementationType==="WEB_REDIRECT")return new wi(r,i);if(r.type===gt.PAYMENT_CARD)return new Ir(r,i);if(r.type===gt.PAYPAL)return new Lr(r,i);if(r.type===gt.APPLE_PAY)return new Or(r,i);if(r.type===gt.GOOGLE_PAY)return new Rr(r,i)}).map(r=>r?.setup().then(o=>o?r:null));return(await Promise.all(t)).filter(r=>!!r)}async function il(i){let t=await $s(i),e=await rl(t);return{context:t,paymentMethods:e}}var Dr=class i{constructor(t,e=window.parent){R(this,"sessionId");R(this,"targetWindow");R(this,"messageHandlers",new Set);this.sessionId=t,this.targetWindow=e}send(t,e,r){let o={sessionId:this.sessionId,type:t,...r&&{target:r},...e&&{data:e}};this.targetWindow.postMessage(o,"*")}listen(t){let e=r=>{let o=r.data;if(o?.sessionId===this.sessionId){let{sessionId:a,...n}=o;t(n)}};return this.messageHandlers.add(e),window.addEventListener("message",e),()=>{window.removeEventListener("message",e),this.messageHandlers.delete(e)}}forIframe(t){if(!t.contentWindow)throw new Error("Iframe contentWindow is not available");return new i(this.sessionId,t.contentWindow)}cleanup(){this.messageHandlers.forEach(t=>{window.removeEventListener("message",t)}),this.messageHandlers.clear()}};async function ol(i){try{await i.start();let t=await i.tokenize(),e=await i.createPayment(t.token);return await i.handleRequiredAction(e)}catch(t){throw t}}var al=async(i,t)=>{if(!i.onBeforePaymentCreate)return!0;let e=setTimeout(()=>{},1e4);return new Promise(r=>{i.onBeforePaymentCreate({paymentMethodType:t},{continuePaymentCreation:()=>{clearTimeout(e),r(!0)},abortPaymentCreation:()=>{clearTimeout(e),r(!1)}})})};async function ua(i,t){if(!await al(i,t.config.type)){i.onCheckoutFail?.(new Error("Payment creation aborted"),{});return}i.onPaymentCreationStart?.();let r=null,o=null;try{o=await ol(t)}catch(a){r=a}finally{if(r||!o){i.onCheckoutFail?.(new Error("Payment creation failed"),{});return}if(o.status==="FAILED")return void i.onCheckoutFail?.(new Error("Payment failed"),{payment:o??{}});i.onCheckoutComplete?.({payment:o})}}function nl(i,t,e,r={}){let o=[],a="LOCAL";return e.store.publicStore.subscribe(({networks:n,networksSource:l})=>{l==="LOCAL"&&a!=="LOCAL"&&r.onCardNetworksLoading?.(),(l!==a||sl(o,n))&&(o=n,a=l,r.onCardNetworksChange?.(ll({networks:o,source:a},t.configuration.clientSession.paymentMethod.orderedAllowedCardNetworks)))}),{createHostedInputs:()=>{let n=new Dr(t.checkoutSessionId),l=d=>{let m=new Map,f=n.listen(u=>{u.target===d&&(u.type==="focus"?m.get("focus")?.():u.type==="blur"?m.get("blur")?.():u.type==="input"&&(m.get("input")?.(u.data),m.get("change")?.(u.data)))});return{cleanup:()=>{f()},getOptions:()=>e.store.optionsStore.getState()[d]||{placeholder:"",ariaLabel:"",style:{}},setOptions:u=>{e.store.optionsStore.setState({[d]:{...e.store.optionsStore.getState()[d],...u}})},render:(u,b)=>{let P=e.iframes[d];if(!P)return Promise.resolve();let A;return A=typeof u=="string"?document.querySelector(u):u,A&&(A.appendChild(P),P.onload=()=>{e.store.optionsStore.setState({[d]:b})}),Promise.resolve()},addEventListener:(u,b)=>{m.set(u,b)},focus:()=>{let u=e.iframes[d];u&&u.contentWindow&&n.forIframe(u).send("focus",void 0,d)},blur:()=>{let u=e.iframes[d];u&&u.contentWindow&&n.forIframe(u).send("blur",void 0,d)},setDisabled:u=>{let b=e.store.publicStore.getState();e.store.publicStore.setState({...b,[d]:{...b[d],disabled:u}})}}};return{cardNumberInput:l("cardNumber"),cardHolderNameInput:l("cardHolderName"),expiryInput:l("cardExpiryDate"),cvvInput:l("cardSecurityCode")}},removeHostedInputs:()=>{e.iframes.cardNumber.remove(),e.iframes.cardSecurityCode.remove(),e.iframes.cardExpiryDate.remove(),e.iframes.cardHolderName.remove()},submit:n=>{if(n?.cardNetwork){let l=e.store.publicStore.getState();e.store.publicStore.setState({...l,preferredNetwork:n.cardNetwork})}return ua(i,e)},validate:()=>{let n=e.store.publicStore.getState(),l=[],d=["cardNumber","cardSecurityCode","cardExpiryDate","cardHolderName"];for(let m of d){let f=n[m];!f.valid&&f.error&&l.push({field:m,name:m,error:f.error,message:f.error})}return Promise.resolve({valid:l.length===0,validationErrors:l})},reset:()=>{t.apiControllerIframe?.contentWindow&&new Dr(t.checkoutSessionId).forIframe(t.apiControllerIframe).send("reset-card-form")}}}function sl(i,t){if(i.length!==t.length)return!0;let e=t.map(({network:r})=>r);return!i.every(({network:r})=>e.includes(r))}function ll({networks:i,source:t},e){let r=e,o=new Set(r.map(d=>Fo(d).backend)),a=i.map(d=>({...d,allowed:o.has(d.network)})).sort((d,m)=>d.allowed?r.indexOf(d.network)-r.indexOf(m.network):1),n=a.filter(d=>d.allowed),l=t==="REMOTE"&&n.length>1;return{detectedCardNetworks:{items:a,preferred:n[0]},...l&&{selectableCardNetworks:{items:n,preferred:n[0]}},source:t}}function dl(i,t,e){return{createButton:()=>({render:async r=>{e.setCallbacks({onStart:()=>{i.onBeforePaymentCreate?.({paymentMethodType:e.config.type},{continuePaymentCreation:()=>{i.onPaymentCreationStart?.()},abortPaymentCreation:()=>{}})},onSuccess(o){i.onCheckoutComplete?.({payment:o})},onError(){i.onCheckoutFail?.(new Error("Payment creation failed"),{})}}),await e.render(r)}})}}function cl(i,t,e){return{start:()=>ua(i,e)}}async function ha(i,t){let{paymentMethods:e,context:r}=await il(i);return t.onAvailablePaymentMethodsLoad?.(e.map(o=>({type:o.config.type,managerType:o.config.type===gt.PAYMENT_CARD?"CARD":o.config.implementationType==="NATIVE_SDK"?"NATIVE":"REDIRECT"}))),{start:()=>Promise.resolve(),createPaymentMethodManager:async(o,a)=>{let n=e.find(({config:l})=>l.type===o);return n?n instanceof Ir?nl(t,r,n,a):n instanceof Lr||n instanceof Or||n instanceof Rr?dl(t,r,n):cl(t,r,n):null},getSDKUtilities:()=>({getCardNetworkAsset:o=>{let{asset:a,display:n}=Fo(o);return{cardUrl:`${ks}/brand/card/${a}.svg`,displayName:n}},getUIOrderAmount:()=>{let{merchantAmount:o,totalOrderAmount:a,currencyCode:n}=r.configuration.clientSession.order;return Nr(o??a,n)},getCDNAssets:o=>{let a=e.find(({config:m})=>m.type===o);if(!a)return null;let{backgroundColor:n,iconUrl:l,text:d}=a.config.displayMetadata?.button||{};return{backgroundColor:n,iconUrl:l,paymentMethodName:d,displayName:a.config.name}},getPaymentMethodConfiguration:o=>e.find(({config:a})=>a.type===o)?.config}),createVaultManager:()=>({})}}var $r=class{constructor(t){this.createPaymentMethodManager=null;this._paymentsList=[];this.currentSdkInstance=null;this.primerJS=null;this.loadingTimeout=null;this.isDisconnected=!1;(this.host=t).addController(this),this.isDisconnected=!1,this.sdkInstanceTask=new L(t,{args:()=>[this.host.clientToken,this.host.options],task:this.initializeHeadless()}),new L(t,{args:()=>[this.sdkInstanceTask.value,this.paymentsList],task:this.initializeLitContext()})}set paymentsList(t){this._paymentsList=t,this.host.requestUpdate()}get paymentsList(){return this._paymentsList}hostConnected(){this.isDisconnected=!1,this.host.sdkStateController.startLoading(),this.setupLoadingTimeout()}hostDisconnected(){this.isDisconnected=!0,this.cleanupResources()}setupLoadingTimeout(){this.clearLoadingTimeout(),this.loadingTimeout=setTimeout(()=>{this.host.sdkStateController.currentState.isLoading&&(S.warn("Loading timeout reached, resetting SDK state"),this.cleanupResources(),this.host.sdkStateController.completeLoading())},1e4)}clearLoadingTimeout(){this.loadingTimeout!==null&&(clearTimeout(this.loadingTimeout),this.loadingTimeout=null)}cleanupResources(){if(this.clearLoadingTimeout(),this.currentSdkInstance)try{this.paymentsList=[],this.createPaymentMethodManager=null,this.host.sdkStateController.reset(),S.info("SDK instance cleaned up")}catch(t){S.error("Error cleaning up SDK instance:",t)}this.currentSdkInstance=null,this.primerJS=null}async _loadV2Sdk(t=wo){let e=window;if(e.Primer&&typeof e.Primer.preloadPrimer=="function"){S.info("SDK already loaded, skipping load script"),await e.Primer.preloadPrimer();return}await Mo(t),await e.Primer.preloadPrimer()}initializeHeadless(){return async([t,e])=>{if(this.isDisconnected)return S.warn("Component disconnected, aborting SDK initialization"),T;if(!t||!e)return T;this.cleanupResources();try{let r;e.sdkCore?r={createHeadless:(l,d)=>ha(l,d)}:(await this._loadV2Sdk(),r=window.Primer),this.primerJS=new Ar(null);let o=await r.createHeadless(t,{...e,onAvailablePaymentMethodsLoad:n=>{this.isDisconnected||(S.info("Configuration payment methods:",n),this.paymentsList=n)},onCheckoutComplete:({payment:n})=>{this.isDisconnected||(S.info("Payment completed:",n),this.host.sdkStateController.completeProcessing(),this.primerJS&&this.primerJS.handlePaymentComplete(n))},onCheckoutFail:(n,l)=>{this.isDisconnected||(S.error("Payment failed:",n),this.host.sdkStateController.setFailure(n.code||"UNKNOWN_ERROR",n.message||"Unknown error occurred"),this.primerJS&&this.primerJS.handlePaymentFailure(n,l.payment))},onBeforePaymentCreate:(n,l)=>{this.isDisconnected||(this.host.sdkStateController.startProcessing(),this.primerJS?this.primerJS.handleBeforePaymentCreate(n,l):l?.continuePaymentCreation())},onPaymentMethodAction:(n,l)=>{this.isDisconnected||n==="PAYMENT_METHOD_UNSELECTED"&&this.host.sdkStateController.stopProcessing()},onPaymentCreationStart:()=>{this.isDisconnected||(this.host.sdkStateController.resetError(),this.primerJS&&this.primerJS.handlePaymentStart())}});if(this.createPaymentMethodManager=o.createPaymentMethodManager.bind(o),this.currentSdkInstance=o,this.primerJS&&Object.defineProperty(this.primerJS,"headlessInstance",{value:o,writable:!1}),await o.start(),this.isDisconnected)return this.cleanupResources(),T;this.host.sdkContextController.setClientOptions(e),this.primerJS&&this.host.primerEventsController.dispatchCheckoutInitialized(this.primerJS);let a=o.getSDKUtilities();return this.host.sdkContextController.setHeadlessUtils(a),this.host.vaultManagerController.initializeVaultManager(o.createVaultManager(),{vaultEnabled:e.vault?.enabled,captureVaultedCardCvv:!!a.getPaymentMethodConfiguration("PAYMENT_CARD")?.options?.captureVaultedCardCvv,showEmptyState:e.vault?.showEmptyState}),o}catch(r){throw r instanceof Error&&(S.error("SDK initialization error:",r),this.host.sdkStateController.setError(r)),this.cleanupResources(),r}}}initializeLitContext(){return async([t,e])=>{if(this.isDisconnected)return T;if(!t||!e.length)return T;let r=new Map,o=new Map;try{for(let n of e){if(this.isDisconnected)break;let l=await this.initializePaymentMethodManager(n)();n&&l&&(r.set(n.type,n),o.set(n.type,l))}if(this.isDisconnected)return T;let a=new Er(r);return this.host.sdkContextController.setPaymentManagers(o),this.host.sdkContextController.setPaymentMethods(a),this.primerJS&&this.primerJS.setPaymentMethods(a),this.host.primerEventsController.dispatchPaymentMethods(a),S.info("Initialized payment methods:",a.toArray()),r}catch(a){if(a instanceof Error)throw this.host.sdkStateController.setError(a),a;return null}finally{this.clearLoadingTimeout(),this.isDisconnected||this.host.sdkStateController.completeLoading()}}}initializePaymentMethodManager(t){let{type:e,managerType:r}=t;return async()=>{if(this.isDisconnected||!this.createPaymentMethodManager)return null;if(r==="KLARNA"){let o=await this.createPaymentMethodManager("KLARNA",{onPaymentMethodCategoriesChange:a=>{this.isDisconnected||this.host.sdkContextController.setKlarnaCategories({categories:a,isLoading:!1})}});return o?{type:e,manager:o}:null}try{if(r==="CARD"){let a=await this.createPaymentMethodManager(e,{onCardNetworksChange:n=>{this.isDisconnected||this.host.cardNetworkController.processCardNetworkChangeEvent(n)},onCardNetworksLoading:()=>{this.isDisconnected||this.host.cardNetworkController.setCardNetworksLoading()}});return a?{type:e,manager:a}:null}let o=await this.createPaymentMethodManager(e);return o?{type:e,manager:o}:null}catch(o){return S.error(`Failed to initialize manager for ${e}:`,o),null}}}};var Vr=class{constructor(t){this.host=t,t.addController(this)}_error(t){let{error:e}=t.detail;this.host.sdkStateController.setFailure("UNKNOWN_ERROR",e.message)}_mandateConfirmed(){this.host.sdkStateController.completeProcessing()}_mandateDeclined(){this.host.sdkStateController.setFailure("UNKNOWN_ERROR","Mandate declined")}hostConnected(){this.host.addEventListener("primer-ach-error",this._error.bind(this)),this.host.addEventListener("primer-ach-mandate-confirmed",this._mandateConfirmed.bind(this)),this.host.addEventListener("primer-ach-mandate-declined",this._mandateDeclined.bind(this))}hostDisconnected(){this.host.removeEventListener("primer-ach-error",this._error.bind(this)),this.host.removeEventListener("primer-ach-mandate-confirmed",this._mandateConfirmed.bind(this)),this.host.removeEventListener("primer-ach-mandate-declined",this._mandateDeclined.bind(this))}};var pl=Ui({"../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.KRXB3WQO.js"),"../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.6SKJRXIR.js"),"../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.SANDLFEK.js"),"../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.FC4I5M3C.js"),"../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.YI32NZ7B.js"),"../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.7M7UFQB7.js"),"../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.XSGTYDZR.js"),"../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.VO4GDE3X.js"),"../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.MNFLVOE3.js"),"../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.TBWVUZEF.js"),"../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.6EMWUABR.js"),"../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.XZLDFHYI.js"),"../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.JBSFMKZ2.js"),"../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.I75VK2ID.js"),"../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.JBNP6RXT.js"),"../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.PW253QAL.js"),"../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.LM4RITYJ.js"),"../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.JGCKQA6J.js"),"../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.VBXULDDY.js"),"../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.7Q6BFLDK.js"),"../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.QOC76SSC.js"),"../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.BANZIFNH.js"),"../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.Q2SRJOKH.js"),"../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.XMNFEN5T.js"),"../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.3AJDTMU5.js"),"../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.TFPDXNEV.js"),"../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.FPTX4NM4.js"),"../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.CAFSKRQ2.js"),"../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.7BPSDYTC.js"),"../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.6ZVCFPVW.js"),"../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.RF34QM23.js"),"../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.AKDHLRUA.js"),"../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.VBALOWHZ.js"),"../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.WN7VCF27.js"),"../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.ICXGVGRR.js"),"../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.SIP5JIOX.js"),"../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.R77UEKCA.js"),"../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.6M2YSTDX.js"),"../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.33ZY4CDS.js"),"../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.M27YUIZC.js"),"../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.Q2SIY6NA.js"),"../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.EJZOGSJR.js"),"../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.3RROGLXM.js"),"../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.GGWFQ3Y7.js"),"../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.MQHNRMN4.js"),"../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.WNR7XUSX.js"),"../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.GNCY2PNY.js")});si(i=>pl(`../../localization/lit-localize/locales/${i}.ts`));var ml={LOADER_DISABLED:"loader-disabled",CUSTOM_STYLES:"custom-styles",CLIENT_TOKEN:"client-token",JS_INIT:"js-initialized"},re=class extends g{constructor(){super();this.customStyles="";this.clientToken="";this.options={};this.disableLoader=!1;this._jsInitialized=!1;this.previousLoadingState=!0;this.hasAssignedContent=!1;this._loadingTimeoutId=null;this.locale="en-GB";this.onSlotChange=e=>{let o=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=o.length>0,this.requestUpdate()};this.sdkContextController=new tr(this),this.sdkStateController=new Qt(this),this.primerEventsController=new ht(this),this.styleProcessingController=new rr(this),this.vaultManagerController=new Tt(this),this.cardNetworkController=new qt(this),this.achPaymentEventsController=new Vr(this),new $r(this)}set jsInitialized(e){this.requestUpdate(),this._jsInitialized=e}get jsInitialized(){return this._jsInitialized}attributeChangedCallback(e,r,o){e===ml.CUSTOM_STYLES?this.styleProcessingController.processCustomStyles(o):super.attributeChangedCallback(e,r,o)}disconnectedCallback(){this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null),this.sdkStateController?.currentState.isLoading&&this.sdkStateController.forceCompleteLoading(),super.disconnectedCallback()}willUpdate(e){e.has("options")&&(this.options?.locale&&(di(this.options?.locale)?this.locale=ci(this.options?.locale):S.warn("\u{1F30E}\u2757 Unsupported locale provided:",this.options?.locale,"- Falling back to default locale `en-GB`")),li(this.locale||"en-GB"))}updated(){let e=getComputedStyle(this);this.sdkContextController.setComputedStyles(e),this.checkLoadingStateChange()}checkLoadingStateChange(){let e=this.sdkStateController?.currentState.isLoading||!1;this.previousLoadingState&&!e&&(this.jsInitialized=!0),this.previousLoadingState=e,e&&!this._loadingTimeoutId?this._loadingTimeoutId=window.setTimeout(()=>{this.sdkStateController?.currentState.isLoading&&(S.warn("Loading timeout in component, forcing completion"),this.sdkStateController.forceCompleteLoading(),this.jsInitialized=!0),this._loadingTimeoutId=null},1e4):!e&&this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null)}render(){let e=this.sdkStateController.currentState,r=e.isLoading,o=e.error,a=!r&&!o;return p` ${I(r,()=>h)} ${I(o,()=>p`<primer-checkout-error></primer-checkout-error>`)} ${I(a,()=>p`<slot name="main" @slotchange=${this.onSlotChange}></slot>${I(this.hasAssignedContent,()=>h,()=>p`<primer-main></primer-main>`)} `,()=>h)} `}addEventListener(e,r,o){super.addEventListener(e,r,o)}removeEventListener(e,r,o){super.removeEventListener(e,r,o)}};re.styles=[E,Po],s([c({type:String,attribute:"custom-styles"})],re.prototype,"customStyles",2),s([c({type:String,attribute:"client-token"})],re.prototype,"clientToken",2),s([c({type:Object})],re.prototype,"options",2),s([c({type:Boolean,attribute:"loader-disabled"})],re.prototype,"disableLoader",2),s([c({type:Boolean,reflect:!0,attribute:"js-initialized"})],re.prototype,"_jsInitialized",2),s([Ge("slot")],re.prototype,"defaultSlot",2),s([_()],re.prototype,"previousLoadingState",2),re=s([M(),v("primer-checkout")],re);function ul(i){return document.querySelector(`#${i}`)}function hl(i,t){let e=document.createElement("style");return e.textContent=i,e.id=t,e}function jt(i,t,e=!0){if(!Sr||ul(t))return;let o=hl(i,t);e&&document.head.firstChild?document.head.insertBefore(o,document.head.firstChild):document.head.appendChild(o)}var fa=`
|
|
112
|
+
`;function Ks(i,t){var e={};for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&t.indexOf(r)<0&&(e[r]=i[r]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(i);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(i,r[o])&&(e[r[o]]=i[r[o]]);return e}function Gs(i,t){var e=document.querySelector('script[src="'.concat(i,'"]'));if(e===null)return null;var r=pa(i,t),o=e.cloneNode();if(delete o.dataset.uidAuto,Object.keys(o.dataset).length!==Object.keys(r.dataset).length)return null;var a=!0;return Object.keys(o.dataset).forEach(function(n){o.dataset[n]!==r.dataset[n]&&(a=!1)}),a?e:null}function qs(i){var t=i.url,e=i.attributes,r=i.onSuccess,o=i.onError,a=pa(t,e);a.onerror=o,a.onload=r,document.head.insertBefore(a,document.head.firstElementChild)}function Ws(i){var t=i.sdkBaseUrl,e=i.environment,r=Ks(i,["sdkBaseUrl","environment"]),o=t||Xs(e),a=r,n=Object.keys(a).filter(function(m){return a[m]!==void 0&&a[m]!==null&&a[m]!==""}).reduce(function(m,f){var u=a[f].toString();return f=Js(f),f.substring(0,4)==="data"||f==="crossorigin"?m.attributes[f]=u:m.queryParams[f]=u,m},{queryParams:{},attributes:{}}),l=n.queryParams,d=n.attributes;return l["merchant-id"]&&l["merchant-id"].indexOf(",")!==-1&&(d["data-merchant-id"]=l["merchant-id"],l["merchant-id"]="*"),{url:"".concat(o,"?").concat(Zs(l)),attributes:d}}function Js(i){var t=function(e,r){return(r?"-":"")+e.toLowerCase()};return i.replace(/[A-Z]+(?![a-z])|[A-Z]/g,t)}function Zs(i){var t="";return Object.keys(i).forEach(function(e){t.length!==0&&(t+="&"),t+=e+"="+i[e]}),t}function Xs(i){return i==="sandbox"?"https://www.sandbox.paypal.com/sdk/js":"https://www.paypal.com/sdk/js"}function pa(i,t){t===void 0&&(t={});var e=document.createElement("script");return e.src=i,Object.keys(t).forEach(function(r){e.setAttribute(r,t[r]),r==="data-csp-nonce"&&e.setAttribute("nonce",t["data-csp-nonce"])}),e}function Qs(i,t){if(t===void 0&&(t=Promise),ma(i,t),typeof document>"u")return t.resolve(null);var e=Ws(i),r=e.url,o=e.attributes,a=o["data-namespace"]||"paypal",n=Yo(a);return o["data-js-sdk-library"]||(o["data-js-sdk-library"]="paypal-js"),Gs(r,o)&&n?t.resolve(n):el({url:r,attributes:o},t).then(function(){var l=Yo(a);if(l)return l;throw new Error("The window.".concat(a," global variable is not available."))})}function el(i,t){t===void 0&&(t=Promise),ma(i,t);var e=i.url,r=i.attributes;if(typeof e!="string"||e.length===0)throw new Error("Invalid url.");if(r!==void 0&&typeof r!="object")throw new Error("Expected attributes to be an object.");return new t(function(o,a){if(typeof document>"u")return o();qs({url:e,attributes:r,onSuccess:function(){return o()},onError:function(){var n=new Error('The script "'.concat(e,'" failed to load. Check the HTTP status code and response body in DevTools to learn more.'));return a(n)}})})}function Yo(i){return window[i]}function ma(i,t){if(typeof i!="object"||i===null)throw new Error("Expected an options object.");var e=i.environment;if(e&&e!=="production"&&e!=="sandbox")throw new Error('The `environment` option must be either "production" or "sandbox".');if(t!==void 0&&typeof t!="function")throw new Error("Expected PromisePonyfill to be a function.")}var Lr=class extends ct{constructor(){super(...arguments);R(this,"paypalInstance");R(this,"dataNamespace",Ft());R(this,"callbacks",{onStart:()=>{},onError:()=>{},onSuccess:()=>{}})}setCallbacks(e){this.callbacks=e}async tokenize(){throw new Error("PayPal does not support direct tokenization")}async setup(){let{clientId:e,intent:r}=this.config.options;if(!e||!r)return!1;try{let o=await Qs({dataNamespace:this.dataNamespace,clientId:e,currency:this.context.configuration.clientSession.order.currencyCode,components:["buttons","funding-eligibility"],disableFunding:["bancontact","card","credit"],intent:r??"authorize"});return o?(this.paypalInstance=o,!0):!1}catch{return!1}}async render(e){if(!this.paypalInstance.Buttons)return;let r=this.paypalInstance.Buttons({style:{color:"gold",shape:"rect",label:"paypal",tagline:!1},createOrder:this.handleCreateOrder.bind(this),onInit:this.handleInit.bind(this),onClick:this.handleClick.bind(this),onApprove:this.handleApprove.bind(this),onCancel:this.handleCancel.bind(this),onError:this.handleError.bind(this)});if(!r.isEligible())throw new Error("PayPal Buttons are not eligible for rendering");await r.render(e)}handleInit(e,r){}handleClick(e,r){return r.resolve()}async handleCreateOrder(){this.callbacks.onStart(),await this.context.clientSessionApi.selectPaymentMethod(this.config.type);let{data:e,error:r}=await this.context.coreApi.createPaypalOrder(this.buildCreateOrderRequestBody());if(r||!e)throw r??new Error("Unable to create PayPal order");return e.orderId}async handleApprove(e,r){let o=null;try{o=await r?.order?.get()??null}catch{}let{error:a,data:n}=await this.context.pciApi.postPaymentInstruments({external_payer_info:{email:o?.payment_source?.paypal?.email_address,external_payer_id:e.payerID??void 0},paypal_order_id:e.orderID,paypal_status:o?.status});if(a||!n)throw a??new Error("Unable to create payment instrument");let l=await this.createPayment(n.token);this.callbacks.onSuccess(l)}handleCancel(){this.context.clientSessionApi.unselectPaymentMethod()}handleError(e){}buildCreateOrderRequestBody(){let{order:{currencyCode:e,merchantAmount:r,totalOrderAmount:o,shipping:a,lineItems:n=[],fees:l=[]}}=this.context.configuration.clientSession;if(!e)throw new Error("Currency code is not provided");let d={amount:r??o,currencyCode:e,paymentMethodConfigId:this.config.id,amountBreakdown:{}},m=!n.some(({description:f})=>!f);if(m&&(d.items=n.map(({description:f,taxAmount:u,amount:b,quantity:P})=>{let A=u?Math.floor(u/P):0;return{name:f,unit_amount:{value:b,currency_code:e},quantity:P.toString(),tax:{value:A,currency_code:e}}})),m&&n.length){let f=n.reduce((A,{amount:k,quantity:O})=>A+k*O,0),u=l?.reduce?.((A,{amount:k})=>A+(k??0),0),b=n?.reduce((A,{discountAmount:k})=>A+(k??0),0),P=n?.reduce((A,{taxAmount:k,quantity:O})=>A+(k??0*O),0);d.amountBreakdown={item_total:{value:f,currency_code:e},tax_total:{value:P,currency_code:e},handling:{value:u??0,currency_code:e},shipping:{value:a?.amount??0,currency_code:e},discount:{value:b,currency_code:e}}}return d}};function Nr(i,t){return(i/100).toFixed(2)}var Uo=5,Or=class extends ct{constructor(){super(...arguments);R(this,"applePaySession",null);R(this,"callbacks",{onStart:()=>{},onError:()=>{},onSuccess:()=>{}})}setCallbacks(e){this.callbacks=e}async tokenize(){throw new Error("ApplePay does not support direct tokenization")}async setup(){try{if(!ApplePaySession||!ApplePaySession.supportsVersion(Uo)||!ApplePaySession.canMakePayments())return!1;let e=window.location.hostname;if(!(this.config.options.merchantDomains||[]).includes(e))return!1}catch{return!1}return!0}async render(e){let r=document.createElement("button");r.setAttribute("style","display: inline-block;width: 100%;cursor: pointer;height: 40px;-webkit-appearance: -apple-pay-button;-apple-pay-button-type: plain;-apple-pay-button-style: black"),r.setAttribute("type","button"),r.classList.add("primer-apple-pay-button"),r.addEventListener("click",this.handleButtonClick.bind(this)),e.appendChild(r)}async handleButtonClick(){try{this.callbacks.onStart(),this.applePaySession=new ApplePaySession(Uo,this.createPaymentRequest()),this.applePaySession.onvalidatemerchant=this.handleValidateMerchant.bind(this),this.applePaySession.onpaymentauthorized=this.handlePaymentAuthorized.bind(this),this.applePaySession.onpaymentmethodselected=this.handlePaymentMethodSelected.bind(this),this.applePaySession.oncancel=this.handleCancel.bind(this),this.applePaySession.begin()}catch{}}async handleValidateMerchant({validationURL:e}){if(this.applePaySession)try{let{data:r,error:o}=await this.context.coreApi.createApplePaySession({validationUrl:e,paymentMethodConfigId:this.config.id,merchantDomain:window.location.hostname});if(o||!r||!this.applePaySession)throw o??new Error("Failed to validate merchant");this.applePaySession.completeMerchantValidation(r)}catch{this.abort()}}async handlePaymentMethodSelected(){if(this.applePaySession)try{let{merchantAmount:e,totalOrderAmount:r,currencyCode:o}=this.context.configuration.clientSession.order;this.applePaySession.completePaymentMethodSelection({newTotal:{label:this.config.options.merchantName,amount:Nr(e??r,o),type:"final"}})}catch{this.abort()}}async handlePaymentAuthorized({payment:e}){if(this.applePaySession)try{let r={paymentMethodConfigId:this.config.id,token:e.token},o=await this.context.pciApi.postPaymentInstruments(r),a=await this.createPayment(o.data.token),n=await this.handleRequiredAction(a);n.status==="SUCCESS"?(this.applePaySession.completePayment(ApplePaySession.STATUS_SUCCESS),this.callbacks.onSuccess(n)):(this.applePaySession.completePayment(ApplePaySession.STATUS_FAILURE),this.callbacks.onError()),this.applePaySession=null}catch{this.applePaySession&&(this.applePaySession.completePayment(ApplePaySession.STATUS_FAILURE),this.applePaySession=null),this.callbacks.onError()}}handleCancel(){this.applePaySession=null,this.callbacks.onError()}abort(){this.applePaySession?.abort(),this.applePaySession=null,this.callbacks.onError()}createPaymentRequest(){let{countryCode:e,currencyCode:r,merchantAmount:o,totalOrderAmount:a}=this.context.configuration.clientSession.order;if(!e||!r)throw new Error("Country code and currency code are required");let n=["visa","masterCard","amex"],l=Nr(o??a,r);return{countryCode:e,currencyCode:r,merchantCapabilities:["supports3DS"],supportedNetworks:n,total:{amount:l,label:this.config.options.merchantName,type:"pending"}}}};function tl(i,t={}){return new Promise((e,r)=>{if(document.querySelector(`script[src="${i}"]`))return void e();let o=document.createElement("script");o.src=i,Object.entries(t).forEach(([a,n])=>{o.setAttribute(a,n)}),o.onload=()=>{e()},o.onerror=()=>{r(new Error(`Failed to load script: ${i}`))},document.head.appendChild(o)})}var Ho=2,zo=0,Rr=class extends ct{constructor(){super(...arguments);R(this,"client");R(this,"callbacks",{onStart:()=>{},onError:()=>{},onSuccess:()=>{}});R(this,"allowedPaymentMethod",{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY"],allowedCardNetworks:["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"]}})}setCallbacks(e){this.callbacks=e}async tokenize(){throw new Error("Google Pay does not support direct tokenization")}async setup(){try{await tl("https://pay.google.com/gp/p/js/pay.js")}catch{return!1}if(!window.google||!window.google.payments||(this.client=new google.payments.api.PaymentsClient({environment:"TEST"}),!this.client.isReadyToPay(this.buildIsReadyToPayRequest())))return!1;let{countryCode:e,currencyCode:r}=this.context.configuration.clientSession.order;return!(!e||!r)}async render(e){let r=this.client.createButton({buttonType:"buy",buttonColor:"black",buttonSizeMode:"fill",buttonRootNode:e instanceof ShadowRoot?e:void 0,onClick:this.handleButtonClick.bind(this)});e.appendChild(r)}async handleButtonClick(){this.callbacks.onStart();try{let e=this.buildPaymentDataRequest(),r=await this.client.loadPaymentData(e),{data:o,error:a}=await this.context.pciApi.postPaymentInstruments({flow:"GATEWAY",network:r.paymentMethodData.info?.cardNetwork??"OTHER",merchant_id:this.config.options.merchantId,encrypted_payload:Tr.encode(r.paymentMethodData.tokenizationData.token)});if(a||!o)throw a??new Error("Failed to tokenize payment data");let n=await this.createPayment(o.token);n.status==="SUCCESS"?this.callbacks.onSuccess(n):this.callbacks.onError()}catch(e){throw this.callbacks.onError(),e}}async handlePaymentDataChanged(e){return{}}buildIsReadyToPayRequest(){return{apiVersion:Ho,apiVersionMinor:zo,allowedPaymentMethods:[this.allowedPaymentMethod]}}buildPaymentDataRequest(){let{countryCode:e,currencyCode:r,merchantAmount:o,totalOrderAmount:a}=this.context.configuration.clientSession.order;return{apiVersion:Ho,apiVersionMinor:zo,transactionInfo:{countryCode:e,currencyCode:r,displayItems:[],totalPriceStatus:"FINAL",totalPrice:Nr(o??a,r),totalPriceLabel:"Total"},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}}}]}}};async function rl(i){let t=i.configuration.paymentMethods.map(r=>{if(r.implementationType==="WEB_REDIRECT")return new wi(r,i);if(r.type===gt.PAYMENT_CARD)return new Ir(r,i);if(r.type===gt.PAYPAL)return new Lr(r,i);if(r.type===gt.APPLE_PAY)return new Or(r,i);if(r.type===gt.GOOGLE_PAY)return new Rr(r,i)}).map(r=>r?.setup().then(o=>o?r:null));return(await Promise.all(t)).filter(r=>!!r)}async function il(i){let t=await $s(i),e=await rl(t);return{context:t,paymentMethods:e}}var Dr=class i{constructor(t,e=window.parent){R(this,"sessionId");R(this,"targetWindow");R(this,"messageHandlers",new Set);this.sessionId=t,this.targetWindow=e}send(t,e,r){let o={sessionId:this.sessionId,type:t,...r&&{target:r},...e&&{data:e}};this.targetWindow.postMessage(o,"*")}listen(t){let e=r=>{let o=r.data;if(o?.sessionId===this.sessionId){let{sessionId:a,...n}=o;t(n)}};return this.messageHandlers.add(e),window.addEventListener("message",e),()=>{window.removeEventListener("message",e),this.messageHandlers.delete(e)}}forIframe(t){if(!t.contentWindow)throw new Error("Iframe contentWindow is not available");return new i(this.sessionId,t.contentWindow)}cleanup(){this.messageHandlers.forEach(t=>{window.removeEventListener("message",t)}),this.messageHandlers.clear()}};async function ol(i){try{await i.start();let t=await i.tokenize(),e=await i.createPayment(t.token);return await i.handleRequiredAction(e)}catch(t){throw t}}var al=async(i,t)=>{if(!i.onBeforePaymentCreate)return!0;let e=setTimeout(()=>{},1e4);return new Promise(r=>{i.onBeforePaymentCreate({paymentMethodType:t},{continuePaymentCreation:()=>{clearTimeout(e),r(!0)},abortPaymentCreation:()=>{clearTimeout(e),r(!1)}})})};async function ua(i,t){if(!await al(i,t.config.type)){i.onCheckoutFail?.(new Error("Payment creation aborted"),{});return}i.onPaymentCreationStart?.();let r=null,o=null;try{o=await ol(t)}catch(a){r=a}finally{if(r||!o){i.onCheckoutFail?.(new Error("Payment creation failed"),{});return}if(o.status==="FAILED")return void i.onCheckoutFail?.(new Error("Payment failed"),{payment:o??{}});i.onCheckoutComplete?.({payment:o})}}function nl(i,t,e,r={}){let o=[],a="LOCAL";return e.store.publicStore.subscribe(({networks:n,networksSource:l})=>{l==="LOCAL"&&a!=="LOCAL"&&r.onCardNetworksLoading?.(),(l!==a||sl(o,n))&&(o=n,a=l,r.onCardNetworksChange?.(ll({networks:o,source:a},t.configuration.clientSession.paymentMethod.orderedAllowedCardNetworks)))}),{createHostedInputs:()=>{let n=new Dr(t.checkoutSessionId),l=d=>{let m=new Map,f=n.listen(u=>{u.target===d&&(u.type==="focus"?m.get("focus")?.():u.type==="blur"?m.get("blur")?.():u.type==="input"&&(m.get("input")?.(u.data),m.get("change")?.(u.data)))});return{cleanup:()=>{f()},getOptions:()=>e.store.optionsStore.getState()[d]||{placeholder:"",ariaLabel:"",style:{}},setOptions:u=>{e.store.optionsStore.setState({[d]:{...e.store.optionsStore.getState()[d],...u}})},render:(u,b)=>{let P=e.iframes[d];if(!P)return Promise.resolve();let A;return A=typeof u=="string"?document.querySelector(u):u,A&&(A.appendChild(P),P.onload=()=>{e.store.optionsStore.setState({[d]:b})}),Promise.resolve()},addEventListener:(u,b)=>{m.set(u,b)},focus:()=>{let u=e.iframes[d];u&&u.contentWindow&&n.forIframe(u).send("focus",void 0,d)},blur:()=>{let u=e.iframes[d];u&&u.contentWindow&&n.forIframe(u).send("blur",void 0,d)},setDisabled:u=>{let b=e.store.publicStore.getState();e.store.publicStore.setState({...b,[d]:{...b[d],disabled:u}})}}};return{cardNumberInput:l("cardNumber"),cardHolderNameInput:l("cardHolderName"),expiryInput:l("cardExpiryDate"),cvvInput:l("cardSecurityCode")}},removeHostedInputs:()=>{e.iframes.cardNumber.remove(),e.iframes.cardSecurityCode.remove(),e.iframes.cardExpiryDate.remove(),e.iframes.cardHolderName.remove()},submit:n=>{if(n?.cardNetwork){let l=e.store.publicStore.getState();e.store.publicStore.setState({...l,preferredNetwork:n.cardNetwork})}return ua(i,e)},validate:()=>{let n=e.store.publicStore.getState(),l=[],d=["cardNumber","cardSecurityCode","cardExpiryDate","cardHolderName"];for(let m of d){let f=n[m];!f.valid&&f.error&&l.push({field:m,name:m,error:f.error,message:f.error})}return Promise.resolve({valid:l.length===0,validationErrors:l})},reset:()=>{t.apiControllerIframe?.contentWindow&&new Dr(t.checkoutSessionId).forIframe(t.apiControllerIframe).send("reset-card-form")}}}function sl(i,t){if(i.length!==t.length)return!0;let e=t.map(({network:r})=>r);return!i.every(({network:r})=>e.includes(r))}function ll({networks:i,source:t},e){let r=e,o=new Set(r.map(d=>Fo(d).backend)),a=i.map(d=>({...d,allowed:o.has(d.network)})).sort((d,m)=>d.allowed?r.indexOf(d.network)-r.indexOf(m.network):1),n=a.filter(d=>d.allowed),l=t==="REMOTE"&&n.length>1;return{detectedCardNetworks:{items:a,preferred:n[0]},...l&&{selectableCardNetworks:{items:n,preferred:n[0]}},source:t}}function dl(i,t,e){return{createButton:()=>({render:async r=>{e.setCallbacks({onStart:()=>{i.onBeforePaymentCreate?.({paymentMethodType:e.config.type},{continuePaymentCreation:()=>{i.onPaymentCreationStart?.()},abortPaymentCreation:()=>{}})},onSuccess(o){i.onCheckoutComplete?.({payment:o})},onError(){i.onCheckoutFail?.(new Error("Payment creation failed"),{})}}),await e.render(r)}})}}function cl(i,t,e){return{start:()=>ua(i,e)}}async function ha(i,t){let{paymentMethods:e,context:r}=await il(i);return t.onAvailablePaymentMethodsLoad?.(e.map(o=>({type:o.config.type,managerType:o.config.type===gt.PAYMENT_CARD?"CARD":o.config.implementationType==="NATIVE_SDK"?"NATIVE":"REDIRECT"}))),{start:()=>Promise.resolve(),createPaymentMethodManager:async(o,a)=>{let n=e.find(({config:l})=>l.type===o);return n?n instanceof Ir?nl(t,r,n,a):n instanceof Lr||n instanceof Or||n instanceof Rr?dl(t,r,n):cl(t,r,n):null},getSDKUtilities:()=>({getCardNetworkAsset:o=>{let{asset:a,display:n}=Fo(o);return{cardUrl:`${ks}/brand/card/${a}.svg`,displayName:n}},getUIOrderAmount:()=>{let{merchantAmount:o,totalOrderAmount:a,currencyCode:n}=r.configuration.clientSession.order;return Nr(o??a,n)},getCDNAssets:o=>{let a=e.find(({config:m})=>m.type===o);if(!a)return null;let{backgroundColor:n,iconUrl:l,text:d}=a.config.displayMetadata?.button||{};return{backgroundColor:n,iconUrl:l,paymentMethodName:d,displayName:a.config.name}},getPaymentMethodConfiguration:o=>e.find(({config:a})=>a.type===o)?.config}),createVaultManager:()=>({})}}var $r=class{constructor(t){this.createPaymentMethodManager=null;this._paymentsList=[];this.currentSdkInstance=null;this.primerJS=null;this.loadingTimeout=null;this.isDisconnected=!1;(this.host=t).addController(this),this.isDisconnected=!1,this.sdkInstanceTask=new L(t,{args:()=>[this.host.clientToken,this.host.options],task:this.initializeHeadless()}),new L(t,{args:()=>[this.sdkInstanceTask.value,this.paymentsList],task:this.initializeLitContext()})}set paymentsList(t){this._paymentsList=t,this.host.requestUpdate()}get paymentsList(){return this._paymentsList}hostConnected(){this.isDisconnected=!1,this.host.sdkStateController.startLoading(),this.setupLoadingTimeout()}hostDisconnected(){this.isDisconnected=!0,this.cleanupResources()}setupLoadingTimeout(){this.clearLoadingTimeout(),this.loadingTimeout=setTimeout(()=>{this.host.sdkStateController.currentState.isLoading&&(S.warn("Loading timeout reached, resetting SDK state"),this.cleanupResources(),this.host.sdkStateController.completeLoading())},1e4)}clearLoadingTimeout(){this.loadingTimeout!==null&&(clearTimeout(this.loadingTimeout),this.loadingTimeout=null)}cleanupResources(){if(this.clearLoadingTimeout(),this.currentSdkInstance)try{this.paymentsList=[],this.createPaymentMethodManager=null,this.host.sdkStateController.reset(),S.info("SDK instance cleaned up")}catch(t){S.error("Error cleaning up SDK instance:",t)}this.currentSdkInstance=null,this.primerJS=null}async _loadV2Sdk(t=wo){let e=window;if(e.Primer&&typeof e.Primer.preloadPrimer=="function"){S.info("SDK already loaded, skipping load script"),await e.Primer.preloadPrimer();return}await Mo(t),await e.Primer.preloadPrimer()}initializeHeadless(){return async([t,e])=>{if(this.isDisconnected)return S.warn("Component disconnected, aborting SDK initialization"),T;if(!t||!e)return T;this.cleanupResources();try{let r;e.sdkCore?r={createHeadless:(l,d)=>ha(l,d)}:(await this._loadV2Sdk(),r=window.Primer),this.primerJS=new Ar(null);let o=await r.createHeadless(t,{...e,onAvailablePaymentMethodsLoad:n=>{this.isDisconnected||(S.info("Configuration payment methods:",n),this.paymentsList=n)},onCheckoutComplete:({payment:n})=>{this.isDisconnected||(S.info("Payment completed:",n),this.host.sdkStateController.completeProcessing(),this.primerJS&&this.primerJS.handlePaymentComplete(n))},onCheckoutFail:(n,l)=>{this.isDisconnected||(S.error("Payment failed:",n),this.host.sdkStateController.setFailure(n.code||"UNKNOWN_ERROR",n.message||"Unknown error occurred"),this.primerJS&&this.primerJS.handlePaymentFailure(n,l.payment))},onBeforePaymentCreate:(n,l)=>{this.isDisconnected||(this.host.sdkStateController.startProcessing(),this.primerJS?this.primerJS.handleBeforePaymentCreate(n,l):l?.continuePaymentCreation())},onPaymentMethodAction:(n,l)=>{this.isDisconnected||n==="PAYMENT_METHOD_UNSELECTED"&&this.host.sdkStateController.stopProcessing()},onPaymentCreationStart:()=>{this.isDisconnected||(this.host.sdkStateController.resetError(),this.primerJS&&this.primerJS.handlePaymentStart())}});if(this.createPaymentMethodManager=o.createPaymentMethodManager.bind(o),this.currentSdkInstance=o,this.primerJS&&Object.defineProperty(this.primerJS,"headlessInstance",{value:o,writable:!1}),await o.start(),this.isDisconnected)return this.cleanupResources(),T;this.host.sdkContextController.setClientOptions(e),this.primerJS&&this.host.primerEventsController.dispatchCheckoutInitialized(this.primerJS);let a=o.getSDKUtilities();return this.host.sdkContextController.setHeadlessUtils(a),this.host.vaultManagerController.initializeVaultManager(o.createVaultManager.bind(o),{vaultEnabled:e.vault?.enabled,captureVaultedCardCvv:!!a.getPaymentMethodConfiguration("PAYMENT_CARD")?.options?.captureVaultedCardCvv,showEmptyState:e.vault?.showEmptyState}),o}catch(r){throw r instanceof Error&&(S.error("SDK initialization error:",r),this.host.sdkStateController.setError(r)),this.cleanupResources(),r}}}initializeLitContext(){return async([t,e])=>{if(this.isDisconnected)return T;if(!t||!e.length)return T;let r=new Map,o=new Map;try{for(let n of e){if(this.isDisconnected)break;let l=await this.initializePaymentMethodManager(n)();n&&l&&(r.set(n.type,n),o.set(n.type,l))}if(this.isDisconnected)return T;let a=new Er(r);return this.host.sdkContextController.setPaymentManagers(o),this.host.sdkContextController.setPaymentMethods(a),this.primerJS&&this.primerJS.setPaymentMethods(a),this.host.primerEventsController.dispatchPaymentMethods(a),S.info("Initialized payment methods:",a.toArray()),r}catch(a){if(a instanceof Error)throw this.host.sdkStateController.setError(a),a;return null}finally{this.clearLoadingTimeout(),this.isDisconnected||this.host.sdkStateController.completeLoading()}}}initializePaymentMethodManager(t){let{type:e,managerType:r}=t;return async()=>{if(this.isDisconnected||!this.createPaymentMethodManager)return null;if(r==="KLARNA"){let o=await this.createPaymentMethodManager("KLARNA",{onPaymentMethodCategoriesChange:a=>{this.isDisconnected||this.host.sdkContextController.setKlarnaCategories({categories:a,isLoading:!1})}});return o?{type:e,manager:o}:null}try{if(r==="CARD"){let a=await this.createPaymentMethodManager(e,{onCardNetworksChange:n=>{this.isDisconnected||this.host.cardNetworkController.processCardNetworkChangeEvent(n)},onCardNetworksLoading:()=>{this.isDisconnected||this.host.cardNetworkController.setCardNetworksLoading()}});return a?{type:e,manager:a}:null}let o=await this.createPaymentMethodManager(e);return o?{type:e,manager:o}:null}catch(o){return S.error(`Failed to initialize manager for ${e}:`,o),null}}}};var Vr=class{constructor(t){this.host=t,t.addController(this)}_error(t){let{error:e}=t.detail;this.host.sdkStateController.setFailure("UNKNOWN_ERROR",e.message)}_mandateConfirmed(){this.host.sdkStateController.completeProcessing()}_mandateDeclined(){this.host.sdkStateController.setFailure("UNKNOWN_ERROR","Mandate declined")}hostConnected(){this.host.addEventListener("primer-ach-error",this._error.bind(this)),this.host.addEventListener("primer-ach-mandate-confirmed",this._mandateConfirmed.bind(this)),this.host.addEventListener("primer-ach-mandate-declined",this._mandateDeclined.bind(this))}hostDisconnected(){this.host.removeEventListener("primer-ach-error",this._error.bind(this)),this.host.removeEventListener("primer-ach-mandate-confirmed",this._mandateConfirmed.bind(this)),this.host.removeEventListener("primer-ach-mandate-declined",this._mandateDeclined.bind(this))}};var pl=Ui({"../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.KRXB3WQO.js"),"../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.6SKJRXIR.js"),"../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.SANDLFEK.js"),"../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.FC4I5M3C.js"),"../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.YI32NZ7B.js"),"../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.7M7UFQB7.js"),"../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.XSGTYDZR.js"),"../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.VO4GDE3X.js"),"../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.MNFLVOE3.js"),"../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.TBWVUZEF.js"),"../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.6EMWUABR.js"),"../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.XZLDFHYI.js"),"../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.JBSFMKZ2.js"),"../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.I75VK2ID.js"),"../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.JBNP6RXT.js"),"../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.PW253QAL.js"),"../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.LM4RITYJ.js"),"../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.JGCKQA6J.js"),"../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.VBXULDDY.js"),"../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.7Q6BFLDK.js"),"../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.QOC76SSC.js"),"../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.BANZIFNH.js"),"../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.Q2SRJOKH.js"),"../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.XMNFEN5T.js"),"../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.3AJDTMU5.js"),"../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.TFPDXNEV.js"),"../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.FPTX4NM4.js"),"../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.CAFSKRQ2.js"),"../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.7BPSDYTC.js"),"../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.6ZVCFPVW.js"),"../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.RF34QM23.js"),"../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.AKDHLRUA.js"),"../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.VBALOWHZ.js"),"../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.WN7VCF27.js"),"../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.ICXGVGRR.js"),"../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.SIP5JIOX.js"),"../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.R77UEKCA.js"),"../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.6M2YSTDX.js"),"../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.33ZY4CDS.js"),"../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.M27YUIZC.js"),"../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.Q2SIY6NA.js"),"../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.EJZOGSJR.js"),"../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.3RROGLXM.js"),"../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.GGWFQ3Y7.js"),"../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.MQHNRMN4.js"),"../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.WNR7XUSX.js"),"../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.GNCY2PNY.js")});si(i=>pl(`../../localization/lit-localize/locales/${i}.ts`));var ml={LOADER_DISABLED:"loader-disabled",CUSTOM_STYLES:"custom-styles",CLIENT_TOKEN:"client-token",JS_INIT:"js-initialized"},re=class extends g{constructor(){super();this.customStyles="";this.clientToken="";this.options={};this.disableLoader=!1;this._jsInitialized=!1;this.previousLoadingState=!0;this.hasAssignedContent=!1;this._loadingTimeoutId=null;this.locale="en-GB";this.onSlotChange=e=>{let o=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=o.length>0,this.requestUpdate()};this.sdkContextController=new tr(this),this.sdkStateController=new Qt(this),this.primerEventsController=new ht(this),this.styleProcessingController=new rr(this),this.vaultManagerController=new Tt(this),this.cardNetworkController=new qt(this),this.achPaymentEventsController=new Vr(this),new $r(this)}set jsInitialized(e){this.requestUpdate(),this._jsInitialized=e}get jsInitialized(){return this._jsInitialized}attributeChangedCallback(e,r,o){e===ml.CUSTOM_STYLES?this.styleProcessingController.processCustomStyles(o):super.attributeChangedCallback(e,r,o)}disconnectedCallback(){this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null),this.sdkStateController?.currentState.isLoading&&this.sdkStateController.forceCompleteLoading(),super.disconnectedCallback()}willUpdate(e){e.has("options")&&(this.options?.locale&&(di(this.options?.locale)?this.locale=ci(this.options?.locale):S.warn("\u{1F30E}\u2757 Unsupported locale provided:",this.options?.locale,"- Falling back to default locale `en-GB`")),li(this.locale||"en-GB"))}updated(){let e=getComputedStyle(this);this.sdkContextController.setComputedStyles(e),this.checkLoadingStateChange()}checkLoadingStateChange(){let e=this.sdkStateController?.currentState.isLoading||!1;this.previousLoadingState&&!e&&(this.jsInitialized=!0),this.previousLoadingState=e,e&&!this._loadingTimeoutId?this._loadingTimeoutId=window.setTimeout(()=>{this.sdkStateController?.currentState.isLoading&&(S.warn("Loading timeout in component, forcing completion"),this.sdkStateController.forceCompleteLoading(),this.jsInitialized=!0),this._loadingTimeoutId=null},1e4):!e&&this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null)}render(){let e=this.sdkStateController.currentState,r=e.isLoading,o=e.error,a=!r&&!o;return p` ${I(r,()=>h)} ${I(o,()=>p`<primer-checkout-error></primer-checkout-error>`)} ${I(a,()=>p`<slot name="main" @slotchange=${this.onSlotChange}></slot>${I(this.hasAssignedContent,()=>h,()=>p`<primer-main></primer-main>`)} `,()=>h)} `}addEventListener(e,r,o){super.addEventListener(e,r,o)}removeEventListener(e,r,o){super.removeEventListener(e,r,o)}};re.styles=[E,Po],s([c({type:String,attribute:"custom-styles"})],re.prototype,"customStyles",2),s([c({type:String,attribute:"client-token"})],re.prototype,"clientToken",2),s([c({type:Object})],re.prototype,"options",2),s([c({type:Boolean,attribute:"loader-disabled"})],re.prototype,"disableLoader",2),s([c({type:Boolean,reflect:!0,attribute:"js-initialized"})],re.prototype,"_jsInitialized",2),s([Ge("slot")],re.prototype,"defaultSlot",2),s([_()],re.prototype,"previousLoadingState",2),re=s([M(),v("primer-checkout")],re);function ul(i){return document.querySelector(`#${i}`)}function hl(i,t){let e=document.createElement("style");return e.textContent=i,e.id=t,e}function jt(i,t,e=!0){if(!Sr||ul(t))return;let o=hl(i,t);e&&document.head.firstChild?document.head.insertBefore(o,document.head.firstChild):document.head.appendChild(o)}var fa=`
|
|
113
113
|
@keyframes primer-css-spinner-rotate {
|
|
114
114
|
0% {
|
|
115
115
|
transform: rotate(0deg);
|